diff options
| author | Tauwni <102470988+Tauwni@users.noreply.github.com> | 2026-11-26 12:19:12 +0100 |
|---|---|---|
| committer | Tauwni <102470988+Tauwni@users.noreply.github.com> | 2026-11-26 12:19:12 +0100 |
| commit | beffaa9a476ca1b3dfd9cfa55e39eafbb1f5eec6 (patch) | |
| tree | 32877805bf4eb46d9a89d5753db6b5a2b06dc845 /runtime/test | |
| parent | f29ca7bacae9507f83e8c56abdb604bd4efb4cf1 (diff) | |
| parent | a73a57e1339be072baf5522351c8ec7f1482b56b (diff) | |
Merge main into fix/null-descriptor-generated-dir
Diffstat (limited to 'runtime/test')
82 files changed, 11938 insertions, 416 deletions
diff --git a/runtime/test/big_compile_gate_test.cpp b/runtime/test/big_compile_gate_test.cpp new file mode 100644 index 000000000..a012ac9f9 --- /dev/null +++ b/runtime/test/big_compile_gate_test.cpp | |||
| @@ -0,0 +1,532 @@ | |||
| 1 | // LargeModuleGate with a budget that is read (runtime/src/large_module_gate.h): who gets in, in which order and when, and | ||
| 2 | // the settings. The threads that wait for a place are real; every check that waits for one gives up after 10 s, so a | ||
| 3 | // missing wake-up fails the test and does not hang it. Fixed budgets (vk_pipeline_check's) are large_module_gate_test.cpp's. | ||
| 4 | // No Vulkan. | ||
| 5 | #include "../src/large_module_gate.h" | ||
| 6 | |||
| 7 | #include <atomic> | ||
| 8 | #include <chrono> | ||
| 9 | #include <condition_variable> | ||
| 10 | #include <cstdint> | ||
| 11 | #include <cstdio> | ||
| 12 | #include <cstdlib> | ||
| 13 | #include <functional> | ||
| 14 | #include <memory> | ||
| 15 | #include <mutex> | ||
| 16 | #include <thread> | ||
| 17 | #include <vector> | ||
| 18 | |||
| 19 | namespace { | ||
| 20 | |||
| 21 | using namespace std::chrono_literals; | ||
| 22 | using leonida::LargeModuleGate; | ||
| 23 | using Work = LargeModuleGate::Work; | ||
| 24 | |||
| 25 | // Ends the process: the threads that the failed check left waiting would keep the rest from ending. | ||
| 26 | #define CHECK(condition) do { \ | ||
| 27 | if (!(condition)) { \ | ||
| 28 | std::fprintf(stderr, "FAIL line %d: %s\n", __LINE__, #condition); \ | ||
| 29 | std::fflush(stderr); \ | ||
| 30 | std::_Exit(1); \ | ||
| 31 | } \ | ||
| 32 | } while (0) | ||
| 33 | |||
| 34 | bool eventually(const std::function<bool()>& what) { | ||
| 35 | const auto end = std::chrono::steady_clock::now() + 10s; | ||
| 36 | while (!what()) { | ||
| 37 | if (std::chrono::steady_clock::now() > end) return false; | ||
| 38 | std::this_thread::sleep_for(1ms); | ||
| 39 | } | ||
| 40 | return true; | ||
| 41 | } | ||
| 42 | |||
| 43 | // A thread in enter() for one estimate, which keeps its place until leave() is called. | ||
| 44 | class Entrant { | ||
| 45 | public: | ||
| 46 | Entrant(LargeModuleGate& gate, std::uint64_t estimate, Work work = Work::demand) { | ||
| 47 | thread_ = std::thread([&gate, estimate, work, this] { | ||
| 48 | LargeModuleGate::Ticket place(gate, estimate, work); | ||
| 49 | in_ = true; | ||
| 50 | std::unique_lock lock(mutex_); | ||
| 51 | go_.wait(lock, [this] { return leave_; }); | ||
| 52 | lock.unlock(); | ||
| 53 | }); | ||
| 54 | } | ||
| 55 | ~Entrant() { | ||
| 56 | if (thread_.joinable()) { | ||
| 57 | leave(); | ||
| 58 | join(); | ||
| 59 | } | ||
| 60 | } | ||
| 61 | Entrant(const Entrant&) = delete; | ||
| 62 | Entrant& operator=(const Entrant&) = delete; | ||
| 63 | bool in() const { return in_; } | ||
| 64 | void leave() { | ||
| 65 | std::lock_guard lock(mutex_); | ||
| 66 | leave_ = true; | ||
| 67 | go_.notify_all(); | ||
| 68 | } | ||
| 69 | void join() { thread_.join(); } | ||
| 70 | |||
| 71 | private: | ||
| 72 | std::atomic<bool> in_{false}; | ||
| 73 | std::mutex mutex_; | ||
| 74 | std::condition_variable go_; | ||
| 75 | bool leave_ = false; | ||
| 76 | std::thread thread_; | ||
| 77 | }; | ||
| 78 | |||
| 79 | bool waiting(LargeModuleGate& gate, Work work, std::size_t count) { | ||
| 80 | return eventually([&] { return gate.waiting(work) == count; }); | ||
| 81 | } | ||
| 82 | bool in(const Entrant& e) { return eventually([&] { return e.in(); }); } | ||
| 83 | // The time a wrong admission would need to happen. | ||
| 84 | bool stays_out(const Entrant& e) { | ||
| 85 | std::this_thread::sleep_for(50ms); | ||
| 86 | return !e.in(); | ||
| 87 | } | ||
| 88 | |||
| 89 | LargeModuleGate fixed(std::uint64_t budget) { | ||
| 90 | return LargeModuleGate([budget] { return budget; }); | ||
| 91 | } | ||
| 92 | |||
| 93 | void bound_and_one_always() { | ||
| 94 | auto gate = fixed(10); | ||
| 95 | Entrant big(gate, 25); // more than the whole budget: it compiles alone | ||
| 96 | CHECK(in(big)); | ||
| 97 | Entrant first(gate, 6), second(gate, 4); | ||
| 98 | CHECK(stays_out(first) && stays_out(second)); | ||
| 99 | big.leave(); | ||
| 100 | big.join(); | ||
| 101 | CHECK(in(first) && in(second)); // 10 fits exactly | ||
| 102 | Entrant third(gate, 1); | ||
| 103 | CHECK(waiting(gate, Work::demand, 1) && stays_out(third)); | ||
| 104 | first.leave(); | ||
| 105 | CHECK(in(third)); | ||
| 106 | CHECK(gate.inflight() == 2); | ||
| 107 | second.leave(); | ||
| 108 | third.leave(); | ||
| 109 | second.join(); | ||
| 110 | third.join(); | ||
| 111 | first.join(); | ||
| 112 | CHECK(eventually([&] { return gate.inflight() == 0; })); | ||
| 113 | } | ||
| 114 | |||
| 115 | // Whatever the sizes, what is in fits, or is one alone; everything gets in, once. | ||
| 116 | void many_threads() { | ||
| 117 | for (const std::uint64_t budget : {0u, 1u, 10u, 40u}) { | ||
| 118 | auto gate = fixed(budget); | ||
| 119 | std::atomic<std::uint64_t> used{0}; | ||
| 120 | std::atomic<unsigned> inside{0}, most{0}; | ||
| 121 | std::atomic<int> over{0}, done{0}; | ||
| 122 | std::vector<std::thread> threads; | ||
| 123 | for (unsigned t = 0; t < 8; ++t) | ||
| 124 | threads.emplace_back([&, t] { | ||
| 125 | for (unsigned i = 0; i < 150; ++i) { | ||
| 126 | const std::uint64_t estimate = 1 + (t * 7 + i) % 13; | ||
| 127 | const LargeModuleGate::Ticket place(gate, estimate, | ||
| 128 | (t + i) % 3 ? Work::demand : Work::speculative); | ||
| 129 | const std::uint64_t sum = used += estimate; | ||
| 130 | const unsigned n = ++inside; | ||
| 131 | if (sum > budget && n > 1) ++over; | ||
| 132 | unsigned m = most; | ||
| 133 | while (n > m && !most.compare_exchange_weak(m, n)) {} | ||
| 134 | for (int spin = 0; spin < 20; ++spin) std::this_thread::yield(); | ||
| 135 | --inside; | ||
| 136 | used -= estimate; | ||
| 137 | ++done; | ||
| 138 | } | ||
| 139 | }); | ||
| 140 | for (auto& t : threads) t.join(); | ||
| 141 | CHECK(over == 0); | ||
| 142 | CHECK(done == 8 * 150); | ||
| 143 | CHECK(gate.inflight() == 0); | ||
| 144 | CHECK(budget < 40 || most > 1); // and where there is room, several are in | ||
| 145 | } | ||
| 146 | } | ||
| 147 | |||
| 148 | // Those that wait get in in the order they came, but for what fits now and also beside the first in line: that one finds | ||
| 149 | // its room when those that were in before it leave, whatever passed it. | ||
| 150 | void order() { | ||
| 151 | auto gate = fixed(10); | ||
| 152 | Entrant first(gate, 8); | ||
| 153 | CHECK(in(first)); | ||
| 154 | Entrant big(gate, 9); | ||
| 155 | CHECK(waiting(gate, Work::demand, 1)); | ||
| 156 | Entrant in_the_way(gate, 2); // it fits beside the first, and not beside the big one | ||
| 157 | CHECK(waiting(gate, Work::demand, 2)); | ||
| 158 | Entrant little(gate, 1); | ||
| 159 | CHECK(in(little)); | ||
| 160 | Entrant next(gate, 1); // beside the big one there is room for one of these | ||
| 161 | CHECK(waiting(gate, Work::demand, 3)); | ||
| 162 | CHECK(stays_out(big) && stays_out(in_the_way) && stays_out(next)); | ||
| 163 | little.leave(); | ||
| 164 | little.join(); | ||
| 165 | CHECK(stays_out(big) && stays_out(in_the_way) && stays_out(next)); // nor when the one that passed has left | ||
| 166 | first.leave(); | ||
| 167 | CHECK(in(big)); | ||
| 168 | CHECK(in(next)); // the first in line is now in_the_way, which it can pass | ||
| 169 | CHECK(stays_out(in_the_way)); | ||
| 170 | big.leave(); | ||
| 171 | CHECK(in(in_the_way)); | ||
| 172 | in_the_way.leave(); | ||
| 173 | next.leave(); | ||
| 174 | } | ||
| 175 | |||
| 176 | // What passes the first in line is bounded: a stream of small ones does not keep it out. | ||
| 177 | void a_stream_of_small_ones_does_not_keep_out() { | ||
| 178 | auto gate = fixed(100); | ||
| 179 | Entrant first(gate, 50); | ||
| 180 | CHECK(in(first)); | ||
| 181 | Entrant big(gate, 70); | ||
| 182 | CHECK(waiting(gate, Work::demand, 1)); | ||
| 183 | std::vector<std::unique_ptr<Entrant>> stream; | ||
| 184 | for (int i = 0; i < 3; ++i) { // 30 beside the big one's 70, one after another | ||
| 185 | stream.push_back(std::make_unique<Entrant>(gate, 10)); | ||
| 186 | CHECK(in(*stream.back())); | ||
| 187 | if (i < 2) { // one of them stays in | ||
| 188 | stream.back()->leave(); | ||
| 189 | stream.back()->join(); | ||
| 190 | } | ||
| 191 | } | ||
| 192 | Entrant more(gate, 10); | ||
| 193 | CHECK(waiting(gate, Work::demand, 2)); | ||
| 194 | CHECK(stays_out(more)); // it fits (70 of 100 with the rest), but the first in line has been passed enough | ||
| 195 | first.leave(); | ||
| 196 | CHECK(in(big)); // 10 of the stream and 70 | ||
| 197 | CHECK(in(more)); | ||
| 198 | big.leave(); | ||
| 199 | more.leave(); | ||
| 200 | stream.back()->leave(); | ||
| 201 | } | ||
| 202 | |||
| 203 | // Of those that can pass, the one that came first does. | ||
| 204 | void those_that_pass_keep_their_order() { | ||
| 205 | for (int round = 0; round < 10; ++round) { | ||
| 206 | auto gate = fixed(20); | ||
| 207 | Entrant first(gate, 15), other(gate, 5); | ||
| 208 | CHECK(in(first) && in(other)); | ||
| 209 | Entrant big(gate, 12); | ||
| 210 | CHECK(waiting(gate, Work::demand, 1)); | ||
| 211 | Entrant a(gate, 4); | ||
| 212 | CHECK(waiting(gate, Work::demand, 2)); | ||
| 213 | Entrant b(gate, 4); | ||
| 214 | CHECK(waiting(gate, Work::demand, 3)); | ||
| 215 | other.leave(); | ||
| 216 | CHECK(in(a)); | ||
| 217 | CHECK(stays_out(b) && stays_out(big)); // 19 of 20 | ||
| 218 | first.leave(); | ||
| 219 | CHECK(in(big) && in(b)); | ||
| 220 | big.leave(); | ||
| 221 | a.leave(); | ||
| 222 | b.leave(); | ||
| 223 | } | ||
| 224 | } | ||
| 225 | |||
| 226 | // One that needs the machine for itself is not passed: what got in beside it would keep it out. | ||
| 227 | void larger_than_the_budget_is_not_passed() { | ||
| 228 | auto gate = fixed(10); | ||
| 229 | Entrant first(gate, 5); | ||
| 230 | CHECK(in(first)); | ||
| 231 | Entrant alone(gate, 25); | ||
| 232 | CHECK(waiting(gate, Work::demand, 1)); | ||
| 233 | Entrant little(gate, 1); | ||
| 234 | CHECK(waiting(gate, Work::demand, 2)); | ||
| 235 | CHECK(stays_out(little)); | ||
| 236 | first.leave(); | ||
| 237 | CHECK(in(alone)); | ||
| 238 | CHECK(stays_out(little)); | ||
| 239 | alone.leave(); | ||
| 240 | CHECK(in(little)); | ||
| 241 | little.leave(); | ||
| 242 | } | ||
| 243 | |||
| 244 | // The same for the speculative ones, within their quarter. | ||
| 245 | void speculative_ones_pass_each_other() { | ||
| 246 | auto gate = fixed(100); | ||
| 247 | Entrant first(gate, 20, Work::speculative); | ||
| 248 | CHECK(in(first)); | ||
| 249 | Entrant big(gate, 18, Work::speculative); | ||
| 250 | CHECK(waiting(gate, Work::speculative, 1)); | ||
| 251 | Entrant little(gate, 5, Work::speculative); | ||
| 252 | CHECK(in(little)); // 25 of 25, and 23 with the big one | ||
| 253 | Entrant next(gate, 1, Work::speculative); | ||
| 254 | CHECK(waiting(gate, Work::speculative, 2)); | ||
| 255 | little.leave(); | ||
| 256 | little.join(); | ||
| 257 | CHECK(in(next)); // 21 of 25, and 24 of what may pass | ||
| 258 | Entrant over(gate, 2, Work::speculative); | ||
| 259 | CHECK(waiting(gate, Work::speculative, 2)); | ||
| 260 | CHECK(stays_out(over) && stays_out(big)); // it would be 26 | ||
| 261 | first.leave(); | ||
| 262 | CHECK(in(big) && in(over)); | ||
| 263 | big.leave(); | ||
| 264 | next.leave(); | ||
| 265 | over.leave(); | ||
| 266 | } | ||
| 267 | |||
| 268 | // The first in the queue leaves it, and the next one, which fits as well, gets in at once and not when something leaves. | ||
| 269 | void one_admission_wakes_the_next() { | ||
| 270 | auto gate = fixed(10); | ||
| 271 | Entrant first(gate, 10); | ||
| 272 | CHECK(in(first)); | ||
| 273 | Entrant a(gate, 4), b(gate, 4), c(gate, 2); | ||
| 274 | CHECK(waiting(gate, Work::demand, 3)); | ||
| 275 | first.leave(); | ||
| 276 | CHECK(in(a) && in(b) && in(c)); | ||
| 277 | CHECK(gate.inflight() == 3); | ||
| 278 | a.leave(); | ||
| 279 | b.leave(); | ||
| 280 | c.leave(); | ||
| 281 | } | ||
| 282 | |||
| 283 | void leaving_wakes_all_that_fit() { | ||
| 284 | auto gate = fixed(10); | ||
| 285 | Entrant a(gate, 5), b(gate, 5); | ||
| 286 | CHECK(in(a) && in(b)); | ||
| 287 | Entrant c(gate, 3), d(gate, 2); | ||
| 288 | CHECK(waiting(gate, Work::demand, 2) && stays_out(c)); | ||
| 289 | a.leave(); | ||
| 290 | CHECK(in(c) && in(d)); | ||
| 291 | b.leave(); | ||
| 292 | c.leave(); | ||
| 293 | d.leave(); | ||
| 294 | } | ||
| 295 | |||
| 296 | // What a submission waits for goes first, whenever it came. | ||
| 297 | void demand_before_speculative() { | ||
| 298 | auto gate = fixed(10); | ||
| 299 | Entrant first(gate, 10); | ||
| 300 | CHECK(in(first)); | ||
| 301 | Entrant speculative(gate, 1, Work::speculative); | ||
| 302 | CHECK(waiting(gate, Work::speculative, 1)); | ||
| 303 | Entrant demand(gate, 9); | ||
| 304 | CHECK(waiting(gate, Work::demand, 1)); | ||
| 305 | first.leave(); | ||
| 306 | CHECK(in(demand)); // the speculative one came first and would have fitted | ||
| 307 | CHECK(stays_out(speculative)); | ||
| 308 | demand.leave(); | ||
| 309 | CHECK(in(speculative)); | ||
| 310 | speculative.leave(); | ||
| 311 | } | ||
| 312 | |||
| 313 | // Waiting demand keeps out speculative work that fits, also the one that is first in line. | ||
| 314 | void waiting_demand_keeps_speculative_out() { | ||
| 315 | auto gate = fixed(100); | ||
| 316 | Entrant first(gate, 40, Work::demand); | ||
| 317 | CHECK(in(first)); | ||
| 318 | Entrant blocked(gate, 100); // waits for the first | ||
| 319 | CHECK(waiting(gate, Work::demand, 1)); | ||
| 320 | Entrant speculative(gate, 5, Work::speculative); // a quarter holds it | ||
| 321 | CHECK(waiting(gate, Work::speculative, 1)); | ||
| 322 | CHECK(stays_out(speculative)); | ||
| 323 | first.leave(); | ||
| 324 | CHECK(in(blocked)); | ||
| 325 | CHECK(stays_out(speculative)); | ||
| 326 | blocked.leave(); | ||
| 327 | CHECK(in(speculative)); | ||
| 328 | speculative.leave(); | ||
| 329 | } | ||
| 330 | |||
| 331 | // While a submission has more to build, the room between two of its modules is not a speculative one's. | ||
| 332 | void a_demand_keeps_speculative_out() { | ||
| 333 | auto gate = fixed(100); | ||
| 334 | auto one = std::make_unique<LargeModuleGate::Demand>(gate), other = std::make_unique<LargeModuleGate::Demand>(gate); | ||
| 335 | Entrant speculative(gate, 10, Work::speculative); | ||
| 336 | CHECK(waiting(gate, Work::speculative, 1)); | ||
| 337 | CHECK(stays_out(speculative)); // it fits, and nothing is in | ||
| 338 | for (int i = 0; i < 2; ++i) { | ||
| 339 | Entrant built(gate, 10); | ||
| 340 | CHECK(in(built)); | ||
| 341 | built.leave(); | ||
| 342 | built.join(); | ||
| 343 | CHECK(stays_out(speculative)); // between two of the submission's modules | ||
| 344 | } | ||
| 345 | one.reset(); | ||
| 346 | CHECK(stays_out(speculative)); // another submission has some | ||
| 347 | other.reset(); | ||
| 348 | CHECK(in(speculative)); // the end of the last one wakes it | ||
| 349 | speculative.leave(); | ||
| 350 | } | ||
| 351 | |||
| 352 | // A speculative one gets in within a quarter of the budget, and what is free of it is there for a demand. | ||
| 353 | void speculative_share() { | ||
| 354 | auto gate = fixed(100); | ||
| 355 | Entrant demand(gate, 30); | ||
| 356 | CHECK(in(demand)); | ||
| 357 | Entrant over(gate, 26, Work::speculative); // 56 of 100, but more than 25 with the rest | ||
| 358 | CHECK(waiting(gate, Work::speculative, 1)); | ||
| 359 | CHECK(stays_out(over)); | ||
| 360 | demand.leave(); | ||
| 361 | CHECK(in(over)); // alone, whatever its size | ||
| 362 | Entrant quick(gate, 70); | ||
| 363 | CHECK(in(quick)); // 96 of 100: the speculative one does not count against it | ||
| 364 | quick.leave(); | ||
| 365 | over.leave(); | ||
| 366 | quick.join(); | ||
| 367 | over.join(); | ||
| 368 | CHECK(eventually([&] { return gate.inflight() == 0; })); | ||
| 369 | Entrant share(gate, 25, Work::speculative); | ||
| 370 | CHECK(in(share)); | ||
| 371 | Entrant second(gate, 1, Work::speculative); | ||
| 372 | CHECK(waiting(gate, Work::speculative, 1)); // one more byte is past the quarter | ||
| 373 | CHECK(stays_out(second)); | ||
| 374 | Entrant next(gate, 75); | ||
| 375 | CHECK(in(next)); // the whole rest | ||
| 376 | CHECK(stays_out(second)); | ||
| 377 | next.leave(); | ||
| 378 | share.leave(); | ||
| 379 | CHECK(in(second)); | ||
| 380 | second.leave(); | ||
| 381 | } | ||
| 382 | |||
| 383 | // Speculative ones get in in the order they came, and alone when nothing is in. | ||
| 384 | void speculative_order_and_alone() { | ||
| 385 | auto gate = fixed(0); // unknown memory: one at a time | ||
| 386 | Entrant a(gate, 5, Work::speculative); | ||
| 387 | CHECK(in(a)); | ||
| 388 | Entrant b(gate, 5, Work::speculative); | ||
| 389 | CHECK(waiting(gate, Work::speculative, 1)); | ||
| 390 | Entrant c(gate, 5, Work::demand); | ||
| 391 | CHECK(waiting(gate, Work::demand, 1)); | ||
| 392 | CHECK(stays_out(b) && stays_out(c)); | ||
| 393 | a.leave(); | ||
| 394 | CHECK(in(c)); | ||
| 395 | CHECK(stays_out(b)); | ||
| 396 | c.leave(); | ||
| 397 | CHECK(in(b)); | ||
| 398 | b.leave(); | ||
| 399 | } | ||
| 400 | |||
| 401 | // The budget is read when a place is asked for and when one is given back, not once. | ||
| 402 | void budget_follows_the_moment() { | ||
| 403 | std::atomic<std::uint64_t> free{100}; | ||
| 404 | LargeModuleGate gate([&] { return free.load(); }); | ||
| 405 | CHECK(gate.budget() == 100); | ||
| 406 | Entrant a(gate, 30), b(gate, 10); | ||
| 407 | CHECK(in(a) && in(b)); | ||
| 408 | free = 35; | ||
| 409 | Entrant c(gate, 20); // 60 of 100 a moment ago | ||
| 410 | CHECK(waiting(gate, Work::demand, 1)); | ||
| 411 | CHECK(stays_out(c)); | ||
| 412 | free = 100; | ||
| 413 | b.leave(); | ||
| 414 | CHECK(in(c)); // 50 of 100 now; it would not be within 35 | ||
| 415 | CHECK(gate.inflight() == 2); | ||
| 416 | a.leave(); | ||
| 417 | c.leave(); | ||
| 418 | a.join(); | ||
| 419 | c.join(); | ||
| 420 | // A budget that shrinks while a module is in does not throw it out, and holds the next. | ||
| 421 | Entrant d(gate, 100); | ||
| 422 | CHECK(in(d)); | ||
| 423 | free = 1; | ||
| 424 | Entrant e(gate, 1); | ||
| 425 | CHECK(waiting(gate, Work::demand, 1)); | ||
| 426 | CHECK(stays_out(e)); | ||
| 427 | CHECK(gate.inflight() == 1); | ||
| 428 | d.leave(); | ||
| 429 | CHECK(in(e)); | ||
| 430 | } | ||
| 431 | |||
| 432 | // An estimate counts for as long as its module is in, whatever the driver has taken of it already. | ||
| 433 | void estimates_stay_reserved() { | ||
| 434 | auto gate = fixed(100); // the driver has taken nothing yet: the memory is all there | ||
| 435 | Entrant a(gate, 60); | ||
| 436 | CHECK(in(a)); | ||
| 437 | Entrant b(gate, 60); | ||
| 438 | CHECK(waiting(gate, Work::demand, 1)); | ||
| 439 | CHECK(stays_out(b)); | ||
| 440 | a.leave(); | ||
| 441 | CHECK(in(b)); | ||
| 442 | b.leave(); | ||
| 443 | } | ||
| 444 | |||
| 445 | // A ticket gives its place back once, however it ends. | ||
| 446 | void tickets() { | ||
| 447 | auto gate = fixed(10); | ||
| 448 | { | ||
| 449 | LargeModuleGate::Ticket a(gate, 6, Work::speculative); | ||
| 450 | LargeModuleGate::Ticket moved = std::move(a); | ||
| 451 | CHECK(gate.inflight() == 1); | ||
| 452 | LargeModuleGate::Ticket b; | ||
| 453 | b = LargeModuleGate::Ticket(gate, 3); | ||
| 454 | CHECK(gate.inflight() == 2); | ||
| 455 | b.release(); | ||
| 456 | b.release(); | ||
| 457 | CHECK(gate.inflight() == 1); | ||
| 458 | } | ||
| 459 | CHECK(gate.inflight() == 0); | ||
| 460 | } | ||
| 461 | |||
| 462 | // The memory budget's setting: what it says, and nothing else. | ||
| 463 | void settings() { | ||
| 464 | using leonida::large_compile_budget; | ||
| 465 | const auto check = [](const char* text, bool valid, bool has, std::uint64_t mib) { | ||
| 466 | const auto s = large_compile_budget(text); | ||
| 467 | CHECK(s.valid == valid); | ||
| 468 | CHECK(s.fixed.has_value() == has); | ||
| 469 | if (has) CHECK(*s.fixed == mib << 20); | ||
| 470 | }; | ||
| 471 | check(nullptr, true, false, 0); | ||
| 472 | check("", true, false, 0); | ||
| 473 | check("0", true, true, 0); | ||
| 474 | check("1", true, true, 1); | ||
| 475 | check("512", true, true, 512); | ||
| 476 | check("0512", true, true, 512); | ||
| 477 | check("12a", false, false, 0); | ||
| 478 | check(" 5", false, false, 0); | ||
| 479 | check("-1", false, false, 0); | ||
| 480 | check("1.5", false, false, 0); | ||
| 481 | check("99999999999999999999999", true, true, UINT64_MAX >> 20); // saturates: no limit, not a small number | ||
| 482 | CHECK(*large_compile_budget("99999999999999999999999").fixed >= (UINT64_MAX >> 20) << 20); | ||
| 483 | } | ||
| 484 | |||
| 485 | // The share of the memory, and what the machine gives now: nothing unknown on Windows and Linux, and no more than three | ||
| 486 | // quarters of either limit. | ||
| 487 | void machine() { | ||
| 488 | using leonida::large_compile_share; | ||
| 489 | CHECK(large_compile_share(1000, 4000) == 750); | ||
| 490 | CHECK(large_compile_share(4000, 1000) == 750); // the commit limit has less room than the RAM | ||
| 491 | CHECK(large_compile_share(0, 4000) == 0); | ||
| 492 | const std::uint64_t budget = leonida::large_compile_budget_bytes(); | ||
| 493 | #if defined(_WIN32) || defined(__linux__) | ||
| 494 | CHECK(budget > 0); | ||
| 495 | #endif | ||
| 496 | // Read a moment apart on a running machine: the budget may not exceed either limit by more than that moment. | ||
| 497 | const std::uint64_t slack = std::uint64_t(256) << 20; | ||
| 498 | CHECK(budget <= leonida::available_memory_bytes() / 4 * 3 + slack); | ||
| 499 | CHECK(leonida::large_module_estimate(1 << 20) == (std::uint64_t(1) << 20) * leonida::kBytesPerSpirvByte); | ||
| 500 | #ifdef _WIN32 | ||
| 501 | MEMORYSTATUSEX status{}; | ||
| 502 | status.dwLength = sizeof(status); | ||
| 503 | CHECK(GlobalMemoryStatusEx(&status) != 0); | ||
| 504 | CHECK(budget <= status.ullAvailPageFile / 4 * 3 + slack); | ||
| 505 | #endif | ||
| 506 | } | ||
| 507 | |||
| 508 | } // namespace | ||
| 509 | |||
| 510 | int main() { | ||
| 511 | bound_and_one_always(); | ||
| 512 | many_threads(); | ||
| 513 | order(); | ||
| 514 | a_stream_of_small_ones_does_not_keep_out(); | ||
| 515 | those_that_pass_keep_their_order(); | ||
| 516 | larger_than_the_budget_is_not_passed(); | ||
| 517 | speculative_ones_pass_each_other(); | ||
| 518 | one_admission_wakes_the_next(); | ||
| 519 | leaving_wakes_all_that_fit(); | ||
| 520 | demand_before_speculative(); | ||
| 521 | waiting_demand_keeps_speculative_out(); | ||
| 522 | a_demand_keeps_speculative_out(); | ||
| 523 | speculative_share(); | ||
| 524 | speculative_order_and_alone(); | ||
| 525 | budget_follows_the_moment(); | ||
| 526 | estimates_stay_reserved(); | ||
| 527 | tickets(); | ||
| 528 | settings(); | ||
| 529 | machine(); | ||
| 530 | std::puts("big_compile_gate: ok"); | ||
| 531 | return 0; | ||
| 532 | } | ||
diff --git a/runtime/test/big_compute_module.h b/runtime/test/big_compute_module.h new file mode 100644 index 000000000..28dde996f --- /dev/null +++ b/runtime/test/big_compute_module.h | |||
| @@ -0,0 +1,298 @@ | |||
| 1 | // Large compute modules that are work for a driver's compiler, not padding: a register file in a Function array that every | ||
| 2 | // instruction loads from and stores to (as the translator's modules have it), integer instructions, selections, nested | ||
| 3 | // conditionals and loops, and loads from memory the compiler knows nothing about. The same instructions run on the CPU, so | ||
| 4 | // the value that a dispatch stores is known. Made from a seed; no game data. | ||
| 5 | #pragma once | ||
| 6 | |||
| 7 | #include <cstddef> | ||
| 8 | #include <cstdint> | ||
| 9 | #include <initializer_list> | ||
| 10 | #include <random> | ||
| 11 | #include <utility> | ||
| 12 | #include <vector> | ||
| 13 | |||
| 14 | namespace bigmodule { | ||
| 15 | |||
| 16 | using Words = std::vector<std::uint32_t>; | ||
| 17 | |||
| 18 | inline void op(Words& out, std::uint16_t code, std::initializer_list<std::uint32_t> operands) { | ||
| 19 | out.push_back((std::uint32_t(operands.size() + 1) << 16) | code); | ||
| 20 | out.insert(out.end(), operands.begin(), operands.end()); | ||
| 21 | } | ||
| 22 | |||
| 23 | enum class Kind : std::uint8_t { add, sub, mul, xor_, and_, or_, shl, shr, select, load, if_, end_if, loop, end_loop }; | ||
| 24 | |||
| 25 | struct Instruction { | ||
| 26 | Kind kind; | ||
| 27 | std::uint8_t d = 0, a = 0, b = 0, c = 0; // registers; c is a shift count or a loop count for those kinds | ||
| 28 | }; | ||
| 29 | |||
| 30 | constexpr unsigned kRegisters = 48, kConstants = 64, kDepth = 3; | ||
| 31 | constexpr unsigned kLoadBase = 256, kLoadWords = 64; // the words of the buffer the loads read (the CPU takes them as 0) | ||
| 32 | |||
| 33 | struct Program { | ||
| 34 | std::vector<Instruction> code; | ||
| 35 | std::uint32_t constants[kConstants]; | ||
| 36 | |||
| 37 | // What the module stores for the dispatch with this root constant. | ||
| 38 | std::uint32_t run(std::uint32_t root_constant) const { | ||
| 39 | std::uint32_t v[kRegisters]; | ||
| 40 | for (unsigned i = 0; i < kRegisters; ++i) v[i] = constants[i % kConstants] ^ (root_constant + i); | ||
| 41 | walk(0, v); | ||
| 42 | std::uint32_t out = 0; | ||
| 43 | for (unsigned i = 0; i < kRegisters; ++i) out ^= v[i]; | ||
| 44 | return out; | ||
| 45 | } | ||
| 46 | |||
| 47 | private: | ||
| 48 | // Runs from `at` to the end marker of its block and returns the index after it. | ||
| 49 | std::size_t walk(std::size_t at, std::uint32_t* v) const { | ||
| 50 | for (; at < code.size();) { | ||
| 51 | const Instruction& i = code[at]; | ||
| 52 | const std::uint32_t k = constants[i.c % kConstants]; | ||
| 53 | switch (i.kind) { | ||
| 54 | case Kind::add: v[i.d] = v[i.a] + v[i.b] + k; break; | ||
| 55 | case Kind::sub: v[i.d] = v[i.a] - v[i.b] - k; break; | ||
| 56 | case Kind::mul: v[i.d] = v[i.a] * v[i.b] * k; break; | ||
| 57 | case Kind::xor_: v[i.d] = v[i.a] ^ v[i.b] ^ k; break; | ||
| 58 | case Kind::and_: v[i.d] = v[i.a] & (v[i.b] | k); break; | ||
| 59 | case Kind::or_: v[i.d] = v[i.a] | (v[i.b] & k); break; | ||
| 60 | case Kind::shl: v[i.d] = (v[i.a] << (i.c & 31)) ^ v[i.b]; break; | ||
| 61 | case Kind::shr: v[i.d] = (v[i.a] >> (i.c & 31)) ^ v[i.b]; break; | ||
| 62 | case Kind::select: v[i.d] = v[i.a] < v[i.b] ? v[i.c % kRegisters] : v[i.a]; break; | ||
| 63 | case Kind::load: v[i.d] = v[i.b]; break; // + the loaded word, which is 0 | ||
| 64 | case Kind::if_: { | ||
| 65 | std::size_t after = at + 1; | ||
| 66 | if (v[i.a] < v[i.b]) | ||
| 67 | after = walk(at + 1, v); | ||
| 68 | else | ||
| 69 | after = skip(at + 1); | ||
| 70 | at = after; | ||
| 71 | continue; | ||
| 72 | } | ||
| 73 | case Kind::loop: { | ||
| 74 | std::size_t after = at + 1; | ||
| 75 | for (unsigned n = 0; n < i.c; ++n) after = walk(at + 1, v); | ||
| 76 | at = after; | ||
| 77 | continue; | ||
| 78 | } | ||
| 79 | case Kind::end_if: | ||
| 80 | case Kind::end_loop: return at + 1; | ||
| 81 | } | ||
| 82 | ++at; | ||
| 83 | } | ||
| 84 | return at; | ||
| 85 | } | ||
| 86 | std::size_t skip(std::size_t at) const { | ||
| 87 | for (int depth = 1; at < code.size(); ++at) { | ||
| 88 | const Kind k = code[at].kind; | ||
| 89 | if (k == Kind::if_ || k == Kind::loop) ++depth; | ||
| 90 | if ((k == Kind::end_if || k == Kind::end_loop) && !--depth) return at + 1; | ||
| 91 | } | ||
| 92 | return at; | ||
| 93 | } | ||
| 94 | }; | ||
| 95 | |||
| 96 | // A module of about `bytes` bytes of SPIR-V (a few KiB more), and the program it runs. `seed` decides everything. It has the | ||
| 97 | // translator's push-constant block: s[4]:s[5] is the console VA of a root UAV, s[6] a root constant. A dispatch stores | ||
| 98 | // Program::run(s[6]) at the UAV's word s[6], and reads its words kLoadBase to kLoadBase + kLoadWords - 1, which have to | ||
| 99 | // be 0. | ||
| 100 | inline Words make(std::size_t bytes, std::uint64_t seed, Program* out = nullptr) { | ||
| 101 | std::mt19937_64 random(seed); | ||
| 102 | Program program; | ||
| 103 | for (auto& c : program.constants) c = std::uint32_t(random()); | ||
| 104 | // Ids. | ||
| 105 | enum : std::uint32_t { | ||
| 106 | id_void = 1, id_fn, id_main, id_uint, id_ulong, id_bool, id_block, id_sarr, id_c32, id_ptr_push_block, | ||
| 107 | id_push, id_ptr_push_uint, id_ptr_push_ulong, id_data, id_ptr_data, id_ptr_phys_uint, id_regs, id_cregs, | ||
| 108 | id_ptr_regs, id_ptr_fn_uint, id_vregs, id_entry, id_c64_32, id_c64_2, id_mask, id_base, | ||
| 109 | id_index0 = 40, // uint constants 0..127 | ||
| 110 | id_const0 = id_index0 + 128, // the program's constants | ||
| 111 | id_counter0 = id_const0 + kConstants, // loop counters by depth | ||
| 112 | id_first = id_counter0 + kDepth + 1, | ||
| 113 | }; | ||
| 114 | std::uint32_t next = id_first; | ||
| 115 | Words w = {0x07230203u, 0x00010500u, 0u, 0u, 0u}; | ||
| 116 | op(w, 17, {1}); // Shader | ||
| 117 | op(w, 17, {11}); // Int64 | ||
| 118 | op(w, 17, {5347}); // PhysicalStorageBufferAddresses | ||
| 119 | op(w, 14, {5348, 1}); | ||
| 120 | op(w, 15, {5, id_main, 0x6e69616du, 0u, id_push}); | ||
| 121 | op(w, 16, {id_main, 17, 1, 1, 1}); | ||
| 122 | op(w, 71, {id_sarr, 6, 4}); | ||
| 123 | op(w, 71, {id_block, 2}); | ||
| 124 | op(w, 72, {id_block, 0, 35, 0}); | ||
| 125 | op(w, 72, {id_block, 1, 35, 128}); | ||
| 126 | op(w, 72, {id_block, 2, 35, 136}); | ||
| 127 | op(w, 71, {id_data, 2}); | ||
| 128 | op(w, 72, {id_data, 0, 35, 0}); | ||
| 129 | op(w, 19, {id_void}); | ||
| 130 | op(w, 33, {id_fn, id_void}); | ||
| 131 | op(w, 21, {id_uint, 32, 0}); | ||
| 132 | op(w, 21, {id_ulong, 64, 0}); | ||
| 133 | op(w, 20, {id_bool}); | ||
| 134 | op(w, 43, {id_uint, id_c32, 32}); | ||
| 135 | op(w, 28, {id_sarr, id_uint, id_c32}); | ||
| 136 | op(w, 30, {id_block, id_sarr, id_ulong, id_ulong}); | ||
| 137 | op(w, 32, {id_ptr_push_block, 9, id_block}); | ||
| 138 | op(w, 59, {id_ptr_push_block, id_push, 9}); | ||
| 139 | op(w, 32, {id_ptr_push_uint, 9, id_uint}); | ||
| 140 | op(w, 32, {id_ptr_push_ulong, 9, id_ulong}); | ||
| 141 | op(w, 30, {id_data, id_uint}); | ||
| 142 | op(w, 32, {id_ptr_data, 5349, id_data}); | ||
| 143 | op(w, 32, {id_ptr_phys_uint, 5349, id_uint}); | ||
| 144 | op(w, 43, {id_uint, id_cregs, kRegisters}); | ||
| 145 | op(w, 28, {id_regs, id_uint, id_cregs}); | ||
| 146 | op(w, 32, {id_ptr_regs, 7, id_regs}); | ||
| 147 | op(w, 32, {id_ptr_fn_uint, 7, id_uint}); | ||
| 148 | op(w, 43, {id_ulong, id_c64_32, 32, 0}); | ||
| 149 | op(w, 43, {id_ulong, id_c64_2, 2, 0}); | ||
| 150 | op(w, 43, {id_uint, id_mask, kLoadWords - 1}); | ||
| 151 | op(w, 43, {id_uint, id_base, kLoadBase}); | ||
| 152 | for (std::uint32_t i = 0; i < 128; ++i) op(w, 43, {id_uint, id_index0 + i, i}); | ||
| 153 | for (std::uint32_t i = 0; i < kConstants; ++i) op(w, 43, {id_uint, id_const0 + i, program.constants[i]}); | ||
| 154 | op(w, 54, {id_void, id_main, 0, id_fn}); | ||
| 155 | op(w, 248, {id_entry}); | ||
| 156 | op(w, 59, {id_ptr_regs, id_vregs, 7}); | ||
| 157 | for (std::uint32_t i = 0; i <= kDepth; ++i) op(w, 59, {id_ptr_fn_uint, id_counter0 + i, 7}); | ||
| 158 | const auto unary = [&](std::uint16_t code, std::uint32_t type, std::uint32_t a) { | ||
| 159 | op(w, code, {type, next, a}); | ||
| 160 | return next++; | ||
| 161 | }; | ||
| 162 | const auto binary = [&](std::uint16_t code, std::uint32_t type, std::uint32_t a, std::uint32_t b) { | ||
| 163 | op(w, code, {type, next, a, b}); | ||
| 164 | return next++; | ||
| 165 | }; | ||
| 166 | const auto push_word = [&](std::uint32_t index) { | ||
| 167 | op(w, 65, {id_ptr_push_uint, next, id_push, id_index0, id_index0 + index}); | ||
| 168 | return unary(61, id_uint, next++); | ||
| 169 | }; | ||
| 170 | const std::uint32_t lo = push_word(4), hi = push_word(5); | ||
| 171 | op(w, 65, {id_ptr_push_ulong, next, id_push, id_index0 + 1}); | ||
| 172 | const std::uint32_t heap = unary(61, id_ulong, next++); | ||
| 173 | const std::uint32_t lo64 = unary(113, id_ulong, lo), hi64 = unary(113, id_ulong, hi); | ||
| 174 | const std::uint32_t high = binary(196, id_ulong, hi64, id_c64_32); | ||
| 175 | const std::uint32_t va = binary(197, id_ulong, high, lo64); | ||
| 176 | const std::uint32_t base = binary(128, id_ulong, va, heap); | ||
| 177 | const std::uint32_t root = push_word(6); | ||
| 178 | const auto slot = [&](std::uint32_t r) { | ||
| 179 | op(w, 65, {id_ptr_fn_uint, next, id_vregs, id_index0 + r}); | ||
| 180 | return next++; | ||
| 181 | }; | ||
| 182 | const auto load_reg = [&](std::uint32_t r) { return unary(61, id_uint, slot(r)); }; | ||
| 183 | const auto store_reg = [&](std::uint32_t r, std::uint32_t value) { | ||
| 184 | const std::uint32_t p = slot(r); | ||
| 185 | op(w, 62, {p, value}); | ||
| 186 | }; | ||
| 187 | for (std::uint32_t i = 0; i < kRegisters; ++i) { | ||
| 188 | const std::uint32_t seeded = binary(128, id_uint, root, id_index0 + i); | ||
| 189 | store_reg(i, binary(198, id_uint, id_const0 + i % kConstants, seeded)); | ||
| 190 | } | ||
| 191 | struct Open { | ||
| 192 | Kind kind; | ||
| 193 | std::uint32_t merge, header, cont, counter; | ||
| 194 | unsigned left; | ||
| 195 | }; | ||
| 196 | std::vector<Open> open; | ||
| 197 | unsigned loops = 0; | ||
| 198 | const auto pick = [&](std::uint32_t n) { return std::uint8_t(random() % n); }; | ||
| 199 | const auto close = [&] { | ||
| 200 | const Open o = open.back(); | ||
| 201 | open.pop_back(); | ||
| 202 | if (o.kind == Kind::if_) { | ||
| 203 | op(w, 249, {o.merge}); | ||
| 204 | op(w, 248, {o.merge}); | ||
| 205 | program.code.push_back({Kind::end_if}); | ||
| 206 | } else { | ||
| 207 | op(w, 249, {o.cont}); | ||
| 208 | op(w, 248, {o.cont}); | ||
| 209 | const std::uint32_t n = unary(61, id_uint, o.counter); | ||
| 210 | op(w, 62, {o.counter, binary(128, id_uint, n, id_index0 + 1)}); | ||
| 211 | op(w, 249, {o.header}); | ||
| 212 | op(w, 248, {o.merge}); | ||
| 213 | program.code.push_back({Kind::end_loop}); | ||
| 214 | --loops; | ||
| 215 | } | ||
| 216 | }; | ||
| 217 | while (w.size() * 4 + 256 < bytes) { | ||
| 218 | const std::uint32_t roll = std::uint32_t(random() % 100); | ||
| 219 | if (roll < 4 && open.size() < kDepth) { | ||
| 220 | const std::uint8_t a = pick(kRegisters), b = pick(kRegisters); | ||
| 221 | const std::uint32_t condition = binary(176, id_bool, load_reg(a), load_reg(b)); // ULessThan | ||
| 222 | const std::uint32_t then = next++, merge = next++; | ||
| 223 | op(w, 247, {merge, 0}); | ||
| 224 | op(w, 250, {condition, then, merge}); | ||
| 225 | op(w, 248, {then}); | ||
| 226 | open.push_back({Kind::if_, merge, 0, 0, 0, 10 + unsigned(random() % 30)}); | ||
| 227 | program.code.push_back({Kind::if_, 0, a, b, 0}); | ||
| 228 | } else if (roll < 5 && open.size() < kDepth && loops < 1) { | ||
| 229 | const std::uint8_t count = std::uint8_t(2 + random() % 3); | ||
| 230 | const std::uint32_t counter = id_counter0 + loops++; | ||
| 231 | op(w, 62, {counter, id_index0}); | ||
| 232 | const std::uint32_t header = next++, check = next++, body = next++, cont = next++, merge = next++; | ||
| 233 | op(w, 249, {header}); | ||
| 234 | op(w, 248, {header}); | ||
| 235 | op(w, 246, {merge, cont, 0}); | ||
| 236 | op(w, 249, {check}); | ||
| 237 | op(w, 248, {check}); | ||
| 238 | const std::uint32_t n = unary(61, id_uint, counter); | ||
| 239 | const std::uint32_t more = binary(176, id_bool, n, id_index0 + count); | ||
| 240 | op(w, 250, {more, body, merge}); | ||
| 241 | op(w, 248, {body}); | ||
| 242 | open.push_back({Kind::loop, merge, header, cont, counter, 20 + unsigned(random() % 20)}); | ||
| 243 | program.code.push_back({Kind::loop, 0, 0, 0, count}); | ||
| 244 | } else { | ||
| 245 | Instruction i{Kind(random() % 10), pick(kRegisters), pick(kRegisters), pick(kRegisters), pick(kConstants)}; | ||
| 246 | if (i.kind == Kind::load && random() % 2) i.kind = Kind::add; | ||
| 247 | const std::uint32_t k = id_const0 + i.c % kConstants; | ||
| 248 | std::uint32_t value = 0; | ||
| 249 | const std::uint32_t a = load_reg(i.a), b = load_reg(i.b); | ||
| 250 | switch (i.kind) { | ||
| 251 | case Kind::add: value = binary(128, id_uint, binary(128, id_uint, a, b), k); break; | ||
| 252 | case Kind::sub: value = binary(130, id_uint, binary(130, id_uint, a, b), k); break; | ||
| 253 | case Kind::mul: value = binary(132, id_uint, binary(132, id_uint, a, b), k); break; | ||
| 254 | case Kind::xor_: value = binary(198, id_uint, binary(198, id_uint, a, b), k); break; | ||
| 255 | case Kind::and_: value = binary(199, id_uint, a, binary(197, id_uint, b, k)); break; | ||
| 256 | case Kind::or_: value = binary(197, id_uint, a, binary(199, id_uint, b, k)); break; | ||
| 257 | case Kind::shl: value = binary(198, id_uint, binary(196, id_uint, a, id_index0 + (i.c & 31)), b); break; | ||
| 258 | case Kind::shr: value = binary(198, id_uint, binary(194, id_uint, a, id_index0 + (i.c & 31)), b); break; | ||
| 259 | case Kind::select: { | ||
| 260 | const std::uint32_t c = load_reg(i.c % kRegisters); | ||
| 261 | const std::uint32_t less = binary(176, id_bool, a, b); | ||
| 262 | op(w, 169, {id_uint, next, less, c, a}); | ||
| 263 | value = next++; | ||
| 264 | break; | ||
| 265 | } | ||
| 266 | default: { // load | ||
| 267 | const std::uint32_t index = binary(128, id_uint, binary(199, id_uint, a, id_mask), id_base); | ||
| 268 | const std::uint32_t offset = binary(196, id_ulong, unary(113, id_ulong, index), id_c64_2); | ||
| 269 | const std::uint32_t address = binary(128, id_ulong, base, offset); | ||
| 270 | const std::uint32_t data = unary(120, id_ptr_data, address); | ||
| 271 | op(w, 65, {id_ptr_phys_uint, next, data, id_index0}); | ||
| 272 | const std::uint32_t pointer = next++; | ||
| 273 | op(w, 61, {id_uint, next, pointer, 2, 4}); | ||
| 274 | const std::uint32_t loaded = next++; | ||
| 275 | value = binary(128, id_uint, b, loaded); | ||
| 276 | break; | ||
| 277 | } | ||
| 278 | } | ||
| 279 | store_reg(i.d, value); | ||
| 280 | program.code.push_back(i); | ||
| 281 | } | ||
| 282 | if (!open.empty() && !open.back().left--) close(); | ||
| 283 | } | ||
| 284 | while (!open.empty()) close(); | ||
| 285 | std::uint32_t result = load_reg(0); | ||
| 286 | for (std::uint32_t i = 1; i < kRegisters; ++i) result = binary(198, id_uint, result, load_reg(i)); | ||
| 287 | const std::uint32_t out_offset = binary(196, id_ulong, unary(113, id_ulong, root), id_c64_2); | ||
| 288 | const std::uint32_t out_data = unary(120, id_ptr_data, binary(128, id_ulong, base, out_offset)); | ||
| 289 | op(w, 65, {id_ptr_phys_uint, next, out_data, id_index0}); | ||
| 290 | op(w, 62, {next++, result, 2, 4}); | ||
| 291 | op(w, 253, {}); | ||
| 292 | op(w, 56, {}); | ||
| 293 | w[3] = next; | ||
| 294 | if (out) *out = std::move(program); | ||
| 295 | return w; | ||
| 296 | } | ||
| 297 | |||
| 298 | } // namespace bigmodule | ||
diff --git a/runtime/test/check_console_paths.cmake b/runtime/test/check_console_paths.cmake index bdd74a7d1..9f9a699b1 100644 --- a/runtime/test/check_console_paths.cmake +++ b/runtime/test/check_console_paths.cmake | |||
| @@ -1,12 +1,12 @@ | |||
| 1 | # Redirect the loader's stdout so both console paths must survive as UTF-8. | 1 | # Redirect the loader's stdout so the console paths (GAME:, the overlay and T:'s folder in it) must survive as UTF-8. |
| 2 | execute_process( | 2 | execute_process( |
| 3 | COMMAND ${RUNNER} "${LOADER}" --game-dir "game-Игра" --overlay "overlay-保存" | 3 | COMMAND ${RUNNER} "${LOADER}" --game-dir "game-Игра" --overlay "overlay-保存" |
| 4 | --run "${GUEST}" -- hello 42 | 4 | --run "${GUEST}" -- hello 42 |
| 5 | TIMEOUT 90 ENCODING UTF-8 | 5 | TIMEOUT 90 ENCODING UTF-8 |
| 6 | RESULT_VARIABLE code OUTPUT_VARIABLE output ERROR_VARIABLE error) | 6 | RESULT_VARIABLE code OUTPUT_VARIABLE output ERROR_VARIABLE error) |
| 7 | if(NOT code STREQUAL "0" OR | 7 | if(NOT code STREQUAL "0" OR |
| 8 | NOT output MATCHES "console paths: GAME: -> [^\n]*game-Игра, writes -> [^\n]*overlay-保存\r?\n") | 8 | NOT output MATCHES "console paths: GAME: -> [^\n]*game-Игра, writes -> [^\n]*overlay-保存, T: -> [^\n]*overlay-保存[\\/]\\.gta6rt-temp[\\/][^\n]*pid[0-9]+\r?\n") |
| 9 | message(FATAL_ERROR "Runtime did not report both Unicode paths (exit ${code})\n${output}\n${error}") | 9 | message(FATAL_ERROR "Runtime did not report the Unicode paths (exit ${code})\n${output}\n${error}") |
| 10 | endif() | 10 | endif() |
| 11 | if(NOT output MATCHES "(^|\n)tiny_game: OK(\r?\n|$)" OR | 11 | if(NOT output MATCHES "(^|\n)tiny_game: OK(\r?\n|$)" OR |
| 12 | NOT output MATCHES "(^|\n)game exited with code 0(\r?\n|$)") | 12 | NOT output MATCHES "(^|\n)game exited with code 0(\r?\n|$)") |
diff --git a/runtime/test/check_game_dir.cmake b/runtime/test/check_game_dir.cmake index 039a1ade3..1c973fd54 100644 --- a/runtime/test/check_game_dir.cmake +++ b/runtime/test/check_game_dir.cmake | |||
| @@ -1,7 +1,8 @@ | |||
| 1 | # Run the stand-in game from its own folder by bare name, as a player would (`gta6rt --run game.exe`), and again | 1 | # Run the stand-in game from its own folder by bare name, as a player would (`gta6rt --run game.exe`), and again |
| 2 | # with `--game-dir .`. In both, GAME: has to name that folder as an absolute path: the guest moves its current | 2 | # with `--game-dir .`. In both, GAME: has to name that folder as an absolute path: the guest moves its current |
| 3 | # directory away and then reads GAME:\tiny_game_probe.txt (argument game-file). Before, a bare name left GAME: with | 3 | # directory away and then reads GAME:\tiny_game_probe.txt (argument game-file). Before, a bare name left GAME: with |
| 4 | # an empty root (`console paths: GAME: -> , writes -> overlay`) and the open failed with ERROR_PATH_NOT_FOUND. | 4 | # an empty root (`console paths: GAME: -> , writes -> overlay`) and the open failed with ERROR_PATH_NOT_FOUND. The line |
| 5 | # also names T:'s folder, this process's own below <overlay>\.gta6rt-temp. | ||
| 5 | # The verdict is checked from the output, as check_loaded_gdk.cmake does, because under Wine an exit status alone | 6 | # The verdict is checked from the output, as check_loaded_gdk.cmake does, because under Wine an exit status alone |
| 6 | # can look successful. | 7 | # can look successful. |
| 7 | get_filename_component(guest_dir "${GUEST}" DIRECTORY) | 8 | get_filename_component(guest_dir "${GUEST}" DIRECTORY) |
| @@ -23,7 +24,7 @@ foreach(variant "bare" "dot") | |||
| 23 | # An absolute GAME: root: a drive letter (Windows, and Wine's Z:) or a leading slash, and an overlay inside it. | 24 | # An absolute GAME: root: a drive letter (Windows, and Wine's Z:) or a leading slash, and an overlay inside it. |
| 24 | if(NOT code STREQUAL "0" OR NOT output MATCHES "(^|\n)tiny_game: PASS GAME:" | 25 | if(NOT code STREQUAL "0" OR NOT output MATCHES "(^|\n)tiny_game: PASS GAME:" |
| 25 | OR NOT output MATCHES "(^|\n)tiny_game: OK(\n|$)" | 26 | OR NOT output MATCHES "(^|\n)tiny_game: OK(\n|$)" |
| 26 | OR NOT output MATCHES "(^|\n)console paths: GAME: -> ([A-Za-z]:|[\\/])[^\n]*, writes -> ([A-Za-z]:|[\\/])[^\n]*overlay(\n|$)" | 27 | OR NOT output MATCHES "(^|\n)console paths: GAME: -> ([A-Za-z]:|[\\/])[^\n]*, writes -> ([A-Za-z]:|[\\/])[^\n]*overlay, T: -> ([A-Za-z]:|[\\/])[^\n]*overlay[\\/]\\.gta6rt-temp[\\/][0-9]+-[0-9]+-[0-9]+-pid[0-9]+(\n|$)" |
| 27 | OR NOT output MATCHES "(^|\n)game exited with code 0(\n|$)") | 28 | OR NOT output MATCHES "(^|\n)game exited with code 0(\n|$)") |
| 28 | string(APPEND failures "--- ${variant}: returned ${code}\n${output}\n") | 29 | string(APPEND failures "--- ${variant}: returned ${code}\n${output}\n") |
| 29 | endif() | 30 | endif() |
diff --git a/runtime/test/compile_helper_test.cpp b/runtime/test/compile_helper_test.cpp new file mode 100644 index 000000000..7ef8d176e --- /dev/null +++ b/runtime/test/compile_helper_test.cpp | |||
| @@ -0,0 +1,176 @@ | |||
| 1 | // The compile helper's file protocol (shims/d3d12_compile_helper.h): request lines, their order, and the markers that | ||
| 2 | // keep two processes from compiling one entry at once. No Vulkan, no helper process. | ||
| 3 | #include "../shims/d3d12_compile_helper.h" | ||
| 4 | |||
| 5 | #include <chrono> | ||
| 6 | #include <cstdio> | ||
| 7 | #include <filesystem> | ||
| 8 | #include <fstream> | ||
| 9 | #include <string> | ||
| 10 | #include <thread> | ||
| 11 | |||
| 12 | namespace fs = std::filesystem; | ||
| 13 | namespace helper = rt::d3d12::compile_helper; | ||
| 14 | |||
| 15 | #define CHECK(condition) do { \ | ||
| 16 | if (!(condition)) { \ | ||
| 17 | std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); \ | ||
| 18 | return 1; \ | ||
| 19 | } \ | ||
| 20 | } while (0) | ||
| 21 | |||
| 22 | static int test_lines() { | ||
| 23 | const auto line = helper::parse_request(helper::format_request("fspx_compute/lib_cs_00001_ab", 4096)); | ||
| 24 | CHECK(line.name == "fspx_compute/lib_cs_00001_ab" && line.priority == 4096); | ||
| 25 | const auto bare = helper::parse_request("name only"); | ||
| 26 | CHECK(bare.name == "name only" && bare.priority == 0); // an older writer's request is urgent | ||
| 27 | return 0; | ||
| 28 | } | ||
| 29 | |||
| 30 | static int test_paths() { | ||
| 31 | const fs::path file = fs::path("J") / "cs-0123456789abcdef.bin"; | ||
| 32 | CHECK(helper::request_path(file) == fs::path("J") / "requests" / "cs-0123456789abcdef.req"); | ||
| 33 | CHECK(helper::failed_path(file) == fs::path("J") / "requests" / "cs-0123456789abcdef.failed"); | ||
| 34 | CHECK(helper::building_path(file) == fs::path("J") / "requests" / "cs-0123456789abcdef.building"); | ||
| 35 | return 0; | ||
| 36 | } | ||
| 37 | |||
| 38 | static int test_order(const fs::path& dir) { | ||
| 39 | const auto requests = dir / "requests"; | ||
| 40 | fs::create_directories(requests); | ||
| 41 | const auto now = fs::file_time_type::clock::now(); | ||
| 42 | const auto put = [&](const char* stem, const std::string& line, std::chrono::seconds age) { | ||
| 43 | const auto path = requests / (std::string(stem) + ".req"); | ||
| 44 | std::ofstream(path, std::ios::binary) << line << "\n"; | ||
| 45 | fs::last_write_time(path, now - age); | ||
| 46 | }; | ||
| 47 | put("cs-0000000000000001", helper::format_request("warm-old", 500000), std::chrono::seconds(30)); | ||
| 48 | put("cs-0000000000000002", helper::format_request("dispatch-new", 0), std::chrono::seconds(1)); | ||
| 49 | put("cs-0000000000000003", helper::format_request("dispatch-old", 0), std::chrono::seconds(20)); | ||
| 50 | put("cs-0000000000000004", helper::format_request("warm-small", 1000), std::chrono::seconds(5)); | ||
| 51 | std::ofstream(requests / "cs-0000000000000005.failed") << "not a request\n"; | ||
| 52 | const auto list = helper::list_requests(requests); | ||
| 53 | CHECK(list.size() == 4); | ||
| 54 | // Urgent (dispatch) first, oldest first among equals, then warm-ups by size. | ||
| 55 | CHECK(list[0].name == "dispatch-old" && list[1].name == "dispatch-new"); | ||
| 56 | CHECK(list[2].name == "warm-small" && list[3].name == "warm-old"); | ||
| 57 | CHECK(list[0].stem == "cs-0000000000000003"); | ||
| 58 | return 0; | ||
| 59 | } | ||
| 60 | |||
| 61 | static int test_markers(const fs::path& dir) { | ||
| 62 | const auto file = dir / "cs-00000000000000aa.bin"; | ||
| 63 | CHECK(helper::mark_building(file)); | ||
| 64 | CHECK(!helper::mark_building(file)); // this process has it already | ||
| 65 | helper::unmark_building(file); | ||
| 66 | CHECK(!fs::exists(helper::building_path(file))); // the held handle's close removes the lock file | ||
| 67 | CHECK(helper::mark_building(file)); | ||
| 68 | helper::unmark_building(file); | ||
| 69 | // A marker left behind names a process that no longer holds it (a killed helper) and is taken over: it is named | ||
| 70 | // after this very process, which is the reused process id that used to make it look busy forever. | ||
| 71 | std::ofstream(helper::building_path(file), std::ios::binary | std::ios::trunc) | ||
| 72 | << std::to_string(GetCurrentProcessId()) << "\n"; | ||
| 73 | CHECK(fs::exists(helper::building_path(file))); | ||
| 74 | CHECK(helper::mark_building(file)); | ||
| 75 | helper::unmark_building(file); | ||
| 76 | CHECK(!fs::exists(helper::building_path(file))); | ||
| 77 | // A lock file another opener holds is a live build: no claim, and nothing removes it. | ||
| 78 | const HANDLE held = CreateFileW(helper::building_path(file).c_str(), GENERIC_WRITE, 0, nullptr, CREATE_NEW, | ||
| 79 | FILE_ATTRIBUTE_NORMAL, nullptr); | ||
| 80 | CHECK(held != INVALID_HANDLE_VALUE); | ||
| 81 | CHECK(!helper::mark_building(file)); | ||
| 82 | CHECK(fs::exists(helper::building_path(file))); | ||
| 83 | CloseHandle(held); | ||
| 84 | fs::remove(helper::building_path(file)); | ||
| 85 | CHECK(helper::mark_building(file)); | ||
| 86 | helper::unmark_building(file); | ||
| 87 | return 0; | ||
| 88 | } | ||
| 89 | |||
| 90 | // What state() answers for a request the helper has taken: no .req and no .failed means it is not coming (the helper | ||
| 91 | // removes .req before it writes .failed and before the build that writes the journal file), so it is failed rather | ||
| 92 | // than pending for as long as the helper lives. | ||
| 93 | static int test_state(const fs::path& dir) { | ||
| 94 | auto& client = helper::Client::instance(); | ||
| 95 | client.pretend_helper_running_for_test(); // no helper process is started | ||
| 96 | const leonida::cached_pso::Identity identity; | ||
| 97 | const auto file = dir / "cs-00000000000000bb.bin"; | ||
| 98 | std::string why; | ||
| 99 | CHECK(client.request(file, "fspx_compute/lib_cs_00001", 4000, identity, &why)); | ||
| 100 | CHECK(fs::exists(helper::request_path(file))); | ||
| 101 | CHECK(client.state(file, identity, &why) == helper::Client::State::pending); | ||
| 102 | // A bump of the priority keeps a .failed: it is the answer to this same request. | ||
| 103 | helper::write_line(helper::failed_path(file), "no compute entry of that name"); | ||
| 104 | CHECK(client.request(file, "fspx_compute/lib_cs_00001", 0, identity, &why)); | ||
| 105 | CHECK(fs::exists(helper::failed_path(file))); | ||
| 106 | CHECK(helper::read_line(helper::failed_path(file)) == "no compute entry of that name"); | ||
| 107 | why.clear(); | ||
| 108 | CHECK(client.state(file, identity, &why) == helper::Client::State::failed); | ||
| 109 | CHECK(why.find("no compute entry of that name") != std::string::npos); | ||
| 110 | // A fresh request drops an older failure, so asking again can retry. | ||
| 111 | CHECK(client.request(file, "fspx_compute/lib_cs_00001", 0, identity, &why)); | ||
| 112 | CHECK(!fs::exists(helper::failed_path(file))); | ||
| 113 | // .req gone, no .failed, no journal file: failed. | ||
| 114 | const auto gone = dir / "cs-00000000000000cc.bin"; | ||
| 115 | CHECK(client.request(gone, "fspx_compute/lib_cs_00002", 0, identity, &why)); | ||
| 116 | CHECK(client.state(gone, identity, &why) == helper::Client::State::pending); | ||
| 117 | fs::remove(helper::request_path(gone)); | ||
| 118 | why.clear(); | ||
| 119 | CHECK(client.state(gone, identity, &why) == helper::Client::State::failed); | ||
| 120 | CHECK(!why.empty()); | ||
| 121 | // .req gone because the helper has started building it (it holds the lock file): pending, also past the pending | ||
| 122 | // bound, since giving up would only start the same build in the game. Failed once the lock is let go with no file. | ||
| 123 | const auto building = dir / "cs-00000000000000ee.bin"; | ||
| 124 | SetEnvironmentVariableA("LEONIDA_COMPILE_HELPER_PENDING_MS", "100"); | ||
| 125 | CHECK(client.request(building, "fspx_compute/lib_cs_00004", 0, identity, &why)); | ||
| 126 | const HANDLE lock = CreateFileW(helper::building_path(building).c_str(), GENERIC_WRITE, 0, nullptr, CREATE_NEW, | ||
| 127 | FILE_ATTRIBUTE_NORMAL | FILE_FLAG_DELETE_ON_CLOSE, nullptr); | ||
| 128 | CHECK(lock != INVALID_HANDLE_VALUE); | ||
| 129 | fs::remove(helper::request_path(building)); | ||
| 130 | CHECK(helper::building_held(building)); | ||
| 131 | CHECK(client.state(building, identity, &why) == helper::Client::State::pending); | ||
| 132 | std::this_thread::sleep_for(std::chrono::milliseconds(250)); | ||
| 133 | CHECK(client.state(building, identity, &why) == helper::Client::State::pending); | ||
| 134 | CloseHandle(lock); | ||
| 135 | CHECK(!helper::building_held(building)); | ||
| 136 | why.clear(); | ||
| 137 | CHECK(client.state(building, identity, &why) == helper::Client::State::failed); | ||
| 138 | SetEnvironmentVariableA("LEONIDA_COMPILE_HELPER_PENDING_MS", nullptr); | ||
| 139 | return 0; | ||
| 140 | } | ||
| 141 | |||
| 142 | // A pending request the helper never answers is failed after LEONIDA_COMPILE_HELPER_PENDING_MS, so a skipped dispatch | ||
| 143 | // becomes a build here instead of never running. | ||
| 144 | static int test_pending_bound(const fs::path& dir) { | ||
| 145 | auto& client = helper::Client::instance(); | ||
| 146 | client.pretend_helper_running_for_test(); | ||
| 147 | const leonida::cached_pso::Identity identity; | ||
| 148 | const auto file = dir / "cs-00000000000000dd.bin"; | ||
| 149 | SetEnvironmentVariableA("LEONIDA_COMPILE_HELPER_PENDING_MS", "150"); | ||
| 150 | std::string why; | ||
| 151 | CHECK(client.request(file, "fspx_compute/lib_cs_00003", 0, identity, &why)); | ||
| 152 | CHECK(client.state(file, identity, &why) == helper::Client::State::pending); | ||
| 153 | std::this_thread::sleep_for(std::chrono::milliseconds(300)); | ||
| 154 | why.clear(); | ||
| 155 | CHECK(client.state(file, identity, &why) == helper::Client::State::failed); | ||
| 156 | CHECK(why.find("150 ms") != std::string::npos); | ||
| 157 | SetEnvironmentVariableA("LEONIDA_COMPILE_HELPER_PENDING_MS", nullptr); | ||
| 158 | return 0; | ||
| 159 | } | ||
| 160 | |||
| 161 | int main() { | ||
| 162 | const auto dir = fs::temp_directory_path() / | ||
| 163 | ("leonida_compile_helper_test_" + std::to_string(std::chrono::steady_clock::now().time_since_epoch().count())); | ||
| 164 | std::error_code ec; | ||
| 165 | fs::create_directories(dir, ec); | ||
| 166 | int failed = test_lines(); | ||
| 167 | if (!failed) failed = test_paths(); | ||
| 168 | if (!failed) failed = test_order(dir); | ||
| 169 | if (!failed) failed = test_markers(dir); | ||
| 170 | if (!failed) failed = test_state(dir); | ||
| 171 | if (!failed) failed = test_pending_bound(dir); | ||
| 172 | fs::remove_all(dir, ec); | ||
| 173 | if (failed) return failed; | ||
| 174 | std::printf("compile_helper_test: ok\n"); | ||
| 175 | return 0; | ||
| 176 | } | ||
diff --git a/runtime/test/console_heap_vsharp_slots_test.cpp b/runtime/test/console_heap_vsharp_slots_test.cpp new file mode 100644 index 000000000..ebb74be45 --- /dev/null +++ b/runtime/test/console_heap_vsharp_slots_test.cpp | |||
| @@ -0,0 +1,259 @@ | |||
| 1 | // Portable CPU-only unit test for leonida::ConsoleHeapVsharpSlots (runtime/src/console_heap_vsharp_slots.h). | ||
| 2 | // Verifies bit-for-bit equivalence with a linear scan of 32-byte descriptor slots, boundary handling, range clears, | ||
| 3 | // callback-time bit clearing (as in refresh_console_heap invalidation passes), and a 5.5 MiB heap stress check. | ||
| 4 | #include "../src/console_heap_vsharp_slots.h" | ||
| 5 | |||
| 6 | #include <array> | ||
| 7 | #include <cstdint> | ||
| 8 | #include <cstdio> | ||
| 9 | #include <cstring> | ||
| 10 | #include <vector> | ||
| 11 | |||
| 12 | #define EXPECT(condition) \ | ||
| 13 | do { \ | ||
| 14 | if (!(condition)) { \ | ||
| 15 | std::fprintf(stderr, "FAIL line %d: %s\n", __LINE__, #condition); \ | ||
| 16 | return 1; \ | ||
| 17 | } \ | ||
| 18 | } while (0) | ||
| 19 | |||
| 20 | namespace { | ||
| 21 | |||
| 22 | using leonida::ConsoleHeapVsharpSlots; | ||
| 23 | |||
| 24 | std::vector<std::size_t> collect(const ConsoleHeapVsharpSlots& slots) { | ||
| 25 | std::vector<std::size_t> out; | ||
| 26 | slots.for_each([&](std::size_t slot) { out.push_back(slot); }); | ||
| 27 | return out; | ||
| 28 | } | ||
| 29 | |||
| 30 | int test_predicate_exactness() { | ||
| 31 | // Primary buffer V#: top 2 bits of w[3] are 0, w[2] (num_records) != 0. | ||
| 32 | std::uint32_t primary[8] = {0x1000, 0x20, 64, 0x3fffffffu, 0, 0, 0, 0}; | ||
| 33 | EXPECT(ConsoleHeapVsharpSlots::is_live_vsharp(primary)); | ||
| 34 | |||
| 35 | // Counter-only buffer V#: w[2] == 0, w[6] != 0, top 2 bits of w[3] == 0. | ||
| 36 | std::uint32_t counter[8] = {0, 0, 0, 0, 0x2000, 0, 16, 0}; | ||
| 37 | EXPECT(ConsoleHeapVsharpSlots::is_live_vsharp(counter)); | ||
| 38 | |||
| 39 | // Empty / zeroed V#: w[2] == 0 and w[6] == 0. | ||
| 40 | std::uint32_t empty[8] = {0x1000, 0, 0, 0x00010000u, 0x2000, 0, 0, 0}; | ||
| 41 | EXPECT(!ConsoleHeapVsharpSlots::is_live_vsharp(empty)); | ||
| 42 | |||
| 43 | // Image T# (w[3] >> 30 != 0): must NOT be treated as a buffer V# even if w[2]/w[6] are non-zero. | ||
| 44 | for (std::uint32_t hi : {1u, 2u, 3u}) { | ||
| 45 | std::uint32_t tsharp[8] = {0x1000, 0, 128, (hi << 30) | 0x55u, 0, 0, 64, 0}; | ||
| 46 | EXPECT(!ConsoleHeapVsharpSlots::is_live_vsharp(tsharp)); | ||
| 47 | } | ||
| 48 | |||
| 49 | // not_tsharp zeroes lower 16 bytes (w[0..3] = 0) while leaving upper 16 bytes (w[4..7]): | ||
| 50 | // if w[6] is non-zero, predicate matches the legacy `!(w[3] >> 30) && (w[2] || w[6])` check. | ||
| 51 | std::uint32_t not_tsharp_with_hi[8] = {0, 0, 0, 0, 0, 0, 1, 0}; | ||
| 52 | EXPECT(ConsoleHeapVsharpSlots::is_live_vsharp(not_tsharp_with_hi)); | ||
| 53 | return 0; | ||
| 54 | } | ||
| 55 | |||
| 56 | int test_boundaries_and_ranges() { | ||
| 57 | // Zero-size heap. | ||
| 58 | ConsoleHeapVsharpSlots zero; | ||
| 59 | zero.reset(0); | ||
| 60 | EXPECT(zero.empty() && zero.slot_count() == 0 && zero.live_count() == 0); | ||
| 61 | zero.set(0, true); | ||
| 62 | zero.clear(0); | ||
| 63 | zero.clear_range(0, 10); | ||
| 64 | EXPECT(zero.empty() && !zero.test(0) && collect(zero).empty()); | ||
| 65 | |||
| 66 | // Word boundary sizes: 1, 63, 64, 65, 128, 129, 257. | ||
| 67 | for (std::size_t n : {std::size_t(1), std::size_t(63), std::size_t(64), std::size_t(65), std::size_t(128), | ||
| 68 | std::size_t(129), std::size_t(257)}) { | ||
| 69 | ConsoleHeapVsharpSlots s; | ||
| 70 | s.reset(n); | ||
| 71 | EXPECT(s.slot_count() == n && s.empty()); | ||
| 72 | // Out-of-range writes are ignored. | ||
| 73 | s.set(n, true); | ||
| 74 | s.set(n + 100, true); | ||
| 75 | EXPECT(s.empty() && !s.test(n)); | ||
| 76 | |||
| 77 | // Set every slot, check idempotency and exact ordering. | ||
| 78 | for (std::size_t i = 0; i < n; ++i) s.set(i, true); | ||
| 79 | s.set(0, true); | ||
| 80 | s.set(n - 1, true); | ||
| 81 | EXPECT(s.live_count() == n); | ||
| 82 | const auto all = collect(s); | ||
| 83 | EXPECT(all.size() == n); | ||
| 84 | for (std::size_t i = 0; i < n; ++i) EXPECT(all[i] == i && s.test(i)); | ||
| 85 | |||
| 86 | // Inverted / empty / past-end clear_range is a no-op. | ||
| 87 | s.clear_range(5, 5); | ||
| 88 | s.clear_range(10, 2); | ||
| 89 | s.clear_range(n, n + 64); | ||
| 90 | EXPECT(s.live_count() == n); | ||
| 91 | |||
| 92 | // Partial single-word and multi-word clear_range. | ||
| 93 | if (n >= 129) { | ||
| 94 | s.clear_range(3, 19); // within word 0 | ||
| 95 | s.clear_range(60, 128); // spans word 0 tail + all of word 1 | ||
| 96 | EXPECT(s.live_count() == n - 16 - 68); | ||
| 97 | EXPECT(s.test(2) && !s.test(3) && !s.test(18) && s.test(19)); | ||
| 98 | EXPECT(s.test(59) && !s.test(60) && !s.test(127) && s.test(128)); | ||
| 99 | } | ||
| 100 | |||
| 101 | // Clear past end clamps cleanly. | ||
| 102 | s.clear_range(0, n + 500); | ||
| 103 | EXPECT(s.empty() && s.live_count() == 0 && collect(s).empty()); | ||
| 104 | } | ||
| 105 | return 0; | ||
| 106 | } | ||
| 107 | |||
| 108 | int test_in_place_invalidation_mutation() { | ||
| 109 | // Mirrors refresh_console_heap: for_each visits each live V# slot and calls fix_console_slot, which may clear | ||
| 110 | // that slot's bit when its backing buffer was released. | ||
| 111 | ConsoleHeapVsharpSlots s; | ||
| 112 | s.reset(260); | ||
| 113 | const std::vector<std::size_t> initial = {0, 1, 62, 63, 64, 65, 127, 128, 191, 255, 259}; | ||
| 114 | for (std::size_t slot : initial) s.set(slot, true); | ||
| 115 | EXPECT(s.live_count() == initial.size()); | ||
| 116 | |||
| 117 | std::vector<std::size_t> visited; | ||
| 118 | s.for_each([&](std::size_t slot) { | ||
| 119 | visited.push_back(slot); | ||
| 120 | // Simulate releasing every even-numbered slot during the invalidation pass. | ||
| 121 | if ((slot & 1u) == 0) s.set(slot, false); | ||
| 122 | }); | ||
| 123 | EXPECT(visited == initial); | ||
| 124 | |||
| 125 | std::vector<std::size_t> remaining; | ||
| 126 | for (std::size_t slot : initial) | ||
| 127 | if ((slot & 1u) != 0) remaining.push_back(slot); | ||
| 128 | EXPECT(s.live_count() == remaining.size()); | ||
| 129 | EXPECT(collect(s) == remaining); | ||
| 130 | |||
| 131 | // Clear the remaining slots and confirm empty fast path visits nothing. | ||
| 132 | s.for_each([&](std::size_t slot) { s.clear(slot); }); | ||
| 133 | EXPECT(s.empty() && collect(s).empty()); | ||
| 134 | return 0; | ||
| 135 | } | ||
| 136 | |||
| 137 | int test_differential_equivalence_against_linear_copy() { | ||
| 138 | // Differential model: maintain a synthetic 32-byte-per-slot `heap.copy` buffer alongside ConsoleHeapVsharpSlots | ||
| 139 | // across thousands of random writes, deferred zeroes, page-range zeroes, and invalidation passes. | ||
| 140 | constexpr std::size_t kSlots = 1029; | ||
| 141 | std::vector<std::array<std::uint32_t, 8>> gpu_copy(kSlots); | ||
| 142 | for (auto& slot : gpu_copy) slot.fill(0); | ||
| 143 | |||
| 144 | ConsoleHeapVsharpSlots tracked; | ||
| 145 | tracked.reset(kSlots); | ||
| 146 | |||
| 147 | auto linear_scan = [&] { | ||
| 148 | std::vector<std::size_t> expected; | ||
| 149 | for (std::size_t i = 0; i < kSlots; ++i) | ||
| 150 | if (ConsoleHeapVsharpSlots::is_live_vsharp(gpu_copy[i].data())) expected.push_back(i); | ||
| 151 | return expected; | ||
| 152 | }; | ||
| 153 | |||
| 154 | std::uint64_t rng = 0x9e3779b97f4a7c15ull; | ||
| 155 | auto next_u32 = [&]() -> std::uint32_t { | ||
| 156 | rng ^= rng >> 12; | ||
| 157 | rng ^= rng << 25; | ||
| 158 | rng ^= rng >> 27; | ||
| 159 | return static_cast<std::uint32_t>((rng * 0x2545f4914f6cdd1dull) >> 32); | ||
| 160 | }; | ||
| 161 | |||
| 162 | for (unsigned step = 0; step < 4000; ++step) { | ||
| 163 | const unsigned op = next_u32() % 10; | ||
| 164 | if (op < 6) { | ||
| 165 | // Simulate fix_console_slot writing a descriptor to heap.copy. | ||
| 166 | const std::size_t slot = next_u32() % kSlots; | ||
| 167 | std::array<std::uint32_t, 8> w{}; | ||
| 168 | const unsigned kind = next_u32() % 5; | ||
| 169 | if (kind == 0) { | ||
| 170 | // Live primary V# | ||
| 171 | w[0] = next_u32(); | ||
| 172 | w[2] = (next_u32() % 256) + 1; | ||
| 173 | w[3] = next_u32() & 0x3fffffffu; | ||
| 174 | } else if (kind == 1) { | ||
| 175 | // Live counter V# only | ||
| 176 | w[6] = (next_u32() % 64) + 1; | ||
| 177 | } else if (kind == 2) { | ||
| 178 | // Empty V# (zero records) | ||
| 179 | w[0] = 0; | ||
| 180 | w[2] = 0; | ||
| 181 | w[3] = next_u32() & 0x3fffffffu; | ||
| 182 | w[6] = 0; | ||
| 183 | } else if (kind == 3) { | ||
| 184 | // Image T# | ||
| 185 | w[2] = 128; | ||
| 186 | w[3] = (2u << 30) | (next_u32() & 0x3fffffffu); | ||
| 187 | w[6] = 32; | ||
| 188 | } else { | ||
| 189 | // not_tsharp (lower 16B zeroed, upper 16B arbitrary) | ||
| 190 | w[4] = next_u32(); | ||
| 191 | w[6] = (next_u32() & 1u) ? 7u : 0u; | ||
| 192 | } | ||
| 193 | gpu_copy[slot] = w; | ||
| 194 | tracked.set(slot, ConsoleHeapVsharpSlots::is_live_vsharp(w.data())); | ||
| 195 | } else if (op < 8) { | ||
| 196 | // Simulate fix_console_slots deferred zeroing. | ||
| 197 | const std::size_t slot = next_u32() % kSlots; | ||
| 198 | gpu_copy[slot].fill(0); | ||
| 199 | tracked.clear(slot); | ||
| 200 | } else if (op == 8) { | ||
| 201 | // Simulate for_each_zeroed (both page-aligned 128-slot and arbitrary sub-ranges). | ||
| 202 | const std::size_t first = next_u32() % (kSlots + 16); | ||
| 203 | const std::size_t len = (next_u32() % 200); | ||
| 204 | const std::size_t end = first + len; | ||
| 205 | for (std::size_t i = first; i < end && i < kSlots; ++i) gpu_copy[i].fill(0); | ||
| 206 | tracked.clear_range(first, end); | ||
| 207 | } else { | ||
| 208 | // Simulate refresh_console_heap invalidation pass clearing a subset of visited slots. | ||
| 209 | const std::vector<std::size_t> expected = linear_scan(); | ||
| 210 | std::vector<std::size_t> got; | ||
| 211 | tracked.for_each([&](std::size_t slot) { | ||
| 212 | got.push_back(slot); | ||
| 213 | if ((slot % 3) == 0) { | ||
| 214 | gpu_copy[slot].fill(0); | ||
| 215 | tracked.set(slot, false); | ||
| 216 | } | ||
| 217 | }); | ||
| 218 | EXPECT(got == expected); | ||
| 219 | } | ||
| 220 | |||
| 221 | if ((step & 63) == 63) { | ||
| 222 | const std::vector<std::size_t> expected = linear_scan(); | ||
| 223 | EXPECT(tracked.live_count() == expected.size()); | ||
| 224 | EXPECT(collect(tracked) == expected); | ||
| 225 | } | ||
| 226 | } | ||
| 227 | EXPECT(collect(tracked) == linear_scan()); | ||
| 228 | return 0; | ||
| 229 | } | ||
| 230 | |||
| 231 | int test_retail_sized_heap_sparse_scan() { | ||
| 232 | // 5.5 MiB resource heap = 180,224 32-byte slots (matching retail console descriptor heap). | ||
| 233 | constexpr std::size_t kRetailSlots = (5632u * 1024u) / 32u; | ||
| 234 | ConsoleHeapVsharpSlots tracked; | ||
| 235 | tracked.reset(kRetailSlots); | ||
| 236 | |||
| 237 | const std::vector<std::size_t> hot = {0, 63, 64, 4095, 4096, 65536, 131072, kRetailSlots - 1}; | ||
| 238 | for (std::size_t slot : hot) tracked.set(slot, true); | ||
| 239 | EXPECT(tracked.live_count() == hot.size()); | ||
| 240 | EXPECT(collect(tracked) == hot); | ||
| 241 | |||
| 242 | // Zero a 4 KiB page (128 slots) containing slots 4096..4223. | ||
| 243 | tracked.clear_range(4096, 4096 + 128); | ||
| 244 | EXPECT(!tracked.test(4096) && tracked.test(4095)); | ||
| 245 | EXPECT(tracked.live_count() == hot.size() - 1); | ||
| 246 | return 0; | ||
| 247 | } | ||
| 248 | |||
| 249 | } // namespace | ||
| 250 | |||
| 251 | int main() { | ||
| 252 | if (test_predicate_exactness()) return 1; | ||
| 253 | if (test_boundaries_and_ranges()) return 1; | ||
| 254 | if (test_in_place_invalidation_mutation()) return 1; | ||
| 255 | if (test_differential_equivalence_against_linear_copy()) return 1; | ||
| 256 | if (test_retail_sized_heap_sparse_scan()) return 1; | ||
| 257 | std::printf("console_heap_vsharp_slots_test: ok\n"); | ||
| 258 | return 0; | ||
| 259 | } | ||
diff --git a/runtime/test/d3d12_big_compute_test.cpp b/runtime/test/d3d12_big_compute_test.cpp new file mode 100644 index 000000000..c6469719e --- /dev/null +++ b/runtime/test/d3d12_big_compute_test.cpp | |||
| @@ -0,0 +1,978 @@ | |||
| 1 | // Large pipelines that a submission compiles (LEONIDA_SERIAL_BIG_COMPILES, LEONIDA_BIG_COMPILE_BUDGET_MB), through the D3D12 | ||
| 2 | // layer on a GPU: real compute modules of more than 128 KiB (big_compute_module.h), small ones, and graphics pipelines of more than | ||
| 3 | // 1 MiB. Both settings are read once for each process, so the test runs once for each: with a fixed budget, one that holds | ||
| 4 | // nothing, the one read from the machine, one at a time and without a limit. Every run | ||
| 5 | // - stores what the CPU computes for each dispatch, and draws the graphics pipelines' cells; | ||
| 6 | // - compiles as many large ones at once as the setting allows and no more, and the small ones meanwhile; | ||
| 7 | // - gives a pipeline the driver refuses the result it has always had, and its place to the next; | ||
| 8 | // - compiles each pipeline once when two queues need the same ones; | ||
| 9 | // - ends when the device's last references go while its workers compile and wait for memory. | ||
| 10 | // `warmup`: a submission's compiles go before those of the warm-up thread, which waits without holding a pipeline state. | ||
| 11 | // `eager`: pipeline states compiled when they are created (LEONIDA_LAZY_COMPUTE=0), by several threads, keep the budget too. | ||
| 12 | // The calls that create pipelines are watched, and held back, through the device's vkGetDeviceProcAddr. | ||
| 13 | // Self-contained: builds its SPIR-V in memory. Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation. | ||
| 14 | #include "big_compute_module.h" | ||
| 15 | #include "vk_test_device.h" | ||
| 16 | #include "d3d12_test_shaders.h" | ||
| 17 | #include "test_temp_dir.h" | ||
| 18 | #include "../shims/d3d12_com.h" | ||
| 19 | #include "../shims/d3d12_pipeline_compile.h" | ||
| 20 | #include "../src/large_module_gate.h" | ||
| 21 | #include "../src/shader_library.h" | ||
| 22 | |||
| 23 | #include <algorithm> | ||
| 24 | #include <atomic> | ||
| 25 | #include <bit> | ||
| 26 | #include <chrono> | ||
| 27 | #include <condition_variable> | ||
| 28 | #include <cstdint> | ||
| 29 | #include <cstdio> | ||
| 30 | #include <cstdlib> | ||
| 31 | #include <cstring> | ||
| 32 | #include <fstream> | ||
| 33 | #include <map> | ||
| 34 | #include <memory> | ||
| 35 | #include <mutex> | ||
| 36 | #include <set> | ||
| 37 | #include <string> | ||
| 38 | #include <thread> | ||
| 39 | #include <type_traits> | ||
| 40 | #include <utility> | ||
| 41 | #include <vector> | ||
| 42 | |||
| 43 | namespace { | ||
| 44 | |||
| 45 | using namespace std::chrono_literals; | ||
| 46 | using d3d12test::Ref; | ||
| 47 | using leonida::ReplayResult; | ||
| 48 | using bigmodule::Words; | ||
| 49 | using bigmodule::op; | ||
| 50 | |||
| 51 | constexpr unsigned kBig = 6, kSmall = 4, kCompute = kBig + kSmall, kGraphics = 2; | ||
| 52 | constexpr std::size_t kBigBytes = 132 * 1024, kSmallBytes = 12 * 1024; | ||
| 53 | constexpr unsigned kExtent = 4; // the render target; each graphics pipeline draws one 2x2 cell | ||
| 54 | constexpr unsigned kWords = bigmodule::kLoadBase + bigmodule::kLoadWords; | ||
| 55 | |||
| 56 | #define CHECK(expr) \ | ||
| 57 | do { \ | ||
| 58 | if (!(expr)) { \ | ||
| 59 | std::fprintf(stderr, "FAIL %s:%d: %s\n", __FILE__, __LINE__, #expr); \ | ||
| 60 | return false; \ | ||
| 61 | } \ | ||
| 62 | } while (0) | ||
| 63 | |||
| 64 | // ---- What the settings of this process say. ---- | ||
| 65 | |||
| 66 | std::string setting(const char* name) { | ||
| 67 | char text[64]{}; | ||
| 68 | std::size_t length = 0; | ||
| 69 | return getenv_s(&length, text, name) == 0 && length > 1 ? text : ""; | ||
| 70 | } | ||
| 71 | const bool serial = setting("LEONIDA_SERIAL_BIG_COMPILES") == "1"; | ||
| 72 | const bool unlimited = setting("LEONIDA_SERIAL_BIG_COMPILES") == "0"; | ||
| 73 | const bool budgeted = !serial && !unlimited; | ||
| 74 | const auto fixed_budget = leonida::large_compile_budget(setting("LEONIDA_BIG_COMPILE_BUDGET_MB").c_str()).fixed; | ||
| 75 | |||
| 76 | // ---- The driver's pipeline calls, watched. ---- | ||
| 77 | |||
| 78 | struct Start { | ||
| 79 | std::thread::id thread; | ||
| 80 | int program = -1; // compute: the index of its module | ||
| 81 | bool large = false; | ||
| 82 | }; | ||
| 83 | |||
| 84 | struct Hooks { | ||
| 85 | std::mutex mutex; | ||
| 86 | std::condition_variable changed; | ||
| 87 | std::map<std::uint64_t, int> programs; // the hash of a compute module's words: its index | ||
| 88 | std::map<VkShaderModule, std::pair<std::size_t, int>> modules; // bytes, program | ||
| 89 | bool closed = false; // large creations wait while it is | ||
| 90 | std::chrono::milliseconds linger{0}; // and each takes at least this long, as does what follows it on its thread | ||
| 91 | std::vector<Start> started; | ||
| 92 | int large_in = 0, most_large = 0, small_done = 0, large_compute_in = 0, most_large_compute = 0; | ||
| 93 | std::uint64_t reserved = 0; // the estimates of the large ones in the driver | ||
| 94 | int over = 0; // how often several were in past the budget, or two where one is allowed | ||
| 95 | int fail_large = -1; // the large compute create (counted from 0) the driver refuses | ||
| 96 | int large_compute = 0; | ||
| 97 | bool track = false; // threads that create a pipeline are counted until they end | ||
| 98 | int live = 0, in_flight = 0, cache_reads = 0; | ||
| 99 | bool cache_read_during_create = false, cache_read_with_workers = false; | ||
| 100 | |||
| 101 | void reset() { | ||
| 102 | std::lock_guard lock(mutex); | ||
| 103 | closed = track = cache_read_during_create = cache_read_with_workers = false; | ||
| 104 | started.clear(); | ||
| 105 | most_large = small_done = most_large_compute = over = large_compute = cache_reads = 0; | ||
| 106 | fail_large = -1; | ||
| 107 | linger = 0ms; | ||
| 108 | } | ||
| 109 | void open() { | ||
| 110 | std::lock_guard lock(mutex); | ||
| 111 | closed = false; | ||
| 112 | changed.notify_all(); | ||
| 113 | } | ||
| 114 | template<typename Until> | ||
| 115 | bool wait(Until&& until) { | ||
| 116 | std::unique_lock lock(mutex); | ||
| 117 | return changed.wait_for(lock, 20s, until); | ||
| 118 | } | ||
| 119 | bool wait_large(int count) { | ||
| 120 | return wait([&] { return large_in >= count; }); | ||
| 121 | } | ||
| 122 | std::size_t creates() { | ||
| 123 | std::lock_guard lock(mutex); | ||
| 124 | return started.size(); | ||
| 125 | } | ||
| 126 | } hooks; | ||
| 127 | |||
| 128 | struct Tracked { | ||
| 129 | bool on = false; | ||
| 130 | ~Tracked() { | ||
| 131 | if (!on) return; | ||
| 132 | std::lock_guard lock(hooks.mutex); | ||
| 133 | --hooks.live; | ||
| 134 | } | ||
| 135 | }; | ||
| 136 | thread_local Tracked tracked; | ||
| 137 | |||
| 138 | PFN_vkGetInstanceProcAddr real_instance_proc = nullptr; | ||
| 139 | PFN_vkGetDeviceProcAddr real_device_proc = nullptr; | ||
| 140 | PFN_vkCreateShaderModule real_create_module = nullptr; | ||
| 141 | PFN_vkDestroyShaderModule real_destroy_module = nullptr; | ||
| 142 | PFN_vkCreateGraphicsPipelines real_create_graphics = nullptr; | ||
| 143 | PFN_vkCreateComputePipelines real_create_compute = nullptr; | ||
| 144 | PFN_vkGetPipelineCacheData real_cache_data = nullptr; | ||
| 145 | |||
| 146 | std::uint64_t hash(const std::uint32_t* words, std::size_t count) { | ||
| 147 | std::uint64_t h = 0xcbf29ce484222325u; | ||
| 148 | for (std::size_t i = 0; i < count; ++i) h = (h ^ words[i]) * 0x100000001b3u; | ||
| 149 | return h; | ||
| 150 | } | ||
| 151 | |||
| 152 | struct Creation { | ||
| 153 | bool large = false, compute = false, refused = false; | ||
| 154 | std::uint64_t estimate = 0; | ||
| 155 | }; | ||
| 156 | |||
| 157 | Creation enter_create(bool compute, std::initializer_list<VkShaderModule> modules) { | ||
| 158 | std::unique_lock lock(hooks.mutex); | ||
| 159 | Creation c; | ||
| 160 | c.compute = compute; | ||
| 161 | std::size_t bytes = 0; | ||
| 162 | Start start{std::this_thread::get_id(), -1, false}; | ||
| 163 | for (const VkShaderModule module : modules) { | ||
| 164 | const auto found = hooks.modules.find(module); | ||
| 165 | if (found == hooks.modules.end()) continue; | ||
| 166 | bytes += found->second.first; | ||
| 167 | if (compute) start.program = found->second.second; | ||
| 168 | } | ||
| 169 | c.large = start.large = bytes > (compute ? 128 * 1024 : leonida::PipelineCompiles::large_spirv_bytes - 1); | ||
| 170 | c.estimate = leonida::large_module_estimate(bytes); | ||
| 171 | ++hooks.in_flight; | ||
| 172 | hooks.started.push_back(start); | ||
| 173 | if (hooks.track && !tracked.on) { | ||
| 174 | tracked.on = true; | ||
| 175 | ++hooks.live; | ||
| 176 | } | ||
| 177 | if (c.large) { | ||
| 178 | ++hooks.large_in; | ||
| 179 | if (compute) ++hooks.large_compute_in; | ||
| 180 | hooks.most_large = std::max(hooks.most_large, hooks.large_in); | ||
| 181 | hooks.most_large_compute = std::max(hooks.most_large_compute, hooks.large_compute_in); | ||
| 182 | hooks.reserved += c.estimate; | ||
| 183 | // One large compute module at a time; with a budget, several only within it. | ||
| 184 | if (serial && hooks.large_compute_in > 1) ++hooks.over; | ||
| 185 | if (budgeted && fixed_budget && hooks.large_in > 1 && hooks.reserved > *fixed_budget) ++hooks.over; | ||
| 186 | if (compute && hooks.large_compute++ == hooks.fail_large) c.refused = true; | ||
| 187 | } | ||
| 188 | hooks.changed.notify_all(); | ||
| 189 | if (c.large) hooks.changed.wait(lock, [] { return !hooks.closed; }); | ||
| 190 | const auto linger = hooks.linger; | ||
| 191 | lock.unlock(); | ||
| 192 | if (c.large && linger > 0ms) std::this_thread::sleep_for(linger); | ||
| 193 | return c; | ||
| 194 | } | ||
| 195 | |||
| 196 | void leave_create(const Creation& c) { | ||
| 197 | std::lock_guard lock(hooks.mutex); | ||
| 198 | --hooks.in_flight; | ||
| 199 | if (c.large) { | ||
| 200 | --hooks.large_in; | ||
| 201 | if (c.compute) --hooks.large_compute_in; | ||
| 202 | hooks.reserved -= c.estimate; | ||
| 203 | } else { | ||
| 204 | ++hooks.small_done; | ||
| 205 | } | ||
| 206 | hooks.changed.notify_all(); | ||
| 207 | } | ||
| 208 | |||
| 209 | VKAPI_ATTR VkResult VKAPI_CALL create_module(VkDevice device, const VkShaderModuleCreateInfo* info, | ||
| 210 | const VkAllocationCallbacks* allocator, VkShaderModule* out) { | ||
| 211 | const VkResult result = real_create_module(device, info, allocator, out); | ||
| 212 | if (result == VK_SUCCESS) { | ||
| 213 | std::lock_guard lock(hooks.mutex); | ||
| 214 | const auto found = hooks.programs.find(hash(info->pCode, info->codeSize / 4)); | ||
| 215 | hooks.modules[*out] = {info->codeSize, found == hooks.programs.end() ? -1 : found->second}; | ||
| 216 | } | ||
| 217 | return result; | ||
| 218 | } | ||
| 219 | |||
| 220 | // Called between the place a compile gives back and the next one its thread asks for: with a linger, time for another | ||
| 221 | // thread to take that place. | ||
| 222 | VKAPI_ATTR void VKAPI_CALL destroy_module(VkDevice device, VkShaderModule module, const VkAllocationCallbacks* allocator) { | ||
| 223 | std::chrono::milliseconds linger; | ||
| 224 | { | ||
| 225 | std::lock_guard lock(hooks.mutex); | ||
| 226 | linger = hooks.linger; | ||
| 227 | } | ||
| 228 | if (linger > 0ms) std::this_thread::sleep_for(linger); | ||
| 229 | real_destroy_module(device, module, allocator); | ||
| 230 | } | ||
| 231 | |||
| 232 | VKAPI_ATTR VkResult VKAPI_CALL create_graphics(VkDevice device, VkPipelineCache cache, std::uint32_t count, | ||
| 233 | const VkGraphicsPipelineCreateInfo* infos, | ||
| 234 | const VkAllocationCallbacks* allocator, VkPipeline* out) { | ||
| 235 | VkShaderModule modules[2]{}; | ||
| 236 | for (std::uint32_t i = 0; i < std::min(infos->stageCount, 2u); ++i) modules[i] = infos->pStages[i].module; | ||
| 237 | const Creation c = enter_create(false, {modules[0], modules[1]}); | ||
| 238 | const VkResult result = real_create_graphics(device, cache, count, infos, allocator, out); | ||
| 239 | leave_create(c); | ||
| 240 | return result; | ||
| 241 | } | ||
| 242 | |||
| 243 | VKAPI_ATTR VkResult VKAPI_CALL create_compute(VkDevice device, VkPipelineCache cache, std::uint32_t count, | ||
| 244 | const VkComputePipelineCreateInfo* infos, | ||
| 245 | const VkAllocationCallbacks* allocator, VkPipeline* out) { | ||
| 246 | const Creation c = enter_create(true, {infos->stage.module}); | ||
| 247 | const VkResult result = c.refused ? VK_ERROR_UNKNOWN | ||
| 248 | : real_create_compute(device, cache, count, infos, allocator, out); | ||
| 249 | leave_create(c); | ||
| 250 | return result; | ||
| 251 | } | ||
| 252 | |||
| 253 | VKAPI_ATTR VkResult VKAPI_CALL cache_data(VkDevice device, VkPipelineCache cache, std::size_t* size, void* data) { | ||
| 254 | { | ||
| 255 | std::lock_guard lock(hooks.mutex); | ||
| 256 | ++hooks.cache_reads; | ||
| 257 | if (hooks.in_flight) hooks.cache_read_during_create = true; | ||
| 258 | if (hooks.live > (tracked.on ? 1 : 0)) hooks.cache_read_with_workers = true; | ||
| 259 | } | ||
| 260 | return real_cache_data(device, cache, size, data); | ||
| 261 | } | ||
| 262 | |||
| 263 | VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL device_proc(VkDevice device, const char* name) { | ||
| 264 | const PFN_vkVoidFunction real = real_device_proc(device, name); | ||
| 265 | if (!real) return nullptr; | ||
| 266 | const auto watch = [&](const char* which, auto& kept, auto* mine) -> PFN_vkVoidFunction { | ||
| 267 | if (std::strcmp(name, which)) return nullptr; | ||
| 268 | kept = reinterpret_cast<std::remove_reference_t<decltype(kept)>>(real); | ||
| 269 | return reinterpret_cast<PFN_vkVoidFunction>(mine); | ||
| 270 | }; | ||
| 271 | if (const auto f = watch("vkCreateShaderModule", real_create_module, create_module)) return f; | ||
| 272 | if (const auto f = watch("vkDestroyShaderModule", real_destroy_module, destroy_module)) return f; | ||
| 273 | if (const auto f = watch("vkCreateGraphicsPipelines", real_create_graphics, create_graphics)) return f; | ||
| 274 | if (const auto f = watch("vkCreateComputePipelines", real_create_compute, create_compute)) return f; | ||
| 275 | if (const auto f = watch("vkGetPipelineCacheData", real_cache_data, cache_data)) return f; | ||
| 276 | return real; | ||
| 277 | } | ||
| 278 | |||
| 279 | VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL instance_proc(VkInstance instance, const char* name) { | ||
| 280 | if (!std::strcmp(name, "vkGetDeviceProcAddr")) { | ||
| 281 | real_device_proc = reinterpret_cast<PFN_vkGetDeviceProcAddr>(real_instance_proc(instance, name)); | ||
| 282 | return reinterpret_cast<PFN_vkVoidFunction>(device_proc); | ||
| 283 | } | ||
| 284 | return real_instance_proc(instance, name); | ||
| 285 | } | ||
| 286 | |||
| 287 | // ---- The shaders. ---- | ||
| 288 | |||
| 289 | std::uint32_t bits(float f) { return std::bit_cast<std::uint32_t>(f); } | ||
| 290 | |||
| 291 | // 1.25 MiB of OpString, which compile to nothing: a graphics pipeline that is large. | ||
| 292 | void pad(Words& w, std::uint32_t first_id) { | ||
| 293 | for (std::uint32_t i = 0; i < 5; ++i) { | ||
| 294 | const std::size_t at = w.size(); | ||
| 295 | w.resize(at + 65535, 0x20202020u); | ||
| 296 | w[at] = 65535u << 16 | 7; | ||
| 297 | w[at + 1] = first_id + i; | ||
| 298 | w.back() = 0; | ||
| 299 | } | ||
| 300 | } | ||
| 301 | |||
| 302 | // A full-screen triangle from VertexIndex. | ||
| 303 | Words vertex_words() { | ||
| 304 | Words w = {0x07230203u, 0x00010500u, 0u, 42u, 0u}; | ||
| 305 | op(w, 17, {1}); // Capability Shader | ||
| 306 | op(w, 14, {0, 1}); // MemoryModel Logical GLSL450 | ||
| 307 | op(w, 15, {0, 4, 0x6e69616du, 0u, 10, 11}); // EntryPoint Vertex "main" | ||
| 308 | op(w, 71, {10, 11, 0}); // BuiltIn Position | ||
| 309 | op(w, 71, {11, 11, 42}); // BuiltIn VertexIndex | ||
| 310 | op(w, 19, {1}); | ||
| 311 | op(w, 33, {2, 1}); | ||
| 312 | op(w, 22, {3, 32}); | ||
| 313 | op(w, 23, {6, 3, 4}); | ||
| 314 | op(w, 21, {15, 32, 1}); | ||
| 315 | op(w, 32, {7, 3, 6}); | ||
| 316 | op(w, 32, {8, 1, 15}); | ||
| 317 | op(w, 59, {7, 10, 3}); | ||
| 318 | op(w, 59, {8, 11, 1}); | ||
| 319 | op(w, 43, {15, 24, 1}); | ||
| 320 | op(w, 43, {15, 25, 2}); | ||
| 321 | op(w, 43, {3, 26, bits(2.0f)}); | ||
| 322 | op(w, 43, {3, 27, bits(-1.0f)}); | ||
| 323 | op(w, 43, {3, 28, bits(0.0f)}); | ||
| 324 | op(w, 43, {3, 29, bits(1.0f)}); | ||
| 325 | op(w, 54, {1, 4, 0, 2}); | ||
| 326 | op(w, 248, {30}); | ||
| 327 | op(w, 61, {15, 31, 11}); | ||
| 328 | op(w, 196, {15, 32, 31, 24}); // index << 1 | ||
| 329 | op(w, 199, {15, 33, 32, 25}); // & 2 | ||
| 330 | op(w, 199, {15, 34, 31, 25}); // index & 2 | ||
| 331 | op(w, 111, {3, 35, 33}); | ||
| 332 | op(w, 111, {3, 36, 34}); | ||
| 333 | op(w, 133, {3, 37, 35, 26}); | ||
| 334 | op(w, 133, {3, 38, 36, 26}); | ||
| 335 | op(w, 129, {3, 39, 37, 27}); | ||
| 336 | op(w, 129, {3, 40, 38, 27}); | ||
| 337 | op(w, 80, {6, 41, 39, 40, 28, 29}); | ||
| 338 | op(w, 62, {10, 41}); | ||
| 339 | op(w, 253, {}); | ||
| 340 | op(w, 56, {}); | ||
| 341 | return w; | ||
| 342 | } | ||
| 343 | |||
| 344 | // The colour (n / 255, 1 - n / 255, 0, 1). | ||
| 345 | Words fragment_words(unsigned n) { | ||
| 346 | Words w = {0x07230203u, 0x00010500u, 0u, 40u, 0u}; | ||
| 347 | op(w, 17, {1}); | ||
| 348 | op(w, 14, {0, 1}); | ||
| 349 | op(w, 15, {4, 4, 0x6e69616du, 0u, 9}); // EntryPoint Fragment "main" | ||
| 350 | op(w, 16, {4, 7}); // OriginUpperLeft | ||
| 351 | pad(w, 30); | ||
| 352 | op(w, 71, {9, 30, 0}); // Location 0 | ||
| 353 | op(w, 19, {1}); | ||
| 354 | op(w, 33, {2, 1}); | ||
| 355 | op(w, 22, {3, 32}); | ||
| 356 | op(w, 23, {6, 3, 4}); | ||
| 357 | op(w, 32, {10, 3, 6}); | ||
| 358 | op(w, 59, {10, 9, 3}); | ||
| 359 | op(w, 43, {3, 20, bits(float(n) / 255.0f)}); | ||
| 360 | op(w, 43, {3, 21, bits(float(255 - n) / 255.0f)}); | ||
| 361 | op(w, 43, {3, 22, bits(0.0f)}); | ||
| 362 | op(w, 43, {3, 23, bits(1.0f)}); | ||
| 363 | op(w, 44, {6, 24, 20, 21, 22, 23}); | ||
| 364 | op(w, 54, {1, 4, 0, 2}); | ||
| 365 | op(w, 248, {11}); | ||
| 366 | op(w, 62, {9, 24}); | ||
| 367 | op(w, 253, {}); | ||
| 368 | op(w, 56, {}); | ||
| 369 | return w; | ||
| 370 | } | ||
| 371 | |||
| 372 | std::vector<std::uint8_t> program(unsigned stage, unsigned n) { | ||
| 373 | return d3d12test::fssm_program({0x42434f00u + stage, n, 0xbf810000u}); | ||
| 374 | } | ||
| 375 | |||
| 376 | std::vector<bigmodule::Program> programs(kCompute); // what each compute module runs | ||
| 377 | std::vector<std::size_t> module_bytes(kCompute); | ||
| 378 | |||
| 379 | bool write_library(const std::filesystem::path& dir) { | ||
| 380 | const auto write = [&](const std::string& name, const Words& words) { | ||
| 381 | std::ofstream f(dir / (name + ".spv"), std::ios::binary | std::ios::trunc); | ||
| 382 | f.write(reinterpret_cast<const char*>(words.data()), std::streamsize(words.size() * 4)); | ||
| 383 | return bool(f); | ||
| 384 | }; | ||
| 385 | CHECK(write("vs", vertex_words())); | ||
| 386 | std::ofstream index(dir / "index.json", std::ios::binary | std::ios::trunc); | ||
| 387 | index << "{\"vs\": {\"stage\": \"vs\", \"fssm_sha256\": \"" << leonida::sha256_hex(program(0, 0)) | ||
| 388 | << "\", \"bindings\": [], \"push_constant_bytes\": 144, \"input_signature\": []}"; | ||
| 389 | for (unsigned n = 0; n < kGraphics; ++n) { | ||
| 390 | const std::string name = "ps" + std::to_string(n); | ||
| 391 | CHECK(write(name, fragment_words(n))); | ||
| 392 | index << ",\n\"" << name << "\": {\"stage\": \"ps\", \"fssm_sha256\": \"" << leonida::sha256_hex(program(1, n)) | ||
| 393 | << "\", \"bindings\": [], \"push_constant_bytes\": 144, \"inputs\": [], \"outputs\": [0]}"; | ||
| 394 | } | ||
| 395 | for (unsigned n = 0; n < kCompute; ++n) { | ||
| 396 | const std::string name = "cs" + std::to_string(n); | ||
| 397 | // Every large one a little larger than the one before, so that the order by size is known. | ||
| 398 | const Words words = bigmodule::make(n < kBig ? kBigBytes + n * 1024 : kSmallBytes, 20251125 + n, &programs[n]); | ||
| 399 | module_bytes[n] = words.size() * 4; | ||
| 400 | CHECK((module_bytes[n] > 128 * 1024) == (n < kBig)); | ||
| 401 | hooks.programs[hash(words.data(), words.size())] = int(n); | ||
| 402 | CHECK(write(name, words)); | ||
| 403 | index << ",\n\"" << name << "\": {\"stage\": \"cs\", \"fssm_sha256\": \"" << leonida::sha256_hex(program(2, n)) | ||
| 404 | << "\", \"bindings\": [], \"push_constant_bytes\": 144, \"local_size\": [1, 1, 1], \"wave64\": false}"; | ||
| 405 | } | ||
| 406 | index << "}"; | ||
| 407 | return bool(index); | ||
| 408 | } | ||
| 409 | |||
| 410 | // ---- The device and what it runs. ---- | ||
| 411 | |||
| 412 | struct Setup { | ||
| 413 | vktest::Device* vk; | ||
| 414 | std::string library; | ||
| 415 | |||
| 416 | bool device(const char* threads, Ref<ID3D12Device>& out) const { | ||
| 417 | _putenv_s("LEONIDA_PIPELINE_THREADS", threads); | ||
| 418 | rt::d3d12::VulkanDeviceInfo info{}; | ||
| 419 | info.get_instance_proc = instance_proc; | ||
| 420 | info.instance = vk->instance; | ||
| 421 | info.physical = vk->physical; | ||
| 422 | info.device = vk->device; | ||
| 423 | info.queue = vk->queue; | ||
| 424 | info.queue_family = vk->family; | ||
| 425 | info.buffer_device_address = true; | ||
| 426 | info.subgroup = vk->subgroup; | ||
| 427 | info.features = vk->enabled; | ||
| 428 | info.shader_dir = library; | ||
| 429 | CHECK(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&out.p)))); | ||
| 430 | return true; | ||
| 431 | } | ||
| 432 | }; | ||
| 433 | |||
| 434 | struct Pipelines { | ||
| 435 | Ref<ID3D12RootSignature> root; | ||
| 436 | std::vector<ID3D12PipelineState*> compute, graphics; | ||
| 437 | ~Pipelines() { release(); } | ||
| 438 | void release() { | ||
| 439 | for (auto* s : compute) | ||
| 440 | if (s) s->Release(); | ||
| 441 | for (auto* s : graphics) s->Release(); | ||
| 442 | compute.clear(); | ||
| 443 | graphics.clear(); | ||
| 444 | } | ||
| 445 | |||
| 446 | static ID3D12PipelineState* compute_state(ID3D12Device* dev, ID3D12RootSignature* root, unsigned n) { | ||
| 447 | const auto cs = d3d12test::shader_container(program(2, n)); | ||
| 448 | D3D12_COMPUTE_PIPELINE_STATE_DESC pd{}; | ||
| 449 | pd.pRootSignature = root; | ||
| 450 | pd.CS = {cs.data(), cs.size()}; | ||
| 451 | ID3D12PipelineState* state = nullptr; | ||
| 452 | return SUCCEEDED(dev->CreateComputePipelineState(&pd, IID_PPV_ARGS(&state))) ? state : nullptr; | ||
| 453 | } | ||
| 454 | |||
| 455 | // The compute states on `threads` threads. | ||
| 456 | bool create(ID3D12Device* dev, unsigned threads = 1) { | ||
| 457 | D3D12_ROOT_PARAMETER params[2]{}; | ||
| 458 | params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV; | ||
| 459 | params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; | ||
| 460 | params[1].Constants.Num32BitValues = 1; | ||
| 461 | D3D12_VERSIONED_ROOT_SIGNATURE_DESC desc{}; | ||
| 462 | desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0; | ||
| 463 | desc.Desc_1_0 = {2, params, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}; | ||
| 464 | const auto blob = d3d12test::serialize_root_signature(desc); | ||
| 465 | CHECK(SUCCEEDED(dev->CreateRootSignature(0, blob.data(), blob.size(), IID_PPV_ARGS(&root.p)))); | ||
| 466 | compute.assign(kCompute, nullptr); | ||
| 467 | std::vector<std::thread> creating; | ||
| 468 | for (unsigned t = 1; t < threads; ++t) | ||
| 469 | creating.emplace_back([&, t] { | ||
| 470 | for (unsigned n = t; n < kCompute; n += threads) compute[n] = compute_state(dev, root.p, n); | ||
| 471 | }); | ||
| 472 | for (unsigned n = 0; n < kCompute; n += threads) compute[n] = compute_state(dev, root.p, n); | ||
| 473 | for (auto& t : creating) t.join(); | ||
| 474 | CHECK(std::find(compute.begin(), compute.end(), nullptr) == compute.end()); | ||
| 475 | const auto vs = d3d12test::shader_container(program(0, 0)); | ||
| 476 | for (unsigned n = 0; n < kGraphics; ++n) { | ||
| 477 | const auto ps = d3d12test::shader_container(program(1, n)); | ||
| 478 | D3D12_GRAPHICS_PIPELINE_STATE_DESC pd{}; | ||
| 479 | pd.pRootSignature = root.p; | ||
| 480 | pd.VS = {vs.data(), vs.size()}; | ||
| 481 | pd.PS = {ps.data(), ps.size()}; | ||
| 482 | for (auto& rt : pd.BlendState.RenderTarget) { | ||
| 483 | rt.SrcBlend = rt.SrcBlendAlpha = D3D12_BLEND_ONE; | ||
| 484 | rt.DestBlend = rt.DestBlendAlpha = D3D12_BLEND_ZERO; | ||
| 485 | rt.BlendOp = rt.BlendOpAlpha = D3D12_BLEND_OP_ADD; | ||
| 486 | rt.LogicOp = D3D12_LOGIC_OP_NOOP; | ||
| 487 | rt.RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL; | ||
| 488 | } | ||
| 489 | pd.SampleMask = UINT_MAX; | ||
| 490 | pd.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID; | ||
| 491 | pd.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; | ||
| 492 | pd.RasterizerState.DepthClipEnable = TRUE; | ||
| 493 | pd.DepthStencilState.DepthFunc = D3D12_COMPARISON_FUNC_ALWAYS; | ||
| 494 | pd.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; | ||
| 495 | pd.NumRenderTargets = 1; | ||
| 496 | pd.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM; | ||
| 497 | pd.SampleDesc = {1, 0}; | ||
| 498 | ID3D12PipelineState* state = nullptr; | ||
| 499 | CHECK(SUCCEEDED(dev->CreateGraphicsPipelineState(&pd, IID_PPV_ARGS(&state)))); | ||
| 500 | graphics.push_back(state); | ||
| 501 | } | ||
| 502 | return true; | ||
| 503 | } | ||
| 504 | }; | ||
| 505 | |||
| 506 | // A queue and a list that dispatches `compute` (and draws the graphics pipelines), then copies what they wrote back. | ||
| 507 | struct Frame { | ||
| 508 | std::vector<unsigned> compute; | ||
| 509 | bool graphics = false; | ||
| 510 | Ref<ID3D12Resource> target, buffer, readback; | ||
| 511 | Ref<ID3D12DescriptorHeap> rtvs; | ||
| 512 | Ref<ID3D12CommandQueue> queue; | ||
| 513 | Ref<ID3D12CommandAllocator> allocator; | ||
| 514 | Ref<ID3D12GraphicsCommandList> list; | ||
| 515 | Ref<ID3D12Fence> fence; | ||
| 516 | UINT64 fence_value = 0; | ||
| 517 | D3D12_PLACED_SUBRESOURCE_FOOTPRINT foot{}; | ||
| 518 | |||
| 519 | bool create(ID3D12Device* dev, const Pipelines& p, std::vector<unsigned> dispatched, bool draws) { | ||
| 520 | compute = std::move(dispatched); | ||
| 521 | graphics = draws; | ||
| 522 | const D3D12_HEAP_PROPERTIES def{D3D12_HEAP_TYPE_DEFAULT}, back{D3D12_HEAP_TYPE_READBACK}; | ||
| 523 | D3D12_RESOURCE_DESC td{}; | ||
| 524 | td.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; | ||
| 525 | td.Width = td.Height = kExtent; | ||
| 526 | td.DepthOrArraySize = td.MipLevels = 1; | ||
| 527 | td.Format = DXGI_FORMAT_R8G8B8A8_UNORM; | ||
| 528 | td.SampleDesc = {1, 0}; | ||
| 529 | td.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; | ||
| 530 | CHECK(SUCCEEDED(dev->CreateCommittedResource(&def, D3D12_HEAP_FLAG_NONE, &td, D3D12_RESOURCE_STATE_RENDER_TARGET, | ||
| 531 | nullptr, IID_PPV_ARGS(&target.p)))); | ||
| 532 | const auto bd = d3d12test::buffer_desc(4 * kWords, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); | ||
| 533 | CHECK(SUCCEEDED(dev->CreateCommittedResource(&def, D3D12_HEAP_FLAG_NONE, &bd, | ||
| 534 | D3D12_RESOURCE_STATE_UNORDERED_ACCESS, nullptr, | ||
| 535 | IID_PPV_ARGS(&buffer.p)))); | ||
| 536 | UINT64 image_bytes = 0; | ||
| 537 | dev->GetCopyableFootprints(&td, 0, 1, 0, &foot, nullptr, nullptr, &image_bytes); | ||
| 538 | CHECK(image_bytes <= 4096); | ||
| 539 | const auto rd = d3d12test::buffer_desc(4096 + 4 * kWords); | ||
| 540 | CHECK(SUCCEEDED(dev->CreateCommittedResource(&back, D3D12_HEAP_FLAG_NONE, &rd, D3D12_RESOURCE_STATE_COPY_DEST, | ||
| 541 | nullptr, IID_PPV_ARGS(&readback.p)))); | ||
| 542 | const D3D12_DESCRIPTOR_HEAP_DESC hd{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1}; | ||
| 543 | CHECK(SUCCEEDED(dev->CreateDescriptorHeap(&hd, IID_PPV_ARGS(&rtvs.p)))); | ||
| 544 | const auto rtv = rtvs->GetCPUDescriptorHandleForHeapStart(); | ||
| 545 | dev->CreateRenderTargetView(target.p, nullptr, rtv); | ||
| 546 | const D3D12_COMMAND_QUEUE_DESC qd{D3D12_COMMAND_LIST_TYPE_DIRECT}; | ||
| 547 | CHECK(SUCCEEDED(dev->CreateCommandQueue(&qd, IID_PPV_ARGS(&queue.p)))); | ||
| 548 | CHECK(SUCCEEDED(dev->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p)))); | ||
| 549 | CHECK(SUCCEEDED(dev->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p)))); | ||
| 550 | CHECK(SUCCEEDED(dev->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, nullptr, | ||
| 551 | IID_PPV_ARGS(&list.p)))); | ||
| 552 | const FLOAT clear[4] = {0, 0, 0, 0}; | ||
| 553 | list->ClearRenderTargetView(rtv, clear, 0, nullptr); | ||
| 554 | list->SetComputeRootSignature(p.root.p); | ||
| 555 | list->SetComputeRootUnorderedAccessView(0, buffer->GetGPUVirtualAddress()); | ||
| 556 | for (const unsigned n : compute) { | ||
| 557 | list->SetPipelineState(p.compute[n]); | ||
| 558 | list->SetComputeRoot32BitConstant(1, n, 0); | ||
| 559 | list->Dispatch(1, 1, 1); | ||
| 560 | } | ||
| 561 | if (graphics) { | ||
| 562 | list->SetGraphicsRootSignature(p.root.p); | ||
| 563 | list->OMSetRenderTargets(1, &rtv, FALSE, nullptr); | ||
| 564 | list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); | ||
| 565 | const D3D12_VIEWPORT vp{0, 0, float(kExtent), float(kExtent), 0, 1}; | ||
| 566 | list->RSSetViewports(1, &vp); | ||
| 567 | for (unsigned n = 0; n < kGraphics; ++n) { | ||
| 568 | const D3D12_RECT cell{LONG(2 * n), 0, LONG(2 * n + 2), 2}; | ||
| 569 | list->RSSetScissorRects(1, &cell); | ||
| 570 | list->SetPipelineState(p.graphics[n]); | ||
| 571 | list->DrawInstanced(3, 1, 0, 0); | ||
| 572 | } | ||
| 573 | } | ||
| 574 | const D3D12_RESOURCE_BARRIER to_source[2] = { | ||
| 575 | d3d12test::transition(target.p, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE), | ||
| 576 | d3d12test::transition(buffer.p, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE)}; | ||
| 577 | list->ResourceBarrier(2, to_source); | ||
| 578 | D3D12_TEXTURE_COPY_LOCATION src{target.p, D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX}; | ||
| 579 | src.SubresourceIndex = 0; | ||
| 580 | D3D12_TEXTURE_COPY_LOCATION dst{readback.p, D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT}; | ||
| 581 | dst.PlacedFootprint = foot; | ||
| 582 | list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); | ||
| 583 | list->CopyBufferRegion(readback.p, 4096, buffer.p, 0, 4 * kWords); | ||
| 584 | const D3D12_RESOURCE_BARRIER back_again[2] = { | ||
| 585 | d3d12test::transition(target.p, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_RENDER_TARGET), | ||
| 586 | d3d12test::transition(buffer.p, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_UNORDERED_ACCESS)}; | ||
| 587 | list->ResourceBarrier(2, back_again); | ||
| 588 | CHECK(SUCCEEDED(list->Close())); | ||
| 589 | return true; | ||
| 590 | } | ||
| 591 | |||
| 592 | ReplayResult submit() { | ||
| 593 | ID3D12CommandList* lists[] = {list.p}; | ||
| 594 | queue->ExecuteCommandLists(1, lists); | ||
| 595 | const ReplayResult result = rt::d3d12::last_execute_result(queue.p); | ||
| 596 | queue->Signal(fence.p, ++fence_value); | ||
| 597 | fence->SetEventOnCompletion(fence_value, nullptr); | ||
| 598 | return result; | ||
| 599 | } | ||
| 600 | |||
| 601 | // What the shaders stored and drew; `dropped` is the compute program that was not built, whose word stays 0. The | ||
| 602 | // readback buffer is cleared, so stale bytes cannot pass. | ||
| 603 | bool right(int dropped = -1) { | ||
| 604 | void* mapped = nullptr; | ||
| 605 | CHECK(SUCCEEDED(readback->Map(0, nullptr, &mapped)) && mapped); | ||
| 606 | auto* bytes = static_cast<std::uint8_t*>(mapped); | ||
| 607 | bool ok = true; | ||
| 608 | std::uint32_t words[kWords]; | ||
| 609 | std::memcpy(words, bytes + 4096, sizeof words); | ||
| 610 | for (const unsigned n : compute) { | ||
| 611 | const std::uint32_t want = int(n) == dropped ? 0 : programs[n].run(n); | ||
| 612 | if (words[n] != want) { | ||
| 613 | std::fprintf(stderr, "compute program %u stored 0x%08x, not 0x%08x\n", n, words[n], want); | ||
| 614 | ok = false; | ||
| 615 | } | ||
| 616 | } | ||
| 617 | for (unsigned n = 0; graphics && n < kGraphics; ++n) | ||
| 618 | for (unsigned y = 0; y < 2; ++y) | ||
| 619 | for (unsigned x = 2 * n; x < 2 * n + 2; ++x) { | ||
| 620 | const auto* pixel = bytes + foot.Offset + y * foot.Footprint.RowPitch + 4 * x; | ||
| 621 | if (pixel[0] != n || pixel[1] != 255 - n || pixel[2] != 0 || pixel[3] != 255) { | ||
| 622 | std::fprintf(stderr, "graphics pipeline %u drew %u %u %u %u\n", n, pixel[0], pixel[1], pixel[2], | ||
| 623 | pixel[3]); | ||
| 624 | ok = false; | ||
| 625 | } | ||
| 626 | } | ||
| 627 | std::memset(bytes, 0xee, 4096 + 4 * kWords); | ||
| 628 | readback->Unmap(0, nullptr); | ||
| 629 | return ok; | ||
| 630 | } | ||
| 631 | }; | ||
| 632 | |||
| 633 | std::vector<unsigned> all_compute() { | ||
| 634 | std::vector<unsigned> out; | ||
| 635 | for (unsigned n = 0; n < kCompute; ++n) out.push_back(n); | ||
| 636 | return out; | ||
| 637 | } | ||
| 638 | |||
| 639 | std::uint64_t estimate(unsigned n) { return leonida::large_module_estimate(module_bytes[n]); } | ||
| 640 | |||
| 641 | // How many of the large compute modules are in the driver at once, with five threads to compile them; 0: not known (the | ||
| 642 | // budget is read from the machine). | ||
| 643 | int expected_at_once() { | ||
| 644 | if (serial) return 1; | ||
| 645 | if (unlimited) return 5; | ||
| 646 | if (!fixed_budget) return 0; | ||
| 647 | // The first wave is the largest, in order, while they fit. | ||
| 648 | std::uint64_t sum = 0; | ||
| 649 | int count = 0; | ||
| 650 | for (unsigned n = kBig; n-- > 0 && sum + estimate(n) <= *fixed_budget; ++count) sum += estimate(n); | ||
| 651 | return std::clamp(count, 1, 5); | ||
| 652 | } | ||
| 653 | |||
| 654 | // The large compute modules are held back in the driver until as many as may be are in, and no more come. | ||
| 655 | bool side_by_side(const Setup& setup) { | ||
| 656 | Ref<ID3D12Device> dev; | ||
| 657 | CHECK(setup.device("4", dev)); | ||
| 658 | Pipelines pipelines; | ||
| 659 | Frame frame; | ||
| 660 | hooks.reset(); | ||
| 661 | CHECK(pipelines.create(dev.p) && frame.create(dev.p, pipelines, all_compute(), false)); | ||
| 662 | CHECK(hooks.creates() == 0); // nothing is compiled at creation | ||
| 663 | const int at_once = expected_at_once(); | ||
| 664 | hooks.closed = true; | ||
| 665 | ReplayResult result = ReplayResult::unsupported; | ||
| 666 | std::thread submitting([&] { result = frame.submit(); }); | ||
| 667 | const bool filled = hooks.wait_large(std::max(at_once, 1)); | ||
| 668 | // With a thread to spare, the small ones are compiled while the large ones wait (unlimited: every thread has a large one). | ||
| 669 | const bool small_ones = unlimited || !at_once || hooks.wait([] { return hooks.small_done == int(kSmall); }); | ||
| 670 | std::this_thread::sleep_for(300ms); | ||
| 671 | int held = 0; | ||
| 672 | { | ||
| 673 | std::lock_guard lock(hooks.mutex); | ||
| 674 | held = hooks.large_in; | ||
| 675 | } | ||
| 676 | hooks.open(); | ||
| 677 | submitting.join(); | ||
| 678 | CHECK(filled); | ||
| 679 | CHECK(!at_once || held == at_once); | ||
| 680 | CHECK(small_ones); | ||
| 681 | CHECK(result == ReplayResult::success && frame.right()); | ||
| 682 | CHECK(hooks.over == 0); | ||
| 683 | CHECK(hooks.creates() == kCompute); // each once | ||
| 684 | CHECK(!at_once || hooks.most_large <= at_once || unlimited); | ||
| 685 | CHECK(frame.submit() == ReplayResult::success && frame.right() && hooks.creates() == kCompute); | ||
| 686 | return true; | ||
| 687 | } | ||
| 688 | |||
| 689 | // The same values whatever compiles them, without workers (each where prepare() meets it) and with them. | ||
| 690 | bool same_values(const Setup& setup) { | ||
| 691 | for (const char* threads : {"0", "16"}) { | ||
| 692 | Ref<ID3D12Device> dev; | ||
| 693 | CHECK(setup.device(threads, dev)); | ||
| 694 | Pipelines pipelines; | ||
| 695 | Frame frame; | ||
| 696 | hooks.reset(); | ||
| 697 | CHECK(pipelines.create(dev.p) && frame.create(dev.p, pipelines, all_compute(), true)); | ||
| 698 | CHECK(frame.submit() == ReplayResult::success && frame.right()); | ||
| 699 | CHECK(hooks.over == 0); | ||
| 700 | CHECK(hooks.creates() == kCompute + kGraphics); | ||
| 701 | CHECK(*threads != '0' || hooks.most_large == 1); | ||
| 702 | } | ||
| 703 | return true; | ||
| 704 | } | ||
| 705 | |||
| 706 | // A graphics pipeline whose estimate is past the budget (or the one at a time of serial) is in alone among the large ones, | ||
| 707 | // and the small ones are compiled beside it. | ||
| 708 | bool graphics_among_the_large(const Setup& setup) { | ||
| 709 | Ref<ID3D12Device> dev; | ||
| 710 | CHECK(setup.device("4", dev)); | ||
| 711 | Pipelines pipelines; | ||
| 712 | Frame frame; | ||
| 713 | hooks.reset(); | ||
| 714 | CHECK(pipelines.create(dev.p) && frame.create(dev.p, pipelines, all_compute(), true)); | ||
| 715 | hooks.closed = true; | ||
| 716 | ReplayResult result = ReplayResult::unsupported; | ||
| 717 | std::thread submitting([&] { result = frame.submit(); }); | ||
| 718 | const bool one = hooks.wait_large(1); | ||
| 719 | const bool small_ones = unlimited || !expected_at_once() || | ||
| 720 | hooks.wait([] { return hooks.small_done == int(kSmall); }); | ||
| 721 | std::this_thread::sleep_for(300ms); | ||
| 722 | int held = 0; | ||
| 723 | bool first_is_graphics = false; | ||
| 724 | { | ||
| 725 | std::lock_guard lock(hooks.mutex); | ||
| 726 | held = hooks.large_in; | ||
| 727 | for (const Start& s : hooks.started) | ||
| 728 | if (s.large) { | ||
| 729 | first_is_graphics = s.program < 0; | ||
| 730 | break; | ||
| 731 | } | ||
| 732 | } | ||
| 733 | hooks.open(); | ||
| 734 | submitting.join(); | ||
| 735 | CHECK(one && small_ones); | ||
| 736 | if (budgeted && fixed_budget) CHECK(held == 1 && first_is_graphics); // the largest first | ||
| 737 | if (serial) CHECK(held == 1); | ||
| 738 | CHECK(result == ReplayResult::success && frame.right()); | ||
| 739 | CHECK(hooks.over == 0); | ||
| 740 | CHECK(hooks.creates() == kCompute + kGraphics); | ||
| 741 | return true; | ||
| 742 | } | ||
| 743 | |||
| 744 | // Two large graphics pipelines and nothing else: one after the other, or both at once without a limit. | ||
| 745 | bool graphics_only(const Setup& setup) { | ||
| 746 | Ref<ID3D12Device> dev; | ||
| 747 | CHECK(setup.device("4", dev)); | ||
| 748 | Pipelines pipelines; | ||
| 749 | Frame frame; | ||
| 750 | hooks.reset(); | ||
| 751 | CHECK(pipelines.create(dev.p) && frame.create(dev.p, pipelines, {}, true)); | ||
| 752 | hooks.closed = true; | ||
| 753 | ReplayResult result = ReplayResult::unsupported; | ||
| 754 | std::thread submitting([&] { result = frame.submit(); }); | ||
| 755 | const int at_once = unlimited ? 2 : 1; | ||
| 756 | const bool filled = hooks.wait_large(at_once); | ||
| 757 | std::this_thread::sleep_for(300ms); | ||
| 758 | int held = 0; | ||
| 759 | { | ||
| 760 | std::lock_guard lock(hooks.mutex); | ||
| 761 | held = hooks.large_in; | ||
| 762 | } | ||
| 763 | hooks.open(); | ||
| 764 | submitting.join(); | ||
| 765 | CHECK(filled); | ||
| 766 | if (!budgeted || fixed_budget) CHECK(held == at_once); | ||
| 767 | CHECK(result == ReplayResult::success && frame.right()); | ||
| 768 | CHECK(hooks.over == 0 && hooks.creates() == kGraphics); | ||
| 769 | return true; | ||
| 770 | } | ||
| 771 | |||
| 772 | // The driver refuses one large compute module: its dispatch is dropped, the rest runs, and it is not tried again. Its place | ||
| 773 | // goes to the next. | ||
| 774 | bool refused(const Setup& setup) { | ||
| 775 | for (const char* threads : {"0", "4"}) { | ||
| 776 | Ref<ID3D12Device> dev; | ||
| 777 | CHECK(setup.device(threads, dev)); | ||
| 778 | Pipelines pipelines; | ||
| 779 | Frame frame; | ||
| 780 | hooks.reset(); | ||
| 781 | CHECK(pipelines.create(dev.p) && frame.create(dev.p, pipelines, all_compute(), false)); | ||
| 782 | hooks.fail_large = 2; | ||
| 783 | CHECK(frame.submit() == ReplayResult::success); | ||
| 784 | int dropped = -1; | ||
| 785 | { | ||
| 786 | std::lock_guard lock(hooks.mutex); | ||
| 787 | int seen = 0; | ||
| 788 | for (const Start& s : hooks.started) | ||
| 789 | if (s.large && s.program >= 0 && seen++ == 2) dropped = s.program; | ||
| 790 | } | ||
| 791 | CHECK(dropped >= 0); | ||
| 792 | CHECK(frame.right(dropped)); | ||
| 793 | CHECK(hooks.creates() == kCompute); | ||
| 794 | CHECK(frame.submit() == ReplayResult::success && frame.right(dropped)); | ||
| 795 | CHECK(hooks.creates() == kCompute); | ||
| 796 | } | ||
| 797 | return true; | ||
| 798 | } | ||
| 799 | |||
| 800 | // Two queues submit the same pipelines at once: each is compiled once, the budget is kept, and nobody waits for ever. | ||
| 801 | bool two_queues(const Setup& setup) { | ||
| 802 | Ref<ID3D12Device> dev; | ||
| 803 | CHECK(setup.device("4", dev)); | ||
| 804 | Pipelines pipelines; | ||
| 805 | Frame frames[2]; | ||
| 806 | CHECK(pipelines.create(dev.p)); | ||
| 807 | auto backwards = all_compute(); | ||
| 808 | std::reverse(backwards.begin(), backwards.end()); | ||
| 809 | CHECK(frames[0].create(dev.p, pipelines, all_compute(), true)); | ||
| 810 | CHECK(frames[1].create(dev.p, pipelines, backwards, true)); | ||
| 811 | hooks.reset(); | ||
| 812 | ReplayResult results[2]{}; | ||
| 813 | std::thread threads[2]; | ||
| 814 | for (int i = 0; i < 2; ++i) threads[i] = std::thread([&, i] { results[i] = frames[i].submit(); }); | ||
| 815 | for (auto& t : threads) t.join(); | ||
| 816 | for (int i = 0; i < 2; ++i) CHECK(results[i] == ReplayResult::success && frames[i].right()); | ||
| 817 | CHECK(hooks.creates() == kCompute + kGraphics); | ||
| 818 | CHECK(hooks.over == 0); | ||
| 819 | return true; | ||
| 820 | } | ||
| 821 | |||
| 822 | // The device's last references are released by the thread whose submission compiles, with large ones waiting for room. | ||
| 823 | bool device_destroyed(const Setup& setup) { | ||
| 824 | _putenv_s("LEONIDA_PIPELINE_CACHE_BYTES", "1"); // read the cache at teardown, write no file | ||
| 825 | Ref<ID3D12Device> dev; | ||
| 826 | CHECK(setup.device("4", dev)); | ||
| 827 | auto pipelines = std::make_unique<Pipelines>(); | ||
| 828 | auto frame = std::make_unique<Frame>(); | ||
| 829 | hooks.reset(); | ||
| 830 | CHECK(pipelines->create(dev.p) && frame->create(dev.p, *pipelines, all_compute(), true)); | ||
| 831 | hooks.track = true; | ||
| 832 | hooks.closed = true; | ||
| 833 | ReplayResult result = ReplayResult::unsupported; | ||
| 834 | bool ok = false; | ||
| 835 | std::thread submitting([&] { | ||
| 836 | result = frame->submit(); | ||
| 837 | ok = frame->right(); | ||
| 838 | frame.reset(); | ||
| 839 | pipelines.reset(); | ||
| 840 | }); | ||
| 841 | const bool compiling = hooks.wait_large(1); | ||
| 842 | std::this_thread::sleep_for(100ms); | ||
| 843 | dev.reset(); | ||
| 844 | hooks.open(); | ||
| 845 | submitting.join(); | ||
| 846 | _putenv_s("LEONIDA_PIPELINE_CACHE_BYTES", "0"); | ||
| 847 | CHECK(compiling); | ||
| 848 | CHECK(result == ReplayResult::success && ok); | ||
| 849 | CHECK(hooks.cache_reads > 0); | ||
| 850 | CHECK(!hooks.cache_read_during_create); | ||
| 851 | CHECK(!hooks.cache_read_with_workers); | ||
| 852 | CHECK(hooks.live == 0); | ||
| 853 | return true; | ||
| 854 | } | ||
| 855 | |||
| 856 | // One place for large compiles. The warm-up thread has it, and wants the next one after it; a submission that needs four | ||
| 857 | // others, one of which the warm-up thread waits to build, gets them all first, and builds that one itself. | ||
| 858 | bool warmup(const Setup& setup) { | ||
| 859 | Ref<ID3D12Device> dev; | ||
| 860 | CHECK(setup.device("4", dev)); | ||
| 861 | Pipelines pipelines; | ||
| 862 | Frame frame; | ||
| 863 | hooks.reset(); | ||
| 864 | hooks.closed = true; | ||
| 865 | hooks.linger = 100ms; | ||
| 866 | CHECK(pipelines.create(dev.p)); | ||
| 867 | if (!hooks.wait_large(1)) { | ||
| 868 | hooks.open(); | ||
| 869 | CHECK(!"the warm-up thread compiles a large one"); | ||
| 870 | } | ||
| 871 | std::thread::id warm; | ||
| 872 | int first = -1; | ||
| 873 | { | ||
| 874 | std::lock_guard lock(hooks.mutex); | ||
| 875 | for (const Start& s : hooks.started) | ||
| 876 | if (s.large) warm = s.thread, first = s.program; | ||
| 877 | } | ||
| 878 | CHECK(first == 0); // their sizes rise with their numbers | ||
| 879 | const std::vector<unsigned> wanted = {4, 5, 3, 1}; // 1 is what the warm-up thread builds after 0 | ||
| 880 | CHECK(frame.create(dev.p, pipelines, wanted, false)); | ||
| 881 | const std::size_t before = hooks.creates(); | ||
| 882 | ReplayResult result = ReplayResult::unsupported; | ||
| 883 | std::thread submitting([&] { result = frame.submit(); }); | ||
| 884 | std::this_thread::sleep_for(500ms); | ||
| 885 | const bool waits = hooks.creates() == before; // the place is taken | ||
| 886 | hooks.open(); | ||
| 887 | submitting.join(); | ||
| 888 | const bool done = result == ReplayResult::success && frame.right(); | ||
| 889 | rt::d3d12::PipelineCompiler::instance().wait_idle(); // the warm-up thread builds the rest | ||
| 890 | std::vector<Start> started; | ||
| 891 | { | ||
| 892 | std::lock_guard lock(hooks.mutex); | ||
| 893 | started = hooks.started; | ||
| 894 | } | ||
| 895 | CHECK(waits); | ||
| 896 | CHECK(done); | ||
| 897 | CHECK(hooks.over == 0 && hooks.most_large == 1); | ||
| 898 | std::set<int> once; | ||
| 899 | for (const Start& s : started) once.insert(s.program); | ||
| 900 | CHECK(started.size() == kCompute && once.size() == kCompute); // each once | ||
| 901 | std::erase_if(started, [](const Start& s) { return !s.large; }); | ||
| 902 | std::set<int> built; | ||
| 903 | for (std::size_t i = 1; i <= wanted.size(); ++i) { | ||
| 904 | CHECK(started[i].thread != warm); // none of the warm-up's between two of the submission's | ||
| 905 | built.insert(started[i].program); | ||
| 906 | } | ||
| 907 | CHECK(built == std::set<int>(wanted.begin(), wanted.end())); | ||
| 908 | for (std::size_t i = wanted.size() + 1; i < started.size(); ++i) CHECK(started[i].thread == warm); | ||
| 909 | return true; | ||
| 910 | } | ||
| 911 | |||
| 912 | // The large ones that four threads create at once are held back in the driver until as many as may be are in. | ||
| 913 | bool eager(const Setup& setup) { | ||
| 914 | Ref<ID3D12Device> dev; | ||
| 915 | CHECK(setup.device("4", dev)); | ||
| 916 | Pipelines pipelines; | ||
| 917 | Frame frame; | ||
| 918 | hooks.reset(); | ||
| 919 | hooks.closed = true; | ||
| 920 | bool created = false; | ||
| 921 | std::thread creating([&] { created = pipelines.create(dev.p, 4); }); | ||
| 922 | const bool one = hooks.wait_large(1); | ||
| 923 | std::this_thread::sleep_for(300ms); | ||
| 924 | int held = 0; | ||
| 925 | { | ||
| 926 | std::lock_guard lock(hooks.mutex); | ||
| 927 | held = hooks.large_in; | ||
| 928 | } | ||
| 929 | hooks.open(); | ||
| 930 | creating.join(); | ||
| 931 | CHECK(one && created); | ||
| 932 | CHECK(held == expected_at_once()); | ||
| 933 | CHECK(hooks.over == 0 && hooks.creates() == kCompute); | ||
| 934 | CHECK(frame.create(dev.p, pipelines, all_compute(), false)); | ||
| 935 | CHECK(frame.submit() == ReplayResult::success && frame.right()); | ||
| 936 | CHECK(hooks.creates() == kCompute); | ||
| 937 | return true; | ||
| 938 | } | ||
| 939 | |||
| 940 | bool run(const Setup& setup, const std::string& scenario) { | ||
| 941 | if (scenario == "warmup") return warmup(setup); | ||
| 942 | if (scenario == "eager") return eager(setup); | ||
| 943 | return side_by_side(setup) && same_values(setup) && graphics_among_the_large(setup) && graphics_only(setup) && | ||
| 944 | refused(setup) && two_queues(setup) && device_destroyed(setup); | ||
| 945 | } | ||
| 946 | |||
| 947 | } // namespace | ||
| 948 | |||
| 949 | int main(int argc, char** argv) { | ||
| 950 | const std::string scenario = argc > 1 ? argv[1] : ""; | ||
| 951 | vktest::Device vk; | ||
| 952 | vk.request_buffer_device_address = true; | ||
| 953 | const auto status = vk.initialize(); | ||
| 954 | if (status == vktest::DeviceStatus::unavailable) return 77; | ||
| 955 | if (status != vktest::DeviceStatus::ready) return 1; | ||
| 956 | VkPhysicalDeviceProperties properties{}; | ||
| 957 | vk.instance_fn<PFN_vkGetPhysicalDeviceProperties>("vkGetPhysicalDeviceProperties")(vk.physical, &properties); | ||
| 958 | if (!vk.buffer_device_address || !vk.enabled.shaderInt64) { | ||
| 959 | std::printf("SKIP: the GPU lacks bufferDeviceAddress or shaderInt64\n"); | ||
| 960 | return 77; | ||
| 961 | } | ||
| 962 | if (properties.limits.maxPushConstantsSize < 144) { | ||
| 963 | std::printf("SKIP: maxPushConstantsSize %u, below the 144-byte block\n", properties.limits.maxPushConstantsSize); | ||
| 964 | return 77; | ||
| 965 | } | ||
| 966 | real_instance_proc = vk.instance_proc; | ||
| 967 | _putenv_s("LEONIDA_PIPELINE_CACHE_BYTES", "0"); // no session file in or out | ||
| 968 | if (scenario != "warmup") _putenv_s("LEONIDA_COMPUTE_WARMUP", "0"); // every compile is a submission's | ||
| 969 | const testfiles::ScratchDir library("leonida_big_compute_test"); | ||
| 970 | if (!write_library(library.path())) return 1; | ||
| 971 | if (!run({&vk, library.path().string()}, scenario)) return 1; | ||
| 972 | if (vk.validation_errors()) { | ||
| 973 | std::fprintf(stderr, "FAIL: %u validation errors\n", vk.validation_errors()); | ||
| 974 | return 1; | ||
| 975 | } | ||
| 976 | std::printf("d3d12_big_compute_test: passed on %s\n", properties.deviceName); | ||
| 977 | return 0; | ||
| 978 | } | ||
diff --git a/runtime/test/d3d12_compile_teardown_test.cpp b/runtime/test/d3d12_compile_teardown_test.cpp index 116c2459d..f9344c069 100644 --- a/runtime/test/d3d12_compile_teardown_test.cpp +++ b/runtime/test/d3d12_compile_teardown_test.cpp | |||
| @@ -16,7 +16,8 @@ | |||
| 16 | // racing many PSOs released at once with builds queued and one usually running, repeated. | 16 | // racing many PSOs released at once with builds queued and one usually running, repeated. |
| 17 | // restart a device made after the worker stopped gets a new one, and its builds run. | 17 | // restart a device made after the worker stopped gets a new one, and its builds run. |
| 18 | // exit stop_pipeline_compiles with a device alive: the queue goes, later builds are refused, a warm-up | 18 | // exit stop_pipeline_compiles with a device alive: the queue goes, later builds are refused, a warm-up |
| 19 | // is skipped and a dispatch (LEONIDA_ASYNC_PIPELINES on) builds its pipeline in place and runs. | 19 | // is skipped and a dispatch (LEONIDA_ASYNC_PIPELINES on) builds its pipeline in place and runs; |
| 20 | // save_pipeline_caches_at_exit then writes the session cache with the device alive, once. | ||
| 20 | // After each case the compiler's thread is gone and the process's thread count is back where it was. | 21 | // After each case the compiler's thread is gone and the process's thread count is back where it was. |
| 21 | // No game data: the shader is test/glsl/cs_user_data.comp, the programs are made-up FSSM bytes. | 22 | // No game data: the shader is test/glsl/cs_user_data.comp, the programs are made-up FSSM bytes. |
| 22 | #include "shader_fixture_path.h" | 23 | #include "shader_fixture_path.h" |
| @@ -423,6 +424,14 @@ int main() { | |||
| 423 | 424 | ||
| 424 | auto& compiler = PipelineCompiler::instance(); | 425 | auto& compiler = PipelineCompiler::instance(); |
| 425 | EXPECT(!compiler.worker_running()); | 426 | EXPECT(!compiler.worker_running()); |
| 427 | // llvmpipe keeps no pipelines in a VkPipelineCache (measured: vkGetPipelineCacheData returns the 32-byte header | ||
| 428 | // alone after the build), and the runtime writes no file of a bare header (save_session_pipeline_cache). | ||
| 429 | VkPhysicalDeviceDriverProperties driver{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DRIVER_PROPERTIES}; | ||
| 430 | VkPhysicalDeviceProperties2 properties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &driver}; | ||
| 431 | reinterpret_cast<PFN_vkGetPhysicalDeviceProperties2>( | ||
| 432 | d.instance_proc(d.instance, "vkGetPhysicalDeviceProperties2"))(d.physical, &properties); | ||
| 433 | const bool caches = driver.driverID != VK_DRIVER_ID_MESA_LLVMPIPE; | ||
| 434 | const auto session_file = cache_dir / "pipeline_cache.session.bin"; | ||
| 426 | 435 | ||
| 427 | // --- cache: one PSO built by the warm-up thread; the device writes the session cache at teardown ------------- | 436 | // --- cache: one PSO built by the warm-up thread; the device writes the session cache at teardown ------------- |
| 428 | { | 437 | { |
| @@ -433,14 +442,7 @@ int main() { | |||
| 433 | EXPECT(built(s.psos[0])); | 442 | EXPECT(built(s.psos[0])); |
| 434 | s.release(); | 443 | s.release(); |
| 435 | EXPECT(!compiler.worker_running()); | 444 | EXPECT(!compiler.worker_running()); |
| 436 | // llvmpipe keeps no pipelines in a VkPipelineCache (measured: vkGetPipelineCacheData returns the 32-byte | 445 | EXPECT(std::filesystem::exists(session_file) == caches); |
| 437 | // header alone after the build), and the runtime writes no file of a bare header (save_session_pipeline_cache). | ||
| 438 | VkPhysicalDeviceDriverProperties driver{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DRIVER_PROPERTIES}; | ||
| 439 | VkPhysicalDeviceProperties2 properties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &driver}; | ||
| 440 | reinterpret_cast<PFN_vkGetPhysicalDeviceProperties2>( | ||
| 441 | d.instance_proc(d.instance, "vkGetPhysicalDeviceProperties2"))(d.physical, &properties); | ||
| 442 | const bool caches = driver.driverID != VK_DRIVER_ID_MESA_LLVMPIPE; | ||
| 443 | EXPECT(std::filesystem::exists(cache_dir / "pipeline_cache.session.bin") == caches); | ||
| 444 | std::printf("cache: built in the background, session cache %s at teardown, worker joined\n", | 446 | std::printf("cache: built in the background, session cache %s at teardown, worker joined\n", |
| 445 | caches ? "written" : "not written (the driver keeps no pipelines in its cache)"); | 447 | caches ? "written" : "not written (the driver keeps no pipelines in its cache)"); |
| 446 | } | 448 | } |
| @@ -660,10 +662,19 @@ int main() { | |||
| 660 | if (s.dispatch(pso, fresh)) return 1; | 662 | if (s.dispatch(pso, fresh)) return 1; |
| 661 | EXPECT(built(pso)); | 663 | EXPECT(built(pso)); |
| 662 | EXPECT(compiler.stats().submitted == before.submitted); | 664 | EXPECT(compiler.stats().submitted == before.submitted); |
| 665 | // The process ends with the device alive (a title never releases it): the exit save writes the session | ||
| 666 | // cache now, not at a teardown that will not come, and only once. | ||
| 667 | std::error_code ec; | ||
| 668 | std::filesystem::remove(session_file, ec); | ||
| 669 | EXPECT(!std::filesystem::exists(session_file)); | ||
| 670 | EXPECT(rt::d3d12::save_pipeline_caches_at_exit(1000)); | ||
| 671 | EXPECT(std::filesystem::exists(session_file) == caches); | ||
| 672 | EXPECT(!rt::d3d12::save_pipeline_caches_at_exit(1000)); | ||
| 663 | s.release(); // the device's teardown after the exit stop: nothing left to cancel or join | 673 | s.release(); // the device's teardown after the exit stop: nothing left to cancel or join |
| 664 | EXPECT(!compiler.worker_running()); | 674 | EXPECT(!compiler.worker_running()); |
| 665 | EXPECT(rt::d3d12::live_pipeline_states() == 0); // no PSO of any case leaked | 675 | EXPECT(rt::d3d12::live_pipeline_states() == 0); // no PSO of any case leaked |
| 666 | std::printf("exit: queue dropped, later builds refused, a dispatch built its pipeline in place and ran\n"); | 676 | std::printf("exit: queue dropped, later builds refused, a dispatch built its pipeline in place and ran, " |
| 677 | "session cache %s with the device alive, once\n", caches ? "written" : "not written (llvmpipe)"); | ||
| 667 | } | 678 | } |
| 668 | std::printf("ok\n"); | 679 | std::printf("ok\n"); |
| 669 | return 0; | 680 | return 0; |
diff --git a/runtime/test/d3d12_compute_journal_test.cpp b/runtime/test/d3d12_compute_journal_test.cpp new file mode 100644 index 000000000..f25076759 --- /dev/null +++ b/runtime/test/d3d12_compute_journal_test.cpp | |||
| @@ -0,0 +1,153 @@ | |||
| 1 | // Exercise one production compute PSO in each invocation. The same authored module, root signature and device | ||
| 2 | // should give the same journal key in separate cold/warm processes. The readback proves the dispatch actually ran; | ||
| 3 | // a journal hit or write is a separate observation from the production runtime, not inferred from these words. | ||
| 4 | #include "vk_test_device.h" | ||
| 5 | #include "d3d12_test_shaders.h" | ||
| 6 | #include "shader_fixture_path.h" | ||
| 7 | #include "test_temp_dir.h" | ||
| 8 | #include "../shims/d3d12_com.h" | ||
| 9 | #include "../src/shader_library.h" | ||
| 10 | |||
| 11 | #include <array> | ||
| 12 | #include <cstdio> | ||
| 13 | #include <cstring> | ||
| 14 | #include <fstream> | ||
| 15 | |||
| 16 | using namespace d3d12test; | ||
| 17 | |||
| 18 | #define CHECK(expr) do { if (!(expr)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #expr); return 1; } } while (0) | ||
| 19 | |||
| 20 | namespace { | ||
| 21 | int dispatch_once(ID3D12Device* dev, const std::vector<std::uint8_t>& container, UINT expected_sum) { | ||
| 22 | D3D12_ROOT_PARAMETER param{}; | ||
| 23 | param.ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV; | ||
| 24 | D3D12_VERSIONED_ROOT_SIGNATURE_DESC root_desc{}; | ||
| 25 | root_desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0; | ||
| 26 | root_desc.Desc_1_0 = {1, ¶m, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}; | ||
| 27 | const auto bytes = serialize_root_signature(root_desc); | ||
| 28 | CHECK(!bytes.empty()); | ||
| 29 | Ref<ID3D12RootSignature> root; | ||
| 30 | CHECK(SUCCEEDED(dev->CreateRootSignature(0, bytes.data(), bytes.size(), IID_PPV_ARGS(&root.p)))); | ||
| 31 | D3D12_COMPUTE_PIPELINE_STATE_DESC desc{}; | ||
| 32 | desc.pRootSignature = root.p; | ||
| 33 | desc.CS = {container.data(), container.size()}; | ||
| 34 | Ref<ID3D12PipelineState> pso; | ||
| 35 | CHECK(SUCCEEDED(dev->CreateComputePipelineState(&desc, IID_PPV_ARGS(&pso.p)))); | ||
| 36 | |||
| 37 | using Counters = std::array<UINT, 2>; | ||
| 38 | const auto buffer = [&](Ref<ID3D12Resource>& dst, D3D12_HEAP_TYPE type, D3D12_RESOURCE_STATES state, | ||
| 39 | D3D12_RESOURCE_FLAGS flags = D3D12_RESOURCE_FLAG_NONE) { | ||
| 40 | const D3D12_HEAP_PROPERTIES heap{type}; | ||
| 41 | const auto resource = buffer_desc(sizeof(Counters), flags); | ||
| 42 | return SUCCEEDED(dev->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &resource, state, nullptr, | ||
| 43 | IID_PPV_ARGS(&dst.p))); | ||
| 44 | }; | ||
| 45 | Ref<ID3D12Resource> upload, result, readback; | ||
| 46 | CHECK(buffer(upload, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ)); | ||
| 47 | CHECK(buffer(result, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COPY_DEST, | ||
| 48 | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)); | ||
| 49 | CHECK(buffer(readback, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST)); | ||
| 50 | const D3D12_RANGE none{0, 0}, both{0, sizeof(Counters)}; | ||
| 51 | void* mapped = nullptr; | ||
| 52 | CHECK(SUCCEEDED(upload->Map(0, &none, &mapped)) && mapped); | ||
| 53 | std::memset(mapped, 0, sizeof(Counters)); | ||
| 54 | upload->Unmap(0, &both); | ||
| 55 | |||
| 56 | constexpr auto type = D3D12_COMMAND_LIST_TYPE_COMPUTE; | ||
| 57 | const D3D12_COMMAND_QUEUE_DESC queue_desc{type}; | ||
| 58 | Ref<ID3D12CommandQueue> queue; | ||
| 59 | Ref<ID3D12CommandAllocator> allocator; | ||
| 60 | Ref<ID3D12GraphicsCommandList> list; | ||
| 61 | Ref<ID3D12Fence> fence; | ||
| 62 | CHECK(SUCCEEDED(dev->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue.p)))); | ||
| 63 | CHECK(SUCCEEDED(dev->CreateCommandAllocator(type, IID_PPV_ARGS(&allocator.p)))); | ||
| 64 | CHECK(SUCCEEDED(dev->CreateCommandList(0, type, allocator.p, nullptr, IID_PPV_ARGS(&list.p)))); | ||
| 65 | CHECK(SUCCEEDED(dev->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p)))); | ||
| 66 | |||
| 67 | list->CopyBufferRegion(result.p, 0, upload.p, 0, sizeof(Counters)); | ||
| 68 | const auto ready = transition(result.p, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); | ||
| 69 | list->ResourceBarrier(1, &ready); | ||
| 70 | list->SetComputeRootSignature(root.p); | ||
| 71 | list->SetPipelineState(pso.p); | ||
| 72 | const auto va = result->GetGPUVirtualAddress(); | ||
| 73 | CHECK(va != 0); | ||
| 74 | list->SetComputeRootUnorderedAccessView(0, va); | ||
| 75 | list->Dispatch(4, 1, 1); // each group adds 1 to counter 0 and groupID.x + the authored term to counter 1 | ||
| 76 | const auto copy = transition(result.p, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE); | ||
| 77 | list->ResourceBarrier(1, ©); | ||
| 78 | list->CopyBufferRegion(readback.p, 0, result.p, 0, sizeof(Counters)); | ||
| 79 | CHECK(SUCCEEDED(list->Close())); | ||
| 80 | ID3D12CommandList* lists[] = {list.p}; | ||
| 81 | queue->ExecuteCommandLists(1, lists); | ||
| 82 | CHECK(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success); | ||
| 83 | CHECK(SUCCEEDED(queue->Signal(fence.p, 1))); | ||
| 84 | CHECK(SUCCEEDED(fence->SetEventOnCompletion(1, nullptr))); | ||
| 85 | mapped = nullptr; | ||
| 86 | CHECK(SUCCEEDED(readback->Map(0, &both, &mapped)) && mapped); | ||
| 87 | Counters got{}; | ||
| 88 | std::memcpy(got.data(), mapped, sizeof(got)); | ||
| 89 | readback->Unmap(0, &none); | ||
| 90 | if (got[0] != 4 || got[1] != expected_sum) { | ||
| 91 | std::fprintf(stderr, "compute journal: expected (4,%u), got (%u,%u)\n", expected_sum, got[0], got[1]); | ||
| 92 | return 1; | ||
| 93 | } | ||
| 94 | return 0; | ||
| 95 | } | ||
| 96 | } // namespace | ||
| 97 | |||
| 98 | int main(int argc, char** argv) { | ||
| 99 | const bool second = argc == 2 && std::strcmp(argv[1], "--second-shader") == 0; | ||
| 100 | if (argc != 1 && !second) { | ||
| 101 | std::fputs("usage: d3d12_compute_journal_test [--second-shader]\n", stderr); | ||
| 102 | return 2; | ||
| 103 | } | ||
| 104 | // One additional constant per group in the second module: (1+2+3+4) versus (2+3+4+5). | ||
| 105 | const UINT expected_sum = second ? 14u : 10u; | ||
| 106 | const testfiles::ScratchDir scratch("leonida_compute_journal_test"); | ||
| 107 | // Default CTest runs use disposable caches. An explicit cache directory lets the host preserve the exact | ||
| 108 | // same state for the second process; never infer a hit from runtime duration. | ||
| 109 | if (!GetEnvironmentVariableW(L"LEONIDA_PIPELINE_CACHE_DIR", nullptr, 0)) { | ||
| 110 | CHECK(SetEnvironmentVariableW(L"LEONIDA_PIPELINE_CACHE_DIR", (scratch.path() / "cache").c_str())); | ||
| 111 | } | ||
| 112 | { | ||
| 113 | vktest::Device vk; | ||
| 114 | vk.request_buffer_device_address = true; | ||
| 115 | const auto status = vk.initialize(); | ||
| 116 | if (status == vktest::DeviceStatus::unavailable) return 77; | ||
| 117 | CHECK(status == vktest::DeviceStatus::ready); | ||
| 118 | if (!vk.buffer_device_address || !vk.pipeline_cache_control_enabled()) { | ||
| 119 | std::puts("SKIP: requires bufferDeviceAddress and enabled Vulkan 1.3 pipelineCreationCacheControl"); | ||
| 120 | return 77; | ||
| 121 | } | ||
| 122 | const auto program = fssm_program({second ? 0x4a435332u : 0x4a435331u, 0x10203040u}); | ||
| 123 | const auto container = shader_container(program); | ||
| 124 | const auto shader = vktest::shader_fixture_path(second ? LEONIDA_TEST_COUNTER_V2_SPV : LEONIDA_TEST_COUNTER_SPV); | ||
| 125 | CHECK(testfiles::copy_file(shader, scratch.path() / "counter.spv")); | ||
| 126 | std::ofstream index(scratch.path() / "index.json", std::ios::binary); | ||
| 127 | index << "{\"counter\":{\"stage\":\"cs\",\"fssm_sha256\":\"" << leonida::sha256_hex(program) | ||
| 128 | << "\",\"bindings\":[],\"push_constant_bytes\":144,\"local_size\":[1,1,1]," | ||
| 129 | "\"uses_code_base\":false,\"wave64\":false}}"; | ||
| 130 | index.close(); | ||
| 131 | CHECK(index); | ||
| 132 | rt::d3d12::VulkanDeviceInfo info{}; | ||
| 133 | info.get_instance_proc = vk.instance_proc; | ||
| 134 | info.instance = vk.instance; | ||
| 135 | info.physical = vk.physical; | ||
| 136 | info.device = vk.device; | ||
| 137 | info.queue = vk.queue; | ||
| 138 | info.queue_family = vk.family; | ||
| 139 | info.buffer_device_address = vk.buffer_device_address; | ||
| 140 | info.pipeline_cache_control = vk.pipeline_cache_control_enabled(); | ||
| 141 | info.shader_dir = scratch.path().string(); | ||
| 142 | Ref<ID3D12Device> dev; | ||
| 143 | CHECK(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&dev.p)))); | ||
| 144 | if (rt::d3d12::device_max_push_constants_size(dev.p) < 144) { | ||
| 145 | std::puts("SKIP: authored shader requires 144 push-constant bytes"); | ||
| 146 | return 77; | ||
| 147 | } | ||
| 148 | CHECK(dispatch_once(dev.p, container, expected_sum) == 0); | ||
| 149 | } | ||
| 150 | CHECK(vktest::validation_error_count() == 0); // includes device teardown | ||
| 151 | std::printf("compute journal: direct Dispatch(4,1,1) copied both expected words (4,%u)\n", expected_sum); | ||
| 152 | return 0; | ||
| 153 | } | ||
diff --git a/runtime/test/d3d12_compute_test.cpp b/runtime/test/d3d12_compute_test.cpp index e1dcef0fd..05591a780 100644 --- a/runtime/test/d3d12_compute_test.cpp +++ b/runtime/test/d3d12_compute_test.cpp | |||
| @@ -10,6 +10,7 @@ | |||
| 10 | // No game data. Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation. | 10 | // No game data. Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation. |
| 11 | #include "shader_fixture_path.h" | 11 | #include "shader_fixture_path.h" |
| 12 | #include "test_temp_dir.h" | 12 | #include "test_temp_dir.h" |
| 13 | #include "d3d12_test_shaders.h" | ||
| 13 | #include "vk_test_device.h" | 14 | #include "vk_test_device.h" |
| 14 | #include "host_wine.h" | 15 | #include "host_wine.h" |
| 15 | #include "../shims/d3d12_com.h" | 16 | #include "../shims/d3d12_com.h" |
| @@ -42,7 +43,6 @@ using XboxComputePipelineFn = HRESULT(WINAPI*)(void* device, const D3D12_COMPUTE | |||
| 42 | std::uint64_t, const IID*, void**); | 43 | std::uint64_t, const IID*, void**); |
| 43 | // Device slot 67 as amd_fidelityfx_upscaler_xbox.dll calls it: (desc, riid, out). | 44 | // Device slot 67 as amd_fidelityfx_upscaler_xbox.dll calls it: (desc, riid, out). |
| 44 | using XboxNativeComputePipelineFn = HRESULT(WINAPI*)(void* device, const void*, const IID*, void**); | 45 | using XboxNativeComputePipelineFn = HRESULT(WINAPI*)(void* device, const void*, const IID*, void**); |
| 45 | using SerializeFn = HRESULT(WINAPI*)(const D3D12_VERSIONED_ROOT_SIGNATURE_DESC*, ID3DBlob**, ID3DBlob**); | ||
| 46 | 46 | ||
| 47 | template<class T> | 47 | template<class T> |
| 48 | struct Ref { | 48 | struct Ref { |
| @@ -103,19 +103,9 @@ std::vector<std::uint8_t> shader_container(const std::vector<std::uint8_t>& fssm | |||
| 103 | return out; | 103 | return out; |
| 104 | } | 104 | } |
| 105 | 105 | ||
| 106 | // The shared helper: Windows 10's in-box d3d12.dll refuses the heap-directly-indexed flags at every version. | ||
| 106 | std::vector<std::uint8_t> serialize(const D3D12_VERSIONED_ROOT_SIGNATURE_DESC& desc) { | 107 | std::vector<std::uint8_t> serialize(const D3D12_VERSIONED_ROOT_SIGNATURE_DESC& desc) { |
| 107 | const HMODULE d3d12 = LoadLibraryExA("d3d12.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); | 108 | return d3d12test::serialize_root_signature(desc); |
| 108 | const auto fn = d3d12 ? reinterpret_cast<SerializeFn>( | ||
| 109 | reinterpret_cast<void*>(GetProcAddress(d3d12, "D3D12SerializeVersionedRootSignature"))) | ||
| 110 | : nullptr; | ||
| 111 | std::vector<std::uint8_t> out; | ||
| 112 | ID3DBlob* blob = nullptr; | ||
| 113 | if (fn && SUCCEEDED(fn(&desc, &blob, nullptr)) && blob) { | ||
| 114 | const auto* p = static_cast<const std::uint8_t*>(blob->GetBufferPointer()); | ||
| 115 | out.assign(p, p + blob->GetBufferSize()); | ||
| 116 | blob->Release(); | ||
| 117 | } | ||
| 118 | return out; | ||
| 119 | } | 109 | } |
| 120 | 110 | ||
| 121 | D3D12_RESOURCE_DESC buffer_desc(UINT64 bytes, D3D12_RESOURCE_FLAGS flags) { | 111 | D3D12_RESOURCE_DESC buffer_desc(UINT64 bytes, D3D12_RESOURCE_FLAGS flags) { |
| @@ -495,6 +485,14 @@ int main() { | |||
| 495 | D3D12_RESOURCE_STATE_COMMON, nullptr, | 485 | D3D12_RESOURCE_STATE_COMMON, nullptr, |
| 496 | IID_PPV_ARGS(&inside.p)))); | 486 | IID_PPV_ARGS(&inside.p)))); |
| 497 | EXPECT(inside->GetGPUVirtualAddress() + (1u << 20) <= capped_arena); | 487 | EXPECT(inside->GetGPUVirtualAddress() + (1u << 20) <= capped_arena); |
| 488 | // The existing buffer and the reserved range prevent a contiguous arena-sized allocation. | ||
| 489 | // A valid default buffer can still use a dedicated allocation and report a usable relative VA. | ||
| 490 | const auto no_slice = buffer_desc(capped_arena, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); | ||
| 491 | Ref<ID3D12Resource> dedicated; | ||
| 492 | EXPECT(SUCCEEDED(capped->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &no_slice, | ||
| 493 | D3D12_RESOURCE_STATE_COMMON, nullptr, | ||
| 494 | IID_PPV_ARGS(&dedicated.p)))); | ||
| 495 | EXPECT(dedicated->GetGPUVirtualAddress() >= capped_arena); | ||
| 498 | EXPECT(capped->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &too_large, D3D12_RESOURCE_STATE_COMMON, | 496 | EXPECT(capped->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &too_large, D3D12_RESOURCE_STATE_COMMON, |
| 499 | nullptr, IID_PPV_ARGS(&past.p)) == E_OUTOFMEMORY && !past.p); | 497 | nullptr, IID_PPV_ARGS(&past.p)) == E_OUTOFMEMORY && !past.p); |
| 500 | std::printf("arena: %llu MiB (device limits: maxBufferSize %llu MiB, maxMemoryAllocationSize %llu MiB); " | 498 | std::printf("arena: %llu MiB (device limits: maxBufferSize %llu MiB, maxMemoryAllocationSize %llu MiB); " |
diff --git a/runtime/test/d3d12_existing_heap_test.cpp b/runtime/test/d3d12_existing_heap_test.cpp index 3d65fc740..25fa1f654 100644 --- a/runtime/test/d3d12_existing_heap_test.cpp +++ b/runtime/test/d3d12_existing_heap_test.cpp | |||
| @@ -1402,6 +1402,58 @@ int check_mapped_plane(ID3D12Device* device) { | |||
| 1402 | return 0; | 1402 | return 0; |
| 1403 | } | 1403 | } |
| 1404 | 1404 | ||
| 1405 | // LEONIDA_TEXTURE_REFRESH_ASYNC=1 (the d3d12_mapped_plane_async test): a texture the title maps and writes, and then | ||
| 1406 | // reads on the GPU in its very first submission, has its bytes there, though the refresh pass runs on a worker: the | ||
| 1407 | // submission fills a mapped texture that was never filled before it records anything (fill_first_mapped_textures). | ||
| 1408 | int check_mapped_plane_first_use(ID3D12Device* device) { | ||
| 1409 | const char* who = "persistent slot-133 plane, first use"; | ||
| 1410 | constexpr UINT width = 256, height = 8, size = width * height; | ||
| 1411 | void* pages = VirtualAlloc(nullptr, 65536, MEM_RESERVE, PAGE_NOACCESS); | ||
| 1412 | EXPECT(pages); | ||
| 1413 | EXPECT(VirtualAlloc(pages, size, MEM_COMMIT, PAGE_READWRITE) == pages); | ||
| 1414 | std::memset(pages, 61, size); | ||
| 1415 | GpuReader gpu; | ||
| 1416 | EXPECT(!gpu.init(device, size)); | ||
| 1417 | D3D12_RESOURCE_DESC desc{}; | ||
| 1418 | desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; | ||
| 1419 | desc.Width = width; | ||
| 1420 | desc.Height = height; | ||
| 1421 | desc.Format = DXGI_FORMAT_R8_UNORM; | ||
| 1422 | desc.SampleDesc.Count = desc.DepthOrArraySize = desc.MipLevels = 1; | ||
| 1423 | leonida::title_xg_layouts::note({UINT(desc.Dimension), UINT(desc.Format), height, 1, 1, width}, 1); | ||
| 1424 | Ref<ID3D12Resource> texture; | ||
| 1425 | EXPECT_HR(rt::d3d12::create_buffer_at_host_address(device, pages, desc, 6, IID_PPV_ARGS(&texture.p)), S_OK); | ||
| 1426 | void* mapped = nullptr; | ||
| 1427 | EXPECT_HR(texture->Map(0, nullptr, &mapped), S_OK); | ||
| 1428 | EXPECT(mapped == pages); | ||
| 1429 | EXPECT_HR(gpu.allocator->Reset(), S_OK); | ||
| 1430 | EXPECT_HR(gpu.list->Reset(gpu.allocator.p, nullptr), S_OK); | ||
| 1431 | D3D12_RESOURCE_BARRIER barrier{}; | ||
| 1432 | barrier.Transition = {texture.p, 0, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_SOURCE}; | ||
| 1433 | gpu.list->ResourceBarrier(1, &barrier); | ||
| 1434 | D3D12_TEXTURE_COPY_LOCATION src{texture.p, D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX}; | ||
| 1435 | D3D12_TEXTURE_COPY_LOCATION dst{gpu.readback.p, D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT}; | ||
| 1436 | dst.PlacedFootprint.Footprint = {desc.Format, width, height, 1, width}; | ||
| 1437 | gpu.list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); | ||
| 1438 | EXPECT_HR(gpu.list->Close(), S_OK); | ||
| 1439 | ID3D12CommandList* lists[]{gpu.list.p}; | ||
| 1440 | gpu.queue->ExecuteCommandLists(1, lists); | ||
| 1441 | EXPECT_HR(gpu.queue->Signal(gpu.fence.p, 1), S_OK); | ||
| 1442 | EXPECT_HR(gpu.fence->SetEventOnCompletion(1, gpu.done), S_OK); | ||
| 1443 | EXPECT(WaitForSingleObject(gpu.done, 30000) == WAIT_OBJECT_0); | ||
| 1444 | void* read = nullptr; | ||
| 1445 | EXPECT_HR(gpu.readback->Map(0, nullptr, &read), S_OK); | ||
| 1446 | const auto* bytes = static_cast<const std::uint8_t*>(read); | ||
| 1447 | const bool filled = std::all_of(bytes, bytes + size, [](auto value) { return value == 61; }); | ||
| 1448 | gpu.readback->Unmap(0, nullptr); | ||
| 1449 | EXPECT(filled); | ||
| 1450 | texture->Unmap(0, nullptr); | ||
| 1451 | texture.p->Release(); | ||
| 1452 | texture.p = nullptr; | ||
| 1453 | VirtualFree(pages, 0, MEM_RELEASE); | ||
| 1454 | return 0; | ||
| 1455 | } | ||
| 1456 | |||
| 1405 | // Several threads write the same watched pages while submissions keep making them read-only again. Two threads that | 1457 | // Several threads write the same watched pages while submissions keep making them read-only again. Two threads that |
| 1406 | // fault on one page race: the first fault reopens it, a submission can protect it again before the second fault is | 1458 | // fault on one page race: the first fault reopens it, a submission can protect it again before the second fault is |
| 1407 | // handled, and the second write must still be retried, not refused (refused, the process ends: seen natively). After | 1459 | // handled, and the second write must still be retried, not refused (refused, the process ends: seen natively). After |
| @@ -1990,7 +2042,9 @@ void print_cases(const std::vector<Case>& cases, const char* who) { | |||
| 1990 | 2042 | ||
| 1991 | int main(int argc, char** argv) { | 2043 | int main(int argc, char** argv) { |
| 1992 | const bool prefix_only = argc == 2 && std::strcmp(argv[1], "--host-prefix-only") == 0; | 2044 | const bool prefix_only = argc == 2 && std::strcmp(argv[1], "--host-prefix-only") == 0; |
| 1993 | if (argc != 1 && !prefix_only) return 2; | 2045 | const bool async_plane = argc == 2 && std::strcmp(argv[1], "--mapped-plane-async") == 0; |
| 2046 | if (argc != 1 && !prefix_only && !async_plane) return 2; | ||
| 2047 | if (async_plane) _putenv_s("LEONIDA_TEXTURE_REFRESH_ASYNC", "1"); // read once, at the device's first refresh | ||
| 1994 | _putenv_s("LEONIDA_TITLE_TEXTURE_PERIOD_MS", "0"); | 2048 | _putenv_s("LEONIDA_TITLE_TEXTURE_PERIOD_MS", "0"); |
| 1995 | _putenv_s("LEONIDA_TITLE_TEXTURE_CHECK_KB", "0"); | 2049 | _putenv_s("LEONIDA_TITLE_TEXTURE_CHECK_KB", "0"); |
| 1996 | vktest::Device vk; | 2050 | vktest::Device vk; |
| @@ -2018,6 +2072,15 @@ int main(int argc, char** argv) { | |||
| 2018 | const int result = check_host_prefix_buffers(ours.p); | 2072 | const int result = check_host_prefix_buffers(ours.p); |
| 2019 | return result || vk.validation_errors() ? 1 : 0; | 2073 | return result || vk.validation_errors() ? 1 : 0; |
| 2020 | } | 2074 | } |
| 2075 | if (async_plane) { | ||
| 2076 | int result = vk.host_image_copy ? check_mapped_plane_first_use(ours.p) : 0; | ||
| 2077 | auto no_host_copy = info; // the staged upload too | ||
| 2078 | no_host_copy.host_image_copy = false; | ||
| 2079 | Ref<ID3D12Device> staged; | ||
| 2080 | if (FAILED(rt::d3d12::create_vulkan_device(no_host_copy, IID_PPV_ARGS(&staged.p)))) return 1; | ||
| 2081 | result += check_mapped_plane_first_use(staged.p); | ||
| 2082 | return result || vk.validation_errors() ? 1 : 0; | ||
| 2083 | } | ||
| 2021 | failures += check(ours.p, "vulkan"); | 2084 | failures += check(ours.p, "vulkan"); |
| 2022 | const std::vector<Case> vulkan_cases = open_cases(ours.p); | 2085 | const std::vector<Case> vulkan_cases = open_cases(ours.p); |
| 2023 | print_cases(vulkan_cases, "vulkan"); | 2086 | print_cases(vulkan_cases, "vulkan"); |
diff --git a/runtime/test/d3d12_f16_halves_test.cpp b/runtime/test/d3d12_f16_halves_test.cpp index bbd516e5c..866153041 100644 --- a/runtime/test/d3d12_f16_halves_test.cpp +++ b/runtime/test/d3d12_f16_halves_test.cpp | |||
| @@ -123,6 +123,61 @@ std::vector<std::uint32_t> make_16param_vs() { | |||
| 123 | return w; | 123 | return w; |
| 124 | } | 124 | } |
| 125 | 125 | ||
| 126 | // Fullscreen triangle VS exporting 10 raw params (0..9) with packed f16 bits in param7. | ||
| 127 | std::vector<std::uint32_t> make_10param_vs() { | ||
| 128 | constexpr std::uint32_t kBound = 45; | ||
| 129 | std::vector<std::uint32_t> w = {kSpirvMagic, 0x00010500u, 0, kBound, 0}; | ||
| 130 | put_inst(w, kOpCapability, {1}); | ||
| 131 | put_inst(w, kOpMemoryModel, {0, 1}); | ||
| 132 | std::vector<std::uint32_t> ep = {kExecModelVertex, 24, 0x6e69616du, 0x00000000u, 8, 9}; | ||
| 133 | for (std::uint32_t id = 31; id <= 40; ++id) ep.push_back(id); | ||
| 134 | put_inst_vec(w, kOpEntryPoint, ep); | ||
| 135 | |||
| 136 | put_inst(w, kOpDecorate, {8, 11, 42}); // BuiltIn VertexIndex | ||
| 137 | put_inst(w, kOpDecorate, {9, 11, 0}); // BuiltIn Position | ||
| 138 | for (std::uint32_t p = 0; p < 10; ++p) put_inst(w, kOpDecorate, {31 + p, kDecorationLocation, p}); | ||
| 139 | |||
| 140 | put_inst(w, 19, {1}); | ||
| 141 | put_inst(w, 33, {2, 1}); | ||
| 142 | put_inst(w, kOpTypeFloat, {3, 32}); | ||
| 143 | put_inst(w, kOpTypeVector, {4, 3, 4}); | ||
| 144 | put_inst(w, kOpTypeInt, {5, 32, 1}); | ||
| 145 | put_inst(w, kOpTypePointer, {6, kStorageInput, 5}); | ||
| 146 | put_inst(w, kOpTypePointer, {7, kStorageOutput, 4}); | ||
| 147 | put_inst(w, 20, {20}); | ||
| 148 | |||
| 149 | put_inst(w, kOpConstantNull, {4, 10}); | ||
| 150 | put_inst(w, 43, {3, 11, 0xbf800000u}); | ||
| 151 | put_inst(w, 43, {3, 12, 0x40400000u}); | ||
| 152 | put_inst(w, 43, {3, 13, 0x00000000u}); | ||
| 153 | put_inst(w, 43, {3, 14, 0x3f800000u}); | ||
| 154 | put_inst(w, 44, {4, 15, 11, 11, 13, 14}); | ||
| 155 | put_inst(w, 44, {4, 16, 12, 11, 13, 14}); | ||
| 156 | put_inst(w, 44, {4, 17, 11, 12, 13, 14}); | ||
| 157 | put_inst(w, 43, {5, 18, 0u}); | ||
| 158 | put_inst(w, 43, {5, 19, 1u}); | ||
| 159 | put_inst(w, 43, {3, 21, 0x3a003400u}); | ||
| 160 | put_inst(w, 43, {3, 22, 0x3c003800u}); | ||
| 161 | put_inst(w, 44, {4, 23, 21, 22, 13, 14}); | ||
| 162 | |||
| 163 | put_inst(w, kOpVariable, {6, 8, kStorageInput}); | ||
| 164 | put_inst(w, kOpVariable, {7, 9, kStorageOutput}); | ||
| 165 | for (std::uint32_t id = 31; id <= 40; ++id) put_inst(w, kOpVariable, {7, id, kStorageOutput}); | ||
| 166 | |||
| 167 | put_inst(w, kOpFunction, {1, 24, 0, 2}); | ||
| 168 | put_inst(w, 248, {25}); | ||
| 169 | put_inst(w, kOpLoad, {5, 26, 8}); | ||
| 170 | put_inst(w, 170, {20, 27, 26, 18}); | ||
| 171 | put_inst(w, 170, {20, 28, 26, 19}); | ||
| 172 | put_inst(w, 169, {4, 29, 28, 16, 17}); | ||
| 173 | put_inst(w, 169, {4, 30, 27, 15, 29}); | ||
| 174 | put_inst(w, kOpStore, {9, 30}); | ||
| 175 | for (std::uint32_t p = 0; p < 10; ++p) put_inst(w, kOpStore, {31 + p, p == 7 ? 23u : 10u}); | ||
| 176 | put_inst(w, kOpReturn, {}); | ||
| 177 | put_inst(w, kOpFunctionEnd, {}); | ||
| 178 | return w; | ||
| 179 | } | ||
| 180 | |||
| 126 | // Fragment shader reading `num_raw` raw inputs (Location 0..num_raw-1) plus decoded halves of param7 at | 181 | // Fragment shader reading `num_raw` raw inputs (Location 0..num_raw-1) plus decoded halves of param7 at |
| 127 | // `lo_loc` and `hi_loc`, writing vec4(lo.x, hi.x, lo.y, hi.y) to MRT 0. | 182 | // `lo_loc` and `hi_loc`, writing vec4(lo.x, hi.x, lo.y, hi.y) to MRT 0. |
| 128 | std::vector<std::uint32_t> make_f16_ps(std::uint32_t num_raw, std::uint32_t lo_loc, std::uint32_t hi_loc) { | 183 | std::vector<std::uint32_t> make_f16_ps(std::uint32_t num_raw, std::uint32_t lo_loc, std::uint32_t hi_loc) { |
| @@ -184,27 +239,38 @@ int main() { | |||
| 184 | const auto vs_prog = fssm_program({0x56530378, 0xbf810000}); | 239 | const auto vs_prog = fssm_program({0x56530378, 0xbf810000}); |
| 185 | const auto ps1_prog = fssm_program({0x50530378, 0x00000001}); | 240 | const auto ps1_prog = fssm_program({0x50530378, 0x00000001}); |
| 186 | const auto ps2_prog = fssm_program({0x50530378, 0x00000002}); | 241 | const auto ps2_prog = fssm_program({0x50530378, 0x00000002}); |
| 242 | const auto vs_low_prog = fssm_program({0x56530378, 0xbf810010}); | ||
| 243 | const auto ps_low_prog = fssm_program({0x50530378, 0x00000010}); | ||
| 187 | const auto vs_c = shader_container(vs_prog); | 244 | const auto vs_c = shader_container(vs_prog); |
| 188 | const auto ps1_c = shader_container(ps1_prog); | 245 | const auto ps1_c = shader_container(ps1_prog); |
| 189 | const auto ps2_c = shader_container(ps2_prog); | 246 | const auto ps2_c = shader_container(ps2_prog); |
| 247 | const auto vs_low_c = shader_container(vs_low_prog); | ||
| 248 | const auto ps_low_c = shader_container(ps_low_prog); | ||
| 190 | 249 | ||
| 191 | const auto lib_dir = std::filesystem::temp_directory_path() / "leonida_f16_halves_gpu_test"; | 250 | const auto lib_dir = std::filesystem::temp_directory_path() / "leonida_f16_halves_gpu_test"; |
| 192 | std::filesystem::create_directories(lib_dir); | 251 | std::filesystem::create_directories(lib_dir); |
| 193 | write_spv(lib_dir / "vs_16p.spv", make_16param_vs()); | 252 | write_spv(lib_dir / "vs_16p.spv", make_16param_vs()); |
| 253 | write_spv(lib_dir / "vs_10p.spv", make_10param_vs()); | ||
| 194 | write_spv(lib_dir / "ps_packed.spv", make_f16_ps(15, 20, 21)); | 254 | write_spv(lib_dir / "ps_packed.spv", make_f16_ps(15, 20, 21)); |
| 195 | write_spv(lib_dir / "ps_reloc.spv", make_f16_ps(14, 14, 15)); | 255 | write_spv(lib_dir / "ps_reloc.spv", make_f16_ps(14, 14, 15)); |
| 256 | write_spv(lib_dir / "ps_low.spv", make_f16_ps(8, 8, 9)); | ||
| 196 | { | 257 | { |
| 197 | std::ofstream idx(lib_dir / "index.json", std::ios::binary | std::ios::trunc); | 258 | std::ofstream idx(lib_dir / "index.json", std::ios::binary | std::ios::trunc); |
| 198 | idx << "{\"vs_16p\": {\"stage\": \"vs\", \"fssm_sha256\": \"" << leonida::sha256_hex(vs_prog) | 259 | idx << "{\"vs_16p\": {\"stage\": \"vs\", \"fssm_sha256\": \"" << leonida::sha256_hex(vs_prog) |
| 199 | << "\", \"bindings\": [], \"push_constant_bytes\": 144, \"input_signature\": [], " | 260 | << "\", \"bindings\": [], \"push_constant_bytes\": 144, \"input_signature\": [], " |
| 200 | "\"f16_halves\": {\"0\": [28, 29], \"1\": [26, 27], \"2\": [24, 25], \"3\": [22, 23], " | 261 | "\"f16_halves\": {\"0\": [28, 29], \"1\": [26, 27], \"2\": [24, 25], \"3\": [22, 23], " |
| 201 | "\"4\": [20, 21], \"5\": [18, 19], \"6\": [16, 17]}},\n" | 262 | "\"4\": [20, 21], \"5\": [18, 19], \"6\": [16, 17]}},\n" |
| 263 | " \"vs_10p\": {\"stage\": \"vs\", \"fssm_sha256\": \"" << leonida::sha256_hex(vs_low_prog) | ||
| 264 | << "\", \"bindings\": [], \"push_constant_bytes\": 144, \"input_signature\": [], \"f16_halves\": {}},\n" | ||
| 202 | " \"ps_packed\": {\"stage\": \"ps\", \"fssm_sha256\": \"" << leonida::sha256_hex(ps1_prog) | 265 | " \"ps_packed\": {\"stage\": \"ps\", \"fssm_sha256\": \"" << leonida::sha256_hex(ps1_prog) |
| 203 | << "\", \"bindings\": [], \"push_constant_bytes\": 144, \"outputs\": [0], " | 266 | << "\", \"bindings\": [], \"push_constant_bytes\": 144, \"outputs\": [0], " |
| 204 | "\"f16_halves\": {\"7\": [20, 21]}},\n" | 267 | "\"f16_halves\": {\"7\": [20, 21]}},\n" |
| 205 | " \"ps_reloc\": {\"stage\": \"ps\", \"fssm_sha256\": \"" << leonida::sha256_hex(ps2_prog) | 268 | " \"ps_reloc\": {\"stage\": \"ps\", \"fssm_sha256\": \"" << leonida::sha256_hex(ps2_prog) |
| 206 | << "\", \"bindings\": [], \"push_constant_bytes\": 144, \"outputs\": [0], " | 269 | << "\", \"bindings\": [], \"push_constant_bytes\": 144, \"outputs\": [0], " |
| 207 | "\"f16_halves\": {\"7\": [14, 15]}}}"; | 270 | "\"f16_halves\": {\"7\": [14, 15]}},\n" |
| 271 | " \"ps_low\": {\"stage\": \"ps\", \"fssm_sha256\": \"" << leonida::sha256_hex(ps_low_prog) | ||
| 272 | << "\", \"bindings\": [], \"push_constant_bytes\": 144, \"outputs\": [0], " | ||
| 273 | "\"f16_halves\": {\"7\": [8, 9]}}}"; | ||
| 208 | } | 274 | } |
| 209 | 275 | ||
| 210 | rt::d3d12::VulkanDeviceInfo info{}; | 276 | rt::d3d12::VulkanDeviceInfo info{}; |
| @@ -363,5 +429,151 @@ int main() { | |||
| 363 | 429 | ||
| 364 | EXPECT(run_case("ps_packed (synth param7 + demote static halves)", ps1_c)); | 430 | EXPECT(run_case("ps_packed (synth param7 + demote static halves)", ps1_c)); |
| 365 | EXPECT(run_case("ps_reloc (relocate colliding PS + VS halves to 28,29)", ps2_c)); | 431 | EXPECT(run_case("ps_reloc (relocate colliding PS + VS halves to 28,29)", ps2_c)); |
| 432 | |||
| 433 | // Verify low f16_half_top_location (14) through CreateGraphicsPipelineState and lazy build at first draw: | ||
| 434 | { | ||
| 435 | rt::d3d12::VulkanDeviceInfo low_info = info; | ||
| 436 | low_info.f16_half_top_location = 14; | ||
| 437 | |||
| 438 | ID3D12Device* low_inner = nullptr; | ||
| 439 | EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(low_info, IID_PPV_ARGS(&low_inner)))); | ||
| 440 | Ref<ID3D12Device> low_device; | ||
| 441 | EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(low_inner, __uuidof(ID3D12Device), | ||
| 442 | reinterpret_cast<void**>(&low_device.p), false))); | ||
| 443 | rt::d3d12::set_device_outer(low_inner, low_device.p); | ||
| 444 | |||
| 445 | Ref<ID3D12RootSignature> low_root; | ||
| 446 | EXPECT(SUCCEEDED(low_device->CreateRootSignature(0, root_blob.data(), root_blob.size(), IID_PPV_ARGS(&low_root.p)))); | ||
| 447 | |||
| 448 | // 1. Out-of-budget pipeline with 16 params rejected at CreateGraphicsPipelineState | ||
| 449 | D3D12_GRAPHICS_PIPELINE_STATE_DESC oob_pd{}; | ||
| 450 | oob_pd.pRootSignature = low_root.p; | ||
| 451 | oob_pd.VS = {vs_c.data(), vs_c.size()}; | ||
| 452 | oob_pd.PS = {ps2_c.data(), ps2_c.size()}; | ||
| 453 | oob_pd.BlendState.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL; | ||
| 454 | oob_pd.SampleMask = 0xffffffffu; | ||
| 455 | oob_pd.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID; | ||
| 456 | oob_pd.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; | ||
| 457 | oob_pd.RasterizerState.DepthClipEnable = TRUE; | ||
| 458 | oob_pd.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; | ||
| 459 | oob_pd.NumRenderTargets = 1; | ||
| 460 | oob_pd.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM; | ||
| 461 | oob_pd.SampleDesc.Count = 1; | ||
| 462 | Ref<ID3D12PipelineState> oob_pso; | ||
| 463 | EXPECT(FAILED(low_device->CreateGraphicsPipelineState(&oob_pd, IID_PPV_ARGS(&oob_pso.p)))); | ||
| 464 | std::printf("ps_oob (16 raw params rejected with top_location 14) OK\n"); | ||
| 465 | |||
| 466 | // 2. In-budget pipeline (10 params, halves relocated to 13,14) created and executed lazily on draw | ||
| 467 | Ref<ID3D12CommandQueue> low_queue; | ||
| 468 | EXPECT(SUCCEEDED(low_device->CreateCommandQueue(&qd, IID_PPV_ARGS(&low_queue.p)))); | ||
| 469 | Ref<ID3D12CommandAllocator> low_alloc; | ||
| 470 | EXPECT(SUCCEEDED(low_device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&low_alloc.p)))); | ||
| 471 | Ref<ID3D12GraphicsCommandList> low_list; | ||
| 472 | EXPECT(SUCCEEDED(low_device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, low_alloc.p, nullptr, | ||
| 473 | IID_PPV_ARGS(&low_list.p)))); | ||
| 474 | EXPECT(SUCCEEDED(low_list->Close())); | ||
| 475 | Ref<ID3D12Fence> low_fence; | ||
| 476 | EXPECT(SUCCEEDED(low_device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&low_fence.p)))); | ||
| 477 | |||
| 478 | Ref<ID3D12Resource> low_rt_res; | ||
| 479 | EXPECT(SUCCEEDED(low_device->CreateCommittedResource(&default_hp, D3D12_HEAP_FLAG_NONE, &rt_desc, | ||
| 480 | D3D12_RESOURCE_STATE_RENDER_TARGET, nullptr, | ||
| 481 | IID_PPV_ARGS(&low_rt_res.p)))); | ||
| 482 | Ref<ID3D12DescriptorHeap> low_rtv_heap; | ||
| 483 | EXPECT(SUCCEEDED(low_device->CreateDescriptorHeap(&rtv_hd, IID_PPV_ARGS(&low_rtv_heap.p)))); | ||
| 484 | const D3D12_CPU_DESCRIPTOR_HANDLE low_rtv_h{ | ||
| 485 | SIZE_T(reinterpret_cast<XboxHeapHandleFn>(slot(low_rtv_heap.p, 9))(low_rtv_heap.p))}; | ||
| 486 | low_device->CreateRenderTargetView(low_rt_res.p, nullptr, low_rtv_h); | ||
| 487 | |||
| 488 | Ref<ID3D12Resource> low_rb_res; | ||
| 489 | EXPECT(SUCCEEDED(low_device->CreateCommittedResource(&rb_hp, D3D12_HEAP_FLAG_NONE, &rb_desc, | ||
| 490 | D3D12_RESOURCE_STATE_COPY_DEST, nullptr, | ||
| 491 | IID_PPV_ARGS(&low_rb_res.p)))); | ||
| 492 | |||
| 493 | D3D12_GRAPHICS_PIPELINE_STATE_DESC in_pd = oob_pd; | ||
| 494 | in_pd.VS = {vs_low_c.data(), vs_low_c.size()}; | ||
| 495 | in_pd.PS = {ps_low_c.data(), ps_low_c.size()}; | ||
| 496 | Ref<ID3D12PipelineState> low_pso; | ||
| 497 | EXPECT(SUCCEEDED(low_device->CreateGraphicsPipelineState(&in_pd, IID_PPV_ARGS(&low_pso.p)))); | ||
| 498 | EXPECT(SUCCEEDED(low_alloc->Reset())); | ||
| 499 | EXPECT(SUCCEEDED(low_list->Reset(low_alloc.p, low_pso.p))); | ||
| 500 | const float clear_col[4] = {0.0f, 0.0f, 0.0f, 0.0f}; | ||
| 501 | low_list->ClearRenderTargetView(low_rtv_h, clear_col, 0, nullptr); | ||
| 502 | low_list->OMSetRenderTargets(1, &low_rtv_h, FALSE, nullptr); | ||
| 503 | const D3D12_VIEWPORT vp = {0.0f, 0.0f, float(kSize), float(kSize), 0.0f, 1.0f}; | ||
| 504 | const D3D12_RECT sc = {0, 0, LONG(kSize), LONG(kSize)}; | ||
| 505 | low_list->RSSetViewports(1, &vp); | ||
| 506 | low_list->RSSetScissorRects(1, &sc); | ||
| 507 | low_list->SetGraphicsRootSignature(low_root.p); | ||
| 508 | low_list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); | ||
| 509 | low_list->DrawInstanced(3, 1, 0, 0); | ||
| 510 | |||
| 511 | D3D12_RESOURCE_BARRIER to_copy{}; | ||
| 512 | to_copy.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; | ||
| 513 | to_copy.Transition = {low_rt_res.p, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, | ||
| 514 | D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE}; | ||
| 515 | low_list->ResourceBarrier(1, &to_copy); | ||
| 516 | D3D12_TEXTURE_COPY_LOCATION dst{}; | ||
| 517 | dst.pResource = low_rb_res.p; | ||
| 518 | dst.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; | ||
| 519 | dst.PlacedFootprint.Footprint = {DXGI_FORMAT_R8G8B8A8_UNORM, kSize, kSize, 1, 256}; | ||
| 520 | D3D12_TEXTURE_COPY_LOCATION src{}; | ||
| 521 | src.pResource = low_rt_res.p; | ||
| 522 | src.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; | ||
| 523 | low_list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); | ||
| 524 | D3D12_RESOURCE_BARRIER to_rt = to_copy; | ||
| 525 | to_rt.Transition.StateBefore = D3D12_RESOURCE_STATE_COPY_SOURCE; | ||
| 526 | to_rt.Transition.StateAfter = D3D12_RESOURCE_STATE_RENDER_TARGET; | ||
| 527 | low_list->ResourceBarrier(1, &to_rt); | ||
| 528 | EXPECT(SUCCEEDED(low_list->Close())); | ||
| 529 | |||
| 530 | ID3D12CommandList* cl = low_list.p; | ||
| 531 | low_queue->ExecuteCommandLists(1, &cl); | ||
| 532 | EXPECT(SUCCEEDED(low_queue->Signal(low_fence.p, 1))); | ||
| 533 | EXPECT(SUCCEEDED(low_fence->SetEventOnCompletion(1, nullptr))); | ||
| 534 | |||
| 535 | void* mapped = nullptr; | ||
| 536 | const D3D12_RANGE read_range = {0, kSize * 256}; | ||
| 537 | EXPECT(SUCCEEDED(low_rb_res->Map(0, &read_range, &mapped)) && mapped != nullptr); | ||
| 538 | const auto* px = static_cast<const std::uint8_t*>(mapped) + (kSize / 2) * 256 + (kSize / 2) * 4; | ||
| 539 | const int r = px[0], g = px[1], b = px[2], a = px[3]; | ||
| 540 | low_rb_res->Unmap(0, nullptr); | ||
| 541 | const bool ok = std::abs(r - 64) <= 1 && std::abs(g - 191) <= 1 && std::abs(b - 128) <= 1 && a == 255; | ||
| 542 | if (!ok) { | ||
| 543 | std::fprintf(stderr, "ps_low_top_location (lazy build at first draw with top_location 14): pixel=(%d,%d,%d,%d), expected~(64,191,128,255)\n", r, g, b, a); | ||
| 544 | return 1; | ||
| 545 | } | ||
| 546 | std::printf("ps_low_top_location (lazy build at first draw with top_location 14): rendered pixel=(%d,%d,%d,%d) OK\n", r, g, b, a); | ||
| 547 | |||
| 548 | // Check the linked SPIR-V stage modules: with f16_half_top_location = 14, every relocated f16 | ||
| 549 | // output/input Location must be <= 14 (specifically, relocated to 13 and 14). Without the fix, | ||
| 550 | // stage_words() defaulted top_location to 29 and relocated them to Location 28 & 29. | ||
| 551 | std::vector<std::vector<std::uint32_t>> words; | ||
| 552 | std::string stage_error; | ||
| 553 | EXPECT(rt::d3d12::pipeline_stage_words(low_pso.p, words, stage_error)); | ||
| 554 | EXPECT(words.size() >= 2); | ||
| 555 | for (std::size_t s = 0; s < 2; ++s) { | ||
| 556 | Module mod; | ||
| 557 | EXPECT(mod.parse(words[s])); | ||
| 558 | std::uint32_t highest_loc = 0; | ||
| 559 | for (const auto& inst : mod.insts) { | ||
| 560 | if (inst.opcode == kOpDecorate && inst.words.size() >= 4 && inst.words[2] == kDecorationLocation) { | ||
| 561 | highest_loc = std::max(highest_loc, inst.words[3]); | ||
| 562 | } | ||
| 563 | } | ||
| 564 | if (highest_loc > 14) { | ||
| 565 | std::fprintf(stderr, "ps_low_top_location stage %zu highest Location %u exceeds top_location 14\n", | ||
| 566 | s, highest_loc); | ||
| 567 | return 1; | ||
| 568 | } | ||
| 569 | if (highest_loc != 14) { | ||
| 570 | std::fprintf(stderr, "ps_low_top_location stage %zu expected highest Location 14, got %u\n", | ||
| 571 | s, highest_loc); | ||
| 572 | return 1; | ||
| 573 | } | ||
| 574 | std::printf("ps_low_top_location stage %zu linked SPIR-V highest Location=%u <= 14 OK\n", s, highest_loc); | ||
| 575 | } | ||
| 576 | } | ||
| 577 | |||
| 366 | return 0; | 578 | return 0; |
| 367 | } | 579 | } |
diff --git a/runtime/test/d3d12_indirect_rt_test.cpp b/runtime/test/d3d12_indirect_rt_test.cpp index 3a58e48c0..7b237ef30 100644 --- a/runtime/test/d3d12_indirect_rt_test.cpp +++ b/runtime/test/d3d12_indirect_rt_test.cpp | |||
| @@ -1,12 +1,18 @@ | |||
| 1 | // Real GPU test for: | 1 | // Real GPU test for: |
| 2 | // 1) D3D12 draw-signature creation and a native Vulkan counted-draw pixel reference. | 2 | // Real GPU test for: |
| 3 | // The pixel reference tests suballocated argument/count offsets, not D3D12 command replay. | 3 | // 1) ExecuteIndirect with CountBuffer (ID3D12Device::CreateCommandSignature + |
| 4 | // ID3D12GraphicsCommandList::ExecuteIndirect -> vkCmdDrawIndirectCount, Vulkan 1.2 core), and the argument clamp | ||
| 5 | // pass (runtime/src/vulkan_indirect_clamp.h): a draw record asking for four billion instances is clamped on the | ||
| 6 | // GPU and renders the same triangle as the in-range one, instead of running until the host resets the driver. | ||
| 7 | // The same pixel reference is also run natively: D3D12 draw-signature creation and a Vulkan counted-draw pixel | ||
| 8 | // reference over suballocated argument/count offsets, independent of the D3D12 command replay. | ||
| 4 | // 2) Hardware Ray Tracing / BVH (ID3D12Device5::GetRaytracingAccelerationStructurePrebuildInfo + | 9 | // 2) Hardware Ray Tracing / BVH (ID3D12Device5::GetRaytracingAccelerationStructurePrebuildInfo + |
| 5 | // ID3D12GraphicsCommandList4::BuildRaytracingAccelerationStructure BLAS + TLAS + RayQueryKHR | 10 | // ID3D12GraphicsCommandList4::BuildRaytracingAccelerationStructure BLAS + TLAS + RayQueryKHR |
| 6 | // hit vs. miss; clean SKIP on GPUs without VK_KHR_acceleration_structure / VK_KHR_ray_query). | 11 | // hit vs. miss; clean SKIP on GPUs without VK_KHR_acceleration_structure / VK_KHR_ray_query). |
| 7 | // Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation (Core + Synchronization Validation). | 12 | // Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation (Core + Synchronization Validation). |
| 8 | 13 | ||
| 9 | #include "../shims/d3d12_com.h" | 14 | #include "../shims/d3d12_com.h" |
| 15 | #include "../src/vulkan_indirect_clamp.h" | ||
| 10 | #include "vulkan_loader.h" | 16 | #include "vulkan_loader.h" |
| 11 | #include "../src/vulkan_device_filter.h" | 17 | #include "../src/vulkan_device_filter.h" |
| 12 | 18 | ||
| @@ -76,6 +82,38 @@ D3D12_RESOURCE_DESC make_buf_desc(UINT64 bytes, D3D12_RESOURCE_FLAGS flags = D3D | |||
| 76 | return d; | 82 | return d; |
| 77 | } | 83 | } |
| 78 | 84 | ||
| 85 | // A driver whose GENERIC acceleration structures do not sit at buffer address + offset, through the device's own | ||
| 86 | // function lookup (VulkanDeviceInfo::get_instance_proc): vkGetAccelerationStructureDeviceAddressKHR answers the real | ||
| 87 | // address plus kShiftedAsDelta. Only resource creation and the address lookup run on such a device, no builds: the | ||
| 88 | // shifted address names no real structure. | ||
| 89 | constexpr VkDeviceAddress kShiftedAsDelta = 0x10000000; | ||
| 90 | PFN_vkGetInstanceProcAddr g_real_gipa = nullptr; | ||
| 91 | PFN_vkGetDeviceProcAddr g_real_gdpa = nullptr; | ||
| 92 | PFN_vkGetAccelerationStructureDeviceAddressKHR g_real_as_address = nullptr; | ||
| 93 | |||
| 94 | VKAPI_ATTR VkDeviceAddress VKAPI_CALL shifted_as_address(VkDevice device, | ||
| 95 | const VkAccelerationStructureDeviceAddressInfoKHR* info) { | ||
| 96 | const VkDeviceAddress real = g_real_as_address(device, info); | ||
| 97 | return real ? real + kShiftedAsDelta : 0; | ||
| 98 | } | ||
| 99 | |||
| 100 | VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL shifted_gdpa(VkDevice device, const char* name) { | ||
| 101 | if (!std::strcmp(name, "vkGetAccelerationStructureDeviceAddressKHR")) { | ||
| 102 | g_real_as_address = | ||
| 103 | reinterpret_cast<PFN_vkGetAccelerationStructureDeviceAddressKHR>(g_real_gdpa(device, name)); | ||
| 104 | return g_real_as_address ? reinterpret_cast<PFN_vkVoidFunction>(&shifted_as_address) : nullptr; | ||
| 105 | } | ||
| 106 | return g_real_gdpa(device, name); | ||
| 107 | } | ||
| 108 | |||
| 109 | VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL shifted_gipa(VkInstance instance, const char* name) { | ||
| 110 | if (!std::strcmp(name, "vkGetDeviceProcAddr")) { | ||
| 111 | g_real_gdpa = reinterpret_cast<PFN_vkGetDeviceProcAddr>(g_real_gipa(instance, name)); | ||
| 112 | return reinterpret_cast<PFN_vkVoidFunction>(&shifted_gdpa); | ||
| 113 | } | ||
| 114 | return g_real_gipa(instance, name); | ||
| 115 | } | ||
| 116 | |||
| 79 | } // namespace | 117 | } // namespace |
| 80 | 118 | ||
| 81 | int main() { | 119 | int main() { |
| @@ -291,6 +329,7 @@ int main() { | |||
| 291 | DF(vkCreateComputePipelines); | 329 | DF(vkCreateComputePipelines); |
| 292 | DF(vkDestroyPipeline); | 330 | DF(vkDestroyPipeline); |
| 293 | DF(vkCreateDescriptorSetLayout); | 331 | DF(vkCreateDescriptorSetLayout); |
| 332 | DF(vkGetAccelerationStructureDeviceAddressKHR); | ||
| 294 | DF(vkDestroyDescriptorSetLayout); | 333 | DF(vkDestroyDescriptorSetLayout); |
| 295 | DF(vkCreateDescriptorPool); | 334 | DF(vkCreateDescriptorPool); |
| 296 | DF(vkDestroyDescriptorPool); | 335 | DF(vkDestroyDescriptorPool); |
| @@ -500,6 +539,51 @@ int main() { | |||
| 500 | cbai.commandBufferCount = 1; | 539 | cbai.commandBufferCount = 1; |
| 501 | vkAllocateCommandBuffers(vk_dev, &cbai, &cb); | 540 | vkAllocateCommandBuffers(vk_dev, &cbai, &cb); |
| 502 | 541 | ||
| 542 | leonida::ReplayFunctions rf{}; | ||
| 543 | rf.external_graphics_scope = true; // bind the graphics pipeline inside our own rendering scope below | ||
| 544 | rf.draw_indirect_count = vkCmdDrawIndirectCount; | ||
| 545 | // The argument clamp pass (runtime/src/vulkan_indirect_clamp.h), installed as gta6rt installs it: every | ||
| 546 | // record of the ExecuteIndirect is copied on the GPU into scratch with its values bounded before the draw | ||
| 547 | // reads it, so a record left by a skipped compute pass cannot ask for four billion vertices or instances. | ||
| 548 | // A device without bufferDeviceAddress keeps the raw path. | ||
| 549 | VkPhysicalDeviceMemoryProperties mem_props{}; | ||
| 550 | reinterpret_cast<PFN_vkGetPhysicalDeviceMemoryProperties>( | ||
| 551 | gipa(instance, "vkGetPhysicalDeviceMemoryProperties"))(physical, &mem_props); | ||
| 552 | const auto clamp_allocate = [&](const VkMemoryRequirements& requirements) -> VkDeviceMemory { | ||
| 553 | VkMemoryAllocateFlagsInfo flags{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO}; | ||
| 554 | flags.flags = VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT; | ||
| 555 | VkMemoryAllocateInfo ai{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, &flags}; | ||
| 556 | ai.allocationSize = requirements.size; | ||
| 557 | const auto allocate = reinterpret_cast<PFN_vkAllocateMemory>(gdpa(vk_dev, "vkAllocateMemory")); | ||
| 558 | for (const std::uint32_t type : leonida::memory_type_order(mem_props, requirements.memoryTypeBits, | ||
| 559 | VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, 0, | ||
| 560 | requirements.size)) { | ||
| 561 | ai.memoryTypeIndex = type; | ||
| 562 | VkDeviceMemory out = VK_NULL_HANDLE; | ||
| 563 | if (allocate(vk_dev, &ai, nullptr, &out) == VK_SUCCESS) return out; | ||
| 564 | } | ||
| 565 | return VK_NULL_HANDLE; | ||
| 566 | }; | ||
| 567 | leonida::IndirectArgumentClamp clamp(gdpa, vk_dev, mem_props, chosen.limits, clamp_allocate); | ||
| 568 | auto clamp_batch = clamp.batch(); | ||
| 569 | // LEONIDA_INDIRECT_CLAMP=0 turns the pass off at replay time, and then the raw argument buffer is read | ||
| 570 | // again: this test must not record its own pass either. | ||
| 571 | const bool clamp_on = clamp.loaded() && leonida::indirect_clamp_enabled(); | ||
| 572 | if (clamp_on) { | ||
| 573 | rf.prepare_indirect_clamp = [&clamp_batch](VkBuffer args, VkDeviceSize args_offset, VkBuffer count, | ||
| 574 | VkDeviceSize count_offset, std::uint32_t kind, | ||
| 575 | std::uint32_t stride, std::uint32_t max_count, | ||
| 576 | leonida::ClampedIndirect& out) { | ||
| 577 | return clamp_batch->prepare(args, args_offset, count, count_offset, kind, stride, max_count, out); | ||
| 578 | }; | ||
| 579 | rf.emit_indirect_clamp = [&clamp](VkCommandBuffer buffer, const leonida::ClampedIndirect& job) { | ||
| 580 | clamp.emit(buffer, job); | ||
| 581 | }; | ||
| 582 | } | ||
| 583 | |||
| 584 | // The native reference draws the same suballocated offsets with vkCmdDrawIndirectCount directly: a | ||
| 585 | // Vulkan-level pixel oracle for the counted draw, not a D3D12 command replay. Both bindings start after | ||
| 586 | // poison prefixes, and the buffer holds the same two records the command list replays below. | ||
| 503 | auto run_native_count = [&](VkDeviceSize count_offset, std::uint8_t exp_r, std::uint8_t exp_g, | 587 | auto run_native_count = [&](VkDeviceSize count_offset, std::uint8_t exp_r, std::uint8_t exp_g, |
| 504 | std::uint8_t exp_b) -> int { | 588 | std::uint8_t exp_b) -> int { |
| 505 | VkCommandBufferBeginInfo bi{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; | 589 | VkCommandBufferBeginInfo bi{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; |
| @@ -580,8 +664,166 @@ int main() { | |||
| 580 | return 0; | 664 | return 0; |
| 581 | }; | 665 | }; |
| 582 | 666 | ||
| 667 | // The same two records through the D3D12 command list and leonida::replay, so the ExecuteIndirect | ||
| 668 | // CountBuffer path - and the clamp pass it emits - is exercised, not just the native Vulkan call. | ||
| 669 | auto run_indirect_count = [&](std::uint64_t count_offset, std::uint8_t exp_r, std::uint8_t exp_g, | ||
| 670 | std::uint8_t exp_b) -> int { | ||
| 671 | leonida::CommandList ir; | ||
| 672 | ir.execute_indirect({leonida::IndirectKind::draw, sizeof(D3D12_DRAW_ARGUMENTS), 2u, | ||
| 673 | rt::d3d12::resource_id(arg_buf), 0, rt::d3d12::resource_id(count_buf), | ||
| 674 | count_offset}); | ||
| 675 | ir.close(); | ||
| 676 | |||
| 677 | // The clamp pass is recorded here, before the drawing scope: vkCmdCopyBuffer and a memory barrier with | ||
| 678 | // a transfer access are outside it (VUID-vkCmdCopyBuffer-renderpass), which is also where gta6rt | ||
| 679 | // emits it for an indirect draw. replay then reads the clamped scratch whose records it is told about. | ||
| 680 | leonida::ClampedIndirect clamped{}; | ||
| 681 | const bool has_clamp = clamp_on; | ||
| 682 | if (has_clamp) { | ||
| 683 | if (!clamp_batch->prepare(rt::d3d12::vulkan_buffer(arg_buf), argument_base, | ||
| 684 | rt::d3d12::vulkan_buffer(count_buf), count_base + count_offset, | ||
| 685 | leonida::indirect_clamp_draw, sizeof(D3D12_DRAW_ARGUMENTS), 2u, clamped)) | ||
| 686 | return fail("clamp prepare"); | ||
| 687 | } | ||
| 688 | |||
| 689 | VkCommandBufferBeginInfo bi{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; | ||
| 690 | bi.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; | ||
| 691 | vkBeginCommandBuffer(cb, &bi); | ||
| 692 | if (has_clamp) clamp.emit(cb, clamped); | ||
| 693 | |||
| 694 | VkImageMemoryBarrier b_to_rt{VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER}; | ||
| 695 | b_to_rt.srcAccessMask = 0; | ||
| 696 | b_to_rt.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; | ||
| 697 | b_to_rt.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED; | ||
| 698 | b_to_rt.newLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; | ||
| 699 | b_to_rt.image = rt::d3d12::vulkan_image(rt); | ||
| 700 | b_to_rt.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; | ||
| 701 | vkCmdPipelineBarrier(cb, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, | ||
| 702 | VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, 0, 0, nullptr, 0, nullptr, 1, | ||
| 703 | &b_to_rt); | ||
| 704 | |||
| 705 | VkRenderingAttachmentInfo att{VK_STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO}; | ||
| 706 | att.imageView = rt_view; | ||
| 707 | att.imageLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; | ||
| 708 | att.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; | ||
| 709 | att.storeOp = VK_ATTACHMENT_STORE_OP_STORE; | ||
| 710 | att.clearValue.color.float32[3] = 1.0f; | ||
| 711 | VkRenderingInfo ri{VK_STRUCTURE_TYPE_RENDERING_INFO}; | ||
| 712 | ri.renderArea = {{0, 0}, {kW, kH}}; | ||
| 713 | ri.layerCount = 1; | ||
| 714 | ri.colorAttachmentCount = 1; | ||
| 715 | ri.pColorAttachments = &att; | ||
| 716 | vkCmdBeginRendering(cb, &ri); | ||
| 717 | VkViewport vp{0, 0, float(kW), float(kH), 0, 1}; | ||
| 718 | VkRect2D sc{{0, 0}, {kW, kH}}; | ||
| 719 | vkCmdSetViewport(cb, 0, 1, &vp); | ||
| 720 | vkCmdSetScissor(cb, 0, 1, &sc); | ||
| 721 | vkCmdBindPipeline(cb, VK_PIPELINE_BIND_POINT_GRAPHICS, pso); | ||
| 722 | |||
| 723 | const auto resolver = [&](leonida::ResourceId id) -> const leonida::ResourceBinding* { | ||
| 724 | // Treat the two upload buffers as backing stores for slices that start after a prefix. | ||
| 725 | static leonida::ResourceBinding arg_b{}, cnt_b{}; | ||
| 726 | arg_b.buffer = rt::d3d12::vulkan_buffer(arg_buf); | ||
| 727 | arg_b.buffer_offset = argument_base; | ||
| 728 | arg_b.size = buffer_size - argument_base; | ||
| 729 | cnt_b.buffer = rt::d3d12::vulkan_buffer(count_buf); | ||
| 730 | cnt_b.buffer_offset = count_base; | ||
| 731 | cnt_b.size = buffer_size - count_base; | ||
| 732 | if (id == rt::d3d12::resource_id(arg_buf)) return &arg_b; | ||
| 733 | if (id == rt::d3d12::resource_id(count_buf)) return &cnt_b; | ||
| 734 | return nullptr; | ||
| 735 | }; | ||
| 736 | if (has_clamp) { | ||
| 737 | rf.prepare_indirect_clamp = [&clamped](VkBuffer, VkDeviceSize, VkBuffer, VkDeviceSize, std::uint32_t, | ||
| 738 | std::uint32_t, std::uint32_t, | ||
| 739 | leonida::ClampedIndirect& out) { | ||
| 740 | out = clamped; // prepared and emitted above, before the drawing scope | ||
| 741 | return true; | ||
| 742 | }; | ||
| 743 | rf.emit_indirect_clamp = [](VkCommandBuffer, const leonida::ClampedIndirect&) {}; | ||
| 744 | } else { | ||
| 745 | rf.prepare_indirect_clamp = {}; | ||
| 746 | rf.emit_indirect_clamp = {}; | ||
| 747 | } | ||
| 748 | const auto replayed = leonida::replay(ir, cb, resolver, rf); | ||
| 749 | if (replayed != leonida::ReplayResult::success) { | ||
| 750 | std::fprintf(stderr, "replay result %d (clamped=%d)\n", int(replayed), int(has_clamp)); | ||
| 751 | return fail("leonida::replay(ExecuteIndirect CountBuffer)"); | ||
| 752 | } | ||
| 753 | |||
| 754 | vkCmdEndRendering(cb); | ||
| 755 | |||
| 756 | VkImageMemoryBarrier b_to_src{VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER}; | ||
| 757 | b_to_src.srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; | ||
| 758 | b_to_src.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT; | ||
| 759 | b_to_src.oldLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; | ||
| 760 | b_to_src.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; | ||
| 761 | b_to_src.image = rt::d3d12::vulkan_image(rt); | ||
| 762 | b_to_src.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; | ||
| 763 | vkCmdPipelineBarrier(cb, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, | ||
| 764 | 0, 0, nullptr, 0, nullptr, 1, &b_to_src); | ||
| 765 | |||
| 766 | VkBufferImageCopy bic{}; | ||
| 767 | bic.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}; | ||
| 768 | bic.imageExtent = {kW, kH, 1}; | ||
| 769 | vkCmdCopyImageToBuffer(cb, rt::d3d12::vulkan_image(rt), VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, | ||
| 770 | rt::d3d12::vulkan_buffer(rb), 1, &bic); | ||
| 771 | |||
| 772 | VkMemoryBarrier host_b{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; | ||
| 773 | host_b.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; | ||
| 774 | host_b.dstAccessMask = VK_ACCESS_HOST_READ_BIT; | ||
| 775 | vkCmdPipelineBarrier(cb, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_HOST_BIT, 0, 1, &host_b, 0, | ||
| 776 | nullptr, 0, nullptr); | ||
| 777 | if (vkEndCommandBuffer(cb) != VK_SUCCESS) return fail("end replayed counted draw"); | ||
| 778 | |||
| 779 | VkSubmitInfo si{VK_STRUCTURE_TYPE_SUBMIT_INFO}; | ||
| 780 | si.commandBufferCount = 1; | ||
| 781 | si.pCommandBuffers = &cb; | ||
| 782 | vkQueueSubmit(vk_queue, 1, &si, VK_NULL_HANDLE); | ||
| 783 | vkQueueWaitIdle(vk_queue); | ||
| 784 | // The clamp's record scratch is idle now: hand it back for the next run, as a completed submission does. | ||
| 785 | clamp.retire(VK_NULL_HANDLE, 0); | ||
| 786 | clamp.collect(); | ||
| 787 | |||
| 788 | void* mp = nullptr; | ||
| 789 | if (FAILED(rb->Map(0, nullptr, &mp)) || !mp) return fail("map replayed counted-draw readback"); | ||
| 790 | const auto* px = static_cast<const std::uint8_t*>(mp); | ||
| 791 | const bool ok = std::abs(int(px[0]) - int(exp_r)) <= 1 && std::abs(int(px[1]) - int(exp_g)) <= 1 && | ||
| 792 | std::abs(int(px[2]) - int(exp_b)) <= 1 && px[3] == 255; | ||
| 793 | rb->Unmap(0, nullptr); | ||
| 794 | if (!ok) return fail("replayed counted-draw pixel mismatch"); | ||
| 795 | return 0; | ||
| 796 | }; | ||
| 797 | |||
| 583 | if (run_native_count(0, 0, 0, 0) != 0) return 1; // count = 0 -> black | 798 | if (run_native_count(0, 0, 0, 0) != 0) return 1; // count = 0 -> black |
| 584 | if (run_native_count(4, 32, 160, 240) != 0) return 1; // count = 1 -> triangle | 799 | if (run_native_count(4, 32, 160, 240) != 0) return 1; // count = 1 -> triangle |
| 800 | if (run_indirect_count(0, 0, 0, 0) != 0) return 1; // count = 0 -> black, through replay | ||
| 801 | if (run_indirect_count(4, 32, 160, 240) != 0) return 1; // count = 1 -> triangle, through replay | ||
| 802 | if (clamp_on) { | ||
| 803 | // What a skipped or mistranslated compute pass leaves: an instance count of four billion, and a count | ||
| 804 | // buffer past max_command_count. The clamp cuts the instances to 2^26 / 3 and the count to | ||
| 805 | // max_command_count, so this draw completes in milliseconds instead of running until the host resets | ||
| 806 | // the display driver - and the triangle it renders is the same one. | ||
| 807 | void* mapped = nullptr; | ||
| 808 | if (FAILED(arg_buf->Map(0, nullptr, &mapped))) return fail("Map(indirect arguments) again"); | ||
| 809 | auto* draws = reinterpret_cast<D3D12_DRAW_ARGUMENTS*>(static_cast<std::uint8_t*>(mapped) + argument_base); | ||
| 810 | draws[0] = {3, 0xFFFFFFFFu, 0, 0}; | ||
| 811 | arg_buf->Unmap(0, nullptr); | ||
| 812 | if (FAILED(count_buf->Map(0, nullptr, &mapped))) return fail("Map(indirect count) again"); | ||
| 813 | *reinterpret_cast<std::uint32_t*>(static_cast<std::uint8_t*>(mapped) + count_base) = 0xFFFFFFFFu; | ||
| 814 | count_buf->Unmap(0, nullptr); | ||
| 815 | if (run_indirect_count(0, 32, 160, 240) != 0) return 1; // count is clamped to max_command_count | ||
| 816 | // Read the pass's counters: destroying the batch releases its slots, as a completed submission does. | ||
| 817 | clamp_batch.reset(); | ||
| 818 | const auto counters = clamp.counters(); | ||
| 819 | if (counters.records_clamped != 1 || counters.counts_clamped != 1) | ||
| 820 | return fail("clamp counters after a garbage record"); | ||
| 821 | std::printf(" [PASS] a draw record of 0xFFFFFFFF instances is clamped on the GPU (%llu record(s), " | ||
| 822 | "%llu count(s), %llu over the batch budget)\n", | ||
| 823 | static_cast<unsigned long long>(counters.records_clamped), | ||
| 824 | static_cast<unsigned long long>(counters.counts_clamped), | ||
| 825 | static_cast<unsigned long long>(counters.over_budget)); | ||
| 826 | } | ||
| 585 | 827 | ||
| 586 | vkDestroyCommandPool(vk_dev, pool, nullptr); | 828 | vkDestroyCommandPool(vk_dev, pool, nullptr); |
| 587 | vkDestroyImageView(vk_dev, rt_view, nullptr); | 829 | vkDestroyImageView(vk_dev, rt_view, nullptr); |
| @@ -590,7 +832,8 @@ int main() { | |||
| 590 | rb->Release(); | 832 | rb->Release(); |
| 591 | rt->Release(); | 833 | rt->Release(); |
| 592 | std::printf(" [PASS] native Vulkan counted-draw reference with suballocated argument/count offsets " | 834 | std::printf(" [PASS] native Vulkan counted-draw reference with suballocated argument/count offsets " |
| 593 | "(count=0 black, count=1 solid triangle)\n"); | 835 | "(count=0 black, count=1 solid triangle), and the same records through the D3D12\n" |
| 836 | " ExecuteIndirect replay (count=0 black, count=1 triangle)\n"); | ||
| 594 | } else { | 837 | } else { |
| 595 | std::printf(" [SKIP] native counted-draw reference: drawIndirectCount unsupported\n"); | 838 | std::printf(" [SKIP] native counted-draw reference: drawIndirectCount unsupported\n"); |
| 596 | } | 839 | } |
| @@ -757,6 +1000,63 @@ int main() { | |||
| 757 | rt::d3d12::vulkan_acceleration_structure(dev, tlas_ptr_buf->GetGPUVirtualAddress()); | 1000 | rt::d3d12::vulkan_acceleration_structure(dev, tlas_ptr_buf->GetGPUVirtualAddress()); |
| 758 | if (!tlas_vk || !tlas_ptr_vk) return fail("vulkan_acceleration_structure(TLAS)"); | 1001 | if (!tlas_vk || !tlas_ptr_vk) return fail("vulkan_acceleration_structure(TLAS)"); |
| 759 | 1002 | ||
| 1003 | // The instance above holds the BLAS's GetGPUVirtualAddress(). Vulkan wants a value obtained from | ||
| 1004 | // vkGetAccelerationStructureDeviceAddressKHR there (VUID-vkCmdBuildAccelerationStructuresKHR-pInfos-12281), | ||
| 1005 | // so every AS resource's GPU VA must be what the driver reports for the structure behind it. GPU-assisted | ||
| 1006 | // validation only accepts addresses it has seen that call return. | ||
| 1007 | if (!vkGetAccelerationStructureDeviceAddressKHR) return fail("vkGetAccelerationStructureDeviceAddressKHR"); | ||
| 1008 | for (ID3D12Resource* as_buf : {blas_buf, tlas_buf, tlas_ptr_buf}) { | ||
| 1009 | const D3D12_GPU_VIRTUAL_ADDRESS va = as_buf->GetGPUVirtualAddress(); | ||
| 1010 | VkAccelerationStructureDeviceAddressInfoKHR dai{ | ||
| 1011 | VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_DEVICE_ADDRESS_INFO_KHR}; | ||
| 1012 | dai.accelerationStructure = rt::d3d12::vulkan_acceleration_structure(dev, va); | ||
| 1013 | if (!dai.accelerationStructure) return fail("vulkan_acceleration_structure(AS resource)"); | ||
| 1014 | const VkDeviceAddress driver_va = vkGetAccelerationStructureDeviceAddressKHR(vk_dev, &dai); | ||
| 1015 | if (driver_va != va) { | ||
| 1016 | std::fprintf(stderr, | ||
| 1017 | "FAIL: AS resource GPU VA 0x%llx, vkGetAccelerationStructureDeviceAddressKHR 0x%llx\n", | ||
| 1018 | static_cast<unsigned long long>(va), static_cast<unsigned long long>(driver_va)); | ||
| 1019 | return 1; | ||
| 1020 | } | ||
| 1021 | } | ||
| 1022 | std::printf(" [PASS] AS resource GPU VAs are the driver's acceleration structure addresses\n"); | ||
| 1023 | |||
| 1024 | // The same on a driver that answers another address than buffer address + offset: the resource's GPU VA is | ||
| 1025 | // the driver's, the arena address still names the structure, and releasing the resource forgets both. | ||
| 1026 | { | ||
| 1027 | g_real_gipa = gipa; | ||
| 1028 | rt::d3d12::VulkanDeviceInfo shifted_info = info; | ||
| 1029 | shifted_info.get_instance_proc = &shifted_gipa; | ||
| 1030 | ID3D12Device5* shifted = nullptr; | ||
| 1031 | if (FAILED(rt::d3d12::create_vulkan_device(shifted_info, IID_PPV_ARGS(&shifted))) || !shifted) | ||
| 1032 | return fail("create_vulkan_device(shifted AS addresses)"); | ||
| 1033 | ID3D12Resource* as_buf = nullptr; | ||
| 1034 | if (FAILED(shifted->CreateCommittedResource(&def_hp, D3D12_HEAP_FLAG_NONE, &blas_desc, | ||
| 1035 | D3D12_RESOURCE_STATE_RAYTRACING_ACCELERATION_STRUCTURE, | ||
| 1036 | nullptr, IID_PPV_ARGS(&as_buf)))) | ||
| 1037 | return fail("CreateCommittedResource(AS, shifted addresses)"); | ||
| 1038 | const D3D12_GPU_VIRTUAL_ADDRESS va = as_buf->GetGPUVirtualAddress(); | ||
| 1039 | VkAccelerationStructureDeviceAddressInfoKHR dai{ | ||
| 1040 | VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_DEVICE_ADDRESS_INFO_KHR}; | ||
| 1041 | dai.accelerationStructure = rt::d3d12::vulkan_acceleration_structure(shifted, va); | ||
| 1042 | if (!dai.accelerationStructure) return fail("shifted AS: the GPU VA does not name the structure"); | ||
| 1043 | const VkDeviceAddress buffer_va = vkGetAccelerationStructureDeviceAddressKHR(vk_dev, &dai); | ||
| 1044 | if (va != buffer_va + kShiftedAsDelta) { | ||
| 1045 | std::fprintf(stderr, "FAIL: shifted AS: GPU VA 0x%llx, driver address 0x%llx\n", | ||
| 1046 | static_cast<unsigned long long>(va), | ||
| 1047 | static_cast<unsigned long long>(buffer_va + kShiftedAsDelta)); | ||
| 1048 | return 1; | ||
| 1049 | } | ||
| 1050 | if (rt::d3d12::vulkan_acceleration_structure(shifted, buffer_va) != dai.accelerationStructure) | ||
| 1051 | return fail("shifted AS: the arena address does not name the structure"); | ||
| 1052 | as_buf->Release(); | ||
| 1053 | if (rt::d3d12::vulkan_acceleration_structure(shifted, va) || | ||
| 1054 | rt::d3d12::vulkan_acceleration_structure(shifted, buffer_va)) | ||
| 1055 | return fail("shifted AS: an address still names the structure after Release"); | ||
| 1056 | shifted->Release(); | ||
| 1057 | std::printf(" [PASS] a driver address other than buffer address + offset is the GPU VA; both freed\n"); | ||
| 1058 | } | ||
| 1059 | |||
| 760 | // BLAS compaction size (inline postbuild + standalone 2-source EmitPostbuild), CLONE, COMPACT, and | 1060 | // BLAS compaction size (inline postbuild + standalone 2-source EmitPostbuild), CLONE, COMPACT, and |
| 761 | // negative rejection checks. | 1061 | // negative rejection checks. |
| 762 | ID3D12Fence* copy_fence = nullptr; | 1062 | ID3D12Fence* copy_fence = nullptr; |
diff --git a/runtime/test/d3d12_m4_compute_test.cpp b/runtime/test/d3d12_m4_compute_test.cpp index 97a4e8600..05d6fe153 100644 --- a/runtime/test/d3d12_m4_compute_test.cpp +++ b/runtime/test/d3d12_m4_compute_test.cpp | |||
| @@ -28,6 +28,7 @@ | |||
| 28 | #include "vk_test_device.h" | 28 | #include "vk_test_device.h" |
| 29 | #include "d3d12_test_shaders.h" | 29 | #include "d3d12_test_shaders.h" |
| 30 | #include "../shims/d3d12_com.h" | 30 | #include "../shims/d3d12_com.h" |
| 31 | #include "../shims/d3d12_pipeline_compile.h" | ||
| 31 | #include "../shims/d3d12_xs_device.h" | 32 | #include "../shims/d3d12_xs_device.h" |
| 32 | #include "../src/shader_library.h" | 33 | #include "../src/shader_library.h" |
| 33 | #include "../src/vulkan_indirect_clamp.h" | 34 | #include "../src/vulkan_indirect_clamp.h" |
| @@ -96,7 +97,8 @@ Reference reference() { | |||
| 96 | 97 | ||
| 97 | } // namespace | 98 | } // namespace |
| 98 | 99 | ||
| 99 | int main() { | 100 | int main(int argc, char** argv) { |
| 101 | const bool check_journal = argc == 2 && std::strcmp(argv[1], "--check-async-journal") == 0; | ||
| 100 | vktest::Device d; | 102 | vktest::Device d; |
| 101 | d.queue_count_wanted = 2; // the copy queue and the compute queue each get a VkQueue where the family has two | 103 | d.queue_count_wanted = 2; // the copy queue and the compute queue each get a VkQueue where the family has two |
| 102 | const auto device_status = d.initialize(); | 104 | const auto device_status = d.initialize(); |
| @@ -129,6 +131,7 @@ int main() { | |||
| 129 | info.queue_family = d.family; | 131 | info.queue_family = d.family; |
| 130 | if (distinct_queues) info.command_queues = d.queues; | 132 | if (distinct_queues) info.command_queues = d.queues; |
| 131 | info.buffer_device_address = true; | 133 | info.buffer_device_address = true; |
| 134 | info.pipeline_cache_control = d.pipeline_cache_control(); | ||
| 132 | info.bindless = d.bindless; | 135 | info.bindless = d.bindless; |
| 133 | info.bindless_partially_bound = d.partially_bound; | 136 | info.bindless_partially_bound = d.partially_bound; |
| 134 | info.image_view_min_lod = d.image_view_min_lod; | 137 | info.image_view_min_lod = d.image_view_min_lod; |
| @@ -167,6 +170,24 @@ int main() { | |||
| 167 | pso_desc.CS = {indirect_container.data(), indirect_container.size()}; | 170 | pso_desc.CS = {indirect_container.data(), indirect_container.size()}; |
| 168 | EXPECT(SUCCEEDED(device->CreateComputePipelineState(&pso_desc, IID_PPV_ARGS(&pso_indirect.p)))); | 171 | EXPECT(SUCCEEDED(device->CreateComputePipelineState(&pso_desc, IID_PPV_ARGS(&pso_indirect.p)))); |
| 169 | 172 | ||
| 173 | if (check_journal) { | ||
| 174 | // Check publication while the device and both PSOs are still alive. The async policy can | ||
| 175 | // drop a dispatch whose worker has not yet published its handle, so wait for these two. | ||
| 176 | EXPECT(rt::d3d12::async_replay_compile()); | ||
| 177 | const auto deadline = GetTickCount64() + 30000; | ||
| 178 | while (rt::d3d12::PipelineCompiler::instance().stats().completed < 2 && GetTickCount64() < deadline) | ||
| 179 | Sleep(1); | ||
| 180 | EXPECT(rt::d3d12::PipelineCompiler::instance().stats().completed >= 2); | ||
| 181 | const auto* cache_dir = _wgetenv(L"LEONIDA_PIPELINE_CACHE_DIR"); | ||
| 182 | EXPECT(cache_dir && *cache_dir); | ||
| 183 | unsigned entries = 0; | ||
| 184 | const auto dir = std::filesystem::path(cache_dir) / L"pipeline_cache.d"; | ||
| 185 | EXPECT(std::filesystem::is_directory(dir)); | ||
| 186 | for (const auto& file : std::filesystem::directory_iterator(dir)) | ||
| 187 | if (file.path().extension() == L".bin" && file.file_size() > 32) ++entries; | ||
| 188 | EXPECT(entries == 2); | ||
| 189 | } | ||
| 190 | |||
| 170 | D3D12_INDIRECT_ARGUMENT_DESC argument{}; | 191 | D3D12_INDIRECT_ARGUMENT_DESC argument{}; |
| 171 | argument.Type = D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH; | 192 | argument.Type = D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH; |
| 172 | D3D12_COMMAND_SIGNATURE_DESC signature_desc{}; | 193 | D3D12_COMMAND_SIGNATURE_DESC signature_desc{}; |
diff --git a/runtime/test/d3d12_mesh_test.cpp b/runtime/test/d3d12_mesh_test.cpp index 2d9bc5212..775cfeb58 100644 --- a/runtime/test/d3d12_mesh_test.cpp +++ b/runtime/test/d3d12_mesh_test.cpp | |||
| @@ -5,15 +5,16 @@ | |||
| 5 | // - With it: MeshShaderTier 1; CreatePipelineState builds an MS + PS PSO and a VS + PS PSO from streams laid out as | 5 | // - With it: MeshShaderTier 1; CreatePipelineState builds an MS + PS PSO and a VS + PS PSO from streams laid out as |
| 6 | // d3dx12.h lays them out (each subobject a type and its description, pointer-aligned); streams the PC runtime | 6 | // d3dx12.h lays them out (each subobject a type and its description, pointer-aligned); streams the PC runtime |
| 7 | // refuses (MS with VS, CS with PS, a subobject twice or in two versions, an unknown type, a truncated stream) are E_INVALIDARG, and | 7 | // refuses (MS with VS, CS with PS, a subobject twice or in two versions, an unknown type, a truncated stream) are E_INVALIDARG, and |
| 8 | // state not built yet (an amplification shader, a depth-bounds test) is E_NOTIMPL. | 8 | // state not built yet (an amplification shader) is E_NOTIMPL; a depth-bounds test builds where the device |
| 9 | // reports DepthBoundsTestSupported, and is E_NOTIMPL where it does not. | ||
| 9 | // - Draws: DispatchMesh(2, 2, 1) with root constants (0, 0) and a red tint fills the top-left quadrant; | 10 | // - Draws: DispatchMesh(2, 2, 1) with root constants (0, 0) and a red tint fills the top-left quadrant; |
| 10 | // DispatchMesh(1, 1, 2) moved by (1, -1) with a green tint fills the top half of the bottom-right one, so the | 11 | // DispatchMesh(1, 1, 2) moved by (1, -1) with a green tint fills the top half of the bottom-right one, so the |
| 11 | // Y and Z counts reach the shader; the stream's VS PSO draws a full-screen triangle through a viewport on the | 12 | // Y and Z counts reach the shader; the stream's VS PSO draws a full-screen triangle through a viewport on the |
| 12 | // bottom-left quadrant (yellow). Each pixel is read back and compared. | 13 | // bottom-left quadrant (yellow). Each pixel is read back and compared. |
| 13 | // - A vertex draw with the mesh PSO, and DispatchMesh with the VS one, fail at execution (ReplayResult:: | 14 | // - A vertex draw with the mesh PSO, and DispatchMesh with the VS one, fail at execution (ReplayResult:: |
| 14 | // invalid_draw); a mesh grid beyond D3D12's limits fails at Close; an empty grid records nothing. | 15 | // invalid_draw); a mesh grid beyond D3D12's limits fails at Close; an empty grid records nothing. |
| 15 | // - A DISPATCH_MESH command signature is created only with the extension; ExecuteIndirect with it records nothing | 16 | // - A DISPATCH_MESH command signature is created only with the extension; ExecuteIndirect with it draws as |
| 16 | // yet, so its list closes. | 17 | // DispatchMesh (one record {2, 1, 1} fills two cells), and without graphics state it records nothing and closes. |
| 17 | // The shaders are GLSL written to the translator's contract (test/glsl/ms_draw.mesh, ps_draw.frag, vs_fullscreen.vert). | 18 | // The shaders are GLSL written to the translator's contract (test/glsl/ms_draw.mesh, ps_draw.frag, vs_fullscreen.vert). |
| 18 | // No game data. Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation. | 19 | // No game data. Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation. |
| 19 | #include "vk_test_device.h" | 20 | #include "vk_test_device.h" |
| @@ -317,7 +318,14 @@ int main(int argc, char** argv) { | |||
| 317 | D3D12_DEPTH_STENCIL_DESC1 bounds{}; | 318 | D3D12_DEPTH_STENCIL_DESC1 bounds{}; |
| 318 | bounds.DepthBoundsTestEnable = TRUE; | 319 | bounds.DepthBoundsTestEnable = TRUE; |
| 319 | bad.add(DepthStencil1Subobject{.inner = bounds}); | 320 | bad.add(DepthStencil1Subobject{.inner = bounds}); |
| 320 | EXPECT(create(device.p, bad, refused) == E_NOTIMPL && !refused.p); | 321 | { |
| 322 | D3D12_FEATURE_DATA_D3D12_OPTIONS2 o2{}; | ||
| 323 | EXPECT(SUCCEEDED(device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS2, &o2, sizeof o2))); | ||
| 324 | Ref<ID3D12PipelineState> with_bounds; | ||
| 325 | const HRESULT bounds_hr = create(device.p, bad, with_bounds); | ||
| 326 | EXPECT(o2.DepthBoundsTestSupported ? SUCCEEDED(bounds_hr) && with_bounds.p | ||
| 327 | : bounds_hr == E_NOTIMPL && !with_bounds.p); | ||
| 328 | } | ||
| 321 | 329 | ||
| 322 | // A console stream: its numbering has no gap at 23, so its mesh shader is 24 (the PC's AS) and its | 330 | // A console stream: its numbering has no gap at 23, so its mesh shader is 24 (the PC's AS) and its |
| 323 | // RASTERIZER1 26 (the PC's DEPTH_STENCIL2). An AS without an MS is no PC stream, so the layer reads it with the | 331 | // RASTERIZER1 26 (the PC's DEPTH_STENCIL2). An AS without an MS is no PC stream, so the layer reads it with the |
| @@ -468,6 +476,54 @@ int main(int argc, char** argv) { | |||
| 468 | EXPECT(SUCCEEDED(readback->Map(0, nullptr, &mapped))); | 476 | EXPECT(SUCCEEDED(readback->Map(0, nullptr, &mapped))); |
| 469 | std::memcpy(pixels.data(), mapped, pixels.size()); | 477 | std::memcpy(pixels.data(), mapped, pixels.size()); |
| 470 | 478 | ||
| 479 | // ExecuteIndirect with a DISPATCH_MESH signature draws as DispatchMesh (vkCmdDrawMeshTasksIndirectEXT after | ||
| 480 | // the clamp pass): one record {2, 1, 1} at upload + 768 fills columns 0 and 1 of row 0, the top half of the | ||
| 481 | // top-left quadrant, red; the rest of the cleared target stays blue. | ||
| 482 | { | ||
| 483 | const std::uint32_t record[3] = {2, 1, 1}; | ||
| 484 | std::memcpy(up + 768, record, sizeof record); | ||
| 485 | const D3D12_INDIRECT_ARGUMENT_DESC mesh_arg{D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH_MESH}; | ||
| 486 | const D3D12_COMMAND_SIGNATURE_DESC mesh_sig{12, 1, &mesh_arg, 0}; | ||
| 487 | Ref<ID3D12CommandSignature> sig; | ||
| 488 | Ref<ID3D12Fence> indirect_fence; | ||
| 489 | EXPECT(SUCCEEDED(device->CreateCommandSignature(&mesh_sig, nullptr, IID_PPV_ARGS(&sig.p))) && sig.p); | ||
| 490 | EXPECT(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&indirect_fence.p)))); | ||
| 491 | EXPECT(SUCCEEDED(allocator->Reset()) && SUCCEEDED(list->Reset(allocator.p, mesh_pso.p))); | ||
| 492 | D3D12_RESOURCE_BARRIER again = | ||
| 493 | transition(target.p, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_RENDER_TARGET); | ||
| 494 | list->ResourceBarrier(1, &again); | ||
| 495 | list->ClearRenderTargetView(rtv, blue, 0, nullptr); | ||
| 496 | list->SetGraphicsRootSignature(root.p); | ||
| 497 | list->RSSetViewports(1, &viewport); | ||
| 498 | list->RSSetScissorRects(1, &scissor); | ||
| 499 | list->OMSetRenderTargets(1, &rtv, FALSE, nullptr); | ||
| 500 | list->SetGraphicsRoot32BitConstants(0, 2, origin, 0); | ||
| 501 | list->SetGraphicsRootConstantBufferView(1, upload_va); | ||
| 502 | list->ExecuteIndirect(sig.p, 1, upload.p, 768, nullptr, 0); | ||
| 503 | list->ResourceBarrier(1, &to_copy); | ||
| 504 | list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); | ||
| 505 | EXPECT(list->Close() == S_OK); | ||
| 506 | queue->ExecuteCommandLists(1, lists); | ||
| 507 | EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success); | ||
| 508 | EXPECT(SUCCEEDED(queue->Signal(indirect_fence.p, 1)) && | ||
| 509 | SUCCEEDED(indirect_fence->SetEventOnCompletion(1, nullptr))); | ||
| 510 | unsigned wrong = 0; | ||
| 511 | for (UINT row = 0; row < size; ++row) { | ||
| 512 | for (UINT col = 0; col < size; ++col) { | ||
| 513 | const bool red = row < size / 4 && col < size / 2; | ||
| 514 | const std::uint8_t want[4] = {std::uint8_t(red ? 255 : 0), 0, std::uint8_t(red ? 0 : 255), 255}; | ||
| 515 | const auto* got = static_cast<const std::uint8_t*>(mapped) + row * 256 + col * 4; | ||
| 516 | if (std::equal(want, want + 4, got)) continue; | ||
| 517 | if (wrong++ < 6) | ||
| 518 | std::fprintf(stderr, "indirect mesh pixel (%u, %u): got %u,%u,%u,%u want %u,%u,%u,%u\n", col, | ||
| 519 | row, got[0], got[1], got[2], got[3], want[0], want[1], want[2], want[3]); | ||
| 520 | } | ||
| 521 | } | ||
| 522 | EXPECT(!wrong); | ||
| 523 | std::printf("ExecuteIndirect DISPATCH_MESH {2, 1, 1} drew as DispatchMesh(2, 1, 1): %u pixels matched\n", | ||
| 524 | size * size); | ||
| 525 | } | ||
| 526 | |||
| 471 | // The wrong kind of draw for the pipeline fails at execution: a vertex draw with the mesh PSO, then | 527 | // The wrong kind of draw for the pipeline fails at execution: a vertex draw with the mesh PSO, then |
| 472 | // DispatchMesh with the VS PSO. | 528 | // DispatchMesh with the VS PSO. |
| 473 | for (const bool vertex_draw : {true, false}) { | 529 | for (const bool vertex_draw : {true, false}) { |
| @@ -591,8 +647,8 @@ int main(int argc, char** argv) { | |||
| 591 | enabled ? "" : " (LEONIDA_GRAPHICS_DIRECT_HEAPS=0: not written)"); | 647 | enabled ? "" : " (LEONIDA_GRAPHICS_DIRECT_HEAPS=0: not written)"); |
| 592 | } | 648 | } |
| 593 | // A DISPATCH_MESH command signature (D3D12_DISPATCH_MESH_ARGUMENTS, 12 bytes) is created; a stride below its | 649 | // A DISPATCH_MESH command signature (D3D12_DISPATCH_MESH_ARGUMENTS, 12 bytes) is created; a stride below its |
| 594 | // 12 bytes is refused as the PC runtime refuses it. ExecuteIndirect with it records nothing yet (#3777 replays | 650 | // 12 bytes is refused as the PC runtime refuses it. ExecuteIndirect with it and no viewport records |
| 595 | // it), so the list still closes. | 651 | // nothing, so the list still closes. |
| 596 | { | 652 | { |
| 597 | const D3D12_INDIRECT_ARGUMENT_DESC mesh_arg{D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH_MESH}; | 653 | const D3D12_INDIRECT_ARGUMENT_DESC mesh_arg{D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH_MESH}; |
| 598 | const D3D12_COMMAND_SIGNATURE_DESC mesh_sig{12, 1, &mesh_arg, 0}; | 654 | const D3D12_COMMAND_SIGNATURE_DESC mesh_sig{12, 1, &mesh_arg, 0}; |
diff --git a/runtime/test/d3d12_placed_depth_test.h b/runtime/test/d3d12_placed_depth_test.h index 5ef9f88a9..73818e19b 100644 --- a/runtime/test/d3d12_placed_depth_test.h +++ b/runtime/test/d3d12_placed_depth_test.h | |||
| @@ -34,6 +34,19 @@ inline bool check_alias_lifetime(ID3D12Device* device, ID3D12Device* xbox, bool | |||
| 34 | const D3D12_CLEAR_VALUE* clear = nullptr) { | 34 | const D3D12_CLEAR_VALUE* clear = nullptr) { |
| 35 | return create(xbox, va, &shape, UINT_MAX, clear, IID_PPV_ARGS(&result.p)); | 35 | return create(xbox, va, &shape, UINT_MAX, clear, IID_PPV_ARGS(&result.p)); |
| 36 | }; | 36 | }; |
| 37 | if (opaque) { | ||
| 38 | auto packed = xbox_desc; | ||
| 39 | packed.Format = static_cast<DXGI_FORMAT>(118); | ||
| 40 | packed.Width = 1280; | ||
| 41 | packed.Height = 720; | ||
| 42 | Ptr<ID3D12Resource> target; | ||
| 43 | // The image is privately backed; reserve a full placement for its title VA. | ||
| 44 | Pages packed_pages{VirtualAlloc(nullptr, 8u << 20, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)}; | ||
| 45 | const auto packed_va = reinterpret_cast<UINT64>(packed_pages.ptr); | ||
| 46 | if (!packed_va || FAILED(place(packed_va, packed, target)) || | ||
| 47 | target->GetGPUVirtualAddress() != packed_va) return false; | ||
| 48 | target.reset(); | ||
| 49 | } | ||
| 37 | Ptr<ID3D12Resource> first, alias, next, invalid; | 50 | Ptr<ID3D12Resource> first, alias, next, invalid; |
| 38 | if (FAILED(place(address, xbox_desc, first)) || FAILED(place(address, xbox_desc, alias)) || | 51 | if (FAILED(place(address, xbox_desc, first)) || FAILED(place(address, xbox_desc, alias)) || |
| 39 | FAILED(place(address + allocation.SizeInBytes, xbox_desc, next))) return false; | 52 | FAILED(place(address + allocation.SizeInBytes, xbox_desc, next))) return false; |
diff --git a/runtime/test/d3d12_set_descriptor_heaps_test.cpp b/runtime/test/d3d12_set_descriptor_heaps_test.cpp index 62ffb1ffe..1251f77a7 100644 --- a/runtime/test/d3d12_set_descriptor_heaps_test.cpp +++ b/runtime/test/d3d12_set_descriptor_heaps_test.cpp | |||
| @@ -344,6 +344,20 @@ bool check_tracking_lifetime_and_direct_indexing(DeviceHeaps& ours) { | |||
| 344 | const rt::d3d12::RootArgumentLayout* layout = rt::d3d12::root_signature_layout(root.p); | 344 | const rt::d3d12::RootArgumentLayout* layout = rt::d3d12::root_signature_layout(root.p); |
| 345 | CHECK(layout && (layout->flags & di_flags) == di_flags); | 345 | CHECK(layout && (layout->flags & di_flags) == di_flags); |
| 346 | 346 | ||
| 347 | // Direct heap indexing passes remapped console_descriptor_table_va into recorded user data. | ||
| 348 | ID3D12DescriptorHeap* heaps[2] = {ours.cbv1.p, ours.smp1.p}; | ||
| 349 | list->SetDescriptorHeaps(2, heaps); | ||
| 350 | list->SetComputeRootSignature(root.p); | ||
| 351 | list->Dispatch(1, 1, 1); | ||
| 352 | std::vector<leonida::Command> cmds; | ||
| 353 | CHECK(rt::d3d12::recorded_commands(list.p, cmds) && !cmds.empty()); | ||
| 354 | const auto* disp = std::get_if<leonida::Dispatch>(&cmds.back()); | ||
| 355 | CHECK(disp != nullptr); | ||
| 356 | const auto expected_cbv = static_cast<std::uint32_t>(rt::d3d12::console_descriptor_table_va(cbv1_va)); | ||
| 357 | const auto expected_smp = static_cast<std::uint32_t>(rt::d3d12::console_descriptor_table_va(smp1_va)); | ||
| 358 | CHECK(disp->user_data[layout->compute_arguments_end] == expected_cbv); | ||
| 359 | CHECK(disp->user_data[layout->compute_arguments_end + 1] == expected_smp); | ||
| 360 | |||
| 347 | CHECK(!rt::d3d12::bound_descriptor_heap_bases(nullptr, got_cbv, got_smp)); | 361 | CHECK(!rt::d3d12::bound_descriptor_heap_bases(nullptr, got_cbv, got_smp)); |
| 348 | return true; | 362 | return true; |
| 349 | } | 363 | } |
diff --git a/runtime/test/d3d12_texture_tiles_test.cpp b/runtime/test/d3d12_texture_tiles_test.cpp index fc08c3422..4d15415f3 100644 --- a/runtime/test/d3d12_texture_tiles_test.cpp +++ b/runtime/test/d3d12_texture_tiles_test.cpp | |||
| @@ -6,9 +6,11 @@ | |||
| 6 | 6 | ||
| 7 | #include <algorithm> | 7 | #include <algorithm> |
| 8 | #include <array> | 8 | #include <array> |
| 9 | #include <cctype> | ||
| 9 | #include <cstdint> | 10 | #include <cstdint> |
| 10 | #include <cstdio> | 11 | #include <cstdio> |
| 11 | #include <cstring> | 12 | #include <cstring> |
| 13 | #include <string> | ||
| 12 | #include <vector> | 14 | #include <vector> |
| 13 | 15 | ||
| 14 | #define EXPECT(condition) do { \ | 16 | #define EXPECT(condition) do { \ |
| @@ -248,14 +250,55 @@ bool run(ID3D12Device& device, UINT width, UINT height, UINT64 tile_copy_offset, | |||
| 248 | return true; | 250 | return true; |
| 249 | } | 251 | } |
| 250 | 252 | ||
| 251 | ComPtr<ID3D12Device> native_device() { | 253 | // D3D12 on the adapter `luid` names, when it has tiled resources tier 2 or more; null otherwise. |
| 254 | ComPtr<ID3D12Device> tiled_device(IDXGIFactory4& factory, LUID luid, bool print = true) { | ||
| 255 | ComPtr<IDXGIAdapter1> adapter; | ||
| 256 | if (!luid.LowPart && !luid.HighPart) return {}; | ||
| 257 | if (FAILED(factory.EnumAdapterByLuid(luid, IID_PPV_ARGS(&adapter)))) return {}; | ||
| 258 | DXGI_ADAPTER_DESC1 desc{}; | ||
| 259 | ComPtr<ID3D12Device> device; | ||
| 260 | D3D12_FEATURE_DATA_D3D12_OPTIONS options{}; | ||
| 261 | if (FAILED(adapter->GetDesc1(&desc)) || (desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) || | ||
| 262 | FAILED(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&device))) || | ||
| 263 | FAILED(device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, &options, sizeof(options))) || | ||
| 264 | options.TiledResourcesTier < D3D12_TILED_RESOURCES_TIER_2) | ||
| 265 | return {}; | ||
| 266 | if (print) | ||
| 267 | std::printf("Native D3D12: %ls (the layer's adapter), tiled resources tier %u\n", desc.Description, | ||
| 268 | unsigned(options.TiledResourcesTier)); | ||
| 269 | return device; | ||
| 270 | } | ||
| 271 | |||
| 272 | // The host adapter for the native half. LEONIDA_HOST_ADAPTER picks it as in d3d12_copy_compare.h: "warp", or part of | ||
| 273 | // an adapter name (case-insensitive); a value that names no adapter with tiled resources tier 2 skips the native half | ||
| 274 | // rather than testing another GPU. Unset: the adapter behind the layer's Vulkan device (`layer_luid`, as | ||
| 275 | // host_adapter.h picks it), so a PC with two GPUs compares the layer with its own GPU's driver; when that adapter | ||
| 276 | // has no tier 2, the first hardware adapter with tier 2 or more. | ||
| 277 | ComPtr<ID3D12Device> native_device(LUID layer_luid) { | ||
| 252 | ComPtr<IDXGIFactory4> factory; | 278 | ComPtr<IDXGIFactory4> factory; |
| 253 | if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)))) return {}; | 279 | if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)))) return {}; |
| 280 | char want[128] = {}; | ||
| 281 | GetEnvironmentVariableA("LEONIDA_HOST_ADAPTER", want, sizeof(want)); | ||
| 282 | std::string needle(want); | ||
| 283 | std::transform(needle.begin(), needle.end(), needle.begin(), [](unsigned char c) { return char(std::tolower(c)); }); | ||
| 284 | if (needle.empty()) | ||
| 285 | if (auto device = tiled_device(*factory.Get(), layer_luid)) return device; | ||
| 254 | for (UINT i = 0;; ++i) { | 286 | for (UINT i = 0;; ++i) { |
| 255 | ComPtr<IDXGIAdapter1> adapter; | 287 | ComPtr<IDXGIAdapter1> adapter; |
| 256 | if (factory->EnumAdapters1(i, &adapter) != S_OK) return {}; | 288 | if (needle == "warp") { |
| 289 | if (i > 0 || FAILED(factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter)))) break; | ||
| 290 | } else if (factory->EnumAdapters1(i, &adapter) != S_OK) { | ||
| 291 | break; | ||
| 292 | } | ||
| 257 | DXGI_ADAPTER_DESC1 desc{}; | 293 | DXGI_ADAPTER_DESC1 desc{}; |
| 258 | if (FAILED(adapter->GetDesc1(&desc)) || (desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE)) continue; | 294 | if (FAILED(adapter->GetDesc1(&desc))) continue; |
| 295 | if (needle.empty()) { | ||
| 296 | if (desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) continue; | ||
| 297 | } else if (needle != "warp") { | ||
| 298 | std::string name; | ||
| 299 | for (const wchar_t* c = desc.Description; *c; ++c) name += char(std::tolower(*c < 128 ? *c : '?')); | ||
| 300 | if (name.find(needle) == std::string::npos) continue; | ||
| 301 | } | ||
| 259 | ComPtr<ID3D12Device> device; | 302 | ComPtr<ID3D12Device> device; |
| 260 | if (FAILED(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&device)))) continue; | 303 | if (FAILED(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&device)))) continue; |
| 261 | D3D12_FEATURE_DATA_D3D12_OPTIONS options{}; | 304 | D3D12_FEATURE_DATA_D3D12_OPTIONS options{}; |
| @@ -264,6 +307,10 @@ ComPtr<ID3D12Device> native_device() { | |||
| 264 | std::printf("Native D3D12: %ls, tiled resources tier %u\n", desc.Description, unsigned(options.TiledResourcesTier)); | 307 | std::printf("Native D3D12: %ls, tiled resources tier %u\n", desc.Description, unsigned(options.TiledResourcesTier)); |
| 265 | return device; | 308 | return device; |
| 266 | } | 309 | } |
| 310 | if (!needle.empty()) | ||
| 311 | std::printf("Native D3D12: no adapter matching LEONIDA_HOST_ADAPTER=%s with tiled resources tier 2 or more; " | ||
| 312 | "native half skipped\n", want); | ||
| 313 | return {}; | ||
| 267 | } | 314 | } |
| 268 | 315 | ||
| 269 | } // namespace | 316 | } // namespace |
| @@ -283,7 +330,22 @@ int main() { | |||
| 283 | std::fputs("A texture with multiple mips did not use the committed fallback\n", stderr); | 330 | std::fputs("A texture with multiple mips did not use the committed fallback\n", stderr); |
| 284 | return 1; | 331 | return 1; |
| 285 | } | 332 | } |
| 286 | auto native = native_device(); | 333 | const LUID layer_luid = vulkan->GetAdapterLuid(); |
| 334 | auto native = native_device(layer_luid); | ||
| 335 | if (native) { | ||
| 336 | // Unset LEONIDA_HOST_ADAPTER means the layer's own GPU whenever its driver can run the cases: comparing with | ||
| 337 | // another GPU's driver measures that driver, not the layer. | ||
| 338 | char want[2] = {}; | ||
| 339 | const LUID host_luid = native->GetAdapterLuid(); | ||
| 340 | ComPtr<IDXGIFactory4> factory; | ||
| 341 | if (!GetEnvironmentVariableA("LEONIDA_HOST_ADAPTER", want, sizeof(want)) && | ||
| 342 | SUCCEEDED(CreateDXGIFactory1(IID_PPV_ARGS(&factory))) && tiled_device(*factory.Get(), layer_luid, false) && | ||
| 343 | (host_luid.LowPart != layer_luid.LowPart || host_luid.HighPart != layer_luid.HighPart)) { | ||
| 344 | std::fprintf(stderr, "Native D3D12 runs on another adapter than the layer's, which has tiled resources " | ||
| 345 | "tier 2 or more\n"); | ||
| 346 | return 1; | ||
| 347 | } | ||
| 348 | } | ||
| 287 | const auto* info = rt::d3d12::vulkan_device_info(vulkan.Get()); | 349 | const auto* info = rt::d3d12::vulkan_device_info(vulkan.Get()); |
| 288 | const bool dedicated_copy = info && !info->copy_queues.empty() && info->copy_family != info->queue_family; | 350 | const bool dedicated_copy = info && !info->copy_queues.empty() && info->copy_family != info->queue_family; |
| 289 | struct ReplayCase { | 351 | struct ReplayCase { |
diff --git a/runtime/test/d3d12_texture_uav_test.cpp b/runtime/test/d3d12_texture_uav_test.cpp index f8ef5177b..d6774438e 100644 --- a/runtime/test/d3d12_texture_uav_test.cpp +++ b/runtime/test/d3d12_texture_uav_test.cpp | |||
| @@ -243,15 +243,93 @@ bool flush_descriptors(ID3D12Device* device) { | |||
| 243 | return rt::d3d12::last_execute_result(queue.Get()) == leonida::ReplayResult::success; | 243 | return rt::d3d12::last_execute_result(queue.Get()) == leonida::ReplayResult::success; |
| 244 | } | 244 | } |
| 245 | 245 | ||
| 246 | bool rejects_partial_clear(ID3D12Device* device, ID3D12Resource* resource, D3D12_CPU_DESCRIPTOR_HANDLE view) { | 246 | bool check_partial_clear(ID3D12Device* device, ID3D12Resource* resource, D3D12_CPU_DESCRIPTOR_HANDLE whole, |
| 247 | D3D12_CPU_DESCRIPTOR_HANDLE partial, const D3D12_RESOURCE_DESC& shape, | ||
| 248 | UINT mip, UINT first, UINT writable) { | ||
| 249 | ComPtr<ID3D12CommandQueue> queue; | ||
| 250 | const D3D12_COMMAND_QUEUE_DESC qdesc{D3D12_COMMAND_LIST_TYPE_DIRECT}; | ||
| 251 | EXPECT(SUCCEEDED(device->CreateCommandQueue(&qdesc, IID_PPV_ARGS(&queue)))); | ||
| 252 | ComPtr<ID3D12Fence> fence; | ||
| 253 | EXPECT(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence)))); | ||
| 247 | ComPtr<ID3D12CommandAllocator> allocator; | 254 | ComPtr<ID3D12CommandAllocator> allocator; |
| 248 | ComPtr<ID3D12GraphicsCommandList> list; | 255 | ComPtr<ID3D12GraphicsCommandList> list; |
| 249 | EXPECT(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator)))); | 256 | EXPECT(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator)))); |
| 250 | EXPECT(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.Get(), nullptr, | 257 | EXPECT(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.Get(), nullptr, |
| 251 | IID_PPV_ARGS(&list)))); | 258 | IID_PPV_ARGS(&list)))); |
| 252 | const UINT colors[4] = {42, 0, 0, 0}; | 259 | const UINT clear_value[4] = {42, 0, 0, 0}; |
| 253 | list->ClearUnorderedAccessViewUint({}, view, resource, colors, 0, nullptr); | 260 | ID3D12CommandList* lists[] = {list.Get()}; |
| 254 | return list->Close() == E_INVALIDARG; | 261 | if (shape.Format == DXGI_FORMAT_R32_TYPELESS) { |
| 262 | // The view is UINT and the backing is SFLOAT. 3D clear format reinterpretation is still unsupported. | ||
| 263 | list->ClearUnorderedAccessViewUint({}, partial, resource, clear_value, 0, nullptr); | ||
| 264 | EXPECT(SUCCEEDED(list->Close())); | ||
| 265 | queue->ExecuteCommandLists(1, lists); | ||
| 266 | return rt::d3d12::last_execute_result(queue.Get()) == leonida::ReplayResult::unsupported; | ||
| 267 | } | ||
| 268 | const UINT w = std::max(1u, UINT(shape.Width) >> mip); | ||
| 269 | const UINT h = std::max(1u, shape.Height >> mip); | ||
| 270 | const UINT d = std::max(1u, UINT(shape.DepthOrArraySize) >> mip); | ||
| 271 | const UINT pitch = (w * 4 + 255) / 256 * 256; | ||
| 272 | const UINT64 total = UINT64(pitch) * h * d; | ||
| 273 | D3D12_HEAP_PROPERTIES rb_heap{D3D12_HEAP_TYPE_READBACK}; | ||
| 274 | D3D12_RESOURCE_DESC rb_desc{}; | ||
| 275 | rb_desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; | ||
| 276 | rb_desc.Width = total; | ||
| 277 | rb_desc.Height = rb_desc.DepthOrArraySize = rb_desc.MipLevels = 1; | ||
| 278 | rb_desc.SampleDesc.Count = 1; | ||
| 279 | rb_desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; | ||
| 280 | ComPtr<ID3D12Resource> readback; | ||
| 281 | EXPECT(SUCCEEDED(device->CreateCommittedResource(&rb_heap, D3D12_HEAP_FLAG_NONE, &rb_desc, | ||
| 282 | D3D12_RESOURCE_STATE_COPY_DEST, nullptr, | ||
| 283 | IID_PPV_ARGS(&readback)))); | ||
| 284 | // A known, nonzero sentinel makes loss of a neighboring slice observable even on a newly allocated image. | ||
| 285 | constexpr UINT sentinel = std::bit_cast<UINT>(1.0f); | ||
| 286 | const UINT seed[4] = {sentinel, 0, 0, 0}; | ||
| 287 | list->ClearUnorderedAccessViewUint({}, whole, resource, seed, 0, nullptr); | ||
| 288 | D3D12_RESOURCE_BARRIER order{}; | ||
| 289 | order.Type = D3D12_RESOURCE_BARRIER_TYPE_UAV; | ||
| 290 | order.UAV.pResource = resource; | ||
| 291 | list->ResourceBarrier(1, &order); | ||
| 292 | const bool floating = shape.Format == DXGI_FORMAT_R32_FLOAT; | ||
| 293 | if (floating) { | ||
| 294 | const FLOAT float_value[4] = {42.0f, 0, 0, 0}; | ||
| 295 | list->ClearUnorderedAccessViewFloat({}, partial, resource, float_value, 0, nullptr); | ||
| 296 | } else { | ||
| 297 | list->ClearUnorderedAccessViewUint({}, partial, resource, clear_value, 0, nullptr); | ||
| 298 | } | ||
| 299 | D3D12_RESOURCE_BARRIER to_src{}; | ||
| 300 | to_src.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; | ||
| 301 | to_src.Transition = {resource, mip, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE}; | ||
| 302 | list->ResourceBarrier(1, &to_src); | ||
| 303 | D3D12_TEXTURE_COPY_LOCATION dst{}; | ||
| 304 | dst.pResource = readback.Get(); | ||
| 305 | dst.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; | ||
| 306 | dst.PlacedFootprint = {0, {shape.Format, w, h, d, pitch}}; | ||
| 307 | D3D12_TEXTURE_COPY_LOCATION src{}; | ||
| 308 | src.pResource = resource; | ||
| 309 | src.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; | ||
| 310 | src.SubresourceIndex = mip; | ||
| 311 | list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); | ||
| 312 | D3D12_RESOURCE_BARRIER to_uav = to_src; | ||
| 313 | std::swap(to_uav.Transition.StateBefore, to_uav.Transition.StateAfter); | ||
| 314 | list->ResourceBarrier(1, &to_uav); | ||
| 315 | EXPECT(list->Close() == S_OK); | ||
| 316 | queue->ExecuteCommandLists(1, lists); | ||
| 317 | EXPECT(rt::d3d12::last_execute_result(queue.Get()) == leonida::ReplayResult::success); | ||
| 318 | EXPECT(SUCCEEDED(queue->Signal(fence.Get(), 1)) && SUCCEEDED(fence->SetEventOnCompletion(1, nullptr))); | ||
| 319 | void* mapped = nullptr; | ||
| 320 | EXPECT(SUCCEEDED(readback->Map(0, nullptr, &mapped))); | ||
| 321 | const auto* bytes = static_cast<const std::uint8_t*>(mapped); | ||
| 322 | const UINT cleared = floating ? std::bit_cast<UINT>(42.0f) : clear_value[0]; | ||
| 323 | for (UINT z = 0; z < d; ++z) { | ||
| 324 | const UINT want = (z >= first && z < first + writable) ? cleared : sentinel; | ||
| 325 | for (UINT y = 0; y < h; ++y) { | ||
| 326 | const auto* row = reinterpret_cast<const UINT*>(bytes + (UINT64(z) * h + y) * pitch); | ||
| 327 | for (UINT x = 0; x < w; ++x) | ||
| 328 | EXPECT(row[x] == want); | ||
| 329 | } | ||
| 330 | } | ||
| 331 | readback->Unmap(0, nullptr); | ||
| 332 | return true; | ||
| 255 | } | 333 | } |
| 256 | 334 | ||
| 257 | bool check_case(ID3D12Device* device, Compute* compute, Kind kind, const D3D12_RESOURCE_DESC& shape, | 335 | bool check_case(ID3D12Device* device, Compute* compute, Kind kind, const D3D12_RESOURCE_DESC& shape, |
| @@ -282,7 +360,14 @@ bool check_case(ID3D12Device* device, Compute* compute, Kind kind, const D3D12_R | |||
| 282 | (decoded.first_layer == first && decoded.layer_count == writable)); | 360 | (decoded.first_layer == first && decoded.layer_count == writable)); |
| 283 | device->CopyDescriptorsSimple(1, copy, source, uav_heap); | 361 | device->CopyDescriptorsSimple(1, copy, source, uav_heap); |
| 284 | EXPECT(read_slot(copy) == key); | 362 | EXPECT(read_slot(copy) == key); |
| 285 | if (partial) EXPECT(rejects_partial_clear(device, resource.Get(), copy)); | 363 | if (partial) { |
| 364 | // Reuse the original slot for the whole-mip seed; the copied descriptor must still select its W range. | ||
| 365 | auto whole = desc; | ||
| 366 | whole.Texture3D.FirstWSlice = 0; | ||
| 367 | whole.Texture3D.WSize = ~0u; | ||
| 368 | device->CreateUnorderedAccessView(resource.Get(), nullptr, &whole, source); | ||
| 369 | EXPECT(check_partial_clear(device, resource.Get(), source, copy, shape, mip, first, writable)); | ||
| 370 | } | ||
| 286 | if (partial && first > 0) { | 371 | if (partial && first > 0) { |
| 287 | // A second view of the same volume and mip must not collide with the copied T#. | 372 | // A second view of the same volume and mip must not collide with the copied T#. |
| 288 | auto other = desc; | 373 | auto other = desc; |
diff --git a/runtime/test/d3d12_title_va_test.cpp b/runtime/test/d3d12_title_va_test.cpp index 81a3b2fe5..e5ef14304 100644 --- a/runtime/test/d3d12_title_va_test.cpp +++ b/runtime/test/d3d12_title_va_test.cpp | |||
| @@ -13,10 +13,11 @@ | |||
| 13 | // into a bound table itself, a created CBV and a root view. | 13 | // into a bound table itself, a created CBV and a root view. |
| 14 | // Negative controls: a second title buffer with other data must not be what the first one's V# reads; an arena | 14 | // Negative controls: a second title buffer with other data must not be what the first one's V# reads; an arena |
| 15 | // buffer's V# keeps its VA; the title's range is forgotten when the buffer is released; a raw arena V# and a | 15 | // buffer's V# keeps its VA; the title's range is forgotten when the buffer is released; a raw arena V# and a |
| 16 | // T#-shaped slot in a scanned table keep their bytes; a reserved, uncommitted address is left alone. The shader is test/glsl/cs_user_data.comp. No game data. LEONIDA_VK_VALIDATION=1 for the | 16 | // T#-shaped slot in a scanned table keep their bytes; a reserved, uncommitted title address and memory that is nobody's get zero-size views. The shader is test/glsl/cs_user_data.comp. No game data. LEONIDA_VK_VALIDATION=1 for the |
| 17 | // Khronos validation layer. | 17 | // Khronos validation layer. |
| 18 | #include "shader_fixture_path.h" | 18 | #include "shader_fixture_path.h" |
| 19 | #include "test_temp_dir.h" | 19 | #include "test_temp_dir.h" |
| 20 | #include "d3d12_test_shaders.h" | ||
| 20 | #include "vk_test_device.h" | 21 | #include "vk_test_device.h" |
| 21 | #include "../shims/d3d12_com.h" | 22 | #include "../shims/d3d12_com.h" |
| 22 | #include "../shims/d3d12_xs_device.h" | 23 | #include "../shims/d3d12_xs_device.h" |
| @@ -46,7 +47,6 @@ namespace { | |||
| 46 | using XboxHeapHandleFn = std::uint64_t(WINAPI*)(void* heap); // heap slots 9/10: handle in RAX | 47 | using XboxHeapHandleFn = std::uint64_t(WINAPI*)(void* heap); // heap slots 9/10: handle in RAX |
| 47 | using XboxComputePipelineFn = HRESULT(WINAPI*)(void* device, const D3D12_COMPUTE_PIPELINE_STATE_DESC*, std::uint64_t, | 48 | using XboxComputePipelineFn = HRESULT(WINAPI*)(void* device, const D3D12_COMPUTE_PIPELINE_STATE_DESC*, std::uint64_t, |
| 48 | std::uint64_t, const IID*, void**); | 49 | std::uint64_t, const IID*, void**); |
| 49 | using SerializeFn = HRESULT(WINAPI*)(const D3D12_VERSIONED_ROOT_SIGNATURE_DESC*, ID3DBlob**, ID3DBlob**); | ||
| 50 | 50 | ||
| 51 | template<class T> | 51 | template<class T> |
| 52 | struct Ref { | 52 | struct Ref { |
| @@ -106,19 +106,9 @@ std::vector<std::uint8_t> shader_container(const std::vector<std::uint8_t>& fssm | |||
| 106 | return out; | 106 | return out; |
| 107 | } | 107 | } |
| 108 | 108 | ||
| 109 | // The shared helper: Windows 10's in-box d3d12.dll refuses the heap-directly-indexed flags at every version. | ||
| 109 | std::vector<std::uint8_t> serialize(const D3D12_VERSIONED_ROOT_SIGNATURE_DESC& desc) { | 110 | std::vector<std::uint8_t> serialize(const D3D12_VERSIONED_ROOT_SIGNATURE_DESC& desc) { |
| 110 | const HMODULE d3d12 = LoadLibraryExA("d3d12.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); | 111 | return d3d12test::serialize_root_signature(desc); |
| 111 | const auto fn = d3d12 ? reinterpret_cast<SerializeFn>( | ||
| 112 | reinterpret_cast<void*>(GetProcAddress(d3d12, "D3D12SerializeVersionedRootSignature"))) | ||
| 113 | : nullptr; | ||
| 114 | std::vector<std::uint8_t> out; | ||
| 115 | ID3DBlob* blob = nullptr; | ||
| 116 | if (fn && SUCCEEDED(fn(&desc, &blob, nullptr)) && blob) { | ||
| 117 | const auto* p = static_cast<const std::uint8_t*>(blob->GetBufferPointer()); | ||
| 118 | out.assign(p, p + blob->GetBufferSize()); | ||
| 119 | blob->Release(); | ||
| 120 | } | ||
| 121 | return out; | ||
| 122 | } | 112 | } |
| 123 | 113 | ||
| 124 | D3D12_RESOURCE_DESC buffer_desc(UINT64 bytes, D3D12_RESOURCE_FLAGS flags = D3D12_RESOURCE_FLAG_NONE) { | 114 | D3D12_RESOURCE_DESC buffer_desc(UINT64 bytes, D3D12_RESOURCE_FLAGS flags = D3D12_RESOURCE_FLAG_NONE) { |
| @@ -731,7 +721,9 @@ int check_title_memory(Context& c, int& checks, bool geometry) { | |||
| 731 | static_cast<unsigned long long>(aliases.translated(leonida::TitleVaAliases::root_view) - root_before)); | 721 | static_cast<unsigned long long>(aliases.translated(leonida::TitleVaAliases::root_view) - root_before)); |
| 732 | EXPECT(raw_ok == kElements && cbv_ok == kElements && root_ok == kElements); | 722 | EXPECT(raw_ok == kElements && cbv_ok == kElements && root_ok == kElements); |
| 733 | EXPECT(rewritten && arena_kept && image_kept); | 723 | EXPECT(rewritten && arena_kept && image_kept); |
| 734 | // Neither unrelated host memory nor a reserved-only title page has a GPU copy. | 724 | // Committed memory that is not the title's (the runtime's own, say) and that no allocation of the device's holds: |
| 725 | // heap_base + its address is no allocation either, so its view gets no base and no records, as a title range | ||
| 726 | // with no committed page does (it gets no copy). Neither is counted as left untranslated, and neither has a copy. | ||
| 735 | const std::uint64_t untranslated_before = aliases.untranslated(leonida::TitleVaAliases::created_view); | 727 | const std::uint64_t untranslated_before = aliases.untranslated(leonida::TitleVaAliases::created_view); |
| 736 | void* host = VirtualAlloc(nullptr, 65536, MEM_TOP_DOWN | MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); | 728 | void* host = VirtualAlloc(nullptr, 65536, MEM_TOP_DOWN | MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); |
| 737 | void* gone = VirtualAlloc(nullptr, 65536, MEM_TOP_DOWN | MEM_RESERVE, PAGE_READWRITE); | 729 | void* gone = VirtualAlloc(nullptr, 65536, MEM_TOP_DOWN | MEM_RESERVE, PAGE_READWRITE); |
diff --git a/runtime/test/d3d12_uav_clear_test.cpp b/runtime/test/d3d12_uav_clear_test.cpp index 2d13ba59b..567010ecd 100644 --- a/runtime/test/d3d12_uav_clear_test.cpp +++ b/runtime/test/d3d12_uav_clear_test.cpp | |||
| @@ -9,6 +9,8 @@ | |||
| 9 | // No shaders or game data. Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation; any validation | 9 | // No shaders or game data. Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation; any validation |
| 10 | // error fails the test. | 10 | // error fails the test. |
| 11 | #include "vk_test_device.h" | 11 | #include "vk_test_device.h" |
| 12 | #include "d3d12_texture_uav_oracle.h" | ||
| 13 | #include "host_wine.h" | ||
| 12 | #include "../shims/d3d12_com.h" | 14 | #include "../shims/d3d12_com.h" |
| 13 | #include "../src/gfx10_descriptors.h" | 15 | #include "../src/gfx10_descriptors.h" |
| 14 | #include "../src/uav_clear.h" | 16 | #include "../src/uav_clear.h" |
| @@ -159,6 +161,9 @@ struct Clear { | |||
| 159 | std::uint32_t mip = 0; // texture | 161 | std::uint32_t mip = 0; // texture |
| 160 | std::uint32_t first_layer = 0; | 162 | std::uint32_t first_layer = 0; |
| 161 | std::uint32_t layer_count = 1; | 163 | std::uint32_t layer_count = 1; |
| 164 | bool tagged_volume = false; // encode volume_uav_flag + volume_uav_word(first_layer, layer_count) | ||
| 165 | bool packed_uav = false; // also set packed_uav_flag (emulated RGB9E5) | ||
| 166 | std::uint32_t descriptor_depth = 0; // override the raw 3D T# depth independently of the resource | ||
| 162 | }; | 167 | }; |
| 163 | 168 | ||
| 164 | struct BufferCase { | 169 | struct BufferCase { |
| @@ -182,16 +187,18 @@ struct Harness { | |||
| 182 | ID3D12CommandQueue* queue = nullptr; | 187 | ID3D12CommandQueue* queue = nullptr; |
| 183 | ID3D12Fence* fence = nullptr; | 188 | ID3D12Fence* fence = nullptr; |
| 184 | UINT64 fence_value = 0; | 189 | UINT64 fence_value = 0; |
| 185 | std::byte* slots = nullptr; // CPU descriptor heap | 190 | D3D12_CPU_DESCRIPTOR_HANDLE cpu_start{}; |
| 191 | ID3D12DescriptorHeap* native_visible = nullptr; // WARP needs matching CPU and GPU descriptors | ||
| 186 | UINT step = 0; | 192 | UINT step = 0; |
| 187 | 193 | ||
| 188 | D3D12_CPU_DESCRIPTOR_HANDLE slot(UINT i) const { return {reinterpret_cast<SIZE_T>(slots + std::size_t(i) * step)}; } | 194 | D3D12_CPU_DESCRIPTOR_HANDLE slot(UINT i) const { return {cpu_start.ptr + SIZE_T(i) * step}; } |
| 189 | 195 | ||
| 190 | template<class Words> | 196 | template<class Words> |
| 191 | D3D12_CPU_DESCRIPTOR_HANDLE write(UINT i, const Words& words) const { | 197 | D3D12_CPU_DESCRIPTOR_HANDLE write(UINT i, const Words& words) const { |
| 192 | std::memset(slots + std::size_t(i) * step, 0, step); | 198 | const auto cpu = slot(i); |
| 193 | std::memcpy(slots + std::size_t(i) * step, words.data(), sizeof(words)); | 199 | std::memset(reinterpret_cast<void*>(cpu.ptr), 0, step); |
| 194 | return slot(i); | 200 | std::memcpy(reinterpret_cast<void*>(cpu.ptr), words.data(), sizeof(words)); |
| 201 | return cpu; | ||
| 195 | } | 202 | } |
| 196 | 203 | ||
| 197 | // Records with `body`, executes, waits. The result of the replay. | 204 | // Records with `body`, executes, waits. The result of the replay. |
| @@ -199,24 +206,26 @@ struct Harness { | |||
| 199 | leonida::ReplayResult run(HRESULT& close, Body&& body) { | 206 | leonida::ReplayResult run(HRESULT& close, Body&& body) { |
| 200 | Ref<ID3D12CommandAllocator> allocator; | 207 | Ref<ID3D12CommandAllocator> allocator; |
| 201 | Ref<ID3D12GraphicsCommandList> list; | 208 | Ref<ID3D12GraphicsCommandList> list; |
| 202 | if (FAILED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p))) || | 209 | const auto type = queue->GetDesc().Type; |
| 203 | FAILED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, nullptr, | 210 | if (FAILED(device->CreateCommandAllocator(type, IID_PPV_ARGS(&allocator.p))) || |
| 204 | IID_PPV_ARGS(&list.p)))) | 211 | FAILED(device->CreateCommandList(0, type, allocator.p, nullptr, IID_PPV_ARGS(&list.p)))) |
| 205 | return leonida::ReplayResult::unsupported; | 212 | return leonida::ReplayResult::unsupported; |
| 213 | if (native_visible) list->SetDescriptorHeaps(1, &native_visible); | ||
| 206 | body(list.p); | 214 | body(list.p); |
| 207 | close = list->Close(); | 215 | close = list->Close(); |
| 208 | if (FAILED(close)) return leonida::ReplayResult::success; | 216 | if (FAILED(close)) return leonida::ReplayResult::success; |
| 209 | ID3D12CommandList* lists[] = {list.p}; | 217 | ID3D12CommandList* lists[] = {list.p}; |
| 210 | queue->ExecuteCommandLists(1, lists); | 218 | queue->ExecuteCommandLists(1, lists); |
| 211 | const auto result = rt::d3d12::last_execute_result(queue); | 219 | const auto result = native_visible ? leonida::ReplayResult::success : rt::d3d12::last_execute_result(queue); |
| 212 | queue->Signal(fence, ++fence_value); | 220 | if (FAILED(queue->Signal(fence, ++fence_value)) || FAILED(fence->SetEventOnCompletion(fence_value, nullptr))) |
| 213 | fence->SetEventOnCompletion(fence_value, nullptr); | 221 | return leonida::ReplayResult::unsupported; |
| 214 | return result; | 222 | return result; |
| 215 | } | 223 | } |
| 216 | 224 | ||
| 217 | Ref<ID3D12Resource> committed(const D3D12_RESOURCE_DESC& desc, D3D12_HEAP_TYPE type) const { | 225 | Ref<ID3D12Resource> committed(const D3D12_RESOURCE_DESC& desc, D3D12_HEAP_TYPE type) const { |
| 218 | Ref<ID3D12Resource> out; | 226 | Ref<ID3D12Resource> out; |
| 219 | D3D12_HEAP_PROPERTIES heap{type}; | 227 | D3D12_HEAP_PROPERTIES heap{type}; |
| 228 | heap.CreationNodeMask = heap.VisibleNodeMask = 1; | ||
| 220 | device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, | 229 | device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, |
| 221 | type == D3D12_HEAP_TYPE_READBACK ? D3D12_RESOURCE_STATE_COPY_DEST | 230 | type == D3D12_HEAP_TYPE_READBACK ? D3D12_RESOURCE_STATE_COPY_DEST |
| 222 | : D3D12_RESOURCE_STATE_UNORDERED_ACCESS, | 231 | : D3D12_RESOURCE_STATE_UNORDERED_ACCESS, |
| @@ -371,19 +380,42 @@ int run_texture(Harness& h, const TextureCase& test) { | |||
| 371 | image.width = test.width; | 380 | image.width = test.width; |
| 372 | image.height = test.height; | 381 | image.height = test.height; |
| 373 | image.depth = test.volume ? test.layers : 1; | 382 | image.depth = test.volume ? test.layers : 1; |
| 374 | image.first_layer = c.first_layer; | 383 | if (c.descriptor_depth) image.depth = c.descriptor_depth; |
| 375 | image.layer_count = c.layer_count; | 384 | image.first_layer = test.volume ? 0 : c.first_layer; |
| 385 | image.layer_count = test.volume ? 1 : c.layer_count; | ||
| 376 | image.first_mip = c.mip; | 386 | image.first_mip = c.mip; |
| 377 | image.mip_count = 1; | 387 | image.mip_count = 1; |
| 378 | image.resource_mips = test.mips; | 388 | image.resource_mips = test.mips; |
| 379 | const auto view = h.write(i, g::encode(image)); | 389 | auto encoded = g::encode(image); |
| 390 | if (test.volume && c.tagged_volume) { | ||
| 391 | encoded[4] |= g::volume_uav_flag; | ||
| 392 | encoded[7] = g::volume_uav_word(c.first_layer, c.layer_count) | | ||
| 393 | (c.packed_uav ? g::packed_uav_flag : 0u); | ||
| 394 | } | ||
| 395 | const auto view = h.slot(i); | ||
| 396 | D3D12_GPU_DESCRIPTOR_HANDLE gpu_view{}; | ||
| 397 | if (h.native_visible) { | ||
| 398 | const UINT depth = std::max(1u, UINT(test.layers) >> c.mip); | ||
| 399 | D3D12_UNORDERED_ACCESS_VIEW_DESC d{}; | ||
| 400 | d.Format = test.format; | ||
| 401 | d.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE3D; | ||
| 402 | d.Texture3D = {c.mip, c.tagged_volume ? c.first_layer : 0u, c.tagged_volume ? c.layer_count : depth}; | ||
| 403 | h.device->CreateUnorderedAccessView(texture.p, nullptr, &d, view); | ||
| 404 | const auto dest = h.native_visible->GetCPUDescriptorHandleForHeapStart(); | ||
| 405 | h.device->CopyDescriptorsSimple(1, {dest.ptr + SIZE_T(i) * h.step}, view, | ||
| 406 | D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); | ||
| 407 | gpu_view = h.native_visible->GetGPUDescriptorHandleForHeapStart(); | ||
| 408 | gpu_view.ptr += UINT64(i) * h.step; | ||
| 409 | } else { | ||
| 410 | h.write(i, encoded); | ||
| 411 | } | ||
| 380 | const auto* rects = c.rects.empty() ? nullptr : c.rects.data(); | 412 | const auto* rects = c.rects.empty() ? nullptr : c.rects.data(); |
| 381 | if (c.is_float) { | 413 | if (c.is_float) { |
| 382 | const float v[4] = {std::bit_cast<float>(c.values[0]), std::bit_cast<float>(c.values[1]), | 414 | const float v[4] = {std::bit_cast<float>(c.values[0]), std::bit_cast<float>(c.values[1]), |
| 383 | std::bit_cast<float>(c.values[2]), std::bit_cast<float>(c.values[3])}; | 415 | std::bit_cast<float>(c.values[2]), std::bit_cast<float>(c.values[3])}; |
| 384 | list->ClearUnorderedAccessViewFloat({0}, view, texture.p, v, UINT(c.rects.size()), rects); | 416 | list->ClearUnorderedAccessViewFloat(gpu_view, view, texture.p, v, UINT(c.rects.size()), rects); |
| 385 | } else { | 417 | } else { |
| 386 | list->ClearUnorderedAccessViewUint({0}, view, texture.p, c.values.data(), UINT(c.rects.size()), rects); | 418 | list->ClearUnorderedAccessViewUint(gpu_view, view, texture.p, c.values.data(), UINT(c.rects.size()), rects); |
| 387 | } | 419 | } |
| 388 | D3D12_RESOURCE_BARRIER uav{}; | 420 | D3D12_RESOURCE_BARRIER uav{}; |
| 389 | uav.Type = D3D12_RESOURCE_BARRIER_TYPE_UAV; | 421 | uav.Type = D3D12_RESOURCE_BARRIER_TYPE_UAV; |
| @@ -395,10 +427,12 @@ int run_texture(Harness& h, const TextureCase& test) { | |||
| 395 | const Sub& sub = subs[s]; | 427 | const Sub& sub = subs[s]; |
| 396 | if (sub.mip != c.mip) continue; | 428 | if (sub.mip != c.mip) continue; |
| 397 | if (!test.volume && (sub.layer < c.first_layer || sub.layer >= c.first_layer + c.layer_count)) continue; | 429 | if (!test.volume && (sub.layer < c.first_layer || sub.layer >= c.first_layer + c.layer_count)) continue; |
| 430 | const UINT z_begin = (test.volume && c.tagged_volume) ? c.first_layer : 0u; | ||
| 431 | const UINT z_end = (test.volume && c.tagged_volume) ? (c.first_layer + c.layer_count) : sub.depth; | ||
| 398 | std::vector<D3D12_RECT> rects_or_all = c.rects; | 432 | std::vector<D3D12_RECT> rects_or_all = c.rects; |
| 399 | if (rects_or_all.empty()) rects_or_all.push_back({0, 0, LONG(sub.width), LONG(sub.height)}); | 433 | if (rects_or_all.empty()) rects_or_all.push_back({0, 0, LONG(sub.width), LONG(sub.height)}); |
| 400 | for (const auto& r : rects_or_all) | 434 | for (const auto& r : rects_or_all) |
| 401 | for (UINT z = 0; z < sub.depth; ++z) | 435 | for (UINT z = z_begin; z < z_end; ++z) |
| 402 | for (LONG y = std::max<LONG>(r.top, 0); y < std::min<LONG>(r.bottom, sub.height); ++y) | 436 | for (LONG y = std::max<LONG>(r.top, 0); y < std::min<LONG>(r.bottom, sub.height); ++y) |
| 403 | for (LONG x = std::max<LONG>(r.left, 0); x < std::min<LONG>(r.right, sub.width); ++x) | 437 | for (LONG x = std::max<LONG>(r.left, 0); x < std::min<LONG>(r.right, sub.width); ++x) |
| 404 | std::memcpy(&model[s][((std::size_t(z) * sub.height + y) * sub.width + x) * texel], | 438 | std::memcpy(&model[s][((std::size_t(z) * sub.height + y) * sub.width + x) * texel], |
| @@ -430,11 +464,89 @@ int run_texture(Harness& h, const TextureCase& test) { | |||
| 430 | for (UINT z = 0; z < s.depth; ++z) | 464 | for (UINT z = 0; z < s.depth; ++z) |
| 431 | for (UINT y = 0; y < s.height; ++y) { | 465 | for (UINT y = 0; y < s.height; ++y) { |
| 432 | char what[96]; | 466 | char what[96]; |
| 433 | std::snprintf(what, sizeof(what), "%s mip %u layer %u z %u row %u", test.name, s.mip, s.layer, z, y); | 467 | std::snprintf(what, sizeof(what), "%s %s mip %u layer %u z %u row %u", |
| 468 | h.native_visible ? "WARP" : "Vulkan", test.name, s.mip, s.layer, z, y); | ||
| 434 | compare(what, static_cast<const std::uint8_t*>(data) + s.offset + (UINT64(z) * s.height + y) * s.pitch, | 469 | compare(what, static_cast<const std::uint8_t*>(data) + s.offset + (UINT64(z) * s.height + y) * s.pitch, |
| 435 | &model[i][(std::size_t(z) * s.height + y) * s.width * texel], std::size_t(s.width) * texel); | 470 | &model[i][(std::size_t(z) * s.height + y) * s.width * texel], std::size_t(s.width) * texel); |
| 436 | } | 471 | } |
| 437 | } | 472 | } |
| 473 | readback->Unmap(0, nullptr); | ||
| 474 | return 0; | ||
| 475 | } | ||
| 476 | |||
| 477 | int check_predicated_volume(ID3D12Device* device, D3D12_COMMAND_LIST_TYPE type, UINT family, bool predicate_family) { | ||
| 478 | Ref<ID3D12CommandQueue> queue; | ||
| 479 | Ref<ID3D12Fence> fence; | ||
| 480 | Ref<ID3D12DescriptorHeap> heap; | ||
| 481 | const D3D12_COMMAND_QUEUE_DESC queue_desc{type}; | ||
| 482 | const D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 2}; | ||
| 483 | EXPECT(SUCCEEDED(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue.p)))); | ||
| 484 | EXPECT(queue->GetDesc().Type == type); | ||
| 485 | EXPECT(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p)))); | ||
| 486 | EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&heap.p)))); | ||
| 487 | Harness h; | ||
| 488 | h.device = device; | ||
| 489 | h.queue = queue.p; | ||
| 490 | h.fence = fence.p; | ||
| 491 | h.cpu_start = heap->GetCPUDescriptorHandleForHeapStart(); | ||
| 492 | h.step = device->GetDescriptorHandleIncrementSize(heap_desc.Type); | ||
| 493 | |||
| 494 | D3D12_HEAP_PROPERTIES properties{D3D12_HEAP_TYPE_DEFAULT}; | ||
| 495 | properties.CreationNodeMask = properties.VisibleNodeMask = 1; | ||
| 496 | const auto buffer = buffer_desc(8); | ||
| 497 | Ref<ID3D12Resource> predicate; | ||
| 498 | EXPECT(SUCCEEDED(device->CreateCommittedResource(&properties, D3D12_HEAP_FLAG_NONE, &buffer, | ||
| 499 | D3D12_RESOURCE_STATE_PREDICATION, nullptr, IID_PPV_ARGS(&predicate.p)))); | ||
| 500 | D3D12_RESOURCE_DESC desc{}; | ||
| 501 | desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE3D; | ||
| 502 | desc.Width = desc.Height = desc.DepthOrArraySize = 4; | ||
| 503 | desc.MipLevels = 1; | ||
| 504 | desc.SampleDesc.Count = 1; | ||
| 505 | desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; | ||
| 506 | desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; | ||
| 507 | auto volume = h.committed(desc, D3D12_HEAP_TYPE_DEFAULT); | ||
| 508 | EXPECT(volume.p); | ||
| 509 | g::Image image{}; | ||
| 510 | image.format = g::format_from_vulkan(VK_FORMAT_R8G8B8A8_UNORM); | ||
| 511 | image.type = g::ImageType::image_3d; | ||
| 512 | image.width = image.height = image.depth = 4; | ||
| 513 | auto words = g::encode(image); | ||
| 514 | const auto whole = h.write(0, words); | ||
| 515 | words[4] |= g::volume_uav_flag; | ||
| 516 | words[7] = g::volume_uav_word(1, 2); | ||
| 517 | const auto partial = h.write(1, words); | ||
| 518 | const UINT values[4] = {1, 2, 3, 4}; | ||
| 519 | const D3D12_RECT rect{0, 0, 2, 2}; | ||
| 520 | |||
| 521 | HRESULT close = E_FAIL; | ||
| 522 | const auto run = [&](auto&& body) { | ||
| 523 | close = E_FAIL; | ||
| 524 | return h.run(close, [&](ID3D12GraphicsCommandList* list) { | ||
| 525 | list->SetPredication(predicate.p, 0, D3D12_PREDICATION_OP_EQUAL_ZERO); | ||
| 526 | body(list); | ||
| 527 | }); | ||
| 528 | }; | ||
| 529 | const auto control = run([](ID3D12GraphicsCommandList* list) { | ||
| 530 | list->SetPredication(nullptr, 0, D3D12_PREDICATION_OP_EQUAL_ZERO); | ||
| 531 | }); | ||
| 532 | EXPECT(close == S_OK && fence->GetCompletedValue() == h.fence_value); | ||
| 533 | // The predicate reducer currently belongs to the direct family. A dedicated compute queue may | ||
| 534 | // refuse the entire batch before replay. The shared-family compute control must reach the clear. | ||
| 535 | EXPECT(control == leonida::ReplayResult::success || | ||
| 536 | (!predicate_family && control == leonida::ReplayResult::unsupported)); | ||
| 537 | EXPECT(run([&](ID3D12GraphicsCommandList* list) { | ||
| 538 | list->ClearUnorderedAccessViewUint({0}, partial, volume.p, values, 0, nullptr); | ||
| 539 | }) == leonida::ReplayResult::unsupported); | ||
| 540 | EXPECT(close == S_OK && fence->GetCompletedValue() == h.fence_value); | ||
| 541 | if (type == D3D12_COMMAND_LIST_TYPE_DIRECT) { | ||
| 542 | EXPECT(run([&](ID3D12GraphicsCommandList* list) { | ||
| 543 | list->ClearUnorderedAccessViewUint({0}, whole, volume.p, values, 1, &rect); | ||
| 544 | }) == leonida::ReplayResult::unsupported); | ||
| 545 | EXPECT(close == S_OK && fence->GetCompletedValue() == h.fence_value); | ||
| 546 | } | ||
| 547 | std::printf("3D UAV predication: %s family %u, predicate control %s, staged clear refused\n", | ||
| 548 | type == D3D12_COMMAND_LIST_TYPE_DIRECT ? "direct" : "compute", family, | ||
| 549 | control == leonida::ReplayResult::success ? "passed" : "refused before replay"); | ||
| 438 | return 0; | 550 | return 0; |
| 439 | } | 551 | } |
| 440 | 552 | ||
| @@ -444,6 +556,7 @@ int main() { | |||
| 444 | if (conversion_checks()) return 1; | 556 | if (conversion_checks()) return 1; |
| 445 | 557 | ||
| 446 | vktest::Device d; | 558 | vktest::Device d; |
| 559 | d.all_queue_types = true; | ||
| 447 | const auto device_status = d.initialize(); | 560 | const auto device_status = d.initialize(); |
| 448 | if (device_status == vktest::DeviceStatus::unavailable) return 77; // no Vulkan GPU: ctest skips | 561 | if (device_status == vktest::DeviceStatus::unavailable) return 77; // no Vulkan GPU: ctest skips |
| 449 | if (device_status != vktest::DeviceStatus::ready) return 1; | 562 | if (device_status != vktest::DeviceStatus::ready) return 1; |
| @@ -455,6 +568,10 @@ int main() { | |||
| 455 | info.device = d.device; | 568 | info.device = d.device; |
| 456 | info.queue = d.queue; | 569 | info.queue = d.queue; |
| 457 | info.queue_family = d.family; | 570 | info.queue_family = d.family; |
| 571 | info.command_queues = d.queues; | ||
| 572 | info.compute_queues = {d.compute_queue}; | ||
| 573 | info.compute_family = d.compute_family; | ||
| 574 | info.conditional_rendering = d.conditional_rendering; | ||
| 458 | Ref<ID3D12Device> device; | 575 | Ref<ID3D12Device> device; |
| 459 | EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&device.p)))); | 576 | EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&device.p)))); |
| 460 | Ref<ID3D12CommandQueue> queue; | 577 | Ref<ID3D12CommandQueue> queue; |
| @@ -470,7 +587,7 @@ int main() { | |||
| 470 | h.device = device.p; | 587 | h.device = device.p; |
| 471 | h.queue = queue.p; | 588 | h.queue = queue.p; |
| 472 | h.fence = fence.p; | 589 | h.fence = fence.p; |
| 473 | h.slots = reinterpret_cast<std::byte*>(heap->GetCPUDescriptorHandleForHeapStart().ptr); | 590 | h.cpu_start = heap->GetCPUDescriptorHandleForHeapStart(); |
| 474 | h.step = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); | 591 | h.step = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); |
| 475 | EXPECT(h.step >= sizeof(g::ImageWords)); | 592 | EXPECT(h.step >= sizeof(g::ImageWords)); |
| 476 | 593 | ||
| @@ -573,7 +690,8 @@ int main() { | |||
| 573 | 690 | ||
| 574 | const auto texture_clear = [](VkFormat format, bool is_float, std::array<std::uint32_t, 4> values, | 691 | const auto texture_clear = [](VkFormat format, bool is_float, std::array<std::uint32_t, 4> values, |
| 575 | std::uint32_t mip, std::uint32_t first_layer, std::uint32_t layer_count, | 692 | std::uint32_t mip, std::uint32_t first_layer, std::uint32_t layer_count, |
| 576 | std::vector<D3D12_RECT> rects = {}) { | 693 | std::vector<D3D12_RECT> rects = {}, bool tagged_volume = false, |
| 694 | bool packed_uav = false) { | ||
| 577 | Clear c; | 695 | Clear c; |
| 578 | c.format = format; | 696 | c.format = format; |
| 579 | c.is_float = is_float; | 697 | c.is_float = is_float; |
| @@ -582,6 +700,8 @@ int main() { | |||
| 582 | c.first_layer = first_layer; | 700 | c.first_layer = first_layer; |
| 583 | c.layer_count = layer_count; | 701 | c.layer_count = layer_count; |
| 584 | c.rects = std::move(rects); | 702 | c.rects = std::move(rects); |
| 703 | c.tagged_volume = tagged_volume; | ||
| 704 | c.packed_uav = packed_uav; | ||
| 585 | return c; | 705 | return c; |
| 586 | }; | 706 | }; |
| 587 | const std::vector<TextureCase> textures = { | 707 | const std::vector<TextureCase> textures = { |
| @@ -649,8 +769,50 @@ int main() { | |||
| 649 | {texture_clear(VK_FORMAT_B8G8R8A8_UNORM, true, floats(1.0f, 0.5f, 0.0f, 1.0f), 0, 0, 1)}}, | 769 | {texture_clear(VK_FORMAT_B8G8R8A8_UNORM, true, floats(1.0f, 0.5f, 0.0f, 1.0f), 0, 0, 1)}}, |
| 650 | {"RGBA8_UNORM volume, one mip", DXGI_FORMAT_R8G8B8A8_UNORM, VK_FORMAT_R8G8B8A8_UNORM, 4, 4, 2, 4, true, | 770 | {"RGBA8_UNORM volume, one mip", DXGI_FORMAT_R8G8B8A8_UNORM, VK_FORMAT_R8G8B8A8_UNORM, 4, 4, 2, 4, true, |
| 651 | {texture_clear(VK_FORMAT_R8G8B8A8_UNORM, false, {1, 2, 3, 4}, 1, 0, 1)}}, | 771 | {texture_clear(VK_FORMAT_R8G8B8A8_UNORM, false, {1, 2, 3, 4}, 1, 0, 1)}}, |
| 772 | {"RGBA8_UNORM volume, partial W slices, non-zero mips and rectangles", DXGI_FORMAT_R8G8B8A8_UNORM, | ||
| 773 | VK_FORMAT_R8G8B8A8_UNORM, 8, 8, 3, 8, true, | ||
| 774 | {texture_clear(VK_FORMAT_R8G8B8A8_UNORM, false, {0x11, 0x22, 0x33, 0x44}, 0, 0, 8, {}, true), | ||
| 775 | texture_clear(VK_FORMAT_R8G8B8A8_UNORM, true, floats(1.0f, 0.25f, 0.0f, 1.0f), 0, 2, 3, {}, true), | ||
| 776 | texture_clear(VK_FORMAT_R8G8B8A8_UNORM, false, {0xaa, 0xbb, 0xcc, 0xdd}, 0, 5, 3, | ||
| 777 | {{-1, 1, 4, 5}, {2, 3, 12, 7}}, true), | ||
| 778 | texture_clear(VK_FORMAT_R8G8B8A8_UNORM, false, {0x55, 0x66, 0x77, 0x88}, 1, 1, 2, {}, true), | ||
| 779 | texture_clear(VK_FORMAT_R8G8B8A8_UNORM, true, floats(0.0f, 1.0f, 0.25f, 1.0f), 1, 0, 4, | ||
| 780 | {{1, 1, 3, 3}}, false), | ||
| 781 | texture_clear(VK_FORMAT_R8G8B8A8_UNORM, false, {0xfe, 0xed, 0xfa, 0xce}, 2, 1, 1, {}, true)}}, | ||
| 782 | {"R8_UNORM volume, tiny 1..3-byte rect payloads and partial W", DXGI_FORMAT_R8_UNORM, VK_FORMAT_R8_UNORM, | ||
| 783 | 6, 6, 1, 4, true, | ||
| 784 | {texture_clear(VK_FORMAT_R8_UNORM, false, {0x22, 0, 0, 0}, 0, 0, 4, {}, true), | ||
| 785 | texture_clear(VK_FORMAT_R8_UNORM, false, {0x7b, 0, 0, 0}, 0, 1, 1, {{2, 2, 3, 3}}, true), | ||
| 786 | texture_clear(VK_FORMAT_R8_UNORM, true, floats(0.25f, 0, 0, 0), 0, 2, 2, {{1, 4, 4, 5}}, true)}}, | ||
| 787 | {"R16_UINT volume, tiny 2-byte rect payload and partial W", DXGI_FORMAT_R16_UINT, VK_FORMAT_R16_UINT, | ||
| 788 | 4, 4, 1, 4, true, | ||
| 789 | {texture_clear(VK_FORMAT_R16_UINT, false, {0x1234, 0, 0, 0}, 0, 0, 4, {}, true), | ||
| 790 | texture_clear(VK_FORMAT_R16_UINT, false, {0xbeef, 0, 0, 0}, 0, 2, 1, {{1, 1, 2, 2}}, true)}}, | ||
| 791 | {"R32G32_SINT volume, 8-byte partial W and rectangles", DXGI_FORMAT_R32G32_SINT, VK_FORMAT_R32G32_SINT, | ||
| 792 | 8, 4, 1, 4, true, | ||
| 793 | {texture_clear(VK_FORMAT_R32G32_SINT, false, {0x11111111u, 0x22222222u, 0, 0}, 0, 0, 4, {}, true), | ||
| 794 | texture_clear(VK_FORMAT_R32G32_SINT, true, floats(-7.9f, 7.9f, 0, 0), 0, 1, 2, {{1, 1, 6, 3}}, true)}}, | ||
| 795 | {"RGBA32_UINT volume, 16-byte partial W and rectangles", DXGI_FORMAT_R32G32B32A32_UINT, | ||
| 796 | VK_FORMAT_R32G32B32A32_UINT, 8, 6, 2, 4, true, | ||
| 797 | {texture_clear(VK_FORMAT_R32G32B32A32_UINT, false, {1, 2, 3, 4}, 0, 0, 4, {}, true), | ||
| 798 | texture_clear(VK_FORMAT_R32G32B32A32_UINT, false, {9, 8, 7, 6}, 0, 1, 2, {{1, 1, 5, 4}}, true), | ||
| 799 | texture_clear(VK_FORMAT_R32G32B32A32_UINT, true, floats(2.9f, -1.0f, 1e10f, NAN), 1, 1, 1, {}, true)}}, | ||
| 800 | {"RGBA16_SFLOAT volume, large tiled slice (> 64 KiB)", DXGI_FORMAT_R16G16B16A16_FLOAT, | ||
| 801 | VK_FORMAT_R16G16B16A16_SFLOAT, 128, 96, 1, 3, true, | ||
| 802 | {texture_clear(VK_FORMAT_R16G16B16A16_SFLOAT, false, {0x3c00, 0x4000, 0xc000, 0x3800}, 0, 0, 3, {}, true), | ||
| 803 | texture_clear(VK_FORMAT_R16G16B16A16_SFLOAT, true, floats(0.25f, -8.0f, 1.0f, 0.0f), 0, 1, 1, {}, true)}}, | ||
| 652 | }; | 804 | }; |
| 653 | std::vector<TextureCase> all_textures = textures; | 805 | std::vector<TextureCase> all_textures = textures; |
| 806 | for (const auto depth : {2u, 8u}) { | ||
| 807 | // An untagged T# covers both W slices of mip 1 of a four-deep resource, regardless of its DEPTH. | ||
| 808 | auto clear = texture_clear(VK_FORMAT_R32_UINT, false, {97, 0, 0, 0}, 1, 0, 2); | ||
| 809 | clear.descriptor_depth = depth; | ||
| 810 | all_textures.push_back({ | ||
| 811 | depth == 2 ? "untagged 3D T# depth 2" : "untagged 3D T# depth 8", | ||
| 812 | DXGI_FORMAT_R32_UINT, VK_FORMAT_R32_UINT, 4, 4, 2, 4, true, | ||
| 813 | {texture_clear(VK_FORMAT_R32_UINT, false, {13, 0, 0, 0}, 0, 0, 4), | ||
| 814 | texture_clear(VK_FORMAT_R32_UINT, false, {31, 0, 0, 0}, 1, 0, 2), clear}}); | ||
| 815 | } | ||
| 654 | { | 816 | { |
| 655 | D3D12_FEATURE_DATA_FORMAT_SUPPORT e5_support{DXGI_FORMAT_R9G9B9E5_SHAREDEXP}; | 817 | D3D12_FEATURE_DATA_FORMAT_SUPPORT e5_support{DXGI_FORMAT_R9G9B9E5_SHAREDEXP}; |
| 656 | if (SUCCEEDED(device->CheckFeatureSupport(D3D12_FEATURE_FORMAT_SUPPORT, &e5_support, sizeof(e5_support))) && | 818 | if (SUCCEEDED(device->CheckFeatureSupport(D3D12_FEATURE_FORMAT_SUPPORT, &e5_support, sizeof(e5_support))) && |
| @@ -677,6 +839,24 @@ int main() { | |||
| 677 | {0x12345678u, 0x9abcdef0u, 0u, 0u}, 0, 0, 1, {{2, 3, 4, 5}})); | 839 | {0x12345678u, 0x9abcdef0u, 0u, 0u}, 0, 0, 1, {{2, 3, 4, 5}})); |
| 678 | } | 840 | } |
| 679 | all_textures.push_back(std::move(e5)); | 841 | all_textures.push_back(std::move(e5)); |
| 842 | |||
| 843 | TextureCase e5_vol{"R9G9B9E5_SHAREDEXP volume, partial W slices and rectangles", | ||
| 844 | DXGI_FORMAT_R9G9B9E5_SHAREDEXP, VK_FORMAT_E5B9G9R9_UFLOAT_PACK32, 8, 8, 2, 4, true, | ||
| 845 | {texture_clear(VK_FORMAT_E5B9G9R9_UFLOAT_PACK32, true, | ||
| 846 | floats(0.5f, 0.25f, 0.125f, 0.0f), 0, 0, 4, {}, true, !native_storage), | ||
| 847 | texture_clear(VK_FORMAT_E5B9G9R9_UFLOAT_PACK32, true, | ||
| 848 | floats(1.0f, 2.0f, 4.0f, 0.0f), 0, 1, 2, {{1, 2, 6, 5}}, true, | ||
| 849 | !native_storage), | ||
| 850 | // Seed both mip-1 slices so skipping or widening the zero-valued Uint clear is visible. | ||
| 851 | texture_clear(VK_FORMAT_E5B9G9R9_UFLOAT_PACK32, true, | ||
| 852 | floats(1.0f, 2.0f, 4.0f, 0.0f), 1, 0, 2, {}, true, !native_storage), | ||
| 853 | texture_clear(VK_FORMAT_E5B9G9R9_UFLOAT_PACK32, false, | ||
| 854 | {0x3f800000u, 0xffffffffu, 1u, 2u}, 1, 1, 1, {}, true, | ||
| 855 | !native_storage), | ||
| 856 | texture_clear(VK_FORMAT_E5B9G9R9_UFLOAT_PACK32, true, | ||
| 857 | floats(4.0f, 2.0f, 1.0f, 0.0f), 1, 0, 1, {{1, 1, 3, 3}}, true, | ||
| 858 | !native_storage)}}; | ||
| 859 | all_textures.push_back(std::move(e5_vol)); | ||
| 680 | } | 860 | } |
| 681 | } | 861 | } |
| 682 | { | 862 | { |
| @@ -697,6 +877,63 @@ int main() { | |||
| 697 | for (const auto& test : all_textures) | 877 | for (const auto& test : all_textures) |
| 698 | if (run_texture(h, test)) return 1; | 878 | if (run_texture(h, test)) return 1; |
| 699 | 879 | ||
| 880 | // The same bounded W view (including its first and last untouched neighbors) and nonzero mip on | ||
| 881 | // both APIs. Submit the clear and copy on the same command-list type and compare every texel. | ||
| 882 | const std::array volume_parity = { | ||
| 883 | TextureCase{"3D Uint clear parity", DXGI_FORMAT_R32_UINT, VK_FORMAT_R32_UINT, 8, 8, 2, 8, true, | ||
| 884 | {texture_clear(VK_FORMAT_R32_UINT, false, {13, 0, 0, 0}, 0, 0, 8), | ||
| 885 | texture_clear(VK_FORMAT_R32_UINT, false, {31, 0, 0, 0}, 1, 0, 4), | ||
| 886 | texture_clear(VK_FORMAT_R32_UINT, false, {57, 0, 0, 0}, 1, 1, 2, {}, true), | ||
| 887 | texture_clear(VK_FORMAT_R32_UINT, false, {99, 0, 0, 0}, 1, 1, 2, {{1, 1, 3, 3}}, true)}}, | ||
| 888 | TextureCase{"3D Float clear parity", DXGI_FORMAT_R32_FLOAT, VK_FORMAT_R32_SFLOAT, 8, 8, 2, 8, true, | ||
| 889 | {texture_clear(VK_FORMAT_R32_SFLOAT, true, floats(0.5f, 0, 0, 0), 0, 0, 8), | ||
| 890 | texture_clear(VK_FORMAT_R32_SFLOAT, true, floats(0.25f, 0, 0, 0), 1, 0, 4), | ||
| 891 | texture_clear(VK_FORMAT_R32_SFLOAT, true, floats(-2.0f, 0, 0, 0), 1, 1, 2, {}, true), | ||
| 892 | texture_clear(VK_FORMAT_R32_SFLOAT, true, floats(4.5f, 0, 0, 0), 1, 1, 2, {{1, 1, 3, 3}}, true)}}, | ||
| 893 | }; | ||
| 894 | const auto run_volume_parity = [&](Harness& target) { | ||
| 895 | for (const auto type : {D3D12_COMMAND_LIST_TYPE_DIRECT, D3D12_COMMAND_LIST_TYPE_COMPUTE}) { | ||
| 896 | Ref<ID3D12CommandQueue> q; | ||
| 897 | const D3D12_COMMAND_QUEUE_DESC desc{type}; | ||
| 898 | EXPECT(SUCCEEDED(target.device->CreateCommandQueue(&desc, IID_PPV_ARGS(&q.p)))); | ||
| 899 | EXPECT(q->GetDesc().Type == type); | ||
| 900 | Harness pass = target; | ||
| 901 | pass.queue = q.p; | ||
| 902 | for (const auto& test : volume_parity) | ||
| 903 | if (run_texture(pass, test)) return 1; | ||
| 904 | target.fence_value = pass.fence_value; | ||
| 905 | } | ||
| 906 | return 0; | ||
| 907 | }; | ||
| 908 | const auto mismatches_before_parity = mismatches; | ||
| 909 | EXPECT(run_volume_parity(h) == 0); | ||
| 910 | if (!hostwine::host_is_wine()) { | ||
| 911 | uav_oracle::detail::Context warp; | ||
| 912 | const auto status = warp.prepare_device(); | ||
| 913 | EXPECT(status != uav_oracle::Status::failed); | ||
| 914 | if (status == uav_oracle::Status::ready) { | ||
| 915 | Ref<ID3D12DescriptorHeap> cpu, visible; | ||
| 916 | Ref<ID3D12Fence> host_fence; | ||
| 917 | auto hd = heap_desc; | ||
| 918 | EXPECT(SUCCEEDED(warp.device->CreateDescriptorHeap(&hd, IID_PPV_ARGS(&cpu.p)))); | ||
| 919 | hd.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE; | ||
| 920 | EXPECT(SUCCEEDED(warp.device->CreateDescriptorHeap(&hd, IID_PPV_ARGS(&visible.p)))); | ||
| 921 | EXPECT(SUCCEEDED(warp.device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&host_fence.p)))); | ||
| 922 | Harness host; | ||
| 923 | host.device = warp.device.Get(); | ||
| 924 | host.fence = host_fence.p; | ||
| 925 | host.cpu_start = cpu->GetCPUDescriptorHandleForHeapStart(); | ||
| 926 | host.native_visible = visible.p; | ||
| 927 | host.step = host.device->GetDescriptorHandleIncrementSize(hd.Type); | ||
| 928 | EXPECT(run_volume_parity(host) == 0); | ||
| 929 | EXPECT(mismatches == mismatches_before_parity); | ||
| 930 | std::printf("3D UAV clear parity: Vulkan (direct family %u, compute family %u) and WARP " | ||
| 931 | "direct/compute Uint/Float readbacks matched\n", d.family, d.compute_family); | ||
| 932 | } else { | ||
| 933 | std::puts("3D UAV clear WARP comparison skipped: WARP unavailable"); | ||
| 934 | } | ||
| 935 | } | ||
| 936 | |||
| 700 | // Refused while recording (Close says E_INVALIDARG): no values, an empty slot, no resource. | 937 | // Refused while recording (Close says E_INVALIDARG): no values, an empty slot, no resource. |
| 701 | { | 938 | { |
| 702 | Ref<ID3D12Resource> buffer = h.committed(buffer_desc(256), D3D12_HEAP_TYPE_DEFAULT); | 939 | Ref<ID3D12Resource> buffer = h.committed(buffer_desc(256), D3D12_HEAP_TYPE_DEFAULT); |
| @@ -707,7 +944,7 @@ int main() { | |||
| 707 | return close; | 944 | return close; |
| 708 | }; | 945 | }; |
| 709 | const auto good = h.write(0, buffer_view(buffer->GetGPUVirtualAddress(), whole(64))); | 946 | const auto good = h.write(0, buffer_view(buffer->GetGPUVirtualAddress(), whole(64))); |
| 710 | std::memset(h.slots + h.step, 0, h.step); | 947 | std::memset(reinterpret_cast<void*>(h.slot(1).ptr), 0, h.step); |
| 711 | EXPECT(check([&](ID3D12GraphicsCommandList* l) { | 948 | EXPECT(check([&](ID3D12GraphicsCommandList* l) { |
| 712 | l->ClearUnorderedAccessViewUint({0}, good, buffer.p, nullptr, 0, nullptr); | 949 | l->ClearUnorderedAccessViewUint({0}, good, buffer.p, nullptr, 0, nullptr); |
| 713 | }) == E_INVALIDARG); | 950 | }) == E_INVALIDARG); |
| @@ -723,7 +960,7 @@ int main() { | |||
| 723 | }) == E_INVALIDARG); | 960 | }) == E_INVALIDARG); |
| 724 | 961 | ||
| 725 | // Refused at execution, before anything is submitted: a buffer view of a texture, a texture view of a | 962 | // Refused at execution, before anything is submitted: a buffer view of a texture, a texture view of a |
| 726 | // buffer, a mip the texture does not have, a buffer view past the end, a rectangle clear of a volume. | 963 | // buffer, a mip the texture does not have, and a buffer view past the end. |
| 727 | D3D12_RESOURCE_DESC desc{}; | 964 | D3D12_RESOURCE_DESC desc{}; |
| 728 | desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; | 965 | desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; |
| 729 | desc.Width = desc.Height = 4; | 966 | desc.Width = desc.Height = 4; |
| @@ -754,7 +991,7 @@ int main() { | |||
| 754 | const auto replay = [&](auto&& body) { | 991 | const auto replay = [&](auto&& body) { |
| 755 | HRESULT close = E_FAIL; | 992 | HRESULT close = E_FAIL; |
| 756 | const auto result = h.run(close, body); | 993 | const auto result = h.run(close, body); |
| 757 | return close == S_OK ? result : leonida::ReplayResult::success; | 994 | return close == S_OK ? result : leonida::ReplayResult::list_open; |
| 758 | }; | 995 | }; |
| 759 | EXPECT(replay([&](ID3D12GraphicsCommandList* l) { | 996 | EXPECT(replay([&](ID3D12GraphicsCommandList* l) { |
| 760 | l->ClearUnorderedAccessViewUint({0}, good, texture.p, values, 0, nullptr); | 997 | l->ClearUnorderedAccessViewUint({0}, good, texture.p, values, 0, nullptr); |
| @@ -768,9 +1005,47 @@ int main() { | |||
| 768 | EXPECT(replay([&](ID3D12GraphicsCommandList* l) { | 1005 | EXPECT(replay([&](ID3D12GraphicsCommandList* l) { |
| 769 | l->ClearUnorderedAccessViewUint({0}, past_view, buffer.p, values, 0, nullptr); | 1006 | l->ClearUnorderedAccessViewUint({0}, past_view, buffer.p, values, 0, nullptr); |
| 770 | }) == leonida::ReplayResult::invalid_subresource); | 1007 | }) == leonida::ReplayResult::invalid_subresource); |
| 1008 | // Untagged whole-volume rectangle clear now succeeds on Vulkan. | ||
| 771 | EXPECT(replay([&](ID3D12GraphicsCommandList* l) { | 1009 | EXPECT(replay([&](ID3D12GraphicsCommandList* l) { |
| 772 | l->ClearUnorderedAccessViewUint({0}, v_view, volume.p, values, 1, &rect); | 1010 | l->ClearUnorderedAccessViewUint({0}, v_view, volume.p, values, 1, &rect); |
| 773 | }) == leonida::ReplayResult::unsupported); | 1011 | }) == leonida::ReplayResult::success); |
| 1012 | // Out-of-range 3D W slice range is refused at execution as invalid_subresource. | ||
| 1013 | auto bad_w = g::encode(image); | ||
| 1014 | bad_w[4] |= g::volume_uav_flag; | ||
| 1015 | bad_w[7] = g::volume_uav_word(2, 3); // 2 + 3 > 4 | ||
| 1016 | const auto bad_w_view = h.write(6, bad_w); | ||
| 1017 | EXPECT(replay([&](ID3D12GraphicsCommandList* l) { | ||
| 1018 | l->ClearUnorderedAccessViewUint({0}, bad_w_view, volume.p, values, 0, nullptr); | ||
| 1019 | }) == leonida::ReplayResult::invalid_subresource); | ||
| 1020 | auto part_w = g::encode(image); | ||
| 1021 | part_w[4] |= g::volume_uav_flag; | ||
| 1022 | part_w[7] = g::volume_uav_word(1, 2); | ||
| 1023 | const auto part_w_view = h.write(7, part_w); | ||
| 1024 | for (auto type : {D3D12_COMMAND_LIST_TYPE_COPY, D3D12_COMMAND_LIST_TYPE_BUNDLE}) { | ||
| 1025 | Ref<ID3D12CommandAllocator> allocator; | ||
| 1026 | Ref<ID3D12GraphicsCommandList> list; | ||
| 1027 | EXPECT(SUCCEEDED(device->CreateCommandAllocator(type, IID_PPV_ARGS(&allocator.p)))); | ||
| 1028 | EXPECT(SUCCEEDED(device->CreateCommandList(0, type, allocator.p, nullptr, IID_PPV_ARGS(&list.p)))); | ||
| 1029 | list->ClearUnorderedAccessViewUint({0}, part_w_view, volume.p, values, 1, &rect); | ||
| 1030 | EXPECT(list->Close() == E_INVALIDARG); | ||
| 1031 | } | ||
| 1032 | } | ||
| 1033 | if (d.conditional_rendering) { | ||
| 1034 | EXPECT(check_predicated_volume(device.p, D3D12_COMMAND_LIST_TYPE_DIRECT, d.family, true) == 0); | ||
| 1035 | EXPECT(check_predicated_volume(device.p, D3D12_COMMAND_LIST_TYPE_COMPUTE, d.compute_family, | ||
| 1036 | d.compute_family == d.family) == 0); | ||
| 1037 | if (d.compute_family != d.family) { | ||
| 1038 | // Exercise the COMPUTE-list clear guard after a successful predicate capture, even on | ||
| 1039 | // devices where the regular compute queue cannot use the direct-family predicate reducer. | ||
| 1040 | auto shared = info; | ||
| 1041 | shared.compute_family = d.family; | ||
| 1042 | shared.compute_queues = {d.queue}; | ||
| 1043 | Ref<ID3D12Device> shared_device; | ||
| 1044 | EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(shared, IID_PPV_ARGS(&shared_device.p)))); | ||
| 1045 | EXPECT(check_predicated_volume(shared_device.p, D3D12_COMMAND_LIST_TYPE_COMPUTE, d.family, true) == 0); | ||
| 1046 | } | ||
| 1047 | } else { | ||
| 1048 | std::puts("3D UAV GPU predication checks skipped: VK_EXT_conditional_rendering unavailable"); | ||
| 774 | } | 1049 | } |
| 775 | } | 1050 | } |
| 776 | 1051 | ||
diff --git a/runtime/test/d3d12_unbound_tsharp_rules_test.cpp b/runtime/test/d3d12_unbound_tsharp_rules_test.cpp new file mode 100644 index 000000000..bc9aa1ca9 --- /dev/null +++ b/runtime/test/d3d12_unbound_tsharp_rules_test.cpp | |||
| @@ -0,0 +1,394 @@ | |||
| 1 | // Tests for console descriptor heap T# binding rules and per-reason refusal tracking (RT-UNBOUND-TSHARP-REASONS). | ||
| 2 | // Verifies: | ||
| 3 | // 1. 1D rule: dimension and layer count compatibility ("T# type or samples do not fit the texture"). | ||
| 4 | // 2. Array rule: layer range bounds ("T# names layers the texture lacks"). | ||
| 5 | // 3. Cube rule: minimum layer requirement ("cube T# on fewer than six layers"). | ||
| 6 | // 4. MSAA rule: sample count matching ("T# type or samples do not fit the texture"). | ||
| 7 | // 5. Unbound T# reason tracking: distinct slots and total refusal counts tracked per reason. | ||
| 8 | #include "../shims/d3d12_com.h" | ||
| 9 | #include "../shims/d3d12_xs_device.h" | ||
| 10 | #include "../src/gfx10_descriptors.h" | ||
| 11 | |||
| 12 | #include <cstdio> | ||
| 13 | #include <cstdlib> | ||
| 14 | #include <cstring> | ||
| 15 | #include <string> | ||
| 16 | |||
| 17 | namespace { | ||
| 18 | |||
| 19 | int g_checks = 0; | ||
| 20 | int g_failures = 0; | ||
| 21 | |||
| 22 | void check(bool condition, const char* what) { | ||
| 23 | ++g_checks; | ||
| 24 | if (!condition) { | ||
| 25 | ++g_failures; | ||
| 26 | std::fprintf(stderr, "FAIL: %s\n", what); | ||
| 27 | } | ||
| 28 | } | ||
| 29 | |||
| 30 | template <class T> | ||
| 31 | struct Ref { | ||
| 32 | T* p = nullptr; | ||
| 33 | ~Ref() { | ||
| 34 | if (p) p->Release(); | ||
| 35 | } | ||
| 36 | T** put() { | ||
| 37 | if (p) { | ||
| 38 | p->Release(); | ||
| 39 | p = nullptr; | ||
| 40 | } | ||
| 41 | return &p; | ||
| 42 | } | ||
| 43 | T* operator->() const { return p; } | ||
| 44 | }; | ||
| 45 | |||
| 46 | } // namespace | ||
| 47 | |||
| 48 | int main() { | ||
| 49 | namespace g = leonida::gfx10; | ||
| 50 | |||
| 51 | // Test 1: Unbound T# statistics and per-reason tracking | ||
| 52 | { | ||
| 53 | rt::d3d12::reset_unbound_tsharp_stats(); | ||
| 54 | std::array<std::uint32_t, 8> dummy_words{}; | ||
| 55 | |||
| 56 | const char* reason_type = "T# type or samples do not fit the texture"; | ||
| 57 | const char* reason_layers = "T# names layers the texture lacks"; | ||
| 58 | |||
| 59 | // Slot 0x00 refused for type | ||
| 60 | rt::d3d12::note_refused_tsharp_for_test(0x10000, 0x00, dummy_words, reason_type); | ||
| 61 | // Slot 0x20 refused for type | ||
| 62 | rt::d3d12::note_refused_tsharp_for_test(0x10000, 0x20, dummy_words, reason_type); | ||
| 63 | // Slot 0x00 refused again for type (repeated scan) | ||
| 64 | rt::d3d12::note_refused_tsharp_for_test(0x10000, 0x00, dummy_words, reason_type); | ||
| 65 | // Slot 0x40 refused for layers | ||
| 66 | rt::d3d12::note_refused_tsharp_for_test(0x10000, 0x40, dummy_words, reason_layers); | ||
| 67 | |||
| 68 | const auto stats = rt::d3d12::unbound_tsharp_stats(); | ||
| 69 | check(stats.total_distinct_slots == 3, "total distinct slots is 3"); | ||
| 70 | check(stats.total_refusals == 4, "total refusals is 4"); | ||
| 71 | |||
| 72 | const auto it_type = stats.by_reason.find(reason_type); | ||
| 73 | check(it_type != stats.by_reason.end(), "reason_type recorded in stats"); | ||
| 74 | if (it_type != stats.by_reason.end()) { | ||
| 75 | check(it_type->second.distinct_slots == 2, "type reason distinct slots is 2"); | ||
| 76 | check(it_type->second.total_refusals == 3, "type reason total refusals is 3"); | ||
| 77 | } | ||
| 78 | |||
| 79 | const auto it_layers = stats.by_reason.find(reason_layers); | ||
| 80 | check(it_layers != stats.by_reason.end(), "reason_layers recorded in stats"); | ||
| 81 | if (it_layers != stats.by_reason.end()) { | ||
| 82 | check(it_layers->second.distinct_slots == 1, "layers reason distinct slots is 1"); | ||
| 83 | check(it_layers->second.total_refusals == 1, "layers reason total refusals is 1"); | ||
| 84 | } | ||
| 85 | } | ||
| 86 | |||
| 87 | // Initialize standalone Vulkan D3D12 device for resource binding rule tests | ||
| 88 | Ref<ID3D12Device> device; | ||
| 89 | if (FAILED(rt::d3d12::create_vulkan_device_standalone(IID_PPV_ARGS(device.put())))) { | ||
| 90 | std::puts("SKIP: no Vulkan D3D12 device"); | ||
| 91 | return 77; | ||
| 92 | } | ||
| 93 | |||
| 94 | const D3D12_HEAP_PROPERTIES heap_props{ | ||
| 95 | .Type = D3D12_HEAP_TYPE_DEFAULT, | ||
| 96 | .CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN, | ||
| 97 | .MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN, | ||
| 98 | .CreationNodeMask = 1, | ||
| 99 | .VisibleNodeMask = 1, | ||
| 100 | }; | ||
| 101 | |||
| 102 | // Test 2: 1D Texture binding rules | ||
| 103 | { | ||
| 104 | D3D12_RESOURCE_DESC desc{}; | ||
| 105 | desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE1D; | ||
| 106 | desc.Width = 64; | ||
| 107 | desc.Height = 1; | ||
| 108 | desc.DepthOrArraySize = 1; | ||
| 109 | desc.MipLevels = 1; | ||
| 110 | desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; | ||
| 111 | desc.SampleDesc.Count = 1; | ||
| 112 | desc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN; | ||
| 113 | |||
| 114 | Ref<ID3D12Resource> res_1d; | ||
| 115 | check(SUCCEEDED(device->CreateCommittedResource(&heap_props, D3D12_HEAP_FLAG_NONE, &desc, | ||
| 116 | D3D12_RESOURCE_STATE_COMMON, nullptr, | ||
| 117 | IID_PPV_ARGS(res_1d.put()))), | ||
| 118 | "created 1D texture"); | ||
| 119 | |||
| 120 | const std::uint64_t addr = rt::d3d12::resource_image_address(res_1d.p); | ||
| 121 | check(addr != 0, "1D texture has registered image address"); | ||
| 122 | |||
| 123 | // Case 2a: T# specifies 2D type for a 1D texture -> refuse type_fits | ||
| 124 | { | ||
| 125 | g::Image img{}; | ||
| 126 | img.address = addr; | ||
| 127 | img.type = g::ImageType::image_2d; | ||
| 128 | img.format = g::format_from_vulkan(VK_FORMAT_R8G8B8A8_UNORM); | ||
| 129 | img.width = 64; | ||
| 130 | img.height = 1; | ||
| 131 | img.layer_count = 1; | ||
| 132 | img.mip_count = 1; | ||
| 133 | const auto words = g::encode(img); | ||
| 134 | |||
| 135 | const char* why = nullptr; | ||
| 136 | const auto result = rt::d3d12::test_bind_title_image(device.p, words, &why); | ||
| 137 | check(result == rt::d3d12::TitleImage::refused, "2D T# on 1D texture refused"); | ||
| 138 | check(why && std::string(why) == "T# type or samples do not fit the texture", | ||
| 139 | "2D T# on 1D texture explains type mismatch"); | ||
| 140 | } | ||
| 141 | |||
| 142 | // Case 2b: T# specifies 1D type but layer_count > 1 -> refuse type_fits | ||
| 143 | { | ||
| 144 | g::Image img{}; | ||
| 145 | img.address = addr; | ||
| 146 | img.type = g::ImageType::image_1d; | ||
| 147 | img.format = g::format_from_vulkan(VK_FORMAT_R8G8B8A8_UNORM); | ||
| 148 | img.width = 64; | ||
| 149 | img.height = 1; | ||
| 150 | img.layer_count = 2; | ||
| 151 | img.mip_count = 1; | ||
| 152 | const auto words = g::encode(img); | ||
| 153 | |||
| 154 | const char* why = nullptr; | ||
| 155 | const auto result = rt::d3d12::test_bind_title_image(device.p, words, &why); | ||
| 156 | check(result == rt::d3d12::TitleImage::refused, "1D T# with layer_count > 1 on 1D texture refused"); | ||
| 157 | check(why && std::string(why) == "T# type or samples do not fit the texture", | ||
| 158 | "1D T# with layer_count > 1 explains type mismatch"); | ||
| 159 | } | ||
| 160 | |||
| 161 | // Case 2c: T# specifies 1D type and layer_count == 1 -> bound | ||
| 162 | { | ||
| 163 | g::Image img{}; | ||
| 164 | img.address = addr; | ||
| 165 | img.type = g::ImageType::image_1d; | ||
| 166 | img.format = g::format_from_vulkan(VK_FORMAT_R8G8B8A8_UNORM); | ||
| 167 | img.width = 64; | ||
| 168 | img.height = 1; | ||
| 169 | img.layer_count = 1; | ||
| 170 | img.mip_count = 1; | ||
| 171 | const auto words = g::encode(img); | ||
| 172 | |||
| 173 | const char* why = nullptr; | ||
| 174 | const auto result = rt::d3d12::test_bind_title_image(device.p, words, &why); | ||
| 175 | check(result == rt::d3d12::TitleImage::bound, "matching 1D T# bound successfully"); | ||
| 176 | } | ||
| 177 | } | ||
| 178 | |||
| 179 | // Test 3: 2D Array and Cube binding rules | ||
| 180 | { | ||
| 181 | D3D12_RESOURCE_DESC desc{}; | ||
| 182 | desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; | ||
| 183 | desc.Width = 64; | ||
| 184 | desc.Height = 64; | ||
| 185 | desc.DepthOrArraySize = 4; // 4 layers | ||
| 186 | desc.MipLevels = 2; | ||
| 187 | desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; | ||
| 188 | desc.SampleDesc.Count = 1; | ||
| 189 | desc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN; | ||
| 190 | |||
| 191 | Ref<ID3D12Resource> res_array; | ||
| 192 | check(SUCCEEDED(device->CreateCommittedResource(&heap_props, D3D12_HEAP_FLAG_NONE, &desc, | ||
| 193 | D3D12_RESOURCE_STATE_COMMON, nullptr, | ||
| 194 | IID_PPV_ARGS(res_array.put()))), | ||
| 195 | "created 2D array texture"); | ||
| 196 | |||
| 197 | const std::uint64_t addr = rt::d3d12::resource_image_address(res_array.p); | ||
| 198 | check(addr != 0, "2D array texture has registered image address"); | ||
| 199 | |||
| 200 | // Case 3a: T# names layers the texture lacks (first_layer + layer_count > 4) -> refuse layers | ||
| 201 | { | ||
| 202 | g::Image img{}; | ||
| 203 | img.address = addr; | ||
| 204 | img.type = g::ImageType::image_2d_array; | ||
| 205 | img.format = g::format_from_vulkan(VK_FORMAT_R8G8B8A8_UNORM); | ||
| 206 | img.width = 64; | ||
| 207 | img.height = 64; | ||
| 208 | img.first_layer = 2; | ||
| 209 | img.layer_count = 3; // 2 + 3 = 5 > 4 | ||
| 210 | img.mip_count = 1; | ||
| 211 | const auto words = g::encode(img); | ||
| 212 | |||
| 213 | const char* why = nullptr; | ||
| 214 | const auto result = rt::d3d12::test_bind_title_image(device.p, words, &why); | ||
| 215 | check(result == rt::d3d12::TitleImage::refused, "T# with excessive layers refused"); | ||
| 216 | check(why && std::string(why) == "T# names layers the texture lacks", | ||
| 217 | "excessive layers explains layers mismatch"); | ||
| 218 | } | ||
| 219 | |||
| 220 | // Case 3b: Cube T# on texture with fewer than six layers (desc.DepthOrArraySize = 4 < 6) -> refuse cube | ||
| 221 | { | ||
| 222 | g::Image img{}; | ||
| 223 | img.address = addr; | ||
| 224 | img.type = g::ImageType::cube; | ||
| 225 | img.format = g::format_from_vulkan(VK_FORMAT_R8G8B8A8_UNORM); | ||
| 226 | img.width = 64; | ||
| 227 | img.height = 64; | ||
| 228 | img.first_layer = 0; | ||
| 229 | img.layer_count = 6; // cube needs at least 6 faces, but texture only has 4 layers | ||
| 230 | img.mip_count = 1; | ||
| 231 | const auto words = g::encode(img); | ||
| 232 | |||
| 233 | const char* why = nullptr; | ||
| 234 | const auto result = rt::d3d12::test_bind_title_image(device.p, words, &why); | ||
| 235 | check(result == rt::d3d12::TitleImage::refused, "cube T# on 4 layers refused"); | ||
| 236 | check(why && std::string(why) == "cube T# on fewer than six layers", | ||
| 237 | "cube T# explains fewer than six layers"); | ||
| 238 | } | ||
| 239 | |||
| 240 | // Case 3c: T# names valid sub-array (first_layer = 1, layer_count = 2 <= 4) -> bound | ||
| 241 | { | ||
| 242 | g::Image img{}; | ||
| 243 | img.address = addr; | ||
| 244 | img.type = g::ImageType::image_2d_array; | ||
| 245 | img.format = g::format_from_vulkan(VK_FORMAT_R8G8B8A8_UNORM); | ||
| 246 | img.width = 64; | ||
| 247 | img.height = 64; | ||
| 248 | img.first_layer = 1; | ||
| 249 | img.layer_count = 2; | ||
| 250 | img.mip_count = 1; | ||
| 251 | const auto words = g::encode(img); | ||
| 252 | |||
| 253 | const char* why = nullptr; | ||
| 254 | const auto result = rt::d3d12::test_bind_title_image(device.p, words, &why); | ||
| 255 | check(result == rt::d3d12::TitleImage::bound, "valid sub-array T# bound successfully"); | ||
| 256 | } | ||
| 257 | |||
| 258 | // Case 3d: T# names mips the texture lacks (first_mip + mip_count > 2) -> refuse mips | ||
| 259 | { | ||
| 260 | g::Image img{}; | ||
| 261 | img.address = addr; | ||
| 262 | img.type = g::ImageType::image_2d_array; | ||
| 263 | img.format = g::format_from_vulkan(VK_FORMAT_R8G8B8A8_UNORM); | ||
| 264 | img.width = 64; | ||
| 265 | img.height = 64; | ||
| 266 | img.first_layer = 0; | ||
| 267 | img.layer_count = 1; | ||
| 268 | img.first_mip = 1; | ||
| 269 | img.mip_count = 2; // 1 + 2 = 3 > 2 | ||
| 270 | const auto words = g::encode(img); | ||
| 271 | |||
| 272 | const char* why = nullptr; | ||
| 273 | const auto result = rt::d3d12::test_bind_title_image(device.p, words, &why); | ||
| 274 | check(result == rt::d3d12::TitleImage::refused, "T# with excessive mips refused"); | ||
| 275 | check(why && std::string(why) == "T# names mips the texture lacks", | ||
| 276 | "excessive mips explains mips mismatch"); | ||
| 277 | } | ||
| 278 | } | ||
| 279 | |||
| 280 | // Test 4: MSAA Texture binding rules | ||
| 281 | { | ||
| 282 | D3D12_RESOURCE_DESC desc{}; | ||
| 283 | desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; | ||
| 284 | desc.Width = 64; | ||
| 285 | desc.Height = 64; | ||
| 286 | desc.DepthOrArraySize = 1; | ||
| 287 | desc.MipLevels = 1; | ||
| 288 | desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; | ||
| 289 | desc.SampleDesc.Count = 4; // 4x MSAA | ||
| 290 | desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; | ||
| 291 | desc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN; | ||
| 292 | |||
| 293 | Ref<ID3D12Resource> res_msaa; | ||
| 294 | check(SUCCEEDED(device->CreateCommittedResource(&heap_props, D3D12_HEAP_FLAG_NONE, &desc, | ||
| 295 | D3D12_RESOURCE_STATE_COMMON, nullptr, | ||
| 296 | IID_PPV_ARGS(res_msaa.put()))), | ||
| 297 | "created 4x MSAA texture"); | ||
| 298 | |||
| 299 | const std::uint64_t addr = rt::d3d12::resource_image_address(res_msaa.p); | ||
| 300 | check(addr != 0, "MSAA texture has registered image address"); | ||
| 301 | |||
| 302 | // Case 4a: Non-MSAA T# on MSAA texture -> refuse type_fits | ||
| 303 | { | ||
| 304 | g::Image img{}; | ||
| 305 | img.address = addr; | ||
| 306 | img.type = g::ImageType::image_2d; | ||
| 307 | img.format = g::format_from_vulkan(VK_FORMAT_R8G8B8A8_UNORM); | ||
| 308 | img.width = 64; | ||
| 309 | img.height = 64; | ||
| 310 | img.layer_count = 1; | ||
| 311 | img.mip_count = 1; | ||
| 312 | const auto words = g::encode(img); | ||
| 313 | |||
| 314 | const char* why = nullptr; | ||
| 315 | const auto result = rt::d3d12::test_bind_title_image(device.p, words, &why); | ||
| 316 | check(result == rt::d3d12::TitleImage::refused, "non-MSAA T# on MSAA texture refused"); | ||
| 317 | check(why && std::string(why) == "T# type or samples do not fit the texture", | ||
| 318 | "non-MSAA T# explains type or samples mismatch"); | ||
| 319 | } | ||
| 320 | |||
| 321 | // Case 4b: MSAA T# with mismatched samples (samples = 2 != 4) -> refuse type_fits | ||
| 322 | { | ||
| 323 | g::Image img{}; | ||
| 324 | img.address = addr; | ||
| 325 | img.type = g::ImageType::image_2d_msaa; | ||
| 326 | img.format = g::format_from_vulkan(VK_FORMAT_R8G8B8A8_UNORM); | ||
| 327 | img.width = 64; | ||
| 328 | img.height = 64; | ||
| 329 | img.samples = 2; | ||
| 330 | img.layer_count = 1; | ||
| 331 | img.mip_count = 1; | ||
| 332 | const auto words = g::encode(img); | ||
| 333 | |||
| 334 | const char* why = nullptr; | ||
| 335 | const auto result = rt::d3d12::test_bind_title_image(device.p, words, &why); | ||
| 336 | check(result == rt::d3d12::TitleImage::refused, "mismatched samples T# refused"); | ||
| 337 | check(why && std::string(why) == "T# type or samples do not fit the texture", | ||
| 338 | "mismatched samples explains type or samples mismatch"); | ||
| 339 | } | ||
| 340 | |||
| 341 | // Case 4c: Matching 4x MSAA T# -> bound | ||
| 342 | { | ||
| 343 | g::Image img{}; | ||
| 344 | img.address = addr; | ||
| 345 | img.type = g::ImageType::image_2d_msaa; | ||
| 346 | img.format = g::format_from_vulkan(VK_FORMAT_R8G8B8A8_UNORM); | ||
| 347 | img.width = 64; | ||
| 348 | img.height = 64; | ||
| 349 | img.samples = 4; | ||
| 350 | img.layer_count = 1; | ||
| 351 | img.mip_count = 1; | ||
| 352 | const auto words = g::encode(img); | ||
| 353 | |||
| 354 | const char* why = nullptr; | ||
| 355 | const auto result = rt::d3d12::test_bind_title_image(device.p, words, &why); | ||
| 356 | check(result == rt::d3d12::TitleImage::bound, "matching 4x MSAA T# bound successfully"); | ||
| 357 | } | ||
| 358 | } | ||
| 359 | |||
| 360 | // Test 5: Unknown texture address and invalid T# words | ||
| 361 | { | ||
| 362 | // Unknown address | ||
| 363 | { | ||
| 364 | g::Image img{}; | ||
| 365 | img.address = 0xdeadbeef00ull; | ||
| 366 | img.type = g::ImageType::image_2d; | ||
| 367 | img.format = g::format_from_vulkan(VK_FORMAT_R8G8B8A8_UNORM); | ||
| 368 | img.width = 64; | ||
| 369 | img.height = 64; | ||
| 370 | img.layer_count = 1; | ||
| 371 | img.mip_count = 1; | ||
| 372 | const auto words = g::encode(img); | ||
| 373 | |||
| 374 | const char* why = nullptr; | ||
| 375 | const auto result = rt::d3d12::test_bind_title_image(device.p, words, &why); | ||
| 376 | check(result == rt::d3d12::TitleImage::unknown, "unknown address returns TitleImage::unknown"); | ||
| 377 | check(why && std::string(why) == "no texture at T# address", | ||
| 378 | "unknown address explains no texture at T# address"); | ||
| 379 | } | ||
| 380 | |||
| 381 | // Not a valid T# (decode failure) | ||
| 382 | { | ||
| 383 | std::array<std::uint32_t, 8> raw_words{0x1, 0x2, 0x3, 0x0, 0x0, 0x0, 0x0, 0x0}; | ||
| 384 | const char* why = nullptr; | ||
| 385 | const auto result = rt::d3d12::test_bind_title_image(device.p, raw_words, &why); | ||
| 386 | check(result == rt::d3d12::TitleImage::not_tsharp, "invalid words return TitleImage::not_tsharp"); | ||
| 387 | check(why && std::string(why) == "not a valid T# (swizzle, levels or layers)", | ||
| 388 | "invalid words explains not a valid T#"); | ||
| 389 | } | ||
| 390 | } | ||
| 391 | |||
| 392 | std::printf("d3d12_unbound_tsharp_rules_test: %d checks, %d failures\n", g_checks, g_failures); | ||
| 393 | return g_failures == 0 ? 0 : 1; | ||
| 394 | } | ||
diff --git a/runtime/test/d3d12_unmapped_vsharp_test.cpp b/runtime/test/d3d12_unmapped_vsharp_test.cpp index 83fe2c090..2e072ce40 100644 --- a/runtime/test/d3d12_unmapped_vsharp_test.cpp +++ b/runtime/test/d3d12_unmapped_vsharp_test.cpp | |||
| @@ -152,7 +152,6 @@ int check_inline_table(ID3D12Device* device, ID3D12CommandQueue* queue, ID3D12Fe | |||
| 152 | std::memcpy(cpu + slot * kDescriptor, w.data(), sizeof(w)); | 152 | std::memcpy(cpu + slot * kDescriptor, w.data(), sizeof(w)); |
| 153 | }; | 153 | }; |
| 154 | put(0, raw_vsharp(unmapped)); | 154 | put(0, raw_vsharp(unmapped)); |
| 155 | for (int i = 4; i < 131; ++i) put(i, raw_vsharp(unmapped)); | ||
| 156 | put(1, raw_vsharp(b.arena_va)); | 155 | put(1, raw_vsharp(b.arena_va)); |
| 157 | put(2, raw_vsharp(b.upload_va & 0xFFFFFFFFFFFFull)); | 156 | put(2, raw_vsharp(b.upload_va & 0xFFFFFFFFFFFFull)); |
| 158 | auto image_like = raw_vsharp(unmapped); | 157 | auto image_like = raw_vsharp(unmapped); |
diff --git a/runtime/test/d3d12_vram_budget_test.cpp b/runtime/test/d3d12_vram_budget_test.cpp new file mode 100644 index 000000000..0f69d7548 --- /dev/null +++ b/runtime/test/d3d12_vram_budget_test.cpp | |||
| @@ -0,0 +1,103 @@ | |||
| 1 | // rt::d3d12::vulkan_vram_budget on the standalone Vulkan-backed device: the GPU memory in use and the budget the | ||
| 2 | // title HUD shows (shims/title_hud.h), from VK_EXT_memory_budget. The device enables the extension exactly when the | ||
| 3 | // GPU has it; then, with a 64 MiB default-heap buffer alive, the device-local budget and the usage are non-zero. | ||
| 4 | // The device publishes that figure for the HUD and the dev overlay (src/memory_figures.h) and withdraws it when it | ||
| 5 | // is released. Without the extension the figure is not available, and the test skips (77) after checking that. | ||
| 6 | // Also skips without a Vulkan GPU. No shaders or game data. | ||
| 7 | #include "../shims/d3d12_com.h" | ||
| 8 | |||
| 9 | #include <cstdint> | ||
| 10 | #include <cstdio> | ||
| 11 | #include <cstring> | ||
| 12 | #include <vector> | ||
| 13 | |||
| 14 | #define EXPECT(condition) do { \ | ||
| 15 | if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ | ||
| 16 | } while (0) | ||
| 17 | |||
| 18 | namespace { | ||
| 19 | |||
| 20 | template<class T> | ||
| 21 | struct Ref { | ||
| 22 | T* p = nullptr; | ||
| 23 | ~Ref() { | ||
| 24 | if (p) p->Release(); | ||
| 25 | } | ||
| 26 | }; | ||
| 27 | |||
| 28 | constexpr std::uint64_t kMiB = 1ull << 20; | ||
| 29 | |||
| 30 | bool physical_has_memory_budget(const rt::d3d12::VulkanDeviceInfo& info) { | ||
| 31 | const auto enumerate = reinterpret_cast<PFN_vkEnumerateDeviceExtensionProperties>( | ||
| 32 | info.get_instance_proc(info.instance, "vkEnumerateDeviceExtensionProperties")); | ||
| 33 | if (!enumerate) return false; | ||
| 34 | std::uint32_t count = 0; | ||
| 35 | if (enumerate(info.physical, nullptr, &count, nullptr) != VK_SUCCESS) return false; | ||
| 36 | std::vector<VkExtensionProperties> extensions(count); | ||
| 37 | if (enumerate(info.physical, nullptr, &count, extensions.data()) != VK_SUCCESS) return false; | ||
| 38 | for (const auto& e : extensions) | ||
| 39 | if (!std::strcmp(e.extensionName, VK_EXT_MEMORY_BUDGET_EXTENSION_NAME)) return true; | ||
| 40 | return false; | ||
| 41 | } | ||
| 42 | |||
| 43 | void print(const char* when, const leonida::VramBudget& b) { | ||
| 44 | std::printf("%s: %s, device-local %llu of %llu MiB, other heaps %llu MiB\n", when, | ||
| 45 | b.available ? "available" : "not available", (unsigned long long)(b.local_usage / kMiB), | ||
| 46 | (unsigned long long)(b.local_budget / kMiB), (unsigned long long)(b.shared_usage / kMiB)); | ||
| 47 | } | ||
| 48 | |||
| 49 | } // namespace | ||
| 50 | |||
| 51 | int main() { | ||
| 52 | Ref<ID3D12Device> device; | ||
| 53 | if (FAILED(rt::d3d12::create_vulkan_device_standalone(IID_PPV_ARGS(&device.p))) || !device.p) { | ||
| 54 | std::printf("SKIP: no Vulkan device\n"); | ||
| 55 | return 77; | ||
| 56 | } | ||
| 57 | const rt::d3d12::VulkanDeviceInfo* info = rt::d3d12::vulkan_device_info(device.p); | ||
| 58 | EXPECT(info && info->get_instance_proc && info->instance && info->physical); | ||
| 59 | EXPECT(!rt::d3d12::vulkan_vram_budget(nullptr).available); | ||
| 60 | |||
| 61 | // Enabled exactly when the GPU has it. | ||
| 62 | const bool supported = physical_has_memory_budget(*info); | ||
| 63 | EXPECT(info->memory_budget == supported); | ||
| 64 | // What the title HUD and the dev overlay show (src/memory_figures.h): this device's figure once it has one. | ||
| 65 | EXPECT(leonida::memory_figures::latest_vram().available == supported); | ||
| 66 | if (!supported) { | ||
| 67 | EXPECT(!rt::d3d12::vulkan_vram_budget(device.p).available); // the HUD and the overlay show "n/a" | ||
| 68 | std::printf("SKIP: the GPU has no VK_EXT_memory_budget; the figure is not available\n"); | ||
| 69 | return 77; | ||
| 70 | } | ||
| 71 | |||
| 72 | print("before", rt::d3d12::vulkan_vram_budget(device.p)); | ||
| 73 | D3D12_HEAP_PROPERTIES heap{}; | ||
| 74 | heap.Type = D3D12_HEAP_TYPE_DEFAULT; | ||
| 75 | D3D12_RESOURCE_DESC desc{}; | ||
| 76 | desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; | ||
| 77 | desc.Width = 64 * kMiB; | ||
| 78 | desc.Height = 1; | ||
| 79 | desc.DepthOrArraySize = 1; | ||
| 80 | desc.MipLevels = 1; | ||
| 81 | desc.SampleDesc.Count = 1; | ||
| 82 | desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; | ||
| 83 | Ref<ID3D12Resource> buffer; | ||
| 84 | EXPECT(SUCCEEDED(device.p->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, | ||
| 85 | nullptr, IID_PPV_ARGS(&buffer.p)))); | ||
| 86 | const leonida::VramBudget after = rt::d3d12::vulkan_vram_budget(device.p); | ||
| 87 | print("with a 64 MiB buffer", after); | ||
| 88 | EXPECT(after.available); | ||
| 89 | EXPECT(after.local_budget > 0); | ||
| 90 | EXPECT(after.local_usage + after.shared_usage > 0); | ||
| 91 | const leonida::VramBudget published = leonida::memory_figures::latest_vram(); | ||
| 92 | EXPECT(published.available && published.local_budget > 0); // may be the read before the buffer: cached | ||
| 93 | |||
| 94 | // A released device withdraws its figure: nothing reads a device that is gone. | ||
| 95 | buffer.p->Release(); | ||
| 96 | buffer.p = nullptr; | ||
| 97 | device.p->Release(); | ||
| 98 | device.p = nullptr; | ||
| 99 | EXPECT(!leonida::memory_figures::latest_vram().available); | ||
| 100 | std::printf("d3d12_vram_budget: VK_EXT_memory_budget enabled; usage and budget read from the device and published" | ||
| 101 | " while it lives\n"); | ||
| 102 | return 0; | ||
| 103 | } | ||
diff --git a/runtime/test/d3d12_vulkan_device_test.cpp b/runtime/test/d3d12_vulkan_device_test.cpp index 9df462d3f..ef60f1855 100644 --- a/runtime/test/d3d12_vulkan_device_test.cpp +++ b/runtime/test/d3d12_vulkan_device_test.cpp | |||
| @@ -2423,8 +2423,8 @@ int compare_feature_options(ID3D12Device* ours, const rt::d3d12::VulkanDeviceInf | |||
| 2423 | fail("unknown feature unexpectedly answered"); | 2423 | fail("unknown feature unexpectedly answered"); |
| 2424 | 2424 | ||
| 2425 | // Local invariants for what this layer actually implements. | 2425 | // Local invariants for what this layer actually implements. |
| 2426 | if (o2.DepthBoundsTestSupported || | 2426 | // DepthBoundsTestSupported follows the device's depthBounds feature. |
| 2427 | o2.ProgrammableSamplePositionsTier != D3D12_PROGRAMMABLE_SAMPLE_POSITIONS_TIER_NOT_SUPPORTED) | 2427 | if (o2.ProgrammableSamplePositionsTier != D3D12_PROGRAMMABLE_SAMPLE_POSITIONS_TIER_NOT_SUPPORTED) |
| 2428 | fail("OPTIONS2 unexpected support"); | 2428 | fail("OPTIONS2 unexpected support"); |
| 2429 | if (o3.CastingFullyTypedFormatSupported || | 2429 | if (o3.CastingFullyTypedFormatSupported || |
| 2430 | o3.WriteBufferImmediateSupportFlags != D3D12_COMMAND_LIST_SUPPORT_FLAG_NONE || | 2430 | o3.WriteBufferImmediateSupportFlags != D3D12_COMMAND_LIST_SUPPORT_FLAG_NONE || |
| @@ -6766,8 +6766,11 @@ int main() { | |||
| 6766 | EXPECT(SUCCEEDED(device->CreateQueryHeap(&query_desc, IID_PPV_ARGS(×tamps.p)))); | 6766 | EXPECT(SUCCEEDED(device->CreateQueryHeap(&query_desc, IID_PPV_ARGS(×tamps.p)))); |
| 6767 | query_desc = {D3D12_QUERY_HEAP_TYPE_OCCLUSION, 0, 0}; | 6767 | query_desc = {D3D12_QUERY_HEAP_TYPE_OCCLUSION, 0, 0}; |
| 6768 | EXPECT(device->CreateQueryHeap(&query_desc, IID_PPV_ARGS(&refused.p)) == E_INVALIDARG && !refused.p); | 6768 | EXPECT(device->CreateQueryHeap(&query_desc, IID_PPV_ARGS(&refused.p)) == E_INVALIDARG && !refused.p); |
| 6769 | // The layer has no stream output, so stream-output statistics heaps are made without a Vulkan pool and | 6769 | // D3D-302: an SO_STATISTICS heap is a real transform-feedback pool on a device with |
| 6770 | // every query reads zero (D3D-302). | 6770 | // VK_EXT_transform_feedback whose transformFeedbackQueries property is set (indexed on the stream); without |
| 6771 | // them the heap is made without a Vulkan pool and every query reads zero. A stream past | ||
| 6772 | // maxTransformFeedbackStreams reads zero too. StreamOutput PSOs are still refused, so no stream output runs | ||
| 6773 | // and the resolved counts are 0 in either case. | ||
| 6771 | query_desc = {D3D12_QUERY_HEAP_TYPE_SO_STATISTICS, 3, 0}; | 6774 | query_desc = {D3D12_QUERY_HEAP_TYPE_SO_STATISTICS, 3, 0}; |
| 6772 | EXPECT(SUCCEEDED(device->CreateQueryHeap(&query_desc, IID_PPV_ARGS(&so.p)))); | 6775 | EXPECT(SUCCEEDED(device->CreateQueryHeap(&query_desc, IID_PPV_ARGS(&so.p)))); |
| 6773 | query_desc = {D3D12_QUERY_HEAP_TYPE_PIPELINE_STATISTICS, 2, 0}; | 6776 | query_desc = {D3D12_QUERY_HEAP_TYPE_PIPELINE_STATISTICS, 2, 0}; |
diff --git a/runtime/test/descriptor_table_test.cpp b/runtime/test/descriptor_table_test.cpp index 387bd0c60..287d68cde 100644 --- a/runtime/test/descriptor_table_test.cpp +++ b/runtime/test/descriptor_table_test.cpp | |||
| @@ -546,6 +546,49 @@ int test_capacity_overflow() { | |||
| 546 | return 0; | 546 | return 0; |
| 547 | } | 547 | } |
| 548 | 548 | ||
| 549 | // The entry's last dword is what a `descriptor_table` tagged module reads next to the index: the occupied bit and | ||
| 550 | // the arrays the index is bound in (kind_sampled_bit / kind_storage_bit). A plain module never reads it, so a table | ||
| 551 | // inserted without a kind must serialize exactly as before (marker, no kind bits). | ||
| 552 | int test_kind_word() { | ||
| 553 | DescriptorTable table(16); | ||
| 554 | const DescriptorKey image = make_tsharp_key(std::array<std::uint32_t, 8>{0x00001000u, 0x00000000u, 0u, 0u, | ||
| 555 | 0u, 0u, 0u, 0u}.data()); | ||
| 556 | const std::uint32_t kind = kind_sampled_bit(1) | kind_storage_bit(1); | ||
| 557 | EXPECT(table.insert(image, 5, kind)); | ||
| 558 | EXPECT(table.lookup(image) == 5); | ||
| 559 | const auto words = table.build_gpu_buffer(); | ||
| 560 | EXPECT(words[0] == 15); | ||
| 561 | const std::uint32_t slot = (hash_descriptor_key(image.data(), DescriptorHashKind::fnv1a) & 15); | ||
| 562 | if (words[1 + slot * 10 + 8] != 5) return 1; // find the slot the key landed in | ||
| 563 | EXPECT((words[1 + slot * 10 + 9] & kSlotOccupiedMarker) != 0); | ||
| 564 | EXPECT((words[1 + slot * 10 + 9] & kKindMask) == kind); | ||
| 565 | |||
| 566 | // A plain entry: the marker and no kind bits, as before the marker existed. | ||
| 567 | const DescriptorKey plain = make_tsharp_key(std::array<std::uint32_t, 8>{0x00002000u, 0u, 0u, 0u, 0u, 0u, 0u, | ||
| 568 | 0u}.data()); | ||
| 569 | EXPECT(table.insert(plain, 6)); | ||
| 570 | std::uint32_t found[10]; | ||
| 571 | EXPECT(table.read_slot(slot, found)); | ||
| 572 | (void)found; | ||
| 573 | DescriptorEntry entry{}; | ||
| 574 | entry.kind = kSlotOccupiedMarker; | ||
| 575 | EXPECT(slot_occupied(entry) && slot_kind(entry) == 0); | ||
| 576 | |||
| 577 | // The same index with a new kind is a change the GPU copy needs. | ||
| 578 | EXPECT(table.insert_or_update(image.data(), 5, kind_sampled_bit(2)) == | ||
| 579 | DescriptorTable::InsertResult::replaced); | ||
| 580 | EXPECT(table.insert_or_update(image.data(), 5, kind_sampled_bit(2)) == | ||
| 581 | DescriptorTable::InsertResult::unchanged); | ||
| 582 | const auto changed = table.take_changes(); | ||
| 583 | EXPECT(!changed.slots.empty() || changed.all); | ||
| 584 | |||
| 585 | // clear_occupied drops the marker but keeps the kind, which is what a shader reads. | ||
| 586 | const auto gpu = table.build_gpu_buffer(true); | ||
| 587 | EXPECT((gpu[1 + slot * 10 + 9] & kSlotOccupiedMarker) == 0); | ||
| 588 | EXPECT((gpu[1 + slot * 10 + 9] & kKindMask) == kind_sampled_bit(2)); | ||
| 589 | return 0; | ||
| 590 | } | ||
| 591 | |||
| 549 | int main() { | 592 | int main() { |
| 550 | EXPECT(test_unresolvable_hash_collision() == 0); | 593 | EXPECT(test_unresolvable_hash_collision() == 0); |
| 551 | EXPECT(test_capacity_overflow() == 0); | 594 | EXPECT(test_capacity_overflow() == 0); |
| @@ -565,6 +608,7 @@ int main() { | |||
| 565 | EXPECT(test_multithreaded_insert_and_lookup() == 0); | 608 | EXPECT(test_multithreaded_insert_and_lookup() == 0); |
| 566 | EXPECT(test_clear_resets_table() == 0); | 609 | EXPECT(test_clear_resets_table() == 0); |
| 567 | EXPECT(test_erase_and_reinsert() == 0); | 610 | EXPECT(test_erase_and_reinsert() == 0); |
| 611 | EXPECT(test_kind_word() == 0); | ||
| 568 | 612 | ||
| 569 | std::printf("descriptor_table_test: all tests passed (0 failures)\n"); | 613 | std::printf("descriptor_table_test: all tests passed (0 failures)\n"); |
| 570 | return 0; | 614 | return 0; |
diff --git a/runtime/test/dev_overlay_test.cpp b/runtime/test/dev_overlay_test.cpp new file mode 100644 index 000000000..55a5a31cc --- /dev/null +++ b/runtime/test/dev_overlay_test.cpp | |||
| @@ -0,0 +1,166 @@ | |||
| 1 | // src/dev_overlay.h: the text of a sample, the counter differences, the phase bookkeeping behind its "now" line | ||
| 2 | // (submit_phases.h), the pipeline builds in flight (dev_status.h) and the memory figures it shares with the title HUD | ||
| 3 | // (memory_figures.h). No window, GPU or game file. | ||
| 4 | #include "dev_overlay.h" | ||
| 5 | |||
| 6 | #include <chrono> | ||
| 7 | #include <cstdint> | ||
| 8 | #include <cstdio> | ||
| 9 | #include <string> | ||
| 10 | #include <thread> | ||
| 11 | #include <vector> | ||
| 12 | |||
| 13 | #define CHECK(condition) do { \ | ||
| 14 | if (!(condition)) { \ | ||
| 15 | std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); \ | ||
| 16 | return 1; \ | ||
| 17 | } \ | ||
| 18 | } while (0) | ||
| 19 | |||
| 20 | namespace sp = leonida::submit_phases; | ||
| 21 | namespace dov = leonida::dev_overlay; | ||
| 22 | |||
| 23 | static bool has(const std::vector<std::string>& lines, const char* part) { | ||
| 24 | for (const auto& line : lines) | ||
| 25 | if (line.find(part) != std::string::npos) return true; | ||
| 26 | return false; | ||
| 27 | } | ||
| 28 | |||
| 29 | // memory_figures.h, which the overlay and the title HUD share: the private bytes Wine reports, the text of both | ||
| 30 | // figures with and without one, and the device's published GPU memory, read at most once per refresh. | ||
| 31 | static int check_memory_figures() { | ||
| 32 | namespace mf = leonida::memory_figures; | ||
| 33 | constexpr std::uint64_t kGiB = 1ull << 30; | ||
| 34 | |||
| 35 | // Wine fills PagefileUsage and leaves PrivateUsage 0; Windows fills both with the same value. | ||
| 36 | mf::ProcessMemory ram; | ||
| 37 | CHECK(mf::ram_text(ram) == "RAM n/a"); // GetProcessMemoryInfo failed | ||
| 38 | ram.read = true; | ||
| 39 | ram.working_set = kGiB; | ||
| 40 | CHECK(mf::ram_text(ram) == "RAM n/a (ws 1.0)"); | ||
| 41 | ram.pagefile_usage = 5 * kGiB / 2; | ||
| 42 | CHECK(mf::private_bytes(ram) == 5 * kGiB / 2 && mf::ram_text(ram) == "RAM 2.5 GB (ws 1.0)"); | ||
| 43 | ram.private_usage = 5 * kGiB / 2; | ||
| 44 | CHECK(mf::private_bytes(ram) == 5 * kGiB / 2 && mf::ram_text(ram) == "RAM 2.5 GB (ws 1.0)"); | ||
| 45 | |||
| 46 | leonida::VramBudget vram; | ||
| 47 | CHECK(mf::vram_text(vram) == "VRAM n/a"); | ||
| 48 | vram.available = true; | ||
| 49 | vram.local_usage = 3 * kGiB + kGiB / 2; | ||
| 50 | vram.local_budget = 16 * kGiB; | ||
| 51 | vram.shared_usage = kGiB / 2; | ||
| 52 | CHECK(mf::vram_text(vram) == "VRAM 3.5/16.0 GB +0.5 shared"); | ||
| 53 | |||
| 54 | // The overlay's line with both figures. | ||
| 55 | dov::Sample s; | ||
| 56 | s.ram = ram; | ||
| 57 | s.vram = vram; | ||
| 58 | CHECK(has(dov::lines(s, 1), "RAM 2.5 GB (ws 1.0) VRAM 3.5/16.0 GB +0.5 shared")); | ||
| 59 | |||
| 60 | // The published figure: none until a device publishes a reader; then read at most once per refresh_ms; another | ||
| 61 | // device's withdrawal leaves it; its own takes it away. | ||
| 62 | struct Fake { | ||
| 63 | int reads = 0; | ||
| 64 | leonida::VramBudget figure; | ||
| 65 | }; | ||
| 66 | static Fake device; | ||
| 67 | static const int other = 0; | ||
| 68 | device.figure = vram; | ||
| 69 | auto& publisher = mf::vram_publisher(); | ||
| 70 | using clock = std::chrono::steady_clock; | ||
| 71 | const clock::time_point t0 = clock::now(); | ||
| 72 | CHECK(!publisher.latest(t0).available); | ||
| 73 | mf::publish_vram_reader( | ||
| 74 | [](const void* context) { | ||
| 75 | auto* fake = static_cast<Fake*>(const_cast<void*>(context)); | ||
| 76 | ++fake->reads; | ||
| 77 | return fake->figure; | ||
| 78 | }, | ||
| 79 | &device); | ||
| 80 | CHECK(publisher.latest(t0).local_usage == 3 * kGiB + kGiB / 2 && device.reads == 1); | ||
| 81 | device.figure.local_usage = 4 * kGiB; | ||
| 82 | CHECK(publisher.latest(t0 + mf::refresh_ms / 2).local_usage == 3 * kGiB + kGiB / 2 && device.reads == 1); | ||
| 83 | CHECK(publisher.latest(t0 + mf::refresh_ms).local_usage == 4 * kGiB && device.reads == 2); | ||
| 84 | mf::withdraw_vram_reader(&other); | ||
| 85 | CHECK(mf::latest_vram().available); | ||
| 86 | mf::withdraw_vram_reader(&device); | ||
| 87 | CHECK(!mf::latest_vram().available); | ||
| 88 | return 0; | ||
| 89 | } | ||
| 90 | |||
| 91 | int main() { | ||
| 92 | // A total that went down was reset by its log line: what it holds is the new part. | ||
| 93 | std::uint64_t before = 0; | ||
| 94 | CHECK(dov::grown(10, before) == 10 && before == 10); | ||
| 95 | CHECK(dov::grown(25, before) == 15); | ||
| 96 | CHECK(dov::grown(4, before) == 4 && before == 4); | ||
| 97 | |||
| 98 | // Nested scopes: the inner one is running, then the outer one again, then none. | ||
| 99 | CHECK(sp::running().phase == -1); | ||
| 100 | { | ||
| 101 | const sp::Scope replay(sp::replay); | ||
| 102 | CHECK(sp::running().phase == sp::replay); | ||
| 103 | { | ||
| 104 | const sp::Scope textures(sp::textures); | ||
| 105 | CHECK(sp::running().phase == sp::textures); | ||
| 106 | } | ||
| 107 | CHECK(sp::running().phase == sp::replay); | ||
| 108 | } | ||
| 109 | CHECK(sp::running().phase == -1); | ||
| 110 | |||
| 111 | // Two threads whose scopes overlap and end in the order they began: no phase stays behind. | ||
| 112 | { | ||
| 113 | std::atomic<int> step{0}; | ||
| 114 | std::thread a([&] { | ||
| 115 | const sp::Scope heaps(sp::heaps); | ||
| 116 | step = 1; | ||
| 117 | while (step.load() < 2) std::this_thread::yield(); | ||
| 118 | }); | ||
| 119 | std::thread b([&] { | ||
| 120 | while (step.load() < 1) std::this_thread::yield(); | ||
| 121 | const sp::Scope shadows(sp::shadows); | ||
| 122 | step = 2; | ||
| 123 | while (step.load() < 3) std::this_thread::yield(); | ||
| 124 | }); | ||
| 125 | a.join(); | ||
| 126 | CHECK(sp::running().phase == sp::shadows); | ||
| 127 | step = 3; | ||
| 128 | b.join(); | ||
| 129 | CHECK(sp::running().phase == -1); | ||
| 130 | } | ||
| 131 | |||
| 132 | // The builds in flight and the last one's name, cut to its buffer. | ||
| 133 | auto& builds = leonida::dev_status::builds(); | ||
| 134 | const auto done = builds.done.load(); | ||
| 135 | { | ||
| 136 | const leonida::dev_status::Build one("one"); | ||
| 137 | const leonida::dev_status::Build two(std::string(500, 'x').c_str()); | ||
| 138 | CHECK(builds.active.load() == 2 && builds.last() == std::string(95, 'x')); | ||
| 139 | } | ||
| 140 | CHECK(builds.active.load() == 0 && builds.done.load() == done + 2); | ||
| 141 | |||
| 142 | dov::Sample s; | ||
| 143 | auto text = dov::lines(s, 12); | ||
| 144 | CHECK(text.size() == 7); | ||
| 145 | // No counters and no device figure: "n/a", never a false 0. | ||
| 146 | CHECK(has(text, "RAM n/a VRAM n/a")); | ||
| 147 | CHECK(has(text, "12 s") && has(text, "now: the title's own code") && has(text, "pipelines: 0 built")); | ||
| 148 | CHECK(!has(text, "building")); | ||
| 149 | s.frames = 8.44; | ||
| 150 | s.phase = sp::textures; | ||
| 151 | s.phase_for = 3.9; | ||
| 152 | s.phase_ms[sp::shadows] = 2; | ||
| 153 | s.phase_ms[sp::geometry] = 1.5; | ||
| 154 | s.building = 3; | ||
| 155 | s.built = 853; | ||
| 156 | s.build = std::string(200, 'n'); // longer than the line's part for it | ||
| 157 | s.drawn = 3029; | ||
| 158 | s.skipped = 38363; | ||
| 159 | text = dov::lines(s, 147); | ||
| 160 | CHECK(has(text, "8.4 fps") && has(text, "now: refreshing textures for 3 s") && has(text, "copies 3.5")); | ||
| 161 | CHECK(has(text, "853 built, 3 building (nnn") && has(text, "3029 drawn, 38363 skipped")); | ||
| 162 | for (const auto& line : text) CHECK(line.size() < 160); | ||
| 163 | if (const int failed = check_memory_figures()) return failed; | ||
| 164 | std::puts("dev_overlay_test: ok"); | ||
| 165 | return 0; | ||
| 166 | } | ||
diff --git a/runtime/test/dxgi_swapchain_count_test.cpp b/runtime/test/dxgi_swapchain_count_test.cpp index fbbca182a..c0ca5f6ad 100644 --- a/runtime/test/dxgi_swapchain_count_test.cpp +++ b/runtime/test/dxgi_swapchain_count_test.cpp | |||
| @@ -267,7 +267,7 @@ int run_case(const char* label, std::uint32_t requested, std::uint32_t native, s | |||
| 267 | g = Fake{}; | 267 | g = Fake{}; |
| 268 | g.min_image_count = minimum; | 268 | g.min_image_count = minimum; |
| 269 | g.returned_images = native; | 269 | g.returned_images = native; |
| 270 | std::mutex mutex; | 270 | leonida::SubmitMutex mutex; |
| 271 | leonida::VulkanSwapchain swapchain(get_instance_proc, reinterpret_cast<VkInstance>(1), | 271 | leonida::VulkanSwapchain swapchain(get_instance_proc, reinterpret_cast<VkInstance>(1), |
| 272 | reinterpret_cast<VkPhysicalDevice>(2), get_device_proc, | 272 | reinterpret_cast<VkPhysicalDevice>(2), get_device_proc, |
| 273 | reinterpret_cast<VkDevice>(3), reinterpret_cast<VkQueue>(4), 0, mutex, | 273 | reinterpret_cast<VkDevice>(3), reinterpret_cast<VkQueue>(4), 0, mutex, |
| @@ -375,7 +375,7 @@ int run_failed_resize(const char* label, std::uint32_t requested, std::uint32_t | |||
| 375 | g = Fake{}; | 375 | g = Fake{}; |
| 376 | g.min_image_count = 2; | 376 | g.min_image_count = 2; |
| 377 | g.returned_images = native; | 377 | g.returned_images = native; |
| 378 | std::mutex mutex; | 378 | leonida::SubmitMutex mutex; |
| 379 | leonida::VulkanSwapchain swapchain(get_instance_proc, reinterpret_cast<VkInstance>(1), | 379 | leonida::VulkanSwapchain swapchain(get_instance_proc, reinterpret_cast<VkInstance>(1), |
| 380 | reinterpret_cast<VkPhysicalDevice>(2), get_device_proc, | 380 | reinterpret_cast<VkPhysicalDevice>(2), get_device_proc, |
| 381 | reinterpret_cast<VkDevice>(3), reinterpret_cast<VkQueue>(4), 0, mutex, | 381 | reinterpret_cast<VkDevice>(3), reinterpret_cast<VkQueue>(4), 0, mutex, |
diff --git a/runtime/test/file_system_test.cpp b/runtime/test/file_system_test.cpp index 493ffd6bf..af37935f6 100644 --- a/runtime/test/file_system_test.cpp +++ b/runtime/test/file_system_test.cpp | |||
| @@ -8,6 +8,7 @@ | |||
| 8 | #include <aclapi.h> | 8 | #include <aclapi.h> |
| 9 | 9 | ||
| 10 | #include <algorithm> | 10 | #include <algorithm> |
| 11 | #include <atomic> | ||
| 11 | #include <clocale> | 12 | #include <clocale> |
| 12 | #include <cstring> | 13 | #include <cstring> |
| 13 | #include <cstdio> | 14 | #include <cstdio> |
| @@ -118,6 +119,81 @@ int count(const std::vector<std::wstring>& names, const wchar_t* name) { | |||
| 118 | 119 | ||
| 119 | bool contains(const std::vector<std::wstring>& names, const wchar_t* name) { return count(names, name) != 0; } | 120 | bool contains(const std::vector<std::wstring>& names, const wchar_t* name) { return count(names, name) != 0; } |
| 120 | 121 | ||
| 122 | // The folder "T:\" names in another process `pid`: the one below <overlay>\.gta6rt-temp whose name ends in | ||
| 123 | // "-pid<pid>" or "-pid<pid>-<n>" (rt::fs::scratch_dir() in that process). Empty when there is none, as when every | ||
| 124 | // process shared .gta6rt-temp. | ||
| 125 | std::filesystem::path t_folder(const std::filesystem::path& overlay, DWORD pid) { | ||
| 126 | const std::wstring marker = L"-pid" + std::to_wstring(pid); | ||
| 127 | std::error_code ec; | ||
| 128 | for (auto it = std::filesystem::directory_iterator(overlay / ".gta6rt-temp", ec); | ||
| 129 | !ec && it != std::filesystem::directory_iterator(); it.increment(ec)) { | ||
| 130 | const std::wstring name = it->path().filename().wstring(); | ||
| 131 | const size_t at = name.rfind(marker); | ||
| 132 | std::error_code type_ec; | ||
| 133 | if (it->is_directory(type_ec) && at != std::wstring::npos && | ||
| 134 | (at + marker.size() == name.size() || name[at + marker.size()] == L'-')) | ||
| 135 | return it->path(); | ||
| 136 | } | ||
| 137 | return {}; | ||
| 138 | } | ||
| 139 | |||
| 140 | // This process's T: folder in the configured overlay. | ||
| 141 | std::filesystem::path own_t_folder(const std::filesystem::path& overlay) { | ||
| 142 | return rt::fs::overlay_dir() == overlay ? rt::fs::scratch_dir() : std::filesystem::path(); | ||
| 143 | } | ||
| 144 | |||
| 145 | // file_system_test started by itself as a second process (run_t_drive_child below): it opens T:\crash.dmp with | ||
| 146 | // CREATE_NEW on the overlay its parent uses, writes "child process" and exits with 0, or with the open's Win32 error. | ||
| 147 | constexpr wchar_t kChildPackage[] = L"LEONIDA_FS_TEST_CHILD_PACKAGE"; | ||
| 148 | constexpr wchar_t kChildOverlay[] = L"LEONIDA_FS_TEST_CHILD_OVERLAY"; | ||
| 149 | |||
| 150 | std::wstring environment(const wchar_t* name) { | ||
| 151 | std::wstring buffer(32768, L'\0'); | ||
| 152 | const DWORD n = ::GetEnvironmentVariableW(name, buffer.data(), static_cast<DWORD>(buffer.size())); | ||
| 153 | if (n == 0 || n >= buffer.size()) return {}; | ||
| 154 | buffer.resize(n); | ||
| 155 | return buffer; | ||
| 156 | } | ||
| 157 | |||
| 158 | int t_drive_child(const std::wstring& package, const std::wstring& overlay) { | ||
| 159 | rt::fs::configure(package, overlay); | ||
| 160 | const auto create_w = resolve<CreateFileWFn>("kernel32.dll", "CreateFileW"); | ||
| 161 | if (!create_w) return 1000; | ||
| 162 | const HANDLE h = create_w(L"T:\\crash.dmp", GENERIC_WRITE, 0, nullptr, CREATE_NEW, 0, nullptr); | ||
| 163 | if (h == INVALID_HANDLE_VALUE) return static_cast<int>(::GetLastError()); | ||
| 164 | DWORD written = 0; | ||
| 165 | ::WriteFile(h, "child process", 13, &written, nullptr); | ||
| 166 | ::CloseHandle(h); | ||
| 167 | return 0; | ||
| 168 | } | ||
| 169 | |||
| 170 | // Runs t_drive_child in a new process of this executable on the given folders. Returns its exit code (~0u when it | ||
| 171 | // could not be started or did not finish) and its process id in `pid`. | ||
| 172 | DWORD run_t_drive_child(const std::filesystem::path& package, const std::filesystem::path& overlay, DWORD& pid) { | ||
| 173 | pid = 0; | ||
| 174 | std::wstring self(32768, L'\0'); | ||
| 175 | const DWORD length = ::GetModuleFileNameW(nullptr, self.data(), static_cast<DWORD>(self.size())); | ||
| 176 | if (length == 0 || length >= self.size()) return ~0u; | ||
| 177 | self.resize(length); | ||
| 178 | std::wstring command = L"\"" + self + L"\""; | ||
| 179 | ::SetEnvironmentVariableW(kChildPackage, package.c_str()); | ||
| 180 | ::SetEnvironmentVariableW(kChildOverlay, overlay.c_str()); | ||
| 181 | STARTUPINFOW startup{}; | ||
| 182 | startup.cb = sizeof(startup); | ||
| 183 | PROCESS_INFORMATION process{}; | ||
| 184 | const BOOL started = ::CreateProcessW(self.c_str(), command.data(), nullptr, nullptr, FALSE, 0, nullptr, nullptr, | ||
| 185 | &startup, &process); | ||
| 186 | ::SetEnvironmentVariableW(kChildPackage, nullptr); | ||
| 187 | ::SetEnvironmentVariableW(kChildOverlay, nullptr); | ||
| 188 | if (!started) return ~0u; | ||
| 189 | DWORD code = ~0u; | ||
| 190 | if (::WaitForSingleObject(process.hProcess, 60000) == WAIT_OBJECT_0) ::GetExitCodeProcess(process.hProcess, &code); | ||
| 191 | pid = process.dwProcessId; | ||
| 192 | ::CloseHandle(process.hThread); | ||
| 193 | ::CloseHandle(process.hProcess); | ||
| 194 | return code; | ||
| 195 | } | ||
| 196 | |||
| 121 | // Denies the current user `rights` on a folder while it lives and puts the folder's old DACL back when it goes, on | 197 | // Denies the current user `rights` on a folder while it lives and puts the folder's old DACL back when it goes, on |
| 122 | // every way out of the check. Both changes go through one handle opened before the deny. Under Wine the DACL is the | 198 | // every way out of the check. Both changes go through one handle opened before the deny. Under Wine the DACL is the |
| 123 | // folder's unix mode: a deny of FILE_LIST_DIRECTORY clears its owner and group read bits (server/file.c, sd_to_mode), | 199 | // folder's unix mode: a deny of FILE_LIST_DIRECTORY clears its owner and group read bits (server/file.c, sd_to_mode), |
| @@ -244,6 +320,8 @@ void check_read_file_first_touch(const std::filesystem::path& root) { | |||
| 244 | } // namespace | 320 | } // namespace |
| 245 | 321 | ||
| 246 | int main() { | 322 | int main() { |
| 323 | if (const std::wstring child_overlay = environment(kChildOverlay); !child_overlay.empty()) | ||
| 324 | return t_drive_child(environment(kChildPackage), child_overlay); | ||
| 247 | // A folder of this run's own: Wine hands each fresh prefix the same small process ids, so a folder named after | 325 | // A folder of this run's own: Wine hands each fresh prefix the same small process ids, so a folder named after |
| 248 | // the process id alone can be one an earlier run left behind. | 326 | // the process id alone can be one an earlier run left behind. |
| 249 | LARGE_INTEGER now{}; | 327 | LARGE_INTEGER now{}; |
| @@ -850,6 +928,75 @@ void run_checks(const std::filesystem::path& root) { | |||
| 850 | } | 928 | } |
| 851 | } | 929 | } |
| 852 | 930 | ||
| 931 | // RemoveDirectory of a folder on one thread and, on another, a creating open of a file in it (CREATE_NEW, | ||
| 932 | // CREATE_ALWAYS, OPEN_ALWAYS) or CreateDirectory of a folder in it. The host orders the two: the remove goes first | ||
| 933 | // and the create fails with ERROR_PATH_NOT_FOUND, or the create goes first and the remove fails with | ||
| 934 | // ERROR_DIR_NOT_EMPTY. Both succeeding left the removed folder back in the title's view with the new entry in it. | ||
| 935 | // Each round takes a folder of its own that only the package has, empty in the title's view, and starts the two | ||
| 936 | // threads together; the remover waits a few more spins each round so the calls meet at different points. | ||
| 937 | { | ||
| 938 | constexpr int kRounds = 2000; | ||
| 939 | const auto race = [&](bool make_folder, const wchar_t* prefix, const char* what) { | ||
| 940 | for (int i = 0; i < kRounds; ++i) | ||
| 941 | std::filesystem::create_directories(package / "rmrace" / (prefix + std::to_wstring(i))); | ||
| 942 | int create_first = 0, remove_first = 0, both = 0, other = 0, back = 0; | ||
| 943 | for (int i = 0; i < kRounds; ++i) { | ||
| 944 | const std::wstring folder = L"GAME:\\rmrace\\" + (prefix + std::to_wstring(i)); | ||
| 945 | const std::wstring child = folder + (make_folder ? L"\\sub" : L"\\new.tmp"); | ||
| 946 | const DWORD disposition = i % 3 == 0 ? CREATE_NEW : i % 3 == 1 ? CREATE_ALWAYS : OPEN_ALWAYS; | ||
| 947 | std::atomic<int> ready{0}; | ||
| 948 | HANDLE handle = INVALID_HANDLE_VALUE; | ||
| 949 | bool made = false; | ||
| 950 | DWORD create_error = 0; | ||
| 951 | std::thread creator([&] { | ||
| 952 | ready.fetch_add(1); | ||
| 953 | while (ready.load() < 2) { | ||
| 954 | } | ||
| 955 | if (make_folder) { | ||
| 956 | made = mkdir_w(child.c_str(), nullptr) != FALSE; | ||
| 957 | } else { | ||
| 958 | handle = create_w(child.c_str(), GENERIC_WRITE, 0, nullptr, disposition, 0, nullptr); | ||
| 959 | made = handle != INVALID_HANDLE_VALUE; | ||
| 960 | } | ||
| 961 | create_error = made ? 0 : GetLastError(); | ||
| 962 | }); | ||
| 963 | ready.fetch_add(1); | ||
| 964 | while (ready.load() < 2) { | ||
| 965 | } | ||
| 966 | for (int spin = 0; spin < (i % 64) * 64; ++spin) YieldProcessor(); | ||
| 967 | const bool removed = rmdir_w(folder.c_str()) != FALSE; | ||
| 968 | const DWORD remove_error = removed ? 0 : GetLastError(); | ||
| 969 | creator.join(); | ||
| 970 | if (handle != INVALID_HANDLE_VALUE) ::CloseHandle(handle); | ||
| 971 | if (made && removed) { | ||
| 972 | ++both; | ||
| 973 | } else if (made && remove_error == ERROR_DIR_NOT_EMPTY) { | ||
| 974 | ++create_first; | ||
| 975 | } else if (removed && create_error == ERROR_PATH_NOT_FOUND) { | ||
| 976 | ++remove_first; | ||
| 977 | } else { | ||
| 978 | ++other; | ||
| 979 | } | ||
| 980 | // A folder the remove took away stays away, whatever the create did. | ||
| 981 | if (removed) { | ||
| 982 | SetLastError(0); | ||
| 983 | if (attributes_w(folder.c_str()) != INVALID_FILE_ATTRIBUTES || GetLastError() != ERROR_FILE_NOT_FOUND) | ||
| 984 | ++back; | ||
| 985 | } | ||
| 986 | } | ||
| 987 | std::printf("NOTE %s against RemoveDirectoryW, %d rounds: create first %d, remove first %d, both succeeded " | ||
| 988 | "%d, other %d, removed folder back %d\n", | ||
| 989 | what, kRounds, create_first, remove_first, both, other, back); | ||
| 990 | const std::string w = what; | ||
| 991 | check(both == 0, (w + " and RemoveDirectoryW of its folder never both succeed").c_str()); | ||
| 992 | check(other == 0, (w + " or RemoveDirectoryW fails as on the host (ERROR_PATH_NOT_FOUND or " | ||
| 993 | "ERROR_DIR_NOT_EMPTY)").c_str()); | ||
| 994 | check(back == 0, (w + ": a folder RemoveDirectoryW removed stays removed").c_str()); | ||
| 995 | }; | ||
| 996 | race(false, L"f", "a creating CreateFileW"); | ||
| 997 | race(true, L"d", "CreateDirectoryW"); | ||
| 998 | } | ||
| 999 | |||
| 853 | // MoveFile: the destination is in the overlay; a moved package file is deleted by a marker. | 1000 | // MoveFile: the destination is in the overlay; a moved package file is deleted by a marker. |
| 854 | { | 1001 | { |
| 855 | check(move_w(L"GAME:\\misc\\one.txt", L"GAME:\\misc\\moved.txt") != FALSE, "MoveFileW moves a package file"); | 1002 | check(move_w(L"GAME:\\misc\\one.txt", L"GAME:\\misc\\moved.txt") != FALSE, "MoveFileW moves a package file"); |
| @@ -1274,18 +1421,18 @@ void run_checks(const std::filesystem::path& root) { | |||
| 1274 | "on a fresh overlay CreateDirectoryW(T:\\shadercache) succeeds"); | 1421 | "on a fresh overlay CreateDirectoryW(T:\\shadercache) succeeds"); |
| 1275 | std::filesystem::path fresh = fresh_overlay(); | 1422 | std::filesystem::path fresh = fresh_overlay(); |
| 1276 | check(copy_w(L"GAME:\\data\\hello.txt", L"T:\\hello.tmp", FALSE) != FALSE && | 1423 | check(copy_w(L"GAME:\\data\\hello.txt", L"T:\\hello.tmp", FALSE) != FALSE && |
| 1277 | read_path(fresh / ".gta6rt-temp" / "hello.tmp") == "package", | 1424 | read_path(own_t_folder(fresh) / "hello.tmp") == "package", |
| 1278 | "on a fresh overlay CopyFileW(GAME:\\data\\hello.txt, T:\\hello.tmp) succeeds"); | 1425 | "on a fresh overlay CopyFileW(GAME:\\data\\hello.txt, T:\\hello.tmp) succeeds"); |
| 1279 | fresh = fresh_overlay(); | 1426 | fresh = fresh_overlay(); |
| 1280 | SetLastError(0); | 1427 | SetLastError(0); |
| 1281 | check(rmdir_w(L"T:\\") == FALSE && GetLastError() == ERROR_ACCESS_DENIED && | 1428 | check(rmdir_w(L"T:\\") == FALSE && GetLastError() == ERROR_ACCESS_DENIED && |
| 1282 | std::filesystem::is_directory(fresh / ".gta6rt-temp"), | 1429 | std::filesystem::is_directory(own_t_folder(fresh)), |
| 1283 | "T:\\ cannot be removed, like GAME:\\"); | 1430 | "T:\\ cannot be removed, like GAME:\\"); |
| 1284 | fresh = fresh_overlay(); | 1431 | fresh = fresh_overlay(); |
| 1285 | SetLastError(0); | 1432 | SetLastError(0); |
| 1286 | check(move_w(L"T:\\", L"GAME:\\moved") == FALSE && GetLastError() == ERROR_ACCESS_DENIED && | 1433 | check(move_w(L"T:\\", L"GAME:\\moved") == FALSE && GetLastError() == ERROR_ACCESS_DENIED && |
| 1287 | attributes_w(L"GAME:\\moved") == INVALID_FILE_ATTRIBUTES && | 1434 | attributes_w(L"GAME:\\moved") == INVALID_FILE_ATTRIBUTES && |
| 1288 | std::filesystem::is_directory(fresh / ".gta6rt-temp"), | 1435 | std::filesystem::is_directory(own_t_folder(fresh)), |
| 1289 | "T:\\ cannot be moved"); | 1436 | "T:\\ cannot be moved"); |
| 1290 | fresh_overlay(); | 1437 | fresh_overlay(); |
| 1291 | attributes_w(L"T:\\"); | 1438 | attributes_w(L"T:\\"); |
| @@ -1302,8 +1449,8 @@ void run_checks(const std::filesystem::path& root) { | |||
| 1302 | ::WriteFile(h, "scratch", 7, &written, nullptr); | 1449 | ::WriteFile(h, "scratch", 7, &written, nullptr); |
| 1303 | ::CloseHandle(h); | 1450 | ::CloseHandle(h); |
| 1304 | } | 1451 | } |
| 1305 | check(read_path(overlay / ".gta6rt-temp" / "cache" / "scratch.bin") == "scratch", | 1452 | check(read_path(own_t_folder(overlay) / "cache" / "scratch.bin") == "scratch", |
| 1306 | "a T: file lands in the overlay's scratch folder"); | 1453 | "a T: file lands in this process's scratch folder in the overlay"); |
| 1307 | check(!std::filesystem::exists(package / "cache" / "scratch.bin") && !std::filesystem::exists(package / ".gta6rt-temp"), | 1454 | check(!std::filesystem::exists(package / "cache" / "scratch.bin") && !std::filesystem::exists(package / ".gta6rt-temp"), |
| 1308 | "and the package is untouched"); | 1455 | "and the package is untouched"); |
| 1309 | h = create_w(L"t:/cache/scratch.bin", GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr); | 1456 | h = create_w(L"t:/cache/scratch.bin", GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr); |
| @@ -1323,6 +1470,8 @@ void run_checks(const std::filesystem::path& root) { | |||
| 1323 | // as an explicit GAME: or G: path, refused like any other invalid name, in every spelling parse_console() | 1470 | // as an explicit GAME: or G: path, refused like any other invalid name, in every spelling parse_console() |
| 1324 | // normalises (RT-294). T:\ still names the scratch folder, and an ordinary dotted name is not reserved. | 1471 | // normalises (RT-294). T:\ still names the scratch folder, and an ordinary dotted name is not reserved. |
| 1325 | write_path(overlay / ".gta6rt-temp" / "runtime.tmp", "runtime"); | 1472 | write_path(overlay / ".gta6rt-temp" / "runtime.tmp", "runtime"); |
| 1473 | if (const std::filesystem::path t_dir = own_t_folder(overlay); !t_dir.empty()) | ||
| 1474 | write_path(t_dir / "runtime.tmp", "runtime"); | ||
| 1326 | write_path(overlay / ".gta6rt-deleted" / "data" / "gone.txt", ""); | 1475 | write_path(overlay / ".gta6rt-deleted" / "data" / "gone.txt", ""); |
| 1327 | write_path(overlay / ".gta6rt-other" / "ok.txt", "ok"); | 1476 | write_path(overlay / ".gta6rt-other" / "ok.txt", "ok"); |
| 1328 | for (const wchar_t* reserved : {L"GAME:\\.gta6rt-temp\\runtime.tmp", L"GAME:\\.GTA6RT-TEMP\\runtime.tmp", | 1477 | for (const wchar_t* reserved : {L"GAME:\\.gta6rt-temp\\runtime.tmp", L"GAME:\\.GTA6RT-TEMP\\runtime.tmp", |
| @@ -1347,7 +1496,8 @@ void run_checks(const std::filesystem::path& root) { | |||
| 1347 | if (markers != INVALID_HANDLE_VALUE) find_close(markers); | 1496 | if (markers != INVALID_HANDLE_VALUE) find_close(markers); |
| 1348 | SetLastError(0); | 1497 | SetLastError(0); |
| 1349 | const HANDLE probe = create_w(L"GAME:\\.gta6rt-temp\\probe.txt", GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, 0, nullptr); | 1498 | const HANDLE probe = create_w(L"GAME:\\.gta6rt-temp\\probe.txt", GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, 0, nullptr); |
| 1350 | check(probe == INVALID_HANDLE_VALUE && !std::filesystem::exists(overlay / ".gta6rt-temp" / "probe.txt"), | 1499 | check(probe == INVALID_HANDLE_VALUE && !std::filesystem::exists(overlay / ".gta6rt-temp" / "probe.txt") && |
| 1500 | !std::filesystem::exists(own_t_folder(overlay) / "probe.txt"), | ||
| 1351 | "a write through GAME:\\.gta6rt-temp creates nothing in the scratch folder"); | 1501 | "a write through GAME:\\.gta6rt-temp creates nothing in the scratch folder"); |
| 1352 | if (probe != INVALID_HANDLE_VALUE) ::CloseHandle(probe); | 1502 | if (probe != INVALID_HANDLE_VALUE) ::CloseHandle(probe); |
| 1353 | check(mkdir_w(L"GAME:\\.gta6rt-copy\\sub", nullptr) == FALSE && !std::filesystem::exists(overlay / ".gta6rt-copy" / "sub"), | 1503 | check(mkdir_w(L"GAME:\\.gta6rt-copy\\sub", nullptr) == FALSE && !std::filesystem::exists(overlay / ".gta6rt-copy" / "sub"), |
| @@ -1376,6 +1526,157 @@ void run_checks(const std::filesystem::path& root) { | |||
| 1376 | rt::fs::configure(package, overlay); | 1526 | rt::fs::configure(package, overlay); |
| 1377 | } | 1527 | } |
| 1378 | 1528 | ||
| 1529 | // T: is the title's temporary drive, which on the console no other run shares: each process gets a folder of its | ||
| 1530 | // own below <overlay>\.gta6rt-temp. With one folder for every run, the title's crash dump and crash log, made with | ||
| 1531 | // CREATE_NEW, failed with ERROR_FILE_EXISTS on names an earlier run had left (old upstream issue 7913, measured | ||
| 1532 | // under Wine). | ||
| 1533 | { | ||
| 1534 | const std::filesystem::path t_overlay = root / "t_overlay"; | ||
| 1535 | const std::filesystem::path temp = t_overlay / ".gta6rt-temp"; | ||
| 1536 | // What earlier runs left: a file in the folder they all shared, and one in an earlier process's own folder. | ||
| 1537 | write_path(temp / "crash.dmp", "earlier run"); | ||
| 1538 | write_path(temp / "20200101-000000-000-pid1" / "crash.dmp", "earlier process"); | ||
| 1539 | write_path(package / "crash.dmp", "package"); // and a GAME: file of the same name | ||
| 1540 | rt::fs::configure(package, t_overlay); | ||
| 1541 | |||
| 1542 | SetLastError(0); | ||
| 1543 | HANDLE h = create_w(L"T:\\crash.dmp", GENERIC_WRITE, 0, nullptr, CREATE_NEW, 0, nullptr); | ||
| 1544 | const DWORD create_error = h == INVALID_HANDLE_VALUE ? GetLastError() : 0; | ||
| 1545 | check(h != INVALID_HANDLE_VALUE, | ||
| 1546 | "CreateFileW(T:\\crash.dmp, CREATE_NEW) succeeds when earlier runs left that name in .gta6rt-temp"); | ||
| 1547 | if (create_error) std::printf(" (failed with Win32 error %lu)\n", static_cast<unsigned long>(create_error)); | ||
| 1548 | if (h != INVALID_HANDLE_VALUE) { | ||
| 1549 | DWORD written = 0; | ||
| 1550 | ::WriteFile(h, "this process", 12, &written, nullptr); | ||
| 1551 | ::CloseHandle(h); | ||
| 1552 | } | ||
| 1553 | const std::filesystem::path mine = own_t_folder(t_overlay); | ||
| 1554 | check(!mine.empty() && mine.parent_path() == temp && read_path(mine / "crash.dmp") == "this process", | ||
| 1555 | "T:\\crash.dmp lands in this process's own folder <overlay>\\.gta6rt-temp\\<start time>-pid<id>"); | ||
| 1556 | const std::wstring name = mine.filename().wstring(); | ||
| 1557 | const auto digits = [&](size_t from, size_t n) { | ||
| 1558 | if (name.size() < from + n) return false; | ||
| 1559 | for (size_t i = from; i < from + n; ++i) | ||
| 1560 | if (name[i] < L'0' || name[i] > L'9') return false; | ||
| 1561 | return true; | ||
| 1562 | }; | ||
| 1563 | check(digits(0, 8) && name.size() > 20 && name[8] == L'-' && digits(9, 6) && name[15] == L'-' && | ||
| 1564 | digits(16, 3) && name.compare(19, 4, L"-pid") == 0, | ||
| 1565 | "the folder is named YYYYMMDD-HHMMSS-mmm-pid<id>, the process's start time and id"); | ||
| 1566 | check(name == rt::fs::scratch_stem(), "with no folder of that name yet, it is the stem itself"); | ||
| 1567 | check(read_path(temp / "crash.dmp") == "earlier run" && | ||
| 1568 | read_path(temp / "20200101-000000-000-pid1" / "crash.dmp") == "earlier process" && | ||
| 1569 | read_path(package / "crash.dmp") == "package", | ||
| 1570 | "the earlier runs' files and the package file of the same name are left as they were"); | ||
| 1571 | |||
| 1572 | // The same folder for every T: call of this process, also after configure() names the overlay again. | ||
| 1573 | rt::fs::configure(package, t_overlay); | ||
| 1574 | h = create_w(L"t:/crash.dmp", GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr); | ||
| 1575 | check(h != INVALID_HANDLE_VALUE && read_handle(h) == "this process", | ||
| 1576 | "T: keeps naming the same folder for the rest of the process"); | ||
| 1577 | if (h != INVALID_HANDLE_VALUE) ::CloseHandle(h); | ||
| 1578 | const std::vector<std::wstring> t_names = list(first_w, next_w, find_close, L"T:\\*"); | ||
| 1579 | check(count(t_names, L"crash.dmp") == 1 && !contains(t_names, L"20200101-000000-000-pid1") && | ||
| 1580 | !contains(t_names, L".gta6rt-temp"), | ||
| 1581 | "a T:\\ listing shows this process's files only"); | ||
| 1582 | SetLastError(0); | ||
| 1583 | check(create_w(L"T:\\..\\crash.dmp", GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr) == | ||
| 1584 | INVALID_HANDLE_VALUE && | ||
| 1585 | GetLastError() == ERROR_INVALID_NAME, | ||
| 1586 | "T:\\.. cannot climb into the shared .gta6rt-temp folder"); | ||
| 1587 | SetLastError(0); | ||
| 1588 | check(rmdir_w(L"T:\\") == FALSE && GetLastError() == ERROR_ACCESS_DENIED && std::filesystem::is_directory(mine), | ||
| 1589 | "this process's T:\\ folder cannot be removed, like GAME:\\"); | ||
| 1590 | |||
| 1591 | // A second process on the same overlay gets a folder of its own, and its CREATE_NEW of the same name succeeds. | ||
| 1592 | DWORD child_pid = 0; | ||
| 1593 | const DWORD child_code = run_t_drive_child(package, t_overlay, child_pid); | ||
| 1594 | check(child_code == 0, | ||
| 1595 | "a second process's CreateFileW(T:\\crash.dmp, CREATE_NEW) on the same overlay succeeds"); | ||
| 1596 | if (child_code != 0) | ||
| 1597 | std::printf(" (the second process exited with %lu)\n", static_cast<unsigned long>(child_code)); | ||
| 1598 | const std::filesystem::path theirs = child_pid ? t_folder(t_overlay, child_pid) : std::filesystem::path(); | ||
| 1599 | check(!theirs.empty() && theirs != mine && theirs.parent_path() == temp && | ||
| 1600 | read_path(theirs / "crash.dmp") == "child process", | ||
| 1601 | "the second process wrote into a folder of its own"); | ||
| 1602 | check(read_path(mine / "crash.dmp") == "this process", "and this process's T: file is unchanged"); | ||
| 1603 | |||
| 1604 | // A reused process id in the same millisecond gives the same stem as a folder an earlier run kept. The folder | ||
| 1605 | // is reserved with a create-only call, so that one (and the next name, taken too) is never used again. | ||
| 1606 | const std::filesystem::path stale_overlay = root / "t_stale_overlay"; | ||
| 1607 | const std::filesystem::path stale = stale_overlay / ".gta6rt-temp" / rt::fs::scratch_stem(); | ||
| 1608 | const std::filesystem::path stale_2 = stale_overlay / ".gta6rt-temp" / (rt::fs::scratch_stem() + L"-2"); | ||
| 1609 | write_path(stale / "crash.dmp", "same stem, earlier run"); | ||
| 1610 | std::filesystem::create_directories(stale_2); | ||
| 1611 | rt::fs::configure(package, stale_overlay); | ||
| 1612 | h = create_w(L"T:\\crash.dmp", GENERIC_WRITE, 0, nullptr, CREATE_NEW, 0, nullptr); | ||
| 1613 | check(h != INVALID_HANDLE_VALUE, | ||
| 1614 | "CreateFileW(T:\\crash.dmp, CREATE_NEW) succeeds when a kept folder has this process's own stem"); | ||
| 1615 | if (h != INVALID_HANDLE_VALUE) ::CloseHandle(h); | ||
| 1616 | check(rt::fs::scratch_dir() == stale_overlay / ".gta6rt-temp" / (rt::fs::scratch_stem() + L"-3") && | ||
| 1617 | std::filesystem::exists(rt::fs::scratch_dir() / "crash.dmp"), | ||
| 1618 | "T: is <stem>-3 when <stem> and <stem>-2 already existed"); | ||
| 1619 | check(read_path(stale / "crash.dmp") == "same stem, earlier run" && std::filesystem::is_empty(stale_2), | ||
| 1620 | "and the folders that already existed are left as they were"); | ||
| 1621 | |||
| 1622 | // Concurrent first T: calls on a new overlay reserve one folder between them. | ||
| 1623 | const std::filesystem::path race_overlay = root / "t_race_overlay"; | ||
| 1624 | rt::fs::configure(package, race_overlay); | ||
| 1625 | { | ||
| 1626 | std::vector<std::thread> threads; | ||
| 1627 | for (int i = 0; i < 8; ++i) threads.emplace_back([&] { attributes_w(L"T:\\"); }); | ||
| 1628 | for (auto& thread : threads) thread.join(); | ||
| 1629 | } | ||
| 1630 | size_t reserved = 0; | ||
| 1631 | for (const auto& entry : std::filesystem::directory_iterator(race_overlay / ".gta6rt-temp")) { | ||
| 1632 | (void)entry; | ||
| 1633 | ++reserved; | ||
| 1634 | } | ||
| 1635 | check(reserved == 1 && std::filesystem::is_directory(rt::fs::scratch_dir()), | ||
| 1636 | "eight threads making their first T: call at once reserve one folder"); | ||
| 1637 | rt::fs::configure(package, t_overlay); | ||
| 1638 | |||
| 1639 | // GAME: is not affected: reads come from the package, writes land in the overlay's mirror of the package. | ||
| 1640 | h = create_w(L"GAME:\\crash.dmp", GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr); | ||
| 1641 | check(h != INVALID_HANDLE_VALUE && read_handle(h) == "package", | ||
| 1642 | "GAME:\\crash.dmp still reads the package file"); | ||
| 1643 | if (h != INVALID_HANDLE_VALUE) ::CloseHandle(h); | ||
| 1644 | h = create_w(L"GAME:\\data\\t_written.txt", GENERIC_WRITE, 0, nullptr, CREATE_NEW, 0, nullptr); | ||
| 1645 | check(h != INVALID_HANDLE_VALUE, "a GAME: write-open still succeeds"); | ||
| 1646 | if (h != INVALID_HANDLE_VALUE) ::CloseHandle(h); | ||
| 1647 | check(std::filesystem::exists(t_overlay / "data" / "t_written.txt") && | ||
| 1648 | !std::filesystem::exists(mine / "data") && | ||
| 1649 | !std::filesystem::exists(package / "data" / "t_written.txt"), | ||
| 1650 | "and lands at <overlay>\\data, not in T:'s folder or the package"); | ||
| 1651 | rt::fs::configure(package, overlay); | ||
| 1652 | } | ||
| 1653 | |||
| 1654 | // reserve_unique_dir: a create-only CreateDirectoryW per name, so the folder it returns is new; a name that exists | ||
| 1655 | // (a folder or a file) is skipped, and after max_tries names the call fails instead of reusing one. | ||
| 1656 | { | ||
| 1657 | const std::filesystem::path base = root / "reserve"; | ||
| 1658 | std::filesystem::create_directories(base / "stem"); | ||
| 1659 | write_path(base / "stem-2" / "old.txt", "old"); | ||
| 1660 | DWORD error = 1; | ||
| 1661 | const std::filesystem::path third = rt::fs::reserve_unique_dir(base, L"stem", error); | ||
| 1662 | check(third == base / "stem-3" && error == 0 && std::filesystem::is_directory(third) && | ||
| 1663 | std::filesystem::is_empty(third), | ||
| 1664 | "reserve_unique_dir(base, stem) with stem and stem-2 taken makes stem-3, new and empty"); | ||
| 1665 | check(read_path(base / "stem-2" / "old.txt") == "old", "and leaves the taken folders alone"); | ||
| 1666 | check(rt::fs::reserve_unique_dir(base, L"stem", error) == base / "stem-4", | ||
| 1667 | "a second call never hands out stem-3 again: it makes stem-4"); | ||
| 1668 | write_path(base / "stem-5", "a file"); | ||
| 1669 | check(rt::fs::reserve_unique_dir(base, L"stem", error) == base / "stem-6", | ||
| 1670 | "a file with the next name counts as taken too"); | ||
| 1671 | error = 0; | ||
| 1672 | check(rt::fs::reserve_unique_dir(base, L"stem", error, 6).empty() && error == ERROR_ALREADY_EXISTS, | ||
| 1673 | "with every name up to max_tries taken it fails with ERROR_ALREADY_EXISTS"); | ||
| 1674 | const std::filesystem::path fresh_base = root / "reserve_new" / "deep"; | ||
| 1675 | check(rt::fs::reserve_unique_dir(fresh_base, L"stem", error) == fresh_base / "stem" && | ||
| 1676 | std::filesystem::is_directory(fresh_base / "stem"), | ||
| 1677 | "a missing base folder is made first, and the stem itself is the first name"); | ||
| 1678 | } | ||
| 1679 | |||
| 1379 | // An open that writes needs its folder to exist in the title's view, and a failed open changes nothing. | 1680 | // An open that writes needs its folder to exist in the title's view, and a failed open changes nothing. |
| 1380 | { | 1681 | { |
| 1381 | const auto overlay_has = [&](const wchar_t* name) { return std::filesystem::exists(overlay / name); }; | 1682 | const auto overlay_has = [&](const wchar_t* name) { return std::filesystem::exists(overlay / name); }; |
| @@ -1650,9 +1951,11 @@ void run_checks(const std::filesystem::path& root) { | |||
| 1650 | check(h != INVALID_HANDLE_VALUE && ::WriteFile(h, "test", 4, &written, nullptr) && written == 4, | 1951 | check(h != INVALID_HANDLE_VALUE && ::WriteFile(h, "test", 4, &written, nullptr) && written == 4, |
| 1651 | "T: creates and writes its scratch directory under a long overlay root"); | 1952 | "T: creates and writes its scratch directory under a long overlay root"); |
| 1652 | if (h != INVALID_HANDLE_VALUE) ::CloseHandle(h); | 1953 | if (h != INVALID_HANDLE_VALUE) ::CloseHandle(h); |
| 1653 | check(read_guest(L"T:\\scratch.bin") == "test" && | 1954 | const std::filesystem::path scratch_folder = rt::fs::scratch_dir(); // configured on scratch_overlay above |
| 1654 | read_path(extended(scratch_overlay / ".gta6rt-temp" / "scratch.bin")) == "test", | 1955 | check(read_guest(L"T:\\scratch.bin") == "test" && !scratch_folder.empty() && |
| 1655 | "T: reads from the same long backing directory"); | 1956 | scratch_folder.parent_path() == scratch_overlay / ".gta6rt-temp" && |
| 1957 | read_path(extended(scratch_folder / "scratch.bin")) == "test", | ||
| 1958 | "T: reads from the same long backing directory, this process's own folder in it"); | ||
| 1656 | rt::fs::configure(package, overlay); | 1959 | rt::fs::configure(package, overlay); |
| 1657 | 1960 | ||
| 1658 | std::error_code cleanup_error; | 1961 | std::error_code cleanup_error; |
diff --git a/runtime/test/fixtures/tiny_game.cpp b/runtime/test/fixtures/tiny_game.cpp index 21feaad5f..69a696d30 100644 --- a/runtime/test/fixtures/tiny_game.cpp +++ b/runtime/test/fixtures/tiny_game.cpp | |||
| @@ -120,6 +120,7 @@ int main(int argc, char** argv) { | |||
| 120 | }; | 120 | }; |
| 121 | check(configured("LEONIDA_D3D12", "vulkan"), "first-run UI Vulkan backend"); | 121 | check(configured("LEONIDA_D3D12", "vulkan"), "first-run UI Vulkan backend"); |
| 122 | check(configured("LEONIDA_PIPELINE_COMPILE", "on-demand"), "first-run UI pipeline profile"); | 122 | check(configured("LEONIDA_PIPELINE_COMPILE", "on-demand"), "first-run UI pipeline profile"); |
| 123 | check(configured("LEONIDA_KEYBOARD_PAD", "1"), "first-run UI keyboard pad reads keys only with focus"); | ||
| 123 | check(configured("LEONIDA_ARENA_MB", "768"), "first-run UI caller override"); | 124 | check(configured("LEONIDA_ARENA_MB", "768"), "first-run UI caller override"); |
| 124 | } | 125 | } |
| 125 | 126 | ||
diff --git a/runtime/test/frame_pacer_test.cpp b/runtime/test/frame_pacer_test.cpp index 7f92d51a7..bb632793b 100644 --- a/runtime/test/frame_pacer_test.cpp +++ b/runtime/test/frame_pacer_test.cpp | |||
| @@ -38,6 +38,23 @@ bool blocked(std::future<Result>& f) { | |||
| 38 | return f.wait_for(std::chrono::milliseconds(40)) == std::future_status::timeout; | 38 | return f.wait_for(std::chrono::milliseconds(40)) == std::future_status::timeout; |
| 39 | } | 39 | } |
| 40 | 40 | ||
| 41 | // True when the wait has returned; otherwise the pacer is suspended, which lets the waiter go, so that a failure ends | ||
| 42 | // the test instead of hanging it on the fake clock. | ||
| 43 | bool finishes(std::future<Result>& f, FramePacer& pacer) { | ||
| 44 | if (f.wait_for(std::chrono::seconds(10)) == std::future_status::ready) return true; | ||
| 45 | pacer.suspend(); | ||
| 46 | return false; | ||
| 47 | } | ||
| 48 | |||
| 49 | // Display time of `token`'s frame, or no_deadline when the pacer has none (not shown, or replaced and never shown). | ||
| 50 | std::uint64_t display_time(FramePacer& pacer, std::uint64_t token) { | ||
| 51 | std::uint32_t count = 1; | ||
| 52 | FrameStatistic stat{}; | ||
| 53 | if (pacer.get_frame_statistics(token, stat_display, &count, &stat) != pacer_hr::ok || count != 1) | ||
| 54 | return no_deadline; | ||
| 55 | return stat.time_us; | ||
| 56 | } | ||
| 57 | |||
| 41 | bool setup(FramePacer& pacer, std::uint32_t latency, std::uint32_t offset = 0) { | 58 | bool setup(FramePacer& pacer, std::uint32_t latency, std::uint32_t offset = 0) { |
| 42 | return pacer.set_frame_interval(period, latency, 0) == pacer_hr::ok && | 59 | return pacer.set_frame_interval(period, latency, 0) == pacer_hr::ok && |
| 43 | pacer.schedule_frame_event(frame_event_origin, offset, 0) == pacer_hr::ok; | 60 | pacer.schedule_frame_event(frame_event_origin, offset, 0) == pacer_hr::ok; |
| @@ -254,6 +271,94 @@ int main() { | |||
| 254 | EXPECT(pacer.frames_in_flight() == 1); | 271 | EXPECT(pacer.frames_in_flight() == 1); |
| 255 | } | 272 | } |
| 256 | 273 | ||
| 274 | // Presents beyond the latency while the event is armed (several presents per wait): at most `latency` frames are | ||
| 275 | // in flight. A present into a full queue replaces the newest queued frame (mailbox) and the older ones keep their | ||
| 276 | // vblanks, so the next wait passes when the oldest is shown, within one period and not 999. Latency 1, 2 and 3. | ||
| 277 | for (std::uint32_t latency = 1; latency <= 3; ++latency) { | ||
| 278 | ManualFrameClock clock; | ||
| 279 | FramePacer pacer(clock); | ||
| 280 | EXPECT(setup(pacer, latency)); | ||
| 281 | clock.advance_us(period); // origin 1 | ||
| 282 | std::uint64_t token = 0; | ||
| 283 | EXPECT(pacer.wait_frame_event(frame_event_origin, 0, 0, &token) == pacer_hr::ok && token == 1); | ||
| 284 | |||
| 285 | // 1000 blank presents with no wait between them: they queue for vblanks 2 .. latency + 1, and no further. | ||
| 286 | for (int i = 0; i < 1000; ++i) pacer.note_untokened_present(); | ||
| 287 | EXPECT(pacer.frames_in_flight() == latency); | ||
| 288 | auto wait = wait_async(pacer, infinite_timeout_ms); | ||
| 289 | EXPECT(blocked(wait)); | ||
| 290 | clock.advance_us(period); // vblank 2 shows the oldest: the wait passes with origin 2, not 999 periods later | ||
| 291 | EXPECT(finishes(wait, pacer)); | ||
| 292 | Result r = wait.get(); | ||
| 293 | EXPECT(r.hr == pacer_hr::ok && r.token == 2); | ||
| 294 | EXPECT(pacer.frames_in_flight() == latency - 1); | ||
| 295 | clock.advance_us(std::uint64_t(period) * (latency - 1)); // vblank latency + 1 shows the newest | ||
| 296 | EXPECT(pacer.frames_in_flight() == 0); | ||
| 297 | |||
| 298 | // Tokened frames: latency + 1 tokens handed out with nothing in flight, then all presented at once. | ||
| 299 | std::uint64_t tokens[4] = {}; | ||
| 300 | for (std::uint32_t i = 0; i <= latency; ++i) { | ||
| 301 | clock.advance_us(period); | ||
| 302 | EXPECT(pacer.wait_frame_event(frame_event_origin, 0, 0, &tokens[i]) == pacer_hr::ok); | ||
| 303 | EXPECT(tokens[i] == 3 + i); | ||
| 304 | } | ||
| 305 | const std::uint64_t now = std::uint64_t(period) * (2 * latency + 2); | ||
| 306 | for (std::uint32_t i = 0; i < latency; ++i) { // `latency` presents fill the queue: nothing is replaced | ||
| 307 | EXPECT(pacer.check_present_token(tokens[i]) == pacer_hr::ok); | ||
| 308 | pacer.commit_present_token(tokens[i], 1); | ||
| 309 | } | ||
| 310 | EXPECT(pacer.frames_in_flight() == latency); | ||
| 311 | pacer.commit_present_token(tokens[latency], 1); // replaces the newest queued frame and takes its vblank | ||
| 312 | EXPECT(pacer.frames_in_flight() == latency); | ||
| 313 | wait = wait_async(pacer, infinite_timeout_ms); | ||
| 314 | EXPECT(blocked(wait)); | ||
| 315 | clock.advance_us(period); | ||
| 316 | EXPECT(finishes(wait, pacer)); | ||
| 317 | r = wait.get(); | ||
| 318 | EXPECT(r.hr == pacer_hr::ok && r.token == latency + 4); | ||
| 319 | clock.advance_us(std::uint64_t(period) * (latency - 1)); | ||
| 320 | EXPECT(pacer.frames_in_flight() == 0); | ||
| 321 | for (std::uint32_t i = 0; i + 1 < latency; ++i) // the older frames keep their vblanks | ||
| 322 | EXPECT(display_time(pacer, tokens[i]) == now + std::uint64_t(period) * (i + 1)); | ||
| 323 | EXPECT(display_time(pacer, tokens[latency - 1]) == no_deadline); // replaced: never shown | ||
| 324 | EXPECT(display_time(pacer, tokens[latency]) == now + std::uint64_t(period) * latency); | ||
| 325 | |||
| 326 | // One present per wait, each a quarter period after its origin: nothing is replaced, each frame is shown at the | ||
| 327 | // vblank after its origin, and that vblank is the next origin. | ||
| 328 | token = r.token; | ||
| 329 | clock.advance_us(period); // back on an origin | ||
| 330 | for (int frame = 0; frame < 8; ++frame) { | ||
| 331 | const std::uint64_t origin = clock.now_us(); | ||
| 332 | std::uint64_t next = 0; | ||
| 333 | EXPECT(pacer.wait_frame_event(frame_event_origin, 0, 0, &next) == pacer_hr::ok && next == token + 1); | ||
| 334 | token = next; | ||
| 335 | clock.advance_us(period / 4); | ||
| 336 | pacer.commit_present_token(token, 1); | ||
| 337 | EXPECT(pacer.frames_in_flight() == 1); | ||
| 338 | clock.advance_us(period - period / 4); | ||
| 339 | EXPECT(pacer.frames_in_flight() == 0); | ||
| 340 | EXPECT(display_time(pacer, token) == origin + period); | ||
| 341 | } | ||
| 342 | } | ||
| 343 | |||
| 344 | // SetFrameIntervalX lowering the latency below the frames already queued: the next present cuts the queue back | ||
| 345 | // to the new latency from the newest end, and the oldest frame keeps its vblank. | ||
| 346 | { | ||
| 347 | ManualFrameClock clock; | ||
| 348 | FramePacer pacer(clock); | ||
| 349 | EXPECT(setup(pacer, 3)); | ||
| 350 | for (int i = 0; i < 3; ++i) pacer.note_untokened_present(); // vblanks 1, 2 and 3 | ||
| 351 | EXPECT(pacer.frames_in_flight() == 3); | ||
| 352 | EXPECT(pacer.set_frame_interval(period, 1, 0) == pacer_hr::ok); | ||
| 353 | EXPECT(pacer.frames_in_flight() == 3); // already queued: left alone until the next present | ||
| 354 | pacer.note_untokened_present(); | ||
| 355 | EXPECT(pacer.frames_in_flight() == 1); | ||
| 356 | clock.advance_us(period - 1); | ||
| 357 | EXPECT(pacer.frames_in_flight() == 1); | ||
| 358 | clock.advance_us(1); // vblank 1, the oldest frame's | ||
| 359 | EXPECT(pacer.frames_in_flight() == 0); | ||
| 360 | } | ||
| 361 | |||
| 257 | // Tokens: only one that was never handed out is refused. Null, stale and repeated ones are accepted and reported | 362 | // Tokens: only one that was never handed out is refused. Null, stale and repeated ones are accepted and reported |
| 258 | // as such, so a title that presents with Token = 0, twice with one token, or out of order does not freeze. | 363 | // as such, so a title that presents with Token = 0, twice with one token, or out of order does not freeze. |
| 259 | { | 364 | { |
| @@ -777,6 +882,44 @@ int main() { | |||
| 777 | EXPECT(uncap.target_interval_us == 0 && near(uncap.drift_us, 0.0) && uncap.p50_us == period); | 882 | EXPECT(uncap.target_interval_us == 0 && near(uncap.drift_us, 0.0) && uncap.p50_us == period); |
| 778 | } | 883 | } |
| 779 | 884 | ||
| 885 | // BL-6 with the bounded queue: the statistics are of PresentX calls, so a frame replaced in a full queue (never | ||
| 886 | // shown) still counts as a present, with its real present-to-present interval; the replacement adds no interval, | ||
| 887 | // removes none, and the frames that are shown keep their vblanks. Latency 1, so every extra present replaces. | ||
| 888 | { | ||
| 889 | auto near = [](double a, double b) { return (a > b ? a - b : b - a) < 1e-6; }; | ||
| 890 | ManualFrameClock clock; | ||
| 891 | FramePacer pacer(clock); | ||
| 892 | EXPECT(setup(pacer, 1)); | ||
| 893 | clock.advance_us(period); // origin 1 | ||
| 894 | std::uint64_t tok1 = 0; | ||
| 895 | EXPECT(pacer.wait_frame_event(frame_event_origin, 0, 0, &tok1) == pacer_hr::ok && tok1 == 1); | ||
| 896 | clock.advance_us(1000); | ||
| 897 | pacer.commit_present_token(tok1, 1); // latency 1000; queued for vblank 2 | ||
| 898 | clock.advance_us(2000); | ||
| 899 | pacer.note_untokened_present(); // interval 2000; replaces tok1 and takes vblank 2 | ||
| 900 | clock.advance_us(4000); | ||
| 901 | pacer.note_untokened_present(); // interval 4000; replaces the blank frame | ||
| 902 | EXPECT(pacer.frames_in_flight() == 1); | ||
| 903 | clock.advance_us(period - 7000); // vblank 2, origin 2 | ||
| 904 | EXPECT(pacer.frames_in_flight() == 0); | ||
| 905 | EXPECT(display_time(pacer, tok1) == no_deadline); // replaced: never shown | ||
| 906 | std::uint64_t tok2 = 0; | ||
| 907 | EXPECT(pacer.wait_frame_event(frame_event_origin, 0, 0, &tok2) == pacer_hr::ok && tok2 == 2); | ||
| 908 | clock.advance_us(8000); | ||
| 909 | pacer.commit_present_token(tok2, 1); // interval period + 1000; latency 8000; vblank 3 | ||
| 910 | clock.advance_us(period - 8000); | ||
| 911 | EXPECT(display_time(pacer, tok2) == 3 * std::uint64_t(period)); | ||
| 912 | |||
| 913 | // 4 presents (2 of them replaced), 3 intervals {2000, 4000, 17000}: nearest-rank p50 4000, p95 and p99 17000. | ||
| 914 | const FramePacingSummary s = pacer.pacing_summary(); | ||
| 915 | EXPECT(s.frames == 4 && s.samples == 3 && s.target_interval_us == period); | ||
| 916 | EXPECT(near(s.mean_us, (2000.0 + 4000.0 + period + 1000.0) / 3.0)); | ||
| 917 | EXPECT(near(s.drift_us, s.mean_us - double(period))); | ||
| 918 | EXPECT(s.p50_us == 4000 && s.p95_us == period + 1000 && s.p99_us == period + 1000); | ||
| 919 | // Origin-to-present latencies of the tokened presents, the replaced tok1 included: {1000, 8000}. | ||
| 920 | EXPECT(s.latency_samples == 2 && s.latency_p50_us == 1000 && s.latency_p99_us == 8000); | ||
| 921 | } | ||
| 922 | |||
| 780 | std::printf("frame_pacer_test: all cases pass\n"); | 923 | std::printf("frame_pacer_test: all cases pass\n"); |
| 781 | return 0; | 924 | return 0; |
| 782 | } | 925 | } |
diff --git a/runtime/test/gameinput_test.cpp b/runtime/test/gameinput_test.cpp index b6658f51c..be9dc5398 100644 --- a/runtime/test/gameinput_test.cpp +++ b/runtime/test/gameinput_test.cpp | |||
| @@ -1742,8 +1742,15 @@ int main(int argc, char** argv) { | |||
| 1742 | Sleep(350); | 1742 | Sleep(350); |
| 1743 | g_focus = true; | 1743 | g_focus = true; |
| 1744 | rt::gameinput::poll(); | 1744 | rt::gameinput::poll(); |
| 1745 | // A scripted press lasts its 300 ms and then until the title has read the pads six times since it began | ||
| 1746 | // (update_keyboard_pad: kReads, at most kMaxHold seconds), so a title that polls slowly still sees it. Each | ||
| 1747 | // pad_state() is one GetCurrentReading, and this is the third since the X began. | ||
| 1748 | check(pad_state(input, nullptr).buttons == (GameInputGamepadX | GameInputGamepadB), | ||
| 1749 | "long script: past its 300 ms the press is still held while the title has read the pads fewer than six times"); | ||
| 1750 | for (int i = 0; i < 6; ++i) pad_state(input, nullptr); | ||
| 1751 | rt::gameinput::poll(); | ||
| 1745 | check(pad_state(input, nullptr).buttons == GameInputGamepadB, | 1752 | check(pad_state(input, nullptr).buttons == GameInputGamepadB, |
| 1746 | "long script: the timed press ends while the physical key stays held"); | 1753 | "long script: the timed press ends once the title has read it, while the physical key stays held"); |
| 1747 | input->Release(); | 1754 | input->Release(); |
| 1748 | std::printf("%d checks, %d failures\n", g_checks, g_failures); | 1755 | std::printf("%d checks, %d failures\n", g_checks, g_failures); |
| 1749 | return g_failures ? 1 : 0; | 1756 | return g_failures ? 1 : 0; |
diff --git a/runtime/test/geometry_views_test.cpp b/runtime/test/geometry_views_test.cpp index 920283f41..caac93dc0 100644 --- a/runtime/test/geometry_views_test.cpp +++ b/runtime/test/geometry_views_test.cpp | |||
| @@ -4,16 +4,31 @@ | |||
| 4 | // 1. a new view is copied whole; | 4 | // 1. a new view is copied whole; |
| 5 | // 2. a write into one tile of a 1 MiB view (16 tiles) copies that tile's 64 KiB again, not the view; | 5 | // 2. a write into one tile of a 1 MiB view (16 tiles) copies that tile's 64 KiB again, not the view; |
| 6 | // 3. a write into a tile two views share is read once and copied into both; | 6 | // 3. a write into a tile two views share is read once and copied into both; |
| 7 | // 4. two written tiles of one view are two tile copies (LEONIDA_GEOMETRY_WHOLE_VIEWS=1, whole views, fails 2-4). | 7 | // 4. two written tiles of one view are two tile copies (LEONIDA_GEOMETRY_WHOLE_VIEWS=1, whole views, fails 2-4); |
| 8 | // 5. a small cap refuses past its budget without re-trying while nothing changed; | ||
| 9 | // 6. retiring a range defers freeing until its GPU ticket completes, then returns budget and lets refused ranges retry; | ||
| 10 | // 7. releasing every view in a sub-4 MiB block via geometry_writes::note_released destroys the block and frees its budget; | ||
| 11 | // 8. note_released ignores ranges outside the watched tile bounds and queues ranges inside them; | ||
| 12 | // 9. overflowing the release queue (65537 disjoint ranges) collapses to one covering range and retires covered views; | ||
| 13 | // 10. reaping the last view in a standard 4 MiB block keeps it as a spare and the next view reuses it; | ||
| 14 | // 11. under a cap, an unfitting 4 MiB spare is destroyed so a larger request can succeed (or fail if still over cap); | ||
| 15 | // 12. one note_released reaches every GeometryViews instance, and a destroyed instance unsubscribes cleanly; | ||
| 16 | // 13. a submission's sequence on an idle GPU (completed == submitted): a view retired by the drain in before_execute_ | ||
| 17 | // (kAfterExecutes) is freed only after every replay begun before the retirement recorded its submissions and those | ||
| 18 | // completed (a ticket read in the drain reaps it at once); its answers made without an alias are invalidated | ||
| 19 | // (forget_copy); its destroyed block leaves the lock-free block list and is reported to the device. | ||
| 8 | #include <windows.h> | 20 | #include <windows.h> |
| 9 | 21 | ||
| 10 | #include <cstdint> | 22 | #include <cstdint> |
| 11 | #include <cstdio> | 23 | #include <cstdio> |
| 12 | #include <cstdlib> | 24 | #include <cstdlib> |
| 13 | #include <cstring> | 25 | #include <cstring> |
| 26 | #include <utility> | ||
| 27 | #include <memory> | ||
| 14 | #include <vector> | 28 | #include <vector> |
| 15 | 29 | ||
| 16 | #include "../shims/d3d12_geometry_views.h" | 30 | #include "../shims/d3d12_geometry_views.h" |
| 31 | #include "../src/title_va_alias.h" | ||
| 17 | 32 | ||
| 18 | namespace { | 33 | namespace { |
| 19 | 34 | ||
| @@ -27,6 +42,10 @@ void check(bool condition, const char* what) { | |||
| 27 | } | 42 | } |
| 28 | 43 | ||
| 29 | // The Vulkan calls TitleBufferWindows::allocate makes, over host memory. | 44 | // The Vulkan calls TitleBufferWindows::allocate makes, over host memory. |
| 45 | int g_live_buffers = 0; | ||
| 46 | int g_gone_blocks = 0; // FakeDevice::title_block_gone calls | ||
| 47 | int g_live_allocs = 0; | ||
| 48 | int g_total_allocs = 0; | ||
| 30 | struct FakeBuffer { | 49 | struct FakeBuffer { |
| 31 | VkDeviceSize size = 0; | 50 | VkDeviceSize size = 0; |
| 32 | void* memory = nullptr; | 51 | void* memory = nullptr; |
| @@ -34,6 +53,7 @@ struct FakeBuffer { | |||
| 34 | VKAPI_ATTR VkResult VKAPI_CALL create_buffer(VkDevice, const VkBufferCreateInfo* info, const VkAllocationCallbacks*, | 53 | VKAPI_ATTR VkResult VKAPI_CALL create_buffer(VkDevice, const VkBufferCreateInfo* info, const VkAllocationCallbacks*, |
| 35 | VkBuffer* out) { | 54 | VkBuffer* out) { |
| 36 | auto* b = new FakeBuffer{info->size}; | 55 | auto* b = new FakeBuffer{info->size}; |
| 56 | ++g_live_buffers; | ||
| 37 | *out = reinterpret_cast<VkBuffer>(b); | 57 | *out = reinterpret_cast<VkBuffer>(b); |
| 38 | return VK_SUCCESS; | 58 | return VK_SUCCESS; |
| 39 | } | 59 | } |
| @@ -57,9 +77,11 @@ VKAPI_ATTR VkDeviceAddress VKAPI_CALL address(VkDevice, const VkBufferDeviceAddr | |||
| 57 | return VkDeviceAddress(reinterpret_cast<std::uintptr_t>(reinterpret_cast<FakeBuffer*>(info->buffer)->memory)); | 77 | return VkDeviceAddress(reinterpret_cast<std::uintptr_t>(reinterpret_cast<FakeBuffer*>(info->buffer)->memory)); |
| 58 | } | 78 | } |
| 59 | VKAPI_ATTR void VKAPI_CALL destroy_buffer(VkDevice, VkBuffer buffer, const VkAllocationCallbacks*) { | 79 | VKAPI_ATTR void VKAPI_CALL destroy_buffer(VkDevice, VkBuffer buffer, const VkAllocationCallbacks*) { |
| 80 | --g_live_buffers; | ||
| 60 | delete reinterpret_cast<FakeBuffer*>(buffer); | 81 | delete reinterpret_cast<FakeBuffer*>(buffer); |
| 61 | } | 82 | } |
| 62 | VKAPI_ATTR void VKAPI_CALL free_memory(VkDevice, VkDeviceMemory memory, const VkAllocationCallbacks*) { | 83 | VKAPI_ATTR void VKAPI_CALL free_memory(VkDevice, VkDeviceMemory memory, const VkAllocationCallbacks*) { |
| 84 | --g_live_allocs; | ||
| 63 | VirtualFree(memory, 0, MEM_RELEASE); | 85 | VirtualFree(memory, 0, MEM_RELEASE); |
| 64 | } | 86 | } |
| 65 | 87 | ||
| @@ -85,10 +107,16 @@ struct FakeDevice { | |||
| 85 | VkDeviceAddress address = 0; | 107 | VkDeviceAddress address = 0; |
| 86 | } arena; | 108 | } arena; |
| 87 | void share(VkBufferCreateInfo&) {} | 109 | void share(VkBufferCreateInfo&) {} |
| 110 | void title_block_gone(VkDeviceAddress, VkDeviceSize) { ++g_gone_blocks; } | ||
| 88 | VkDeviceMemory allocate(const VkMemoryRequirements& r, VkMemoryPropertyFlags required, | 111 | VkDeviceMemory allocate(const VkMemoryRequirements& r, VkMemoryPropertyFlags required, |
| 89 | VkMemoryPropertyFlags preferred, VkMemoryPropertyFlags* chosen, bool) { | 112 | VkMemoryPropertyFlags preferred, VkMemoryPropertyFlags* chosen, bool) { |
| 90 | if (chosen) *chosen = required | preferred; | 113 | if (chosen) *chosen = required | preferred; |
| 91 | return reinterpret_cast<VkDeviceMemory>(VirtualAlloc(nullptr, r.size, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE)); | 114 | void* mem = VirtualAlloc(nullptr, r.size, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); |
| 115 | if (mem) { | ||
| 116 | ++g_live_allocs; | ||
| 117 | ++g_total_allocs; | ||
| 118 | } | ||
| 119 | return reinterpret_cast<VkDeviceMemory>(mem); | ||
| 92 | } | 120 | } |
| 93 | }; | 121 | }; |
| 94 | 122 | ||
| @@ -118,7 +146,8 @@ int main() { | |||
| 118 | const auto base = reinterpret_cast<std::uintptr_t>(title); | 146 | const auto base = reinterpret_cast<std::uintptr_t>(title); |
| 119 | 147 | ||
| 120 | FakeDevice device; | 148 | FakeDevice device; |
| 121 | rt::d3d12::GeometryViews views; | 149 | const auto views_owner = std::make_unique<rt::d3d12::GeometryViews>(); |
| 150 | auto& views = *views_owner; | ||
| 122 | g_copies.clear(); | 151 | g_copies.clear(); |
| 123 | const std::uint64_t va = views.resolve(device, base, kView, copy); | 152 | const std::uint64_t va = views.resolve(device, base, kView, copy); |
| 124 | check(va != 0 && g_copies.size() == 1 && g_copies[0] == kView, "a new 1 MiB view is copied whole"); | 153 | check(va != 0 && g_copies.size() == 1 && g_copies[0] == kView, "a new 1 MiB view is copied whole"); |
| @@ -161,6 +190,326 @@ int main() { | |||
| 161 | check(!std::memcmp(copy_bytes, title, kView), "the copy matches the title's pages"); | 190 | check(!std::memcmp(copy_bytes, title, kView), "the copy matches the title's pages"); |
| 162 | 191 | ||
| 163 | views.release(device); | 192 | views.release(device); |
| 193 | VirtualFree(title, 0, MEM_RELEASE); | ||
| 194 | |||
| 195 | // 5-7. Small cap (2 MiB): fill, cap refusal (cached while nothing freed), deferred retirement for in-flight GPU | ||
| 196 | // work, retry after reap, and full block reclamation via geometry_writes::note_released. | ||
| 197 | auto* small_title = | ||
| 198 | static_cast<std::uint8_t*>(VirtualAlloc(nullptr, 3 * kView, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE)); | ||
| 199 | if (!small_title) return 1; | ||
| 200 | for (std::size_t i = 0; i < 3 * kView; ++i) small_title[i] = std::uint8_t((i * 13) ^ 0x5a); | ||
| 201 | const auto sbase = reinterpret_cast<std::uintptr_t>(small_title); | ||
| 202 | const auto range_a = sbase; | ||
| 203 | const auto range_b = sbase + kView; | ||
| 204 | const auto range_c = sbase + 2 * kView; | ||
| 205 | |||
| 206 | const auto capped_owner = std::make_unique<rt::d3d12::GeometryViews>(2 * kView); | ||
| 207 | |||
| 208 | auto& capped = *capped_owner; | ||
| 209 | const std::uint64_t va_a = capped.resolve(device, range_a, kView, copy); | ||
| 210 | const std::uint64_t va_b = capped.resolve(device, range_b, kView, copy); | ||
| 211 | check(va_a != 0 && va_b != 0 && capped.bytes() == 2 * kView && capped.reserved() == 2 * kView && | ||
| 212 | capped.live_views() == 2, | ||
| 213 | "small cap fills to its 2 MiB budget"); | ||
| 214 | |||
| 215 | // 5. Third 1 MiB view is refused; a repeat resolve without freeing short-circuits without re-counting a refusal. | ||
| 216 | const std::uint64_t va_c1 = capped.resolve(device, range_c, kView, copy); | ||
| 217 | check(va_c1 == 0 && capped.cap_refusals() == 1, "view past the 2 MiB cap is refused"); | ||
| 218 | const std::uint64_t va_c2 = capped.resolve(device, range_c, kView, copy); | ||
| 219 | check(va_c2 == 0 && capped.cap_refusals() == 1, | ||
| 220 | "repeated resolve of a refused range short-circuits while nothing has been freed"); | ||
| 221 | |||
| 222 | // 6. Retire A while GPU ticket 5 is still in flight: A disappears from lookup/find immediately, but its storage | ||
| 223 | // and budget are held until completed_ticket reaches 5. | ||
| 224 | std::uint64_t alias_removed_source = 0; | ||
| 225 | VkDeviceSize alias_removed_va = 0; | ||
| 226 | const std::size_t retired_a = capped.retire_range( | ||
| 227 | range_a, range_a + kView, 5, [&](std::uintptr_t src, std::size_t, VkDeviceSize v) { | ||
| 228 | alias_removed_source = src; | ||
| 229 | alias_removed_va = v; | ||
| 230 | }); | ||
| 231 | check(retired_a == 1 && alias_removed_source == range_a && alias_removed_va == va_a, | ||
| 232 | "retiring A's range reports A's view and invokes the alias-removal callback"); | ||
| 233 | std::uint64_t lookup_host = 0, lookup_bytes = 0; | ||
| 234 | check(capped.find(range_a, kView) == 0 && !capped.lookup(device.arena.address + va_a, lookup_host, lookup_bytes) && | ||
| 235 | capped.live_views() == 1 && capped.retired_count() == 1, | ||
| 236 | "retired view is immediately unlinked from find and lookup"); | ||
| 237 | |||
| 238 | check(capped.reap(device, 4) == 0 && capped.retired_count() == 1 && capped.bytes() == 2 * kView && | ||
| 239 | capped.free_generation() == 0 && g_live_buffers == 1 && g_live_allocs == 1, | ||
| 240 | "reap before GPU ticket completes does not free an in-use view"); | ||
| 241 | check(capped.resolve(device, range_c, kView, copy) == 0 && capped.cap_refusals() == 1, | ||
| 242 | "refused range stays refused while retired view is still in flight"); | ||
| 243 | |||
| 244 | // GPU completes ticket 5: A's sub-range is reclaimed and free_generation bumps, letting C retry and succeed. | ||
| 245 | check(capped.reap(device, 5) == 1 && capped.retired_count() == 0 && capped.bytes() == kView && | ||
| 246 | capped.free_generation() == 1 && capped.block_count() == 1, | ||
| 247 | "reap at GPU ticket 5 reclaims A's budget while keeping B's block live"); | ||
| 248 | const std::uint64_t va_c3 = capped.resolve(device, range_c, kView, copy); | ||
| 249 | check(va_c3 != 0 && capped.bytes() == 2 * kView && capped.live_views() == 2, | ||
| 250 | "previously refused range retries and succeeds after budget is freed"); | ||
| 251 | check(capped.lookup(device.arena.address + va_c3, lookup_host, lookup_bytes) && lookup_bytes == kView && | ||
| 252 | !std::memcmp(reinterpret_cast<const void*>(lookup_host), small_title + 2 * kView, kView), | ||
| 253 | "retried view holds C's title bytes"); | ||
| 254 | |||
| 255 | // 7. Release B and C via the xmem notification bridge (geometry_writes::note_released + drain_released): | ||
| 256 | // once their GPU ticket completes, the block becomes empty and its Vulkan buffer and memory are destroyed. | ||
| 257 | leonida::geometry_writes::note_released(range_b, range_c + kView); | ||
| 258 | check(capped.has_released(), "note_released queues released title ranges"); | ||
| 259 | capped.drain_released(device, 6, 5); | ||
| 260 | check(!capped.has_released() && capped.live_views() == 0 && capped.retired_count() == 2 && | ||
| 261 | g_live_buffers == 1 && g_live_allocs == 1, | ||
| 262 | "drain_released retires B and C at ticket 6 and defers freeing while completed ticket is 5"); | ||
| 263 | check(capped.reap(device, 6) == 2 && capped.retired_count() == 0 && capped.bytes() == 0 && | ||
| 264 | capped.reserved() == 0 && capped.block_count() == 0 && g_live_buffers == 0 && g_live_allocs == 0, | ||
| 265 | "reaping the last views in a block destroys its Vulkan buffer and returns all reserved budget"); | ||
| 266 | |||
| 267 | // A fresh 2 MiB view now fits in the fully reclaimed cap. | ||
| 268 | const std::uint64_t va_full = capped.resolve(device, range_a, 2 * kView, copy); | ||
| 269 | check(va_full != 0 && capped.bytes() == 2 * kView && capped.reserved() == 2 * kView && capped.live_views() == 1, | ||
| 270 | "a fresh 2 MiB view succeeds after full reclamation"); | ||
| 271 | |||
| 272 | capped.release(device); | ||
| 273 | check(g_live_buffers == 0 && g_live_allocs == 0, "teardown frees all remaining Vulkan buffers and memory"); | ||
| 274 | VirtualFree(small_title, 0, MEM_RELEASE); | ||
| 275 | |||
| 276 | // 8-11. Watched-bounds filtering, release-queue overflow collapse, 4 MiB spare block reuse and cap eviction. | ||
| 277 | auto* pool_title = | ||
| 278 | static_cast<std::uint8_t*>(VirtualAlloc(nullptr, 6 * kView, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE)); | ||
| 279 | if (!pool_title) return 1; | ||
| 280 | for (std::size_t i = 0; i < 6 * kView; ++i) pool_title[i] = std::uint8_t((i * 17) ^ 0x3c); | ||
| 281 | const auto pbase = reinterpret_cast<std::uintptr_t>(pool_title); | ||
| 282 | |||
| 283 | // 8. note_released outside [watched_lo, watched_hi) is ignored; inside is queued. | ||
| 284 | const auto watched_owner = std::make_unique<rt::d3d12::GeometryViews>(6 * kView); | ||
| 285 | auto& watched = *watched_owner; | ||
| 286 | const std::uint64_t va_w1 = watched.resolve(device, pbase, kView, copy); | ||
| 287 | const std::uint64_t va_w2 = watched.resolve(device, pbase + kView, kView, copy); | ||
| 288 | check(va_w1 != 0 && va_w2 != 0 && watched.live_views() == 2 && watched.block_count() == 1 && | ||
| 289 | watched.empty_blocks() == 0, | ||
| 290 | "two 1 MiB views share one 4 MiB block"); | ||
| 291 | const auto watched_lo = leonida::geometry_writes::state().watched_lo.load(std::memory_order_acquire); | ||
| 292 | const auto watched_hi = leonida::geometry_writes::state().watched_hi.load(std::memory_order_acquire); | ||
| 293 | check(watched_lo <= pbase && watched_hi >= pbase + 2 * kView, "watched bounds cover resolved views"); | ||
| 294 | leonida::geometry_writes::note_released(watched_lo - 4096, watched_lo); | ||
| 295 | leonida::geometry_writes::note_released(watched_hi, watched_hi + 4096); | ||
| 296 | check(!watched.has_released(), "note_released outside watched bounds is not queued"); | ||
| 297 | leonida::geometry_writes::note_released(pbase, pbase + 4096); | ||
| 298 | check(watched.has_released(), "note_released inside watched bounds is queued"); | ||
| 299 | std::vector<std::pair<std::uintptr_t, std::uintptr_t>> drained; | ||
| 300 | leonida::geometry_writes::take_released(watched.release_queue(), drained); | ||
| 301 | check(drained.size() == 1 && drained[0].first == pbase && drained[0].second == pbase + 4096 && | ||
| 302 | !watched.has_released(), | ||
| 303 | "take_released returns the queued in-bounds range"); | ||
| 304 | // A GPU-only twin freed by its own address lies outside the watched (CPU) bounds but still counts: its CPU view | ||
| 305 | // holds the views. Only the address arithmetic of the pair is used; nothing is mapped at the GPU address. | ||
| 306 | const std::uintptr_t gpu_twin = std::uintptr_t(0x600000000000ull); | ||
| 307 | leonida::title_gpu_views::note_reservation(pbase, 2 * kView, false); | ||
| 308 | check(leonida::title_gpu_views::note_reservation(gpu_twin, 2 * kView, true), "the GPU-only twin pairs"); | ||
| 309 | leonida::geometry_writes::note_released(gpu_twin + 2 * kView, gpu_twin + 2 * kView + 4096); | ||
| 310 | check(!watched.has_released(), "a range past the twin is not queued"); | ||
| 311 | leonida::geometry_writes::note_released(gpu_twin + kView, gpu_twin + kView + 4096); | ||
| 312 | check(watched.has_released(), "a range of the GPU-only twin over a watched view is queued"); | ||
| 313 | watched.drain_released(device, 3, 0); | ||
| 314 | check(watched.live_views() == 1 && watched.retired_count() == 1 && watched.find(pbase + kView, kView) == 0 && | ||
| 315 | watched.find(pbase, kView) == va_w1, | ||
| 316 | "draining the twin's range retires the view at its CPU address only"); | ||
| 317 | const std::uint64_t va_w2b = watched.resolve(device, pbase + kView, kView, copy); | ||
| 318 | check(va_w2b != 0, "the retired view is made again on the next resolve"); | ||
| 319 | |||
| 320 | // 9. Queue overflow: 65537 disjoint ranges collapse into one covering range; drain retires every covered view. | ||
| 321 | constexpr std::size_t kOverflowCount = 65537; | ||
| 322 | for (std::size_t i = 0; i < kOverflowCount; ++i) | ||
| 323 | leonida::geometry_writes::note_released(pbase + i * 16, pbase + i * 16 + 8); | ||
| 324 | leonida::geometry_writes::take_released(watched.release_queue(), drained); | ||
| 325 | check(drained.size() == 1 && drained[0].first == pbase && | ||
| 326 | drained[0].second == pbase + (kOverflowCount - 1) * 16 + 8 && !watched.has_released(), | ||
| 327 | "65537 disjoint ranges collapse into a single covering range"); | ||
| 328 | for (std::size_t i = 0; i < kOverflowCount; ++i) | ||
| 329 | leonida::geometry_writes::note_released(pbase + i * 16, pbase + i * 16 + 8); | ||
| 330 | watched.drain_released(device, 10, 9); | ||
| 331 | check(!watched.has_released() && watched.live_views() == 0 && watched.retired_count() == 2, | ||
| 332 | "drain_released after overflow retires every view inside the collapsed range"); | ||
| 333 | watched.release(device); | ||
| 334 | check(g_live_buffers == 0 && g_live_allocs == 0, "watched teardown frees its block"); | ||
| 335 | |||
| 336 | // 10. Spare 4 MiB block: retiring and reaping the sole view keeps the block empty and the next view reuses it. | ||
| 337 | const auto spare_owner = std::make_unique<rt::d3d12::GeometryViews>(6 * kView); | ||
| 338 | auto& spare = *spare_owner; | ||
| 339 | const std::uint64_t va_s1 = spare.resolve(device, pbase, kView, copy); | ||
| 340 | const int allocs_after_first = g_total_allocs; | ||
| 341 | check(va_s1 != 0 && spare.block_count() == 1 && spare.empty_blocks() == 0 && spare.reserved() == 4 * kView && | ||
| 342 | g_live_buffers == 1 && g_live_allocs == 1, | ||
| 343 | "first view under a 6 MiB cap allocates one standard 4 MiB block"); | ||
| 344 | check(spare.retire_range(pbase + kView - 16, pbase + kView, 1) == 1 && spare.reap(device, 1) == 1, | ||
| 345 | "retiring a tail subrange and reaping frees the view"); | ||
| 346 | check(spare.live_views() == 0 && spare.block_count() == 1 && spare.empty_blocks() == 1 && | ||
| 347 | spare.reserved() == 4 * kView && g_live_buffers == 1 && g_live_allocs == 1, | ||
| 348 | "reaping the last view keeps the empty 4 MiB block as a spare"); | ||
| 349 | const std::uint64_t va_s2 = spare.resolve(device, pbase + kView, kView, copy); | ||
| 350 | check(va_s2 != 0 && spare.block_count() == 1 && spare.empty_blocks() == 0 && g_live_buffers == 1 && | ||
| 351 | g_live_allocs == 1 && g_total_allocs == allocs_after_first, | ||
| 352 | "a new view reuses the spare 4 MiB block with no new allocation"); | ||
| 353 | |||
| 354 | // 11. Spare given up under the cap: destroy the unfitting 4 MiB spare so a larger request succeeds, and still | ||
| 355 | // refuse a request that remains over the cap after the spare is destroyed. | ||
| 356 | check(spare.retire_range(pbase + kView, pbase + 2 * kView, 2) == 1 && spare.reap(device, 2) == 1 && | ||
| 357 | spare.block_count() == 1 && spare.empty_blocks() == 1 && spare.reserved() == 4 * kView, | ||
| 358 | "reaping the reused view returns the 4 MiB block to spare"); | ||
| 359 | const std::uint64_t va_big = spare.resolve(device, pbase, 5 * kView, copy); | ||
| 360 | check(va_big != 0 && spare.block_count() == 1 && spare.empty_blocks() == 0 && spare.reserved() == 5 * kView && | ||
| 361 | g_live_buffers == 1 && g_live_allocs == 1, | ||
| 362 | "a 5 MiB request under a 6 MiB cap destroys the 4 MiB spare and succeeds"); | ||
| 363 | spare.release(device); | ||
| 364 | check(g_live_buffers == 0 && g_live_allocs == 0, "spare teardown frees its block"); | ||
| 365 | |||
| 366 | const auto tight_owner = std::make_unique<rt::d3d12::GeometryViews>(9 * kView); | ||
| 367 | |||
| 368 | auto& tight = *tight_owner; | ||
| 369 | const std::uint64_t va_t1 = tight.resolve(device, pbase, 3 * kView, copy); | ||
| 370 | const std::uint64_t va_t2 = tight.resolve(device, pbase + 3 * kView, 2 * kView, copy); | ||
| 371 | check(va_t1 != 0 && va_t2 != 0 && tight.block_count() == 2 && tight.reserved() == 8 * kView, | ||
| 372 | "two views that do not share one 4 MiB block reserve 8 MiB"); | ||
| 373 | check(tight.retire_range(pbase + 3 * kView, pbase + 5 * kView, 1) == 1 && tight.reap(device, 1) == 1 && | ||
| 374 | tight.block_count() == 2 && tight.empty_blocks() == 1 && tight.reserved() == 8 * kView, | ||
| 375 | "reaping the second block leaves one 4 MiB spare alongside one live 4 MiB block"); | ||
| 376 | const std::uint64_t va_over = tight.resolve(device, pbase, 6 * kView, copy); | ||
| 377 | check(va_over == 0 && tight.cap_refusals() == 1 && tight.block_count() == 1 && tight.empty_blocks() == 0 && | ||
| 378 | tight.reserved() == 4 * kView && g_live_buffers == 1 && g_live_allocs == 1, | ||
| 379 | "a 6 MiB request drops the 4 MiB spare and is refused because only 5 MiB of cap remain"); | ||
| 380 | const std::uint64_t va_fit = tight.resolve(device, pbase, 5 * kView, copy); | ||
| 381 | check(va_fit != 0 && tight.block_count() == 2 && tight.reserved() == 9 * kView && g_live_buffers == 2 && | ||
| 382 | g_live_allocs == 2, | ||
| 383 | "a 5 MiB request succeeds in the cap freed by dropping the spare"); | ||
| 384 | tight.release(device); | ||
| 385 | check(g_live_buffers == 0 && g_live_allocs == 0, "tight cap teardown frees all blocks"); | ||
| 386 | |||
| 387 | VirtualFree(pool_title, 0, MEM_RELEASE); | ||
| 388 | |||
| 389 | // 12. Two GeometryViews instances over the same title extent both receive one note_released; a destroyed instance | ||
| 390 | // unsubscribes so later releases do not touch it and surviving instances still receive them. | ||
| 391 | auto* shared_title = | ||
| 392 | static_cast<std::uint8_t*>(VirtualAlloc(nullptr, 2 * kView, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE)); | ||
| 393 | if (!shared_title) return 1; | ||
| 394 | for (std::size_t i = 0; i < 2 * kView; ++i) shared_title[i] = std::uint8_t((i * 29) ^ 0xa5); | ||
| 395 | const auto shbase = reinterpret_cast<std::uintptr_t>(shared_title); | ||
| 396 | |||
| 397 | { | ||
| 398 | const auto dev_a_owner = std::make_unique<rt::d3d12::GeometryViews>(2 * kView); | ||
| 399 | auto& dev_a = *dev_a_owner; | ||
| 400 | const auto dev_b_owner = std::make_unique<rt::d3d12::GeometryViews>(2 * kView); | ||
| 401 | auto& dev_b = *dev_b_owner; | ||
| 402 | const std::uint64_t va_a1 = dev_a.resolve(device, shbase, kView, copy); | ||
| 403 | const std::uint64_t va_b1 = dev_b.resolve(device, shbase, kView, copy); | ||
| 404 | check(va_a1 != 0 && va_b1 != 0 && dev_a.live_views() == 1 && dev_b.live_views() == 1 && | ||
| 405 | dev_a.bytes() == kView && dev_b.bytes() == kView, | ||
| 406 | "two GeometryViews instances resolve the same title range"); | ||
| 407 | |||
| 408 | leonida::geometry_writes::note_released(shbase, shbase + kView); | ||
| 409 | check(dev_a.has_released() && dev_b.has_released(), | ||
| 410 | "one note_released queues the range in both instances"); | ||
| 411 | |||
| 412 | dev_a.drain_released(device, 1, 1); | ||
| 413 | check(!dev_a.has_released() && dev_a.live_views() == 0 && dev_a.retired_count() == 0 && dev_a.bytes() == 0 && | ||
| 414 | dev_b.has_released() && dev_b.live_views() == 1 && dev_b.bytes() == kView, | ||
| 415 | "draining the first instance retires and reaps its view without emptying the second instance's queue"); | ||
| 416 | |||
| 417 | dev_b.drain_released(device, 1, 1); | ||
| 418 | check(!dev_b.has_released() && dev_b.live_views() == 0 && dev_b.retired_count() == 0 && dev_b.bytes() == 0, | ||
| 419 | "draining the second instance also retires and reaps its view"); | ||
| 420 | |||
| 421 | const std::uint64_t va_keep = dev_a.resolve(device, shbase + kView, kView, copy); | ||
| 422 | check(va_keep != 0 && dev_a.live_views() == 1 && dev_a.bytes() == kView, | ||
| 423 | "surviving instance resolves a second range"); | ||
| 424 | { | ||
| 425 | const auto ephemeral_owner = std::make_unique<rt::d3d12::GeometryViews>(2 * kView); | ||
| 426 | auto& ephemeral = *ephemeral_owner; | ||
| 427 | const std::uint64_t va_eph = ephemeral.resolve(device, shbase + kView, kView, copy); | ||
| 428 | check(va_eph != 0 && ephemeral.live_views() == 1, "scoped instance resolves the same range"); | ||
| 429 | ephemeral.release(device); | ||
| 430 | } | ||
| 431 | leonida::geometry_writes::note_released(shbase + kView, shbase + 2 * kView); | ||
| 432 | check(dev_a.has_released(), "note_released after another instance is destroyed reaches the surviving instance"); | ||
| 433 | dev_a.drain_released(device, 2, 2); | ||
| 434 | check(!dev_a.has_released() && dev_a.live_views() == 0 && dev_a.retired_count() == 0 && dev_a.bytes() == 0, | ||
| 435 | "surviving instance retires and reaps after the destroyed instance unsubscribed"); | ||
| 436 | |||
| 437 | dev_a.release(device); | ||
| 438 | dev_b.release(device); | ||
| 439 | } | ||
| 440 | check(g_live_buffers == 0 && g_live_allocs == 0, "multi-instance teardown frees all blocks"); | ||
| 441 | VirtualFree(shared_title, 0, MEM_RELEASE); | ||
| 442 | |||
| 443 | // 13. DeviceState's order for one submission: execute_begin, drain_geometry_releases (kAfterExecutes) and the | ||
| 444 | // console heaps in before_execute_, the replay records its submission, execute_end. Another queue's replay began | ||
| 445 | // before the release (its heap slots may already name the view); one more begins after the retirement. | ||
| 446 | auto* fly_title = static_cast<std::uint8_t*>(VirtualAlloc(nullptr, kView, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE)); | ||
| 447 | if (!fly_title) return 1; | ||
| 448 | for (std::size_t i = 0; i < kView; ++i) fly_title[i] = std::uint8_t(i * 13 + 1); | ||
| 449 | const auto flybase = reinterpret_cast<std::uintptr_t>(fly_title); | ||
| 450 | { | ||
| 451 | const auto fly_owner = std::make_unique<rt::d3d12::GeometryViews>(2 * kView); | ||
| 452 | auto& fly = *fly_owner; | ||
| 453 | const auto named_blocks = [&] { | ||
| 454 | std::size_t n = 0; | ||
| 455 | fly.pool().for_each_block([&](VkDeviceAddress address, VkDeviceSize) { n += address != 0; }); | ||
| 456 | return n; | ||
| 457 | }; | ||
| 458 | const std::uint64_t va_f = fly.resolve(device, flybase, kView, copy); | ||
| 459 | check(va_f != 0 && fly.live_views() == 1 && named_blocks() == 1, "a view in its own block, published"); | ||
| 460 | const std::uint64_t layout = fly.pool().layout_generation(); | ||
| 461 | const int gone = g_gone_blocks; | ||
| 462 | |||
| 463 | std::uint64_t submitted = 7; // completed == submitted below: the GPU is idle | ||
| 464 | const std::uint64_t other = fly.execute_begin(); | ||
| 465 | const std::uint64_t own = fly.execute_begin(); | ||
| 466 | leonida::TitleVaAliases aliases; | ||
| 467 | aliases.record_removals(true); | ||
| 468 | std::uint64_t cursor = 0; | ||
| 469 | { | ||
| 470 | leonida::DescriptorRanges skip; | ||
| 471 | aliases.changed_ranges(cursor, skip); | ||
| 472 | } | ||
| 473 | const std::uint64_t invalidations = aliases.invalidations(); | ||
| 474 | leonida::geometry_writes::note_released(flybase, flybase + kView); | ||
| 475 | fly.drain_released(device, rt::d3d12::GeometryViews::kAfterExecutes, submitted, | ||
| 476 | [&](std::uintptr_t source, std::size_t size, VkDeviceSize va) { | ||
| 477 | aliases.forget_copy(source, size, va); | ||
| 478 | }); | ||
| 479 | check(fly.live_views() == 0 && fly.find(flybase, kView) == 0 && fly.retired_count() == 1 && | ||
| 480 | fly.bytes() == kView && g_gone_blocks == gone, | ||
| 481 | "a view retired in before_execute_ is not reaped there, though the GPU is idle"); | ||
| 482 | |||
| 483 | leonida::DescriptorRanges changed; | ||
| 484 | const bool read = aliases.changed_ranges(cursor, changed); | ||
| 485 | changed.merge(); | ||
| 486 | std::vector<std::pair<std::uint64_t, std::uint64_t>> removed; | ||
| 487 | aliases.take_removed(removed); | ||
| 488 | check(read && aliases.invalidations() != invalidations && changed.overlaps(flybase, kView) && | ||
| 489 | removed.size() == 1 && removed[0].first == va_f && removed[0].second == kView, | ||
| 490 | "the retirement invalidates the heap slots and key answers made through the view without an alias"); | ||
| 491 | |||
| 492 | submitted = 8; // this replay's submission | ||
| 493 | fly.execute_end(own, [&] { return submitted; }); | ||
| 494 | check(fly.reap(device, 8) == 0 && fly.retired_count() == 1 && fly.bytes() == kView, | ||
| 495 | "not freed while a replay begun before the retirement is still in progress"); | ||
| 496 | |||
| 497 | const std::uint64_t later = fly.execute_begin(); | ||
| 498 | submitted = 9; // the other queue's submission | ||
| 499 | fly.execute_end(other, [&] { return submitted; }); | ||
| 500 | check(fly.reap(device, 8) == 0 && fly.retired_count() == 1, | ||
| 501 | "once those replays recorded theirs, the view waits for the last of their tickets"); | ||
| 502 | check(fly.reap(device, 9) == 1 && fly.retired_count() == 0 && fly.bytes() == 0, | ||
| 503 | "freed once that ticket completed; a replay begun after the retirement does not hold it"); | ||
| 504 | fly.execute_end(later, [&] { return submitted; }); | ||
| 505 | |||
| 506 | check(named_blocks() == 0 && fly.pool().layout_generation() != layout && g_gone_blocks == gone + 1 && | ||
| 507 | g_live_buffers == 0, | ||
| 508 | "the destroyed block leaves the lock-free block list and the device is told"); | ||
| 509 | fly.release(device); | ||
| 510 | } | ||
| 511 | VirtualFree(fly_title, 0, MEM_RELEASE); | ||
| 512 | |||
| 164 | std::printf("%d checks, %d failures\n", g_checks, g_failures); | 513 | std::printf("%d checks, %d failures\n", g_checks, g_failures); |
| 165 | return g_failures ? 1 : 0; | 514 | return g_failures ? 1 : 0; |
| 166 | } | 515 | } |
diff --git a/runtime/test/gfx10_descriptors_test.cpp b/runtime/test/gfx10_descriptors_test.cpp index efd0ce4ee..f30d7f026 100644 --- a/runtime/test/gfx10_descriptors_test.cpp +++ b/runtime/test/gfx10_descriptors_test.cpp | |||
| @@ -114,6 +114,25 @@ int main() { | |||
| 114 | CHECK(is_image(words) && decode(words, out) && out == in); | 114 | CHECK(is_image(words) && decode(words, out) && out == in); |
| 115 | } | 115 | } |
| 116 | 116 | ||
| 117 | ImageWords volume_words = encode(Image{.type = ImageType::image_3d, .depth = 16, | ||
| 118 | .first_mip = 1, .mip_count = 2, .resource_mips = 4}); | ||
| 119 | volume_words[4] |= 37u << 16; | ||
| 120 | CHECK(decode(volume_words, image) && image.first_layer == 37 && image.depth == 16); | ||
| 121 | CHECK(!has_hardware_volume_uav_slice_offset(volume_words, image)); | ||
| 122 | const auto volume_range = vulkan_subresource_range(image, VK_IMAGE_ASPECT_COLOR_BIT); | ||
| 123 | CHECK(volume_range.aspectMask == VK_IMAGE_ASPECT_COLOR_BIT); | ||
| 124 | CHECK(volume_range.baseMipLevel == 1 && volume_range.levelCount == 2); | ||
| 125 | CHECK(volume_range.baseArrayLayer == 0 && volume_range.layerCount == 1); | ||
| 126 | volume_words = encode(Image{.type = ImageType::image_3d, .depth = 7, .first_mip = 1, .resource_mips = 4}); | ||
| 127 | volume_words[4] |= 2u << 16; | ||
| 128 | volume_words[5] |= 1u; | ||
| 129 | CHECK(decode(volume_words, image) && has_hardware_volume_uav_slice_offset(volume_words, image)); | ||
| 130 | volume_words[4] &= 0xffffu; | ||
| 131 | CHECK(decode(volume_words, image) && !has_hardware_volume_uav_slice_offset(volume_words, image)); | ||
| 132 | |||
| 133 | const auto array_range = vulkan_subresource_range(images[2], VK_IMAGE_ASPECT_COLOR_BIT); | ||
| 134 | CHECK(array_range.baseArrayLayer == 3 && array_range.layerCount == 7); | ||
| 135 | |||
| 117 | // Bits this header does not encode are ignored: SW_MODE and BC_SWIZZLE (word 3), PITCH_MSB (word 4), PERF_MOD | 136 | // Bits this header does not encode are ignored: SW_MODE and BC_SWIZZLE (word 3), PITCH_MSB (word 4), PERF_MOD |
| 118 | // and the rest of word 5, the compression and metadata fields of words 6 and 7, RESOURCE_LEVEL (word 2 bit 31). | 137 | // and the rest of word 5, the compression and metadata fields of words 6 and 7, RESOURCE_LEVEL (word 2 bit 31). |
| 119 | ImageWords busy = encode(images[3]); | 138 | ImageWords busy = encode(images[3]); |
diff --git a/runtime/test/glsl/cs_indirect_dispatch_count.comp b/runtime/test/glsl/cs_indirect_dispatch_count.comp index 05bc68517..e08053790 100644 --- a/runtime/test/glsl/cs_indirect_dispatch_count.comp +++ b/runtime/test/glsl/cs_indirect_dispatch_count.comp | |||
| @@ -3,6 +3,9 @@ | |||
| 3 | // which start at s4), plus the 144-byte user-data contract. | 3 | // which start at s4), plus the 144-byte user-data contract. |
| 4 | #extension GL_EXT_buffer_reference : require | 4 | #extension GL_EXT_buffer_reference : require |
| 5 | #extension GL_EXT_buffer_reference_uvec2 : require | 5 | #extension GL_EXT_buffer_reference_uvec2 : require |
| 6 | #ifndef TEST_COUNTER_TERM | ||
| 7 | #define TEST_COUNTER_TERM 1u | ||
| 8 | #endif | ||
| 6 | layout(local_size_x = 1) in; | 9 | layout(local_size_x = 1) in; |
| 7 | layout(buffer_reference, std430, buffer_reference_align = 4) buffer Words { uint w[]; }; | 10 | layout(buffer_reference, std430, buffer_reference_align = 4) buffer Words { uint w[]; }; |
| 8 | layout(push_constant) uniform UserData { uint s[32]; uvec2 heap_base; uvec2 code_base; } pc; | 11 | layout(push_constant) uniform UserData { uint s[32]; uvec2 heap_base; uvec2 code_base; } pc; |
| @@ -14,5 +17,5 @@ uvec2 add64(uvec2 a, uvec2 b) { | |||
| 14 | void main() { | 17 | void main() { |
| 15 | Words result = Words(add64(pc.heap_base, uvec2(pc.s[4], pc.s[5]))); | 18 | Words result = Words(add64(pc.heap_base, uvec2(pc.s[4], pc.s[5]))); |
| 16 | atomicAdd(result.w[0], 1u); | 19 | atomicAdd(result.w[0], 1u); |
| 17 | atomicAdd(result.w[1], gl_WorkGroupID.x + 1u); | 20 | atomicAdd(result.w[1], gl_WorkGroupID.x + TEST_COUNTER_TERM); |
| 18 | } | 21 | } |
diff --git a/runtime/test/indirect_clamp_safety_test.cpp b/runtime/test/indirect_clamp_safety_test.cpp new file mode 100644 index 000000000..3a296e91b --- /dev/null +++ b/runtime/test/indirect_clamp_safety_test.cpp | |||
| @@ -0,0 +1,419 @@ | |||
| 1 | // Pure-CPU mock-Vulkan tests for runtime/src/vulkan_indirect_clamp.h and runtime/src/vulkan_scratch.h: | ||
| 2 | // - multi-queue-family sharing (VK_SHARING_MODE_CONCURRENT) on both scratch chunks and HostArea counter buffers; | ||
| 3 | // - freeing VkDeviceMemory before retrying the next memory type when vkBindBufferMemory fails in make_area(); | ||
| 4 | // - zeroing released counter slots so an aborted/unsubmitted batch never double-counts stale counters; | ||
| 5 | // - rejecting non-4-byte-aligned argument_offset and count_offset; | ||
| 6 | // - thread-safe concurrent prepare() + release() while areas_ grows (TSan clean). | ||
| 7 | // No GPU, Vulkan loader, or game files required. | ||
| 8 | #ifndef VK_NO_PROTOTYPES | ||
| 9 | #define VK_NO_PROTOTYPES | ||
| 10 | #endif | ||
| 11 | #include "../src/vulkan_indirect_clamp.h" | ||
| 12 | |||
| 13 | #include <atomic> | ||
| 14 | #include <cstdint> | ||
| 15 | #include <cstdio> | ||
| 16 | #include <cstring> | ||
| 17 | #include <memory> | ||
| 18 | #include <mutex> | ||
| 19 | #include <thread> | ||
| 20 | #include <unordered_map> | ||
| 21 | #include <vector> | ||
| 22 | |||
| 23 | #define CHECK(cond) \ | ||
| 24 | do { \ | ||
| 25 | if (!(cond)) { \ | ||
| 26 | std::fprintf(stderr, "line %d: CHECK failed: %s\n", __LINE__, #cond); \ | ||
| 27 | return 1; \ | ||
| 28 | } \ | ||
| 29 | } while (0) | ||
| 30 | |||
| 31 | namespace { | ||
| 32 | |||
| 33 | struct BufferRecord { | ||
| 34 | VkBufferUsageFlags usage = 0; | ||
| 35 | VkSharingMode sharing_mode = VK_SHARING_MODE_EXCLUSIVE; | ||
| 36 | std::vector<std::uint32_t> families; | ||
| 37 | VkDeviceSize size = 0; | ||
| 38 | }; | ||
| 39 | |||
| 40 | struct MockState { | ||
| 41 | std::mutex mutex; | ||
| 42 | std::uint64_t next_handle = 1; | ||
| 43 | std::uint32_t fail_bind_type = UINT32_MAX; | ||
| 44 | int alloc_memory_calls = 0; | ||
| 45 | int free_memory_calls = 0; | ||
| 46 | int create_buffer_calls = 0; | ||
| 47 | int destroy_buffer_calls = 0; | ||
| 48 | std::unordered_map<std::uintptr_t, BufferRecord> buffers; | ||
| 49 | std::unordered_map<std::uintptr_t, std::uint32_t> mem_types; | ||
| 50 | std::unordered_map<std::uintptr_t, std::unique_ptr<std::uint8_t[]>> host_maps; | ||
| 51 | std::unordered_map<std::uintptr_t, std::uint8_t*> buffer_host; | ||
| 52 | }; | ||
| 53 | |||
| 54 | MockState* g_mock = nullptr; | ||
| 55 | |||
| 56 | template <typename Handle> | ||
| 57 | Handle make_handle(std::uint64_t id) { | ||
| 58 | return reinterpret_cast<Handle>(static_cast<std::uintptr_t>(id)); | ||
| 59 | } | ||
| 60 | |||
| 61 | VKAPI_ATTR VkResult VKAPI_CALL mock_create_buffer(VkDevice, const VkBufferCreateInfo* info, | ||
| 62 | const VkAllocationCallbacks*, VkBuffer* out) { | ||
| 63 | std::lock_guard lock(g_mock->mutex); | ||
| 64 | ++g_mock->create_buffer_calls; | ||
| 65 | const auto id = ++g_mock->next_handle; | ||
| 66 | BufferRecord rec{}; | ||
| 67 | rec.usage = info->usage; | ||
| 68 | rec.sharing_mode = info->sharingMode; | ||
| 69 | rec.size = info->size; | ||
| 70 | if (info->pQueueFamilyIndices && info->queueFamilyIndexCount) | ||
| 71 | rec.families.assign(info->pQueueFamilyIndices, info->pQueueFamilyIndices + info->queueFamilyIndexCount); | ||
| 72 | g_mock->buffers[static_cast<std::uintptr_t>(id)] = std::move(rec); | ||
| 73 | *out = make_handle<VkBuffer>(id); | ||
| 74 | return VK_SUCCESS; | ||
| 75 | } | ||
| 76 | |||
| 77 | VKAPI_ATTR void VKAPI_CALL mock_destroy_buffer(VkDevice, VkBuffer buffer, const VkAllocationCallbacks*) { | ||
| 78 | std::lock_guard lock(g_mock->mutex); | ||
| 79 | ++g_mock->destroy_buffer_calls; | ||
| 80 | g_mock->buffers.erase(reinterpret_cast<std::uintptr_t>(buffer)); | ||
| 81 | g_mock->buffer_host.erase(reinterpret_cast<std::uintptr_t>(buffer)); | ||
| 82 | } | ||
| 83 | |||
| 84 | VKAPI_ATTR void VKAPI_CALL mock_get_buffer_memory_requirements(VkDevice, VkBuffer buffer, | ||
| 85 | VkMemoryRequirements* req) { | ||
| 86 | std::lock_guard lock(g_mock->mutex); | ||
| 87 | const auto it = g_mock->buffers.find(reinterpret_cast<std::uintptr_t>(buffer)); | ||
| 88 | req->size = it != g_mock->buffers.end() ? it->second.size : 256; | ||
| 89 | req->alignment = 256; | ||
| 90 | req->memoryTypeBits = 0x3u; | ||
| 91 | } | ||
| 92 | |||
| 93 | VKAPI_ATTR VkResult VKAPI_CALL mock_allocate_memory(VkDevice, const VkMemoryAllocateInfo* info, | ||
| 94 | const VkAllocationCallbacks*, VkDeviceMemory* out) { | ||
| 95 | std::lock_guard lock(g_mock->mutex); | ||
| 96 | ++g_mock->alloc_memory_calls; | ||
| 97 | const auto id = ++g_mock->next_handle; | ||
| 98 | g_mock->mem_types[static_cast<std::uintptr_t>(id)] = info->memoryTypeIndex; | ||
| 99 | g_mock->host_maps[static_cast<std::uintptr_t>(id)] = std::make_unique<std::uint8_t[]>(size_t(info->allocationSize)); | ||
| 100 | std::memset(g_mock->host_maps[static_cast<std::uintptr_t>(id)].get(), 0, size_t(info->allocationSize)); | ||
| 101 | *out = make_handle<VkDeviceMemory>(id); | ||
| 102 | return VK_SUCCESS; | ||
| 103 | } | ||
| 104 | |||
| 105 | VKAPI_ATTR void VKAPI_CALL mock_free_memory(VkDevice, VkDeviceMemory mem, const VkAllocationCallbacks*) { | ||
| 106 | std::lock_guard lock(g_mock->mutex); | ||
| 107 | ++g_mock->free_memory_calls; | ||
| 108 | g_mock->mem_types.erase(reinterpret_cast<std::uintptr_t>(mem)); | ||
| 109 | g_mock->host_maps.erase(reinterpret_cast<std::uintptr_t>(mem)); | ||
| 110 | } | ||
| 111 | |||
| 112 | VKAPI_ATTR VkResult VKAPI_CALL mock_bind_buffer_memory(VkDevice, VkBuffer buffer, VkDeviceMemory mem, VkDeviceSize) { | ||
| 113 | std::lock_guard lock(g_mock->mutex); | ||
| 114 | const auto it = g_mock->mem_types.find(reinterpret_cast<std::uintptr_t>(mem)); | ||
| 115 | if (it != g_mock->mem_types.end() && it->second == g_mock->fail_bind_type) | ||
| 116 | return VK_ERROR_OUT_OF_DEVICE_MEMORY; | ||
| 117 | const auto mit = g_mock->host_maps.find(reinterpret_cast<std::uintptr_t>(mem)); | ||
| 118 | if (mit != g_mock->host_maps.end()) g_mock->buffer_host[reinterpret_cast<std::uintptr_t>(buffer)] = mit->second.get(); | ||
| 119 | return VK_SUCCESS; | ||
| 120 | } | ||
| 121 | |||
| 122 | VKAPI_ATTR VkResult VKAPI_CALL mock_map_memory(VkDevice, VkDeviceMemory mem, VkDeviceSize offset, VkDeviceSize, | ||
| 123 | VkMemoryMapFlags, void** ppData) { | ||
| 124 | std::lock_guard lock(g_mock->mutex); | ||
| 125 | const auto it = g_mock->host_maps.find(reinterpret_cast<std::uintptr_t>(mem)); | ||
| 126 | if (it == g_mock->host_maps.end()) return VK_ERROR_MEMORY_MAP_FAILED; | ||
| 127 | *ppData = it->second.get() + offset; | ||
| 128 | return VK_SUCCESS; | ||
| 129 | } | ||
| 130 | |||
| 131 | VKAPI_ATTR void VKAPI_CALL mock_unmap_memory(VkDevice, VkDeviceMemory) {} | ||
| 132 | |||
| 133 | VKAPI_ATTR VkDeviceAddress VKAPI_CALL mock_get_buffer_device_address(VkDevice, const VkBufferDeviceAddressInfo* info) { | ||
| 134 | return static_cast<VkDeviceAddress>(0x10000000ull + reinterpret_cast<std::uintptr_t>(info->buffer) * 0x1000ull); | ||
| 135 | } | ||
| 136 | |||
| 137 | VKAPI_ATTR VkResult VKAPI_CALL mock_get_semaphore_counter_value(VkDevice, VkSemaphore, std::uint64_t* value) { | ||
| 138 | *value = UINT64_MAX; | ||
| 139 | return VK_SUCCESS; | ||
| 140 | } | ||
| 141 | |||
| 142 | VKAPI_ATTR VkResult VKAPI_CALL mock_device_wait_idle(VkDevice) { return VK_SUCCESS; } | ||
| 143 | |||
| 144 | VKAPI_ATTR VkResult VKAPI_CALL mock_create_shader_module(VkDevice, const VkShaderModuleCreateInfo*, | ||
| 145 | const VkAllocationCallbacks*, VkShaderModule* out) { | ||
| 146 | std::lock_guard lock(g_mock->mutex); | ||
| 147 | *out = make_handle<VkShaderModule>(++g_mock->next_handle); | ||
| 148 | return VK_SUCCESS; | ||
| 149 | } | ||
| 150 | VKAPI_ATTR void VKAPI_CALL mock_destroy_shader_module(VkDevice, VkShaderModule, const VkAllocationCallbacks*) {} | ||
| 151 | |||
| 152 | VKAPI_ATTR VkResult VKAPI_CALL mock_create_pipeline_layout(VkDevice, const VkPipelineLayoutCreateInfo*, | ||
| 153 | const VkAllocationCallbacks*, VkPipelineLayout* out) { | ||
| 154 | std::lock_guard lock(g_mock->mutex); | ||
| 155 | *out = make_handle<VkPipelineLayout>(++g_mock->next_handle); | ||
| 156 | return VK_SUCCESS; | ||
| 157 | } | ||
| 158 | VKAPI_ATTR void VKAPI_CALL mock_destroy_pipeline_layout(VkDevice, VkPipelineLayout, const VkAllocationCallbacks*) {} | ||
| 159 | |||
| 160 | VKAPI_ATTR VkResult VKAPI_CALL mock_create_compute_pipelines(VkDevice, VkPipelineCache, std::uint32_t, | ||
| 161 | const VkComputePipelineCreateInfo*, | ||
| 162 | const VkAllocationCallbacks*, VkPipeline* out) { | ||
| 163 | std::lock_guard lock(g_mock->mutex); | ||
| 164 | *out = make_handle<VkPipeline>(++g_mock->next_handle); | ||
| 165 | return VK_SUCCESS; | ||
| 166 | } | ||
| 167 | VKAPI_ATTR void VKAPI_CALL mock_destroy_pipeline(VkDevice, VkPipeline, const VkAllocationCallbacks*) {} | ||
| 168 | |||
| 169 | VKAPI_ATTR void VKAPI_CALL mock_cmd_pipeline_barrier(VkCommandBuffer, VkPipelineStageFlags, VkPipelineStageFlags, | ||
| 170 | VkDependencyFlags, std::uint32_t, const VkMemoryBarrier*, | ||
| 171 | std::uint32_t, const VkBufferMemoryBarrier*, std::uint32_t, | ||
| 172 | const VkImageMemoryBarrier*) {} | ||
| 173 | VKAPI_ATTR void VKAPI_CALL mock_cmd_bind_pipeline(VkCommandBuffer, VkPipelineBindPoint, VkPipeline) {} | ||
| 174 | VKAPI_ATTR void VKAPI_CALL mock_cmd_push_constants(VkCommandBuffer, VkPipelineLayout, VkShaderStageFlags, std::uint32_t, | ||
| 175 | std::uint32_t, const void*) {} | ||
| 176 | VKAPI_ATTR void VKAPI_CALL mock_cmd_dispatch(VkCommandBuffer, std::uint32_t, std::uint32_t, std::uint32_t) {} | ||
| 177 | VKAPI_ATTR void VKAPI_CALL mock_cmd_fill_buffer(VkCommandBuffer, VkBuffer, VkDeviceSize, VkDeviceSize, std::uint32_t) {} | ||
| 178 | VKAPI_ATTR void VKAPI_CALL mock_cmd_copy_buffer(VkCommandBuffer, VkBuffer, VkBuffer, std::uint32_t, | ||
| 179 | const VkBufferCopy*) {} | ||
| 180 | |||
| 181 | VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL mock_get_device_proc_addr(VkDevice, const char* name) { | ||
| 182 | #define ENTRY(fn_name, impl) \ | ||
| 183 | if (std::strcmp(name, #fn_name) == 0) return reinterpret_cast<PFN_vkVoidFunction>(impl) | ||
| 184 | ENTRY(vkCreateBuffer, mock_create_buffer); | ||
| 185 | ENTRY(vkDestroyBuffer, mock_destroy_buffer); | ||
| 186 | ENTRY(vkGetBufferMemoryRequirements, mock_get_buffer_memory_requirements); | ||
| 187 | ENTRY(vkAllocateMemory, mock_allocate_memory); | ||
| 188 | ENTRY(vkFreeMemory, mock_free_memory); | ||
| 189 | ENTRY(vkBindBufferMemory, mock_bind_buffer_memory); | ||
| 190 | ENTRY(vkMapMemory, mock_map_memory); | ||
| 191 | ENTRY(vkUnmapMemory, mock_unmap_memory); | ||
| 192 | ENTRY(vkGetBufferDeviceAddress, mock_get_buffer_device_address); | ||
| 193 | ENTRY(vkGetSemaphoreCounterValue, mock_get_semaphore_counter_value); | ||
| 194 | ENTRY(vkDeviceWaitIdle, mock_device_wait_idle); | ||
| 195 | ENTRY(vkCreateShaderModule, mock_create_shader_module); | ||
| 196 | ENTRY(vkDestroyShaderModule, mock_destroy_shader_module); | ||
| 197 | ENTRY(vkCreatePipelineLayout, mock_create_pipeline_layout); | ||
| 198 | ENTRY(vkDestroyPipelineLayout, mock_destroy_pipeline_layout); | ||
| 199 | ENTRY(vkCreateComputePipelines, mock_create_compute_pipelines); | ||
| 200 | ENTRY(vkDestroyPipeline, mock_destroy_pipeline); | ||
| 201 | ENTRY(vkCmdPipelineBarrier, mock_cmd_pipeline_barrier); | ||
| 202 | ENTRY(vkCmdBindPipeline, mock_cmd_bind_pipeline); | ||
| 203 | ENTRY(vkCmdPushConstants, mock_cmd_push_constants); | ||
| 204 | ENTRY(vkCmdDispatch, mock_cmd_dispatch); | ||
| 205 | ENTRY(vkCmdFillBuffer, mock_cmd_fill_buffer); | ||
| 206 | ENTRY(vkCmdCopyBuffer, mock_cmd_copy_buffer); | ||
| 207 | #undef ENTRY | ||
| 208 | return nullptr; | ||
| 209 | } | ||
| 210 | |||
| 211 | VkPhysicalDeviceMemoryProperties make_memory_props() { | ||
| 212 | VkPhysicalDeviceMemoryProperties mem{}; | ||
| 213 | mem.memoryHeapCount = 2; | ||
| 214 | mem.memoryHeaps[0] = {VkDeviceSize(1) << 30, VK_MEMORY_HEAP_DEVICE_LOCAL_BIT}; | ||
| 215 | mem.memoryHeaps[1] = {VkDeviceSize(4) << 30, 0}; | ||
| 216 | mem.memoryTypeCount = 2; | ||
| 217 | mem.memoryTypes[0] = {VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, 0}; | ||
| 218 | mem.memoryTypes[1] = {VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, 1}; | ||
| 219 | return mem; | ||
| 220 | } | ||
| 221 | |||
| 222 | VkPhysicalDeviceLimits make_limits() { | ||
| 223 | VkPhysicalDeviceLimits limits{}; | ||
| 224 | limits.maxComputeWorkGroupCount[0] = 65535u; | ||
| 225 | return limits; | ||
| 226 | } | ||
| 227 | |||
| 228 | leonida::ScratchBuffers::Allocate make_scratch_allocator() { | ||
| 229 | return [](const VkMemoryRequirements& req) -> VkDeviceMemory { | ||
| 230 | VkMemoryAllocateInfo info{}; | ||
| 231 | info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; | ||
| 232 | info.allocationSize = req.size; | ||
| 233 | info.memoryTypeIndex = 1; // never blocked by fail_bind_type = 0 | ||
| 234 | VkDeviceMemory mem = VK_NULL_HANDLE; | ||
| 235 | mock_allocate_memory(VK_NULL_HANDLE, &info, nullptr, &mem); | ||
| 236 | return mem; | ||
| 237 | }; | ||
| 238 | } | ||
| 239 | |||
| 240 | } // namespace | ||
| 241 | |||
| 242 | int main() { | ||
| 243 | using namespace leonida; | ||
| 244 | const VkDevice dummy_device = make_handle<VkDevice>(1); | ||
| 245 | const VkBuffer args_buf = make_handle<VkBuffer>(0x100); | ||
| 246 | const VkBuffer count_buf = make_handle<VkBuffer>(0x200); | ||
| 247 | |||
| 248 | // 1. Multi-family sharing: both scratch chunks and HostArea counter buffers must use VK_SHARING_MODE_CONCURRENT. | ||
| 249 | { | ||
| 250 | MockState state; | ||
| 251 | g_mock = &state; | ||
| 252 | const std::vector<std::uint32_t> families = {0u, 2u}; | ||
| 253 | IndirectArgumentClamp clamp(mock_get_device_proc_addr, dummy_device, make_memory_props(), make_limits(), | ||
| 254 | make_scratch_allocator(), nullptr, families); | ||
| 255 | CHECK(clamp.loaded()); | ||
| 256 | auto batch = clamp.batch(); | ||
| 257 | ClampedIndirect job{}; | ||
| 258 | CHECK(batch->prepare(args_buf, 0, count_buf, 0, indirect_clamp_draw, 16, 4, job)); | ||
| 259 | CHECK(job.buffer != VK_NULL_HANDLE && job.stats_buffer != VK_NULL_HANDLE); | ||
| 260 | const auto scratch_it = state.buffers.find(reinterpret_cast<std::uintptr_t>(job.buffer)); | ||
| 261 | const auto area_it = state.buffers.find(reinterpret_cast<std::uintptr_t>(job.stats_buffer)); | ||
| 262 | CHECK(scratch_it != state.buffers.end() && area_it != state.buffers.end()); | ||
| 263 | CHECK(scratch_it->second.sharing_mode == VK_SHARING_MODE_CONCURRENT); | ||
| 264 | CHECK(scratch_it->second.families == families); | ||
| 265 | CHECK(area_it->second.sharing_mode == VK_SHARING_MODE_CONCURRENT); | ||
| 266 | CHECK(area_it->second.families == families); | ||
| 267 | batch.reset(); | ||
| 268 | clamp.retire(VK_NULL_HANDLE, 0); | ||
| 269 | clamp.collect(); | ||
| 270 | } | ||
| 271 | |||
| 272 | // 1b. Single-family stays VK_SHARING_MODE_EXCLUSIVE. | ||
| 273 | { | ||
| 274 | MockState state; | ||
| 275 | g_mock = &state; | ||
| 276 | IndirectArgumentClamp clamp(mock_get_device_proc_addr, dummy_device, make_memory_props(), make_limits(), | ||
| 277 | make_scratch_allocator(), nullptr, {0u}); | ||
| 278 | auto batch = clamp.batch(); | ||
| 279 | ClampedIndirect job{}; | ||
| 280 | CHECK(batch->prepare(args_buf, 0, VK_NULL_HANDLE, 0, indirect_clamp_dispatch, 12, 2, job)); | ||
| 281 | CHECK(state.buffers.at(reinterpret_cast<std::uintptr_t>(job.buffer)).sharing_mode == | ||
| 282 | VK_SHARING_MODE_EXCLUSIVE); | ||
| 283 | CHECK(state.buffers.at(reinterpret_cast<std::uintptr_t>(job.stats_buffer)).sharing_mode == | ||
| 284 | VK_SHARING_MODE_EXCLUSIVE); | ||
| 285 | } | ||
| 286 | |||
| 287 | // 2. vkBindBufferMemory failure on the first memory type in make_area() must free that VkDeviceMemory before | ||
| 288 | // retrying the next type (zero leaked allocations). | ||
| 289 | { | ||
| 290 | MockState state; | ||
| 291 | state.fail_bind_type = 0u; | ||
| 292 | g_mock = &state; | ||
| 293 | { | ||
| 294 | IndirectArgumentClamp clamp(mock_get_device_proc_addr, dummy_device, make_memory_props(), make_limits(), | ||
| 295 | make_scratch_allocator()); | ||
| 296 | auto batch = clamp.batch(); | ||
| 297 | ClampedIndirect job{}; | ||
| 298 | CHECK(batch->prepare(args_buf, 0, VK_NULL_HANDLE, 0, indirect_clamp_draw, 16, 1, job)); | ||
| 299 | // 2 host-area memory attempts (type 0 failed bind & freed immediately, type 1 succeeded) + 1 scratch alloc. | ||
| 300 | CHECK(state.alloc_memory_calls == 3); | ||
| 301 | CHECK(state.free_memory_calls == 1); | ||
| 302 | } | ||
| 303 | CHECK(state.alloc_memory_calls == state.free_memory_calls); | ||
| 304 | CHECK(state.create_buffer_calls == state.destroy_buffer_calls); | ||
| 305 | } | ||
| 306 | |||
| 307 | // 3. Released counter slots are zeroed so a subsequent aborted batch reusing the same slot never double-counts | ||
| 308 | // the prior submission's counters. | ||
| 309 | { | ||
| 310 | MockState state; | ||
| 311 | g_mock = &state; | ||
| 312 | IndirectArgumentClamp clamp(mock_get_device_proc_addr, dummy_device, make_memory_props(), make_limits(), | ||
| 313 | make_scratch_allocator()); | ||
| 314 | VkBuffer area_buf = VK_NULL_HANDLE; | ||
| 315 | VkDeviceSize slot_off = 0; | ||
| 316 | { | ||
| 317 | auto batch1 = clamp.batch(); | ||
| 318 | ClampedIndirect job1{}; | ||
| 319 | CHECK(batch1->prepare(args_buf, 0, VK_NULL_HANDLE, 0, indirect_clamp_draw, 16, 1, job1)); | ||
| 320 | area_buf = job1.stats_buffer; | ||
| 321 | slot_off = job1.stats_offset; | ||
| 322 | std::uint8_t* host = state.buffer_host.at(reinterpret_cast<std::uintptr_t>(area_buf)); | ||
| 323 | const std::uint32_t gpu_written[12] = {5u, 1u, 2u, 3u, 0u, 0u, 0u, 0u, 7u, 4u, 3u, 2u}; | ||
| 324 | std::memcpy(host + slot_off, gpu_written, sizeof(gpu_written)); | ||
| 325 | } | ||
| 326 | const auto after1 = clamp.counters(); | ||
| 327 | CHECK(after1.records_clamped == 5 && after1.counts_clamped == 1 && after1.over_budget == 2 && | ||
| 328 | after1.zeroed == 3); | ||
| 329 | CHECK(after1.mesh_records == 7 && after1.mesh_yz_records == 4 && | ||
| 330 | after1.mesh_max_y == 3 && after1.mesh_max_z == 2); | ||
| 331 | |||
| 332 | // Batch 2 reuses the exact same slot (LIFO free_slots_) and is destroyed without GPU submission. | ||
| 333 | { | ||
| 334 | auto batch2 = clamp.batch(); | ||
| 335 | ClampedIndirect job2{}; | ||
| 336 | CHECK(batch2->prepare(args_buf, 0, VK_NULL_HANDLE, 0, indirect_clamp_draw, 16, 1, job2)); | ||
| 337 | CHECK(job2.stats_buffer == area_buf && job2.stats_offset == slot_off); | ||
| 338 | } | ||
| 339 | const auto after2 = clamp.counters(); | ||
| 340 | CHECK(after2.records_clamped == 5 && after2.counts_clamped == 1 && after2.over_budget == 2 && | ||
| 341 | after2.zeroed == 3); | ||
| 342 | CHECK(after2.mesh_records == 7 && after2.mesh_yz_records == 4 && | ||
| 343 | after2.mesh_max_y == 3 && after2.mesh_max_z == 2); | ||
| 344 | } | ||
| 345 | |||
| 346 | // 4. Non-4-byte-aligned argument_offset or count_offset is rejected before allocating scratch. | ||
| 347 | { | ||
| 348 | MockState state; | ||
| 349 | g_mock = &state; | ||
| 350 | IndirectArgumentClamp clamp(mock_get_device_proc_addr, dummy_device, make_memory_props(), make_limits(), | ||
| 351 | make_scratch_allocator()); | ||
| 352 | auto batch = clamp.batch(); | ||
| 353 | ClampedIndirect job{}; | ||
| 354 | CHECK(!batch->prepare(args_buf, 2, VK_NULL_HANDLE, 0, indirect_clamp_draw, 16, 1, job)); | ||
| 355 | CHECK(!batch->prepare(args_buf, 0, count_buf, 6, indirect_clamp_draw, 16, 1, job)); | ||
| 356 | CHECK(batch->calls() == 0); | ||
| 357 | // An uncounted call ignores count_offset == 0 and still succeeds on 4-byte-aligned argument_offset. | ||
| 358 | CHECK(batch->prepare(args_buf, 4, VK_NULL_HANDLE, 0, indirect_clamp_draw, 16, 1, job)); | ||
| 359 | CHECK(batch->calls() == 1); | ||
| 360 | } | ||
| 361 | |||
| 362 | // 5. Concurrent area growth during prepare() + background batch release() + counters() under TSan. | ||
| 363 | { | ||
| 364 | MockState state; | ||
| 365 | g_mock = &state; | ||
| 366 | IndirectArgumentClamp clamp(mock_get_device_proc_addr, dummy_device, make_memory_props(), make_limits(), | ||
| 367 | make_scratch_allocator(), nullptr, {0u, 1u}); | ||
| 368 | std::mutex queue_mutex; | ||
| 369 | std::vector<std::unique_ptr<IndirectArgumentClamp::Batch>> completed; | ||
| 370 | std::atomic<bool> done{false}; | ||
| 371 | |||
| 372 | std::thread releaser([&] { | ||
| 373 | while (!done.load(std::memory_order_acquire)) { | ||
| 374 | std::unique_ptr<IndirectArgumentClamp::Batch> b; | ||
| 375 | { | ||
| 376 | std::lock_guard lock(queue_mutex); | ||
| 377 | if (!completed.empty()) { | ||
| 378 | b = std::move(completed.back()); | ||
| 379 | completed.pop_back(); | ||
| 380 | } | ||
| 381 | } | ||
| 382 | if (b) b.reset(); | ||
| 383 | else std::this_thread::yield(); | ||
| 384 | (void)clamp.counters(); | ||
| 385 | } | ||
| 386 | for (;;) { | ||
| 387 | std::unique_ptr<IndirectArgumentClamp::Batch> b; | ||
| 388 | { | ||
| 389 | std::lock_guard lock(queue_mutex); | ||
| 390 | if (completed.empty()) break; | ||
| 391 | b = std::move(completed.back()); | ||
| 392 | completed.pop_back(); | ||
| 393 | } | ||
| 394 | b.reset(); | ||
| 395 | } | ||
| 396 | }); | ||
| 397 | |||
| 398 | // Allocate > 128 slots across several batches so areas_ grows and reallocates while releaser runs. | ||
| 399 | for (int b = 0; b < 8; ++b) { | ||
| 400 | auto batch = clamp.batch(); | ||
| 401 | for (int i = 0; i < 40; ++i) { | ||
| 402 | ClampedIndirect job{}; | ||
| 403 | CHECK(batch->prepare(args_buf, 0, VK_NULL_HANDLE, 0, indirect_clamp_draw, 16, 1, job)); | ||
| 404 | CHECK(job.stats_buffer != VK_NULL_HANDLE); | ||
| 405 | } | ||
| 406 | clamp.retire(VK_NULL_HANDLE, 0); | ||
| 407 | clamp.collect(); | ||
| 408 | { | ||
| 409 | std::lock_guard lock(queue_mutex); | ||
| 410 | completed.push_back(std::move(batch)); | ||
| 411 | } | ||
| 412 | } | ||
| 413 | done.store(true, std::memory_order_release); | ||
| 414 | releaser.join(); | ||
| 415 | } | ||
| 416 | |||
| 417 | std::printf("indirect_clamp_safety_test: all checks passed\n"); | ||
| 418 | return 0; | ||
| 419 | } | ||
diff --git a/runtime/test/indirect_topology_and_stats_test.cpp b/runtime/test/indirect_topology_and_stats_test.cpp new file mode 100644 index 000000000..79b6756b4 --- /dev/null +++ b/runtime/test/indirect_topology_and_stats_test.cpp | |||
| @@ -0,0 +1,409 @@ | |||
| 1 | // Portable CPU-only tests for stateful indirect draw topology coverage and per-reason indirect_stats reporting. | ||
| 2 | // No GPU, driver, or game data required. | ||
| 3 | #include "../src/vulkan_replay.h" | ||
| 4 | |||
| 5 | #include <cstdio> | ||
| 6 | #include <cstdlib> | ||
| 7 | #include <cstring> | ||
| 8 | #include <string> | ||
| 9 | #include <thread> | ||
| 10 | #include <vector> | ||
| 11 | |||
| 12 | #define CHECK(cond) \ | ||
| 13 | do { \ | ||
| 14 | if (!(cond)) { \ | ||
| 15 | std::fprintf(stderr, "FAIL %s:%d: %s\n", __FILE__, __LINE__, #cond); \ | ||
| 16 | std::exit(1); \ | ||
| 17 | } \ | ||
| 18 | } while (0) | ||
| 19 | |||
| 20 | namespace { | ||
| 21 | |||
| 22 | template <class T> | ||
| 23 | T fake_handle(std::uintptr_t value) { | ||
| 24 | return reinterpret_cast<T>(value); | ||
| 25 | } | ||
| 26 | |||
| 27 | struct RecordedDraw { | ||
| 28 | VkPipeline pipeline = VK_NULL_HANDLE; | ||
| 29 | VkPrimitiveTopology topology = VK_PRIMITIVE_TOPOLOGY_MAX_ENUM; | ||
| 30 | VkBool32 primitive_restart = VK_FALSE; | ||
| 31 | bool indexed = false; | ||
| 32 | bool counted = false; | ||
| 33 | std::uint32_t max_count = 0; | ||
| 34 | }; | ||
| 35 | |||
| 36 | struct Harness; | ||
| 37 | Harness* g_harness = nullptr; | ||
| 38 | |||
| 39 | struct Harness { | ||
| 40 | leonida::GraphicsPipeline pipeline{}; | ||
| 41 | leonida::ResourceBinding args{}; | ||
| 42 | leonida::ResourceBinding counts{}; | ||
| 43 | leonida::ReplayFunctions vk{}; | ||
| 44 | std::vector<RecordedDraw> draws; | ||
| 45 | std::uint32_t last_variant_flags = 0; | ||
| 46 | std::uint32_t variant_calls = 0; | ||
| 47 | |||
| 48 | VkPipeline bound_pipeline = VK_NULL_HANDLE; | ||
| 49 | VkPrimitiveTopology bound_topology = VK_PRIMITIVE_TOPOLOGY_MAX_ENUM; | ||
| 50 | VkBool32 bound_restart = VK_FALSE; | ||
| 51 | |||
| 52 | static VKAPI_ATTR void VKAPI_CALL cb_begin_rendering(VkCommandBuffer, const VkRenderingInfo*) {} | ||
| 53 | static VKAPI_ATTR void VKAPI_CALL cb_end_rendering(VkCommandBuffer) {} | ||
| 54 | static VKAPI_ATTR void VKAPI_CALL cb_bind_vb2(VkCommandBuffer, std::uint32_t, std::uint32_t, const VkBuffer*, | ||
| 55 | const VkDeviceSize*, const VkDeviceSize*, const VkDeviceSize*) {} | ||
| 56 | static VKAPI_ATTR void VKAPI_CALL cb_bind_ib(VkCommandBuffer, VkBuffer, VkDeviceSize, VkIndexType) {} | ||
| 57 | static VKAPI_ATTR void VKAPI_CALL cb_bind_ib2(VkCommandBuffer, VkBuffer, VkDeviceSize, VkDeviceSize, VkIndexType) {} | ||
| 58 | static VKAPI_ATTR void VKAPI_CALL cb_set_vp(VkCommandBuffer, std::uint32_t, std::uint32_t, const VkViewport*) {} | ||
| 59 | static VKAPI_ATTR void VKAPI_CALL cb_set_sc(VkCommandBuffer, std::uint32_t, std::uint32_t, const VkRect2D*) {} | ||
| 60 | static VKAPI_ATTR void VKAPI_CALL cb_set_topo(VkCommandBuffer, VkPrimitiveTopology t) { | ||
| 61 | g_harness->bound_topology = t; | ||
| 62 | } | ||
| 63 | static VKAPI_ATTR void VKAPI_CALL cb_set_restart(VkCommandBuffer, VkBool32 en) { | ||
| 64 | g_harness->bound_restart = en; | ||
| 65 | } | ||
| 66 | static VKAPI_ATTR void VKAPI_CALL cb_set_stencil(VkCommandBuffer, VkStencilFaceFlags, std::uint32_t) {} | ||
| 67 | static VKAPI_ATTR void VKAPI_CALL cb_set_blend(VkCommandBuffer, const float[4]) {} | ||
| 68 | static VKAPI_ATTR void VKAPI_CALL cb_bind_pipeline(VkCommandBuffer, VkPipelineBindPoint, VkPipeline p) { | ||
| 69 | g_harness->bound_pipeline = p; | ||
| 70 | } | ||
| 71 | static VKAPI_ATTR void VKAPI_CALL cb_push_constants(VkCommandBuffer, VkPipelineLayout, VkShaderStageFlags, | ||
| 72 | std::uint32_t, std::uint32_t, const void*) {} | ||
| 73 | static VKAPI_ATTR void VKAPI_CALL cb_draw(VkCommandBuffer, std::uint32_t, std::uint32_t, std::uint32_t, | ||
| 74 | std::uint32_t) {} | ||
| 75 | static VKAPI_ATTR void VKAPI_CALL cb_draw_indexed(VkCommandBuffer, std::uint32_t, std::uint32_t, std::uint32_t, | ||
| 76 | std::int32_t, std::uint32_t) {} | ||
| 77 | static VKAPI_ATTR void VKAPI_CALL cb_draw_indirect(VkCommandBuffer, VkBuffer, VkDeviceSize, std::uint32_t count, | ||
| 78 | std::uint32_t) { | ||
| 79 | g_harness->draws.push_back( | ||
| 80 | {g_harness->bound_pipeline, g_harness->bound_topology, g_harness->bound_restart, false, false, count}); | ||
| 81 | } | ||
| 82 | static VKAPI_ATTR void VKAPI_CALL cb_draw_indexed_indirect(VkCommandBuffer, VkBuffer, VkDeviceSize, | ||
| 83 | std::uint32_t count, std::uint32_t) { | ||
| 84 | g_harness->draws.push_back( | ||
| 85 | {g_harness->bound_pipeline, g_harness->bound_topology, g_harness->bound_restart, true, false, count}); | ||
| 86 | } | ||
| 87 | static VKAPI_ATTR void VKAPI_CALL cb_draw_indirect_count(VkCommandBuffer, VkBuffer, VkDeviceSize, VkBuffer, | ||
| 88 | VkDeviceSize, std::uint32_t max_count, std::uint32_t) { | ||
| 89 | g_harness->draws.push_back( | ||
| 90 | {g_harness->bound_pipeline, g_harness->bound_topology, g_harness->bound_restart, false, true, max_count}); | ||
| 91 | } | ||
| 92 | static VKAPI_ATTR void VKAPI_CALL cb_draw_indexed_indirect_count(VkCommandBuffer, VkBuffer, VkDeviceSize, VkBuffer, | ||
| 93 | VkDeviceSize, std::uint32_t max_count, | ||
| 94 | std::uint32_t) { | ||
| 95 | g_harness->draws.push_back( | ||
| 96 | {g_harness->bound_pipeline, g_harness->bound_topology, g_harness->bound_restart, true, true, max_count}); | ||
| 97 | } | ||
| 98 | |||
| 99 | Harness() { | ||
| 100 | g_harness = this; | ||
| 101 | pipeline.pipeline = fake_handle<VkPipeline>(0x1001); | ||
| 102 | pipeline.layout = fake_handle<VkPipelineLayout>(0x2001); | ||
| 103 | pipeline.push_stages = VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT; | ||
| 104 | pipeline.rectangle_variant_topology = leonida::topology_rect_list; | ||
| 105 | pipeline.variant = [this](std::uint32_t flags) { | ||
| 106 | ++variant_calls; | ||
| 107 | last_variant_flags = flags; | ||
| 108 | if (flags & leonida::GraphicsPipeline::rectangle_stage) | ||
| 109 | return fake_handle<VkPipeline>(0x1000 + flags); | ||
| 110 | return fake_handle<VkPipeline>(0x1001); | ||
| 111 | }; | ||
| 112 | |||
| 113 | args.buffer = fake_handle<VkBuffer>(0x3001); | ||
| 114 | args.buffer_offset = 64; | ||
| 115 | args.size = 256; | ||
| 116 | args.indirect_arguments = true; | ||
| 117 | |||
| 118 | counts.buffer = fake_handle<VkBuffer>(0x3002); | ||
| 119 | counts.buffer_offset = 128; | ||
| 120 | counts.size = 64; | ||
| 121 | counts.indirect_arguments = true; | ||
| 122 | |||
| 123 | vk.graphics_pipeline = [this](std::uintptr_t id) -> const leonida::GraphicsPipeline* { | ||
| 124 | return id == 7 ? &pipeline : nullptr; | ||
| 125 | }; | ||
| 126 | vk.buffer_at = [](std::uint64_t va, std::uint64_t& size, VkBuffer& buf, VkDeviceSize& off) { | ||
| 127 | if (va != 0x10000) return false; | ||
| 128 | buf = fake_handle<VkBuffer>(0x3003); | ||
| 129 | off = 16; | ||
| 130 | size = 256; | ||
| 131 | return true; | ||
| 132 | }; | ||
| 133 | vk.image_view = [](const leonida::ResourceBinding&, const VkImageSubresourceRange&) { | ||
| 134 | return fake_handle<VkImageView>(0x4001); | ||
| 135 | }; | ||
| 136 | vk.begin_rendering = &cb_begin_rendering; | ||
| 137 | vk.end_rendering = &cb_end_rendering; | ||
| 138 | vk.bind_vertex_buffers2 = &cb_bind_vb2; | ||
| 139 | vk.bind_index_buffer = &cb_bind_ib; | ||
| 140 | vk.bind_robust_index_view = &cb_bind_ib2; | ||
| 141 | vk.set_viewport = &cb_set_vp; | ||
| 142 | vk.set_scissor = &cb_set_sc; | ||
| 143 | vk.set_primitive_topology = &cb_set_topo; | ||
| 144 | vk.set_primitive_restart_enable = &cb_set_restart; | ||
| 145 | vk.set_stencil_reference = &cb_set_stencil; | ||
| 146 | vk.set_blend_constants = &cb_set_blend; | ||
| 147 | vk.bind_pipeline = &cb_bind_pipeline; | ||
| 148 | vk.push_constants = &cb_push_constants; | ||
| 149 | vk.draw = &cb_draw; | ||
| 150 | vk.draw_indexed = &cb_draw_indexed; | ||
| 151 | vk.draw_indirect = &cb_draw_indirect; | ||
| 152 | vk.draw_indexed_indirect = &cb_draw_indexed_indirect; | ||
| 153 | vk.draw_indirect_count = &cb_draw_indirect_count; | ||
| 154 | vk.draw_indexed_indirect_count = &cb_draw_indexed_indirect_count; | ||
| 155 | vk.draw_indirect_first_instance = true; | ||
| 156 | vk.multi_draw_indirect = true; | ||
| 157 | vk.draw_indirect_count_enabled = true; | ||
| 158 | vk.max_draw_indirect_count = UINT32_MAX; | ||
| 159 | } | ||
| 160 | |||
| 161 | ~Harness() { | ||
| 162 | if (g_harness == this) g_harness = nullptr; | ||
| 163 | } | ||
| 164 | |||
| 165 | leonida::ReplayResult run_indirect(const leonida::Draw& draw, const leonida::IndirectDrawArgs& arg) { | ||
| 166 | g_harness = this; | ||
| 167 | draws.clear(); | ||
| 168 | bound_pipeline = VK_NULL_HANDLE; | ||
| 169 | bound_topology = VK_PRIMITIVE_TOPOLOGY_MAX_ENUM; | ||
| 170 | bound_restart = VK_FALSE; | ||
| 171 | leonida::CommandList list; | ||
| 172 | CHECK(list.draw_indirect(leonida::Draw{draw}, arg)); | ||
| 173 | CHECK(list.close()); | ||
| 174 | const auto resolve = [this](leonida::ResourceId id) -> const leonida::ResourceBinding* { | ||
| 175 | if (id == 1) return &args; | ||
| 176 | if (id == 2) return &counts; | ||
| 177 | return nullptr; | ||
| 178 | }; | ||
| 179 | return leonida::replay(list, VK_NULL_HANDLE, resolve, vk); | ||
| 180 | } | ||
| 181 | }; | ||
| 182 | |||
| 183 | leonida::Draw make_base_draw(std::uint32_t topology, bool indexed, std::uint32_t index_format = 57) { | ||
| 184 | leonida::Draw d{}; | ||
| 185 | d.pipeline = 7; | ||
| 186 | d.topology = topology; | ||
| 187 | d.viewport = {0.0f, 0.0f, 64.0f, 64.0f, 0.0f, 1.0f}; | ||
| 188 | d.scissor = {0, 0, 64, 64}; | ||
| 189 | d.indexed = indexed; | ||
| 190 | if (indexed) d.index = {0x10000, 64, index_format}; // 57 = R16_UINT, 42 = R32_UINT | ||
| 191 | return d; | ||
| 192 | } | ||
| 193 | |||
| 194 | void test_topology_predicate() { | ||
| 195 | using leonida::indirect_stats::topology_supported; | ||
| 196 | for (std::uint32_t t = 0; t <= 100; ++t) { | ||
| 197 | const bool expected = (t == 1 || t == 2 || t == 3 || t == 4 || t == 5 || t == 10 || t == 11 || t == 12 || | ||
| 198 | t == 13 || t == leonida::topology_rect_list); | ||
| 199 | CHECK(topology_supported(t) == expected); | ||
| 200 | } | ||
| 201 | CHECK(!topology_supported(0)); | ||
| 202 | CHECK(!topology_supported(leonida::topology_quad_list)); | ||
| 203 | CHECK(!topology_supported(33)); // D3D_PRIMITIVE_TOPOLOGY_1_CONTROL_POINT_PATCHLIST | ||
| 204 | CHECK(!topology_supported(64)); // D3D_PRIMITIVE_TOPOLOGY_32_CONTROL_POINT_PATCHLIST | ||
| 205 | } | ||
| 206 | |||
| 207 | void test_supported_topologies_emit() { | ||
| 208 | struct Case { | ||
| 209 | std::uint32_t d3d_topology; | ||
| 210 | VkPrimitiveTopology vk_topology; | ||
| 211 | bool is_strip; | ||
| 212 | bool expects_rect_stage; | ||
| 213 | }; | ||
| 214 | constexpr Case cases[] = { | ||
| 215 | {1, VK_PRIMITIVE_TOPOLOGY_POINT_LIST, false, false}, | ||
| 216 | {2, VK_PRIMITIVE_TOPOLOGY_LINE_LIST, false, false}, | ||
| 217 | {3, VK_PRIMITIVE_TOPOLOGY_LINE_STRIP, true, false}, | ||
| 218 | {4, VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, false, false}, | ||
| 219 | {5, VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP, true, false}, | ||
| 220 | {10, VK_PRIMITIVE_TOPOLOGY_LINE_LIST_WITH_ADJACENCY, false, false}, | ||
| 221 | {11, VK_PRIMITIVE_TOPOLOGY_LINE_STRIP_WITH_ADJACENCY, true, false}, | ||
| 222 | {12, VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST_WITH_ADJACENCY, false, false}, | ||
| 223 | {13, VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP_WITH_ADJACENCY, true, false}, | ||
| 224 | {leonida::topology_rect_list, VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, false, true}, | ||
| 225 | }; | ||
| 226 | |||
| 227 | Harness h; | ||
| 228 | for (const auto& c : cases) { | ||
| 229 | for (const bool indexed : {false, true}) { | ||
| 230 | for (const bool counted : {false, true}) { | ||
| 231 | for (const std::uint32_t strip_cut : {0u, 1u, 2u}) { | ||
| 232 | for (const std::uint32_t idx_fmt : {57u, 42u}) { | ||
| 233 | if (!indexed && idx_fmt == 42u) continue; | ||
| 234 | h.pipeline.strip_cut = strip_cut; | ||
| 235 | h.variant_calls = 0; | ||
| 236 | h.last_variant_flags = 0; | ||
| 237 | const leonida::Draw d = make_base_draw(c.d3d_topology, indexed, idx_fmt); | ||
| 238 | leonida::IndirectDrawArgs arg{}; | ||
| 239 | arg.argument_buffer = 1; | ||
| 240 | arg.argument_offset = 0; | ||
| 241 | arg.stride = indexed ? 20 : 16; | ||
| 242 | arg.max_count = 3; | ||
| 243 | if (counted) { | ||
| 244 | arg.count_buffer = 2; | ||
| 245 | arg.count_offset = 4; | ||
| 246 | } | ||
| 247 | CHECK(h.run_indirect(d, arg) == leonida::ReplayResult::success); | ||
| 248 | CHECK(h.draws.size() == 1); | ||
| 249 | const auto& got = h.draws[0]; | ||
| 250 | CHECK(got.topology == c.vk_topology); | ||
| 251 | CHECK(got.indexed == indexed); | ||
| 252 | CHECK(got.counted == counted); | ||
| 253 | CHECK(got.max_count == 3); | ||
| 254 | const bool cut_matches = (strip_cut == 1 && idx_fmt == 57) || (strip_cut == 2 && idx_fmt == 42); | ||
| 255 | const VkBool32 want_restart = (indexed && c.is_strip && cut_matches) ? VK_TRUE : VK_FALSE; | ||
| 256 | CHECK(got.primitive_restart == want_restart); | ||
| 257 | if (c.expects_rect_stage) { | ||
| 258 | CHECK(h.variant_calls == 1); | ||
| 259 | CHECK((h.last_variant_flags & leonida::GraphicsPipeline::rectangle_stage) != 0); | ||
| 260 | CHECK(got.pipeline == fake_handle<VkPipeline>(0x1000 + h.last_variant_flags)); | ||
| 261 | } else { | ||
| 262 | CHECK(h.variant_calls == 0); | ||
| 263 | CHECK(got.pipeline == h.pipeline.pipeline); | ||
| 264 | } | ||
| 265 | } | ||
| 266 | } | ||
| 267 | } | ||
| 268 | } | ||
| 269 | } | ||
| 270 | } | ||
| 271 | |||
| 272 | void test_rect_list_builtin_and_fallback() { | ||
| 273 | // 1. PSO created with topology_type_rect_list (19) already contains the GS -> rectangle_variant_topology == 0. | ||
| 274 | { | ||
| 275 | Harness h; | ||
| 276 | h.pipeline.rectangle_variant_topology = 0; | ||
| 277 | const leonida::Draw d = make_base_draw(leonida::topology_rect_list, false); | ||
| 278 | leonida::IndirectDrawArgs arg{1, 0, 16, 1, 0, 0}; | ||
| 279 | CHECK(h.run_indirect(d, arg) == leonida::ReplayResult::success); | ||
| 280 | CHECK(h.draws.size() == 1); | ||
| 281 | CHECK(h.variant_calls == 0); | ||
| 282 | CHECK(h.draws[0].pipeline == h.pipeline.pipeline); | ||
| 283 | CHECK(h.draws[0].topology == VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST); | ||
| 284 | } | ||
| 285 | |||
| 286 | // 2. Indirect RECTLIST when the pipeline cannot build a rectangle_stage variant -> skips cleanly with topology, | ||
| 287 | // never fails the command list (both without and with vk.compiles). | ||
| 288 | for (const bool with_compiles : {false, true}) { | ||
| 289 | Harness h; | ||
| 290 | h.pipeline.variant = [](std::uint32_t) { return VkPipeline(VK_NULL_HANDLE); }; | ||
| 291 | h.pipeline.built = [](std::uint32_t) { return VkPipeline(VK_NULL_HANDLE); }; | ||
| 292 | leonida::PipelineCompiles compiles; | ||
| 293 | if (with_compiles) h.vk.compiles = &compiles; | ||
| 294 | |||
| 295 | const auto before = leonida::indirect_stats::reason_skips(leonida::indirect_stats::topology); | ||
| 296 | const leonida::Draw d = make_base_draw(leonida::topology_rect_list, false); | ||
| 297 | leonida::IndirectDrawArgs arg{1, 0, 16, 2, 0, 0}; | ||
| 298 | CHECK(h.run_indirect(d, arg) == leonida::ReplayResult::success); | ||
| 299 | CHECK(h.draws.empty()); | ||
| 300 | CHECK(compiles.empty()); | ||
| 301 | CHECK(leonida::indirect_stats::reason_skips(leonida::indirect_stats::topology) == before + 1); | ||
| 302 | } | ||
| 303 | |||
| 304 | // 3. Direct RECTLIST when rectangle_stage variant cannot be built still returns unsupported (unchanged). | ||
| 305 | { | ||
| 306 | Harness h; | ||
| 307 | h.pipeline.variant = [](std::uint32_t) { return VkPipeline(VK_NULL_HANDLE); }; | ||
| 308 | leonida::CommandList list; | ||
| 309 | leonida::Draw d = make_base_draw(leonida::topology_rect_list, false); | ||
| 310 | d.count = 3; | ||
| 311 | d.instances = 1; | ||
| 312 | CHECK(list.draw(d) && list.close()); | ||
| 313 | const auto res = leonida::replay(list, VK_NULL_HANDLE, | ||
| 314 | [](leonida::ResourceId) -> const leonida::ResourceBinding* { return nullptr; }, | ||
| 315 | h.vk); | ||
| 316 | CHECK(res == leonida::ReplayResult::unsupported); | ||
| 317 | } | ||
| 318 | } | ||
| 319 | |||
| 320 | void test_unsupported_topologies_skip() { | ||
| 321 | Harness h; | ||
| 322 | constexpr std::uint32_t unsupported[] = {0, 6, 7, 9, 14, 18, leonida::topology_quad_list, 33, 64}; | ||
| 323 | for (const std::uint32_t topo : unsupported) { | ||
| 324 | const auto before = leonida::indirect_stats::reason_skips(leonida::indirect_stats::topology); | ||
| 325 | const leonida::Draw d = make_base_draw(topo, false); | ||
| 326 | leonida::IndirectDrawArgs arg{1, 0, 16, 1, 0, 0}; | ||
| 327 | CHECK(h.run_indirect(d, arg) == leonida::ReplayResult::success); | ||
| 328 | CHECK(h.draws.empty()); | ||
| 329 | CHECK(leonida::indirect_stats::reason_skips(leonida::indirect_stats::topology) == before + 1); | ||
| 330 | } | ||
| 331 | } | ||
| 332 | |||
| 333 | std::string capture_report(const leonida::indirect_stats::Counts& counts) { | ||
| 334 | std::FILE* f = std::tmpfile(); | ||
| 335 | CHECK(f != nullptr); | ||
| 336 | counts.report(f); | ||
| 337 | std::rewind(f); | ||
| 338 | char buf[1536]{}; | ||
| 339 | const std::size_t n = std::fread(buf, 1, sizeof(buf) - 1, f); | ||
| 340 | std::fclose(f); | ||
| 341 | return std::string(buf, n); | ||
| 342 | } | ||
| 343 | |||
| 344 | void test_counts_report_and_concurrency() { | ||
| 345 | using namespace leonida::indirect_stats; | ||
| 346 | |||
| 347 | // 1. Clean prefix with no bracketed breakdown when all per-reason counts are zero. | ||
| 348 | { | ||
| 349 | Counts c; | ||
| 350 | c.values[static_cast<unsigned>(Event::recorded)].store(16); | ||
| 351 | c.values[static_cast<unsigned>(Event::emitted)].store(15); | ||
| 352 | const std::string line = capture_report(c); | ||
| 353 | CHECK(line == "[rt] indirect graphics: recorded=16 emitted=15 record_skips=0 replay_skips=0\n"); | ||
| 354 | } | ||
| 355 | |||
| 356 | // 2. Non-zero per-reason counts appear in stable enum order inside [...]. | ||
| 357 | { | ||
| 358 | Counts c; | ||
| 359 | c.values[static_cast<unsigned>(Event::recorded)].store(4096); | ||
| 360 | c.values[static_cast<unsigned>(Event::emitted)].store(3918); | ||
| 361 | c.values[static_cast<unsigned>(Event::record_skip)].store(53405); | ||
| 362 | c.values[static_cast<unsigned>(Event::replay_skip)].store(7); | ||
| 363 | c.by_reason[compound].store(2); | ||
| 364 | c.by_reason[mesh].store(53000); | ||
| 365 | c.by_reason[topology].store(403); | ||
| 366 | c.by_reason[pending_pipeline].store(7); | ||
| 367 | const std::string line = capture_report(c); | ||
| 368 | CHECK(line == | ||
| 369 | "[rt] indirect graphics: recorded=4096 emitted=3918 record_skips=53405 replay_skips=7 " | ||
| 370 | "[compound=2, mesh=53000, topology=403, pending_pipeline=7]\n"); | ||
| 371 | } | ||
| 372 | |||
| 373 | // 3. Out-of-range reason is ignored safely without corrupting counts. | ||
| 374 | { | ||
| 375 | const auto before_total = counts().values[static_cast<unsigned>(Event::record_skip)].load(); | ||
| 376 | skip(Event::record_skip, reason_count); | ||
| 377 | CHECK(counts().values[static_cast<unsigned>(Event::record_skip)].load() == before_total); | ||
| 378 | CHECK(reason_skips(reason_count) == 0); | ||
| 379 | } | ||
| 380 | |||
| 381 | // 4. Multi-threaded skip increments are race-free and exact. | ||
| 382 | { | ||
| 383 | const auto mesh_before = reason_skips(mesh); | ||
| 384 | const auto div_before = reason_skips(divisor); | ||
| 385 | std::vector<std::thread> threads; | ||
| 386 | for (int t = 0; t < 4; ++t) { | ||
| 387 | threads.emplace_back([t] { | ||
| 388 | for (int i = 0; i < 250; ++i) { | ||
| 389 | skip(Event::record_skip, (t % 2 == 0) ? mesh : divisor); | ||
| 390 | } | ||
| 391 | }); | ||
| 392 | } | ||
| 393 | for (auto& th : threads) th.join(); | ||
| 394 | CHECK(reason_skips(mesh) == mesh_before + 500); | ||
| 395 | CHECK(reason_skips(divisor) == div_before + 500); | ||
| 396 | } | ||
| 397 | } | ||
| 398 | |||
| 399 | } // namespace | ||
| 400 | |||
| 401 | int main() { | ||
| 402 | test_topology_predicate(); | ||
| 403 | test_supported_topologies_emit(); | ||
| 404 | test_rect_list_builtin_and_fallback(); | ||
| 405 | test_unsupported_topologies_skip(); | ||
| 406 | test_counts_report_and_concurrency(); | ||
| 407 | std::printf("indirect_topology_and_stats_test: PASS\n"); | ||
| 408 | return 0; | ||
| 409 | } | ||
diff --git a/runtime/test/int3_skip_test.cpp b/runtime/test/int3_skip_test.cpp index 3c06302eb..9fa05386e 100644 --- a/runtime/test/int3_skip_test.cpp +++ b/runtime/test/int3_skip_test.cpp | |||
| @@ -1,9 +1,21 @@ | |||
| 1 | // LEONIDA_SKIP_INT3 (shims/startup_trace.h): with the variable set and a trace open, an int3 is logged once per | 1 | // LEONIDA_SKIP_INT3 (shims/startup_trace.h): with the variable set and a trace open, an int3 is logged once per |
| 2 | // address and stepped over, so execution continues. A separate executable because the variable is read once. | 2 | // address and stepped over, so execution continues. |
| 3 | // | ||
| 4 | // Each case runs in a child process of its own (`int3_skip_test --case NAME`), so a case that crashes fails alone and | ||
| 5 | // each one opens the trace with its own environment: | ||
| 6 | // real a real int3 at two sites, one of them hit twice: execution continues, one event per address | ||
| 7 | // windows a synthetic breakpoint with Rip on the 0xCC (Windows): Rip ends one past it, one event | ||
| 8 | // wine Rip one byte past the 0xCC (Wine, old upstream 7599): the same result | ||
| 9 | // null null EXCEPTION_POINTERS, ExceptionRecord or ContextRecord: no skip and no crash | ||
| 10 | // init the variable is read when the trace opens: removed after open(), int3s are still skipped | ||
| 11 | // off without the variable, nothing is skipped | ||
| 3 | #include <windows.h> | 12 | #include <windows.h> |
| 4 | 13 | ||
| 5 | #include <cstdio> | 14 | #include <cstdio> |
| 15 | #include <cstring> | ||
| 16 | #include <filesystem> | ||
| 6 | #include <fstream> | 17 | #include <fstream> |
| 18 | #include <memory> | ||
| 7 | #include <sstream> | 19 | #include <sstream> |
| 8 | #include <string> | 20 | #include <string> |
| 9 | 21 | ||
| @@ -35,31 +47,195 @@ __declspec(noinline) void site_b(int& reached) { | |||
| 35 | ++reached; | 47 | ++reached; |
| 36 | } | 48 | } |
| 37 | 49 | ||
| 38 | } // namespace | 50 | // A trace file of this process; the text is read back after close(). |
| 51 | struct Trace { | ||
| 52 | std::wstring path; | ||
| 53 | Trace() { | ||
| 54 | wchar_t temp[MAX_PATH]; | ||
| 55 | GetTempPathW(MAX_PATH, temp); | ||
| 56 | path = std::wstring(temp) + L"int3_skip_test_" + std::to_wstring(GetCurrentProcessId()) + L".jsonl"; | ||
| 57 | DeleteFileW(path.c_str()); | ||
| 58 | check(rt::startup_trace::open(path.c_str()), "open the startup trace file"); | ||
| 59 | } | ||
| 60 | std::string close_and_read() { | ||
| 61 | rt::startup_trace::close(); | ||
| 62 | std::string log; | ||
| 63 | { | ||
| 64 | std::ifstream in{std::filesystem::path(path)}; | ||
| 65 | std::stringstream text; | ||
| 66 | text << in.rdbuf(); | ||
| 67 | log = text.str(); | ||
| 68 | } | ||
| 69 | DeleteFileW(path.c_str()); | ||
| 70 | return log; | ||
| 71 | } | ||
| 72 | }; | ||
| 73 | |||
| 74 | // A synthetic EXCEPTION_BREAKPOINT for skip_int3, as the vectored handler receives it. | ||
| 75 | struct Breakpoint { | ||
| 76 | EXCEPTION_RECORD record{}; | ||
| 77 | std::unique_ptr<CONTEXT> context = std::make_unique<CONTEXT>(); // heap: a 16-byte-aligned member pads the struct | ||
| 78 | EXCEPTION_POINTERS pointers{}; | ||
| 79 | Breakpoint(const unsigned char* address, const unsigned char* rip) { | ||
| 80 | record.ExceptionCode = EXCEPTION_BREAKPOINT; | ||
| 81 | record.ExceptionAddress = const_cast<unsigned char*>(address); | ||
| 82 | record.NumberParameters = 1; | ||
| 83 | context->ContextFlags = CONTEXT_CONTROL; | ||
| 84 | context->Rip = reinterpret_cast<DWORD64>(rip); | ||
| 85 | pointers.ExceptionRecord = &record; | ||
| 86 | pointers.ContextRecord = context.get(); | ||
| 87 | } | ||
| 88 | bool skip() { return rt::startup_trace::detail::skip_int3(&pointers); } | ||
| 89 | bool rip_is(const unsigned char* p) const { return context->Rip == reinterpret_cast<DWORD64>(p); } | ||
| 90 | }; | ||
| 91 | |||
| 92 | // nop, int3, nop: the int3 at code + 1, with a byte on each side that is not one. | ||
| 93 | alignas(16) unsigned char g_code[4] = {0x90, 0xCC, 0x90, 0x90}; | ||
| 39 | 94 | ||
| 40 | int main() { | 95 | std::string event_at(const unsigned char* at) { |
| 41 | SetEnvironmentVariableW(L"LEONIDA_SKIP_INT3", L"1"); // before the first exception: the flag is read once | 96 | const std::string where = rt::startup_trace::where(reinterpret_cast<uint64_t>(at)); |
| 42 | wchar_t temp[MAX_PATH]; | 97 | return "\"kind\":\"int3_skipped\",\"at\":" + rt::startup_trace::quote(where); |
| 43 | GetTempPathW(MAX_PATH, temp); | 98 | } |
| 44 | const std::wstring path = std::wstring(temp) + L"int3_skip_test_" + std::to_wstring(GetCurrentProcessId()) + L".jsonl"; | ||
| 45 | DeleteFileW(path.c_str()); | ||
| 46 | check(rt::startup_trace::open(path.c_str()), "open the startup trace file"); | ||
| 47 | 99 | ||
| 100 | void case_real() { | ||
| 101 | SetEnvironmentVariableW(L"LEONIDA_SKIP_INT3", L"1"); | ||
| 102 | Trace trace; | ||
| 48 | int reached = 0; | 103 | int reached = 0; |
| 49 | for (int i = 0; i < 2; ++i) site_a(reached); // the same site twice: one event | 104 | for (int i = 0; i < 2; ++i) site_a(reached); // the same site twice: one event |
| 50 | site_b(reached); // another site | 105 | site_b(reached); // another site |
| 51 | check(reached == 3, "execution continues past every int3"); | 106 | check(reached == 3, "execution continues past every int3"); |
| 52 | rt::startup_trace::close(); | 107 | const std::string log = trace.close_and_read(); |
| 53 | |||
| 54 | std::ifstream in(path); | ||
| 55 | std::stringstream text; | ||
| 56 | text << in.rdbuf(); | ||
| 57 | const std::string log = text.str(); | ||
| 58 | in.close(); | ||
| 59 | DeleteFileW(path.c_str()); | ||
| 60 | check(count(log, "\"kind\":\"int3_skipped\"") == 2, "exactly two int3_skipped events (one per address)"); | 108 | check(count(log, "\"kind\":\"int3_skipped\"") == 2, "exactly two int3_skipped events (one per address)"); |
| 61 | check(count(log, "\"kind\":\"exception\"") == 0, "a skipped int3 is not also logged as an exception"); | 109 | check(count(log, "\"kind\":\"exception\"") == 0, "a skipped int3 is not also logged as an exception"); |
| 62 | check(log.find("\"at\":\"host:") != std::string::npos, "the event names the address"); | 110 | check(log.find("\"at\":\"host:") != std::string::npos, "the event names the address"); |
| 111 | } | ||
| 112 | |||
| 113 | void case_windows() { | ||
| 114 | SetEnvironmentVariableW(L"LEONIDA_SKIP_INT3", L"1"); | ||
| 115 | Trace trace; | ||
| 116 | const unsigned char* at = g_code + 1; | ||
| 117 | Breakpoint first(at, at); | ||
| 118 | check(first.skip(), "Rip on the 0xCC: skipped"); | ||
| 119 | check(first.rip_is(at + 1), "Rip on the 0xCC: Rip ends one byte past it"); | ||
| 120 | Breakpoint again(at, at); | ||
| 121 | check(again.skip() && again.rip_is(at + 1), "the same site again: skipped the same way"); | ||
| 122 | Breakpoint no_int3(g_code + 3, g_code + 3); | ||
| 123 | check(!no_int3.skip() && no_int3.rip_is(g_code + 3), "no 0xCC at or before Rip: not skipped, Rip unchanged"); | ||
| 124 | Breakpoint elsewhere(g_code, at); | ||
| 125 | check(!elsewhere.skip() && elsewhere.rip_is(at), "ExceptionAddress not at the int3 or past it: not skipped"); | ||
| 126 | const std::string log = trace.close_and_read(); | ||
| 127 | check(count(log, "\"kind\":\"int3_skipped\"") == 1, "one int3_skipped event for the site"); | ||
| 128 | check(log.find(event_at(at)) != std::string::npos, "the event names the 0xCC byte"); | ||
| 129 | } | ||
| 130 | |||
| 131 | void case_wine() { | ||
| 132 | SetEnvironmentVariableW(L"LEONIDA_SKIP_INT3", L"1"); | ||
| 133 | Trace trace; | ||
| 134 | const unsigned char* at = g_code + 1; | ||
| 135 | Breakpoint past(at + 1, at + 1); // ExceptionAddress and Rip one byte past the 0xCC | ||
| 136 | check(past.skip(), "Rip one byte past the 0xCC: skipped"); | ||
| 137 | check(past.rip_is(at + 1), "Rip one byte past the 0xCC: Rip ends one byte past it"); | ||
| 138 | Breakpoint mixed(at, at + 1); // ExceptionAddress on the 0xCC, Rip past it | ||
| 139 | check(mixed.skip() && mixed.rip_is(at + 1), "ExceptionAddress on the 0xCC, Rip past it: skipped"); | ||
| 140 | const std::string log = trace.close_and_read(); | ||
| 141 | check(count(log, "\"kind\":\"int3_skipped\"") == 1, "one int3_skipped event for the site"); | ||
| 142 | check(log.find(event_at(at)) != std::string::npos, "the event names the 0xCC byte, not the byte after it"); | ||
| 143 | } | ||
| 144 | |||
| 145 | // nop, int3, int3, nop: a run of int3 padding. | ||
| 146 | alignas(16) unsigned char g_padding[4] = {0x90, 0xCC, 0xCC, 0x90}; | ||
| 147 | |||
| 148 | void case_padding() { | ||
| 149 | SetEnvironmentVariableW(L"LEONIDA_SKIP_INT3", L"1"); | ||
| 150 | Trace trace; | ||
| 151 | const unsigned char* at = g_padding + 1; | ||
| 152 | Breakpoint mixed(at, at + 1); // ExceptionAddress on the first 0xCC, Rip on the second | ||
| 153 | check(mixed.skip() && mixed.rip_is(at + 1), | ||
| 154 | "ExceptionAddress on an int3 followed by another, Rip past it: the int3 ExceptionAddress names is skipped"); | ||
| 155 | const std::string log = trace.close_and_read(); | ||
| 156 | check(count(log, "\"kind\":\"int3_skipped\"") == 1, "one int3_skipped event"); | ||
| 157 | check(log.find(event_at(at)) != std::string::npos, "the event names the int3 ExceptionAddress names"); | ||
| 158 | } | ||
| 159 | |||
| 160 | void case_null() { | ||
| 161 | SetEnvironmentVariableW(L"LEONIDA_SKIP_INT3", L"1"); | ||
| 162 | Trace trace; | ||
| 163 | check(!rt::startup_trace::detail::skip_int3(nullptr), "null EXCEPTION_POINTERS: not skipped"); | ||
| 164 | Breakpoint no_record(g_code + 1, g_code + 1); | ||
| 165 | no_record.pointers.ExceptionRecord = nullptr; | ||
| 166 | check(!no_record.skip() && no_record.rip_is(g_code + 1), "null ExceptionRecord: not skipped"); | ||
| 167 | Breakpoint no_context(g_code + 1, g_code + 1); | ||
| 168 | no_context.pointers.ContextRecord = nullptr; | ||
| 169 | check(!no_context.skip(), "null ContextRecord: not skipped"); | ||
| 170 | const std::string log = trace.close_and_read(); | ||
| 171 | check(count(log, "\"kind\":\"int3_skipped\"") == 0, "no int3_skipped event"); | ||
| 172 | } | ||
| 173 | |||
| 174 | void case_init() { | ||
| 175 | SetEnvironmentVariableW(L"LEONIDA_SKIP_INT3", L"1"); | ||
| 176 | Trace trace; | ||
| 177 | SetEnvironmentVariableW(L"LEONIDA_SKIP_INT3", nullptr); // read when the trace opened, not at the first int3 | ||
| 178 | check(rt::startup_trace::detail::skip_int3_on.load(), "the flag holds the value read when the trace opened"); | ||
| 179 | Breakpoint bp(g_code + 1, g_code + 1); | ||
| 180 | check(bp.skip() && bp.rip_is(g_code + 2), "an int3 after the variable is removed is still skipped"); | ||
| 181 | trace.close_and_read(); | ||
| 182 | } | ||
| 183 | |||
| 184 | void case_off() { | ||
| 185 | SetEnvironmentVariableW(L"LEONIDA_SKIP_INT3", nullptr); | ||
| 186 | Trace trace; | ||
| 187 | check(!rt::startup_trace::detail::skip_int3_on.load(), "without the variable the flag is off"); | ||
| 188 | Breakpoint bp(g_code + 1, g_code + 1); | ||
| 189 | check(!bp.skip() && bp.rip_is(g_code + 1), "without the variable an int3 is not skipped"); | ||
| 190 | trace.close_and_read(); | ||
| 191 | } | ||
| 192 | |||
| 193 | struct Case { | ||
| 194 | const char* name; | ||
| 195 | void (*run)(); | ||
| 196 | }; | ||
| 197 | constexpr Case kCases[] = {{"real", case_real}, {"windows", case_windows}, {"wine", case_wine}, | ||
| 198 | {"padding", case_padding}, {"null", case_null}, {"init", case_init}, | ||
| 199 | {"off", case_off}}; | ||
| 200 | |||
| 201 | // Runs `this-exe --case NAME` and returns its exit code. | ||
| 202 | DWORD run_child(const char* name) { | ||
| 203 | wchar_t exe[MAX_PATH]; | ||
| 204 | GetModuleFileNameW(nullptr, exe, MAX_PATH); | ||
| 205 | std::wstring command = L"\"" + std::wstring(exe) + L"\" --case "; | ||
| 206 | for (const char* c = name; *c; ++c) command += static_cast<wchar_t>(*c); | ||
| 207 | STARTUPINFOW si{}; | ||
| 208 | si.cb = sizeof si; | ||
| 209 | PROCESS_INFORMATION pi{}; | ||
| 210 | if (!CreateProcessW(exe, command.data(), nullptr, nullptr, FALSE, 0, nullptr, nullptr, &si, &pi)) return 0xFFFFFFFF; | ||
| 211 | WaitForSingleObject(pi.hProcess, INFINITE); | ||
| 212 | DWORD code = 0xFFFFFFFF; | ||
| 213 | GetExitCodeProcess(pi.hProcess, &code); | ||
| 214 | CloseHandle(pi.hThread); | ||
| 215 | CloseHandle(pi.hProcess); | ||
| 216 | return code; | ||
| 217 | } | ||
| 218 | |||
| 219 | } // namespace | ||
| 220 | |||
| 221 | int main(int argc, char** argv) { | ||
| 222 | if (argc == 3 && std::strcmp(argv[1], "--case") == 0) { | ||
| 223 | for (const Case& c : kCases) | ||
| 224 | if (std::strcmp(argv[2], c.name) == 0) { | ||
| 225 | c.run(); | ||
| 226 | std::fflush(stdout); | ||
| 227 | return g_failed ? 1 : 0; | ||
| 228 | } | ||
| 229 | std::printf("unknown case %s\n", argv[2]); | ||
| 230 | return 2; | ||
| 231 | } | ||
| 232 | for (const Case& c : kCases) { | ||
| 233 | std::printf("-- %s\n", c.name); | ||
| 234 | std::fflush(stdout); | ||
| 235 | const DWORD code = run_child(c.name); | ||
| 236 | if (code != 0) std::printf("FAIL case %s exited with 0x%08lx\n", c.name, static_cast<unsigned long>(code)); | ||
| 237 | if (code != 0) ++g_failed; | ||
| 238 | } | ||
| 63 | std::printf("%s\n", g_failed ? "FAILED" : "all checks passed"); | 239 | std::printf("%s\n", g_failed ? "FAILED" : "all checks passed"); |
| 64 | return g_failed ? 1 : 0; | 240 | return g_failed ? 1 : 0; |
| 65 | } | 241 | } |
diff --git a/runtime/test/keyboard_pad_retry_test.cpp b/runtime/test/keyboard_pad_retry_test.cpp new file mode 100644 index 000000000..6c4e41757 --- /dev/null +++ b/runtime/test/keyboard_pad_retry_test.cpp | |||
| @@ -0,0 +1,137 @@ | |||
| 1 | // No SDL, Windows, window, input sampling or worker. The shim instantiates this exact lifecycle with its SDL backend. | ||
| 2 | #include "../shims/keyboard_pad_connection.h" | ||
| 3 | |||
| 4 | #include <cstdio> | ||
| 5 | #include <cstdlib> | ||
| 6 | #include <limits> | ||
| 7 | #include <string> | ||
| 8 | |||
| 9 | #define CHECK(x) do { if (!(x)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #x); std::exit(1); } } while (0) | ||
| 10 | |||
| 11 | namespace { | ||
| 12 | using Connection = rt::gameinput::detail::KeyboardPadConnection<int, int>; | ||
| 13 | |||
| 14 | struct Fake { | ||
| 15 | std::uint64_t clock = 0; | ||
| 16 | unsigned clock_reads = 0; | ||
| 17 | int live = 0, handle = 0, serial = 0; | ||
| 18 | bool attach_ok = true, open_ok = true, detach_ok = true; | ||
| 19 | std::string events; | ||
| 20 | |||
| 21 | std::uint64_t now() { ++clock_reads; return clock; } | ||
| 22 | int attach() { | ||
| 23 | CHECK(!live && !handle); // never leak or create two virtual devices | ||
| 24 | events += 'A'; | ||
| 25 | return attach_ok ? (live = ++serial) : 0; | ||
| 26 | } | ||
| 27 | int open(int id) { | ||
| 28 | CHECK(id && id == live && !handle); | ||
| 29 | events += 'O'; | ||
| 30 | return open_ok ? (handle = live + 10) : 0; | ||
| 31 | } | ||
| 32 | void close(int js) { | ||
| 33 | CHECK(js && js == handle); | ||
| 34 | events += 'C'; | ||
| 35 | handle = 0; | ||
| 36 | } | ||
| 37 | bool detach(int id) { | ||
| 38 | CHECK(id && id == serial && !handle); | ||
| 39 | events += 'D'; | ||
| 40 | if (id != live) return false; // SDL returns false for an already-removed device | ||
| 41 | if (detach_ok) live = 0; | ||
| 42 | return detach_ok; | ||
| 43 | } | ||
| 44 | bool is_virtual(int id) const { return id != 0 && id == live; } | ||
| 45 | void failed() { events += '!'; } | ||
| 46 | void attached() { CHECK(handle); events += '+'; } | ||
| 47 | void removed() { CHECK(!live && !handle); events += '-'; } | ||
| 48 | }; | ||
| 49 | |||
| 50 | void throttled_recovery() { | ||
| 51 | Connection pad; | ||
| 52 | Fake b; | ||
| 53 | b.attach_ok = false; | ||
| 54 | CHECK(!pad.update(false, b) && b.events.empty() && !b.clock_reads); | ||
| 55 | CHECK(!pad.update(true, b) && b.events == "A!"); // first failure, including at clock zero | ||
| 56 | for (b.clock = 2'000; b.clock < 1'000'000; b.clock += 2'000) CHECK(!pad.update(true, b)); | ||
| 57 | b.clock = 999'999; | ||
| 58 | CHECK(!pad.update(true, b) && b.events == "A!"); | ||
| 59 | ++b.clock; | ||
| 60 | CHECK(!pad.update(true, b) && b.events == "A!A"); // no extra warning | ||
| 61 | b.clock += 8'500'000; | ||
| 62 | CHECK(!pad.update(true, b) && b.events == "A!AA"); // one attempt, no catch-up loop | ||
| 63 | b.attach_ok = true; | ||
| 64 | b.clock += 999'999; | ||
| 65 | CHECK(!pad.update(true, b)); | ||
| 66 | ++b.clock; | ||
| 67 | CHECK(pad.update(true, b) && b.events == "A!AAAO+"); | ||
| 68 | CHECK(pad.id == b.live && pad.js == b.handle); | ||
| 69 | const unsigned previous = b.clock_reads; | ||
| 70 | for (int n = 0; n < 500; ++n) CHECK(pad.update(true, b)); | ||
| 71 | CHECK(b.events == "A!AAAO+" && previous == b.clock_reads); // hot path does not even read the retry clock | ||
| 72 | CHECK(!pad.update(false, b) && b.events == "A!AAAO+CD-" && !pad.id && !pad.js); | ||
| 73 | CHECK(!pad.update(false, b) && b.events == "A!AAAO+CD-"); | ||
| 74 | b.attach_ok = false; | ||
| 75 | CHECK(!pad.update(true, b) && b.events == "A!AAAO+CD-A!"); // new outage reports once | ||
| 76 | CHECK(!pad.update(false, b)); | ||
| 77 | b.attach_ok = true; | ||
| 78 | CHECK(pad.update(true, b) && b.events == "A!AAAO+CD-A!AO+"); // no old cooldown after off | ||
| 79 | } | ||
| 80 | |||
| 81 | void partial_open_and_cleanup() { | ||
| 82 | Connection pad; | ||
| 83 | Fake b; | ||
| 84 | b.open_ok = false; | ||
| 85 | CHECK(!pad.update(true, b) && b.events == "AO!D" && !pad.id && !pad.js); | ||
| 86 | b.clock += 1'000'000; | ||
| 87 | b.detach_ok = false; | ||
| 88 | CHECK(!pad.update(true, b) && b.events == "AO!DAOD"); | ||
| 89 | CHECK(pad.id == b.live && !pad.js); | ||
| 90 | b.clock += 1'000'000; | ||
| 91 | CHECK(!pad.update(true, b) && b.events == "AO!DAODD"); // no new attach while old ID is owned | ||
| 92 | b.open_ok = b.detach_ok = true; | ||
| 93 | b.clock += 1'000'000; | ||
| 94 | CHECK(pad.update(true, b) && b.events == "AO!DAODDDAO+"); | ||
| 95 | b.events.clear(); | ||
| 96 | b.detach_ok = false; | ||
| 97 | CHECK(!pad.update(false, b) && b.events == "CD" && !pad.js && pad.id); | ||
| 98 | CHECK(!pad.update(false, b) && b.events == "CD"); // no second close/removal or per-poll detach | ||
| 99 | b.clock += 1'000'000; | ||
| 100 | CHECK(!pad.update(false, b) && b.events == "CDD"); | ||
| 101 | b.detach_ok = true; | ||
| 102 | CHECK(pad.update(true, b) && b.events == "CDDD-AO+"); // finish real removal before reattaching | ||
| 103 | CHECK(!pad.update(false, b) && b.events == "CDDD-AO+CD-"); | ||
| 104 | } | ||
| 105 | |||
| 106 | void elapsed_clock_rollover() { | ||
| 107 | Connection pad; | ||
| 108 | Fake b; | ||
| 109 | b.clock = std::numeric_limits<std::uint64_t>::max() - 9; | ||
| 110 | b.attach_ok = false; | ||
| 111 | CHECK(!pad.update(true, b)); | ||
| 112 | b.clock += 999'999; | ||
| 113 | b.attach_ok = true; | ||
| 114 | CHECK(!pad.update(true, b) && b.events == "A!"); | ||
| 115 | ++b.clock; | ||
| 116 | CHECK(pad.update(true, b) && b.events == "A!AO+"); | ||
| 117 | } | ||
| 118 | |||
| 119 | void already_removed_during_cleanup() { | ||
| 120 | Connection pad; | ||
| 121 | Fake b; | ||
| 122 | b.open_ok = b.detach_ok = false; | ||
| 123 | CHECK(!pad.update(true, b) && b.events == "AO!D" && pad.id == b.live && !pad.js); | ||
| 124 | b.live = 0; // SDL no longer owns this virtual ID when cleanup retries | ||
| 125 | b.clock += 1'000'000; | ||
| 126 | b.open_ok = b.detach_ok = true; | ||
| 127 | CHECK(pad.update(true, b) && b.events == "AO!DDAO+" && pad.id == 2); | ||
| 128 | } | ||
| 129 | } // namespace | ||
| 130 | |||
| 131 | int main() { | ||
| 132 | throttled_recovery(); | ||
| 133 | partial_open_and_cleanup(); | ||
| 134 | elapsed_clock_rollover(); | ||
| 135 | already_removed_during_cleanup(); | ||
| 136 | std::puts("keyboard pad retry: cadence, recovery, partial ownership, off/re-enable and rollover passed"); | ||
| 137 | } | ||
diff --git a/runtime/test/large_module_gate.h b/runtime/test/large_module_gate.h index ea805c926..fcd29ed0e 100644 --- a/runtime/test/large_module_gate.h +++ b/runtime/test/large_module_gate.h | |||
| @@ -1,181 +1,4 @@ | |||
| 1 | // How many large SPIR-V modules vk_pipeline_check lets into the driver at once, by a memory budget. | 1 | // Moved to runtime/src: the runtime uses it too (large_module_gate.h there). |
| 2 | // | ||
| 3 | // Measured on RADV GFX1201 (Mesa 25.3.6) with the Mesa shader cache off: a 5.7 MB translated ray-tracing compute | ||
| 4 | // module peaks at 1.96 GB of process memory compiling alone (~330 bytes per SPIR-V byte), a 0.36 MB one at 94 MB. | ||
| 5 | // Compiling the large ones strictly one at a time left the other threads idle: 40 modules (27 over 4 MiB) on 6 | ||
| 6 | // threads took 308 s exclusively and 75 s in parallel, 7.0 GB and 8.7 GB peak. kBytesPerSpirvByte keeps a margin | ||
| 7 | // over the measurement. | ||
| 8 | // | ||
| 9 | // The process grew past one module's peak even one at a time because glibc keeps freed memory in per-thread arenas | ||
| 10 | // (6 threads: 6.2 GB; MALLOC_ARENA_MAX=1: 2.1 GB, same modules). release_free_memory() hands it back after each | ||
| 11 | // large module. | ||
| 12 | #pragma once | 2 | #pragma once |
| 13 | 3 | ||
| 14 | #include <algorithm> | 4 | #include "../src/large_module_gate.h" |
| 15 | #include <condition_variable> | ||
| 16 | #include <cstdint> | ||
| 17 | #include <cstdio> | ||
| 18 | #include <mutex> | ||
| 19 | #include <string> | ||
| 20 | |||
| 21 | #ifdef _WIN32 | ||
| 22 | #ifndef NOMINMAX | ||
| 23 | #define NOMINMAX | ||
| 24 | #endif | ||
| 25 | #include <windows.h> | ||
| 26 | #endif | ||
| 27 | #if defined(__GLIBC__) | ||
| 28 | #include <malloc.h> | ||
| 29 | #endif | ||
| 30 | |||
| 31 | namespace leonida { | ||
| 32 | |||
| 33 | inline constexpr uint64_t kBytesPerSpirvByte = 512; | ||
| 34 | |||
| 35 | inline uint64_t large_module_estimate(uint64_t spirv_bytes) { return spirv_bytes * kBytesPerSpirvByte; } | ||
| 36 | |||
| 37 | #if defined(__linux__) | ||
| 38 | // The first unsigned number in a file ("max" and unreadable files give no value). | ||
| 39 | inline bool read_u64_file(const std::string& path, uint64_t& value) { | ||
| 40 | std::FILE* f = std::fopen(path.c_str(), "r"); | ||
| 41 | if (!f) return false; | ||
| 42 | unsigned long long v = 0; | ||
| 43 | const bool ok = std::fscanf(f, "%llu", &v) == 1; | ||
| 44 | std::fclose(f); | ||
| 45 | value = v; | ||
| 46 | return ok; | ||
| 47 | } | ||
| 48 | |||
| 49 | // The room left under the cgroup v2 memory.max of this process and of every cgroup above it (a container or | ||
| 50 | // systemd-run -p MemoryMax=...), or UINT64_MAX when none sets a limit. cgroup_root is a parameter for the tests. | ||
| 51 | inline uint64_t cgroup_memory_room(const std::string& self_cgroup_file = "/proc/self/cgroup", | ||
| 52 | const std::string& cgroup_root = "/sys/fs/cgroup") { | ||
| 53 | std::FILE* f = std::fopen(self_cgroup_file.c_str(), "r"); | ||
| 54 | if (!f) return UINT64_MAX; | ||
| 55 | char line[4096]; | ||
| 56 | std::string rel; | ||
| 57 | while (std::fgets(line, sizeof(line), f)) { | ||
| 58 | std::string l(line); | ||
| 59 | if (l.rfind("0::", 0) == 0) { // the cgroup v2 line | ||
| 60 | rel = l.substr(3); | ||
| 61 | while (!rel.empty() && (rel.back() == '\n' || rel.back() == '\r')) rel.pop_back(); | ||
| 62 | break; | ||
| 63 | } | ||
| 64 | } | ||
| 65 | std::fclose(f); | ||
| 66 | uint64_t room = UINT64_MAX; | ||
| 67 | for (std::string dir = rel; !dir.empty();) { | ||
| 68 | // In a cgroup namespace, "/" can be a constrained cgroup mounted as the visible root. | ||
| 69 | const std::string base = dir == "/" ? cgroup_root : cgroup_root + dir; | ||
| 70 | uint64_t max = 0, current = 0; | ||
| 71 | if (read_u64_file(base + "/memory.max", max) && read_u64_file(base + "/memory.current", current)) | ||
| 72 | room = std::min(room, max > current ? max - current : 0); | ||
| 73 | const auto slash = dir.find_last_of('/'); | ||
| 74 | if (dir == "/" || slash == std::string::npos) break; | ||
| 75 | dir.resize(slash == 0 ? 1 : slash); | ||
| 76 | } | ||
| 77 | return room; | ||
| 78 | } | ||
| 79 | #endif | ||
| 80 | |||
| 81 | // Memory the OS could give this process now, or 0 when it can't tell (then the caller keeps the old exclusive gate). | ||
| 82 | inline uint64_t available_memory_bytes() { | ||
| 83 | #ifdef _WIN32 | ||
| 84 | MEMORYSTATUSEX status{}; | ||
| 85 | status.dwLength = sizeof(status); | ||
| 86 | return GlobalMemoryStatusEx(&status) ? uint64_t(status.ullAvailPhys) : 0; | ||
| 87 | #elif defined(__linux__) | ||
| 88 | std::FILE* f = std::fopen("/proc/meminfo", "r"); | ||
| 89 | if (!f) return 0; | ||
| 90 | char line[256]; | ||
| 91 | unsigned long long kb = 0; | ||
| 92 | bool found = false; | ||
| 93 | while (std::fgets(line, sizeof(line), f)) | ||
| 94 | if (std::sscanf(line, "MemAvailable: %llu kB", &kb) == 1) { found = true; break; } | ||
| 95 | std::fclose(f); | ||
| 96 | if (!found) return 0; | ||
| 97 | const uint64_t room = cgroup_memory_room(); | ||
| 98 | return std::max<uint64_t>(1, std::min(uint64_t(kb) * 1024, room)); // 0 would mean "unknown" | ||
| 99 | #else | ||
| 100 | return 0; | ||
| 101 | #endif | ||
| 102 | } | ||
| 103 | |||
| 104 | // Return memory freed by the driver's compiler to the OS (glibc keeps it in the arena of the thread that freed it). | ||
| 105 | inline void release_free_memory() { | ||
| 106 | #if defined(__GLIBC__) | ||
| 107 | malloc_trim(0); | ||
| 108 | #endif | ||
| 109 | } | ||
| 110 | |||
| 111 | // Lets large modules in while their estimates fit the budget and fewer than max_inflight are in. One always gets in | ||
| 112 | // when none is, so a module bigger than the whole budget still compiles (alone among the large ones). | ||
| 113 | class LargeModuleGate { | ||
| 114 | public: | ||
| 115 | LargeModuleGate(uint64_t budget, unsigned max_inflight) | ||
| 116 | : budget_(budget), max_inflight_(max_inflight ? max_inflight : 1) {} | ||
| 117 | |||
| 118 | bool admits(uint64_t estimate) const { | ||
| 119 | std::lock_guard<std::mutex> g(mu_); | ||
| 120 | return admits_locked(estimate); | ||
| 121 | } | ||
| 122 | void enter(uint64_t estimate) { | ||
| 123 | std::unique_lock<std::mutex> l(mu_); | ||
| 124 | cv_.wait(l, [&] { return admits_locked(estimate); }); | ||
| 125 | used_ += estimate; | ||
| 126 | ++inflight_; | ||
| 127 | } | ||
| 128 | void leave(uint64_t estimate) { | ||
| 129 | { | ||
| 130 | std::lock_guard<std::mutex> g(mu_); | ||
| 131 | used_ -= estimate; | ||
| 132 | --inflight_; | ||
| 133 | } | ||
| 134 | cv_.notify_all(); | ||
| 135 | } | ||
| 136 | unsigned inflight() const { | ||
| 137 | std::lock_guard<std::mutex> g(mu_); | ||
| 138 | return inflight_; | ||
| 139 | } | ||
| 140 | uint64_t budget() const { return budget_; } | ||
| 141 | unsigned max_inflight() const { return max_inflight_; } | ||
| 142 | |||
| 143 | // Holds a place from construction until destruction (or release()), then hands freed memory back. | ||
| 144 | class Ticket { | ||
| 145 | public: | ||
| 146 | Ticket() = default; | ||
| 147 | Ticket(LargeModuleGate& gate, uint64_t estimate) : gate_(&gate), estimate_(estimate) { gate.enter(estimate); } | ||
| 148 | Ticket(Ticket&& o) noexcept : gate_(o.gate_), estimate_(o.estimate_) { o.gate_ = nullptr; } | ||
| 149 | Ticket& operator=(Ticket&& o) noexcept { | ||
| 150 | if (this != &o) { release(); gate_ = o.gate_; estimate_ = o.estimate_; o.gate_ = nullptr; } | ||
| 151 | return *this; | ||
| 152 | } | ||
| 153 | Ticket(const Ticket&) = delete; | ||
| 154 | Ticket& operator=(const Ticket&) = delete; | ||
| 155 | ~Ticket() { release(); } | ||
| 156 | void release() { | ||
| 157 | if (!gate_) return; | ||
| 158 | gate_->leave(estimate_); | ||
| 159 | gate_ = nullptr; | ||
| 160 | release_free_memory(); | ||
| 161 | } | ||
| 162 | private: | ||
| 163 | LargeModuleGate* gate_ = nullptr; | ||
| 164 | uint64_t estimate_ = 0; | ||
| 165 | }; | ||
| 166 | |||
| 167 | private: | ||
| 168 | bool admits_locked(uint64_t estimate) const { | ||
| 169 | if (inflight_ == 0) return true; | ||
| 170 | return inflight_ < max_inflight_ && used_ + estimate <= budget_; | ||
| 171 | } | ||
| 172 | |||
| 173 | const uint64_t budget_; | ||
| 174 | const unsigned max_inflight_; | ||
| 175 | mutable std::mutex mu_; | ||
| 176 | std::condition_variable cv_; | ||
| 177 | uint64_t used_ = 0; | ||
| 178 | unsigned inflight_ = 0; | ||
| 179 | }; | ||
| 180 | |||
| 181 | } // namespace leonida | ||
diff --git a/runtime/test/loader_test.cpp b/runtime/test/loader_test.cpp index d985ba423..6930878a9 100644 --- a/runtime/test/loader_test.cpp +++ b/runtime/test/loader_test.cpp | |||
| @@ -654,6 +654,93 @@ void test_initialise_rejects() { | |||
| 654 | } | 654 | } |
| 655 | } | 655 | } |
| 656 | 656 | ||
| 657 | // IMAGE_FILE_RELOCS_STRIPPED against a relocation directory, when the preferred base is taken. Measured on the | ||
| 658 | // Windows 11 (26200) loader with synthetic DLLs (runtime/README.md): with no relocation directory the flag refuses | ||
| 659 | // the move and an image with the flag clear is moved with nothing fixed up; with a relocation table the image is | ||
| 660 | // moved and fixed up whatever the flag says. The DllMain stub stores through an absolute address in this process, | ||
| 661 | // not in the image, so it runs correctly wherever the image lands. | ||
| 662 | void test_moved_without_relocations() { | ||
| 663 | auto img = make_image(); | ||
| 664 | auto* nt = nt_of(img); | ||
| 665 | nt->FileHeader.Characteristics |= IMAGE_FILE_DLL; | ||
| 666 | nt->OptionalHeader.ImageBase = leonida_test::free_image_base(0x1C0000000); | ||
| 667 | nt->OptionalHeader.AddressOfEntryPoint = 0x1040; | ||
| 668 | emit_store_stub(img, 0x240, reinterpret_cast<uint64_t>(&g_main_ran), 5, 1); | ||
| 669 | const uint64_t preferred = nt->OptionalHeader.ImageBase; | ||
| 670 | void* held = VirtualAlloc(reinterpret_cast<void*>(preferred), 0x2000, MEM_RESERVE, PAGE_NOACCESS); | ||
| 671 | if (!held) { | ||
| 672 | // Something else holds it already, which is the case under test as well; but make sure it is held. | ||
| 673 | MEMORY_BASIC_INFORMATION info{}; | ||
| 674 | if (!VirtualQuery(reinterpret_cast<void*>(preferred), &info, sizeof info) || info.State == MEM_FREE) | ||
| 675 | return failed("an image without relocations moves when its base is taken", "cannot hold its base"); | ||
| 676 | } | ||
| 677 | { | ||
| 678 | const char* what = "an image without relocations, flag clear, moves when its base is taken"; | ||
| 679 | g_main_ran = 0; | ||
| 680 | auto p = write_image(img); | ||
| 681 | try { | ||
| 682 | rt::Loader loader(g_dir); | ||
| 683 | rt::Module& m = loader.load(p); | ||
| 684 | if (reinterpret_cast<uint64_t>(m.base) == preferred || !m.relocated) | ||
| 685 | failed(what, "it was not moved"); | ||
| 686 | else if (std::memcmp(m.base + 0x1000, text_raw(img), 0x200) != 0) | ||
| 687 | failed(what, "the mapped section doesn't match the file (something was fixed up)"); | ||
| 688 | else { | ||
| 689 | loader.initialise(); | ||
| 690 | if (g_main_ran != 5) failed(what, "its DllMain never ran at the new address"); | ||
| 691 | else pass(what); | ||
| 692 | } | ||
| 693 | } catch (const std::exception& e) { | ||
| 694 | failed(what, e.what()); | ||
| 695 | } | ||
| 696 | } | ||
| 697 | { | ||
| 698 | auto stripped = img; | ||
| 699 | nt_of(stripped)->FileHeader.Characteristics |= IMAGE_FILE_RELOCS_STRIPPED; | ||
| 700 | std::string error; | ||
| 701 | const char* what = "an image with IMAGE_FILE_RELOCS_STRIPPED is refused when its base is taken"; | ||
| 702 | if (load(write_image(stripped), error) == 0) failed(what, "the image loaded"); | ||
| 703 | else if (error.find("stripped") == std::string::npos) failed(what, "refused for another reason: " + error); | ||
| 704 | else pass(what); | ||
| 705 | } | ||
| 706 | if (held) VirtualFree(held, 0, MEM_RELEASE); | ||
| 707 | { | ||
| 708 | // At a free base such an image maps, as it did before. Not Windows parity: the Windows 11 loader refused these | ||
| 709 | // DLLs (error 487) at a free base too, for a reason not yet known; runtime/README.md keeps the question. | ||
| 710 | auto stripped = img; | ||
| 711 | nt_of(stripped)->FileHeader.Characteristics |= IMAGE_FILE_RELOCS_STRIPPED; | ||
| 712 | expect_loads("an image with IMAGE_FILE_RELOCS_STRIPPED and no relocations maps at its free base", stripped); | ||
| 713 | } | ||
| 714 | { | ||
| 715 | // With a relocation table the flag does not stop the move: the table is applied, as Windows does it. | ||
| 716 | // ImageBase 0 makes the loader move it; the one DIR64 entry points at the qword at RVA 0x1100. | ||
| 717 | const char* what = "an image with IMAGE_FILE_RELOCS_STRIPPED and a relocation table is moved and fixed up"; | ||
| 718 | auto stripped = make_image(); | ||
| 719 | auto* snt = nt_of(stripped); | ||
| 720 | snt->FileHeader.Characteristics |= IMAGE_FILE_RELOCS_STRIPPED; | ||
| 721 | snt->OptionalHeader.ImageBase = 0; | ||
| 722 | snt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC] = {0x1000, 0x0A}; | ||
| 723 | auto* block = reinterpret_cast<IMAGE_BASE_RELOCATION*>(stripped.data() + 0x200); | ||
| 724 | block->VirtualAddress = 0x1000; | ||
| 725 | block->SizeOfBlock = 0x0A; | ||
| 726 | reinterpret_cast<uint16_t*>(block + 1)[0] = (IMAGE_REL_BASED_DIR64 << 12) | 0x100; | ||
| 727 | uint64_t original; | ||
| 728 | std::memcpy(&original, stripped.data() + 0x300, sizeof original); | ||
| 729 | auto p = write_image(stripped); | ||
| 730 | try { | ||
| 731 | rt::Loader loader(g_dir); | ||
| 732 | rt::Module& m = loader.load(p); | ||
| 733 | uint64_t moved; | ||
| 734 | std::memcpy(&moved, m.base + 0x1100, sizeof moved); | ||
| 735 | if (!m.relocated) failed(what, "it was not moved"); | ||
| 736 | else if (moved != original + reinterpret_cast<uint64_t>(m.base)) failed(what, "the pointer wasn't fixed up"); | ||
| 737 | else pass(what); | ||
| 738 | } catch (const std::exception& e) { | ||
| 739 | failed(what, e.what()); | ||
| 740 | } | ||
| 741 | } | ||
| 742 | } | ||
| 743 | |||
| 657 | // The images below jump to host observers so notifications remain observable after the mappings are freed. | 744 | // The images below jump to host observers so notifications remain observable after the mappings are freed. |
| 658 | // The FLS destructor itself starts in mapped code: leaving it registered would call unmapped memory at exit. | 745 | // The FLS destructor itself starts in mapped code: leaving it registered would call unmapped memory at exit. |
| 659 | void emit_jump_stub(std::vector<uint8_t>& img, size_t off, uint64_t target) { | 746 | void emit_jump_stub(std::vector<uint8_t>& img, size_t off, uint64_t target) { |
| @@ -1471,6 +1558,7 @@ int main() { | |||
| 1471 | test_section_bounds(); | 1558 | test_section_bounds(); |
| 1472 | test_truncation(); | 1559 | test_truncation(); |
| 1473 | test_relocations(); | 1560 | test_relocations(); |
| 1561 | test_moved_without_relocations(); | ||
| 1474 | test_exports(); | 1562 | test_exports(); |
| 1475 | test_empty_named_export(); | 1563 | test_empty_named_export(); |
| 1476 | test_imports(); | 1564 | test_imports(); |
diff --git a/runtime/test/pipeline_cache_journal_test.cpp b/runtime/test/pipeline_cache_journal_test.cpp new file mode 100644 index 000000000..c3793c96c --- /dev/null +++ b/runtime/test/pipeline_cache_journal_test.cpp | |||
| @@ -0,0 +1,337 @@ | |||
| 1 | // The pipeline journal's file naming, reading and writing (pipeline_cache_journal.h). No Vulkan, no GPU. | ||
| 2 | #include "../src/pipeline_cache_journal.h" | ||
| 3 | |||
| 4 | #include <chrono> | ||
| 5 | #include <cstdint> | ||
| 6 | #include <cstdio> | ||
| 7 | #include <cstring> | ||
| 8 | #include <filesystem> | ||
| 9 | #include <fstream> | ||
| 10 | #include <string> | ||
| 11 | #include <vector> | ||
| 12 | |||
| 13 | namespace fs = std::filesystem; | ||
| 14 | namespace journal = leonida::pipeline_journal; | ||
| 15 | namespace store = leonida::pipeline_cache_store; | ||
| 16 | |||
| 17 | #define CHECK(condition) do { \ | ||
| 18 | if (!(condition)) { \ | ||
| 19 | std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); \ | ||
| 20 | return 1; \ | ||
| 21 | } \ | ||
| 22 | } while (0) | ||
| 23 | |||
| 24 | static void put32(std::uint8_t* p, std::uint32_t value) { | ||
| 25 | for (int i = 0; i < 4; ++i) p[i] = static_cast<std::uint8_t>(value >> (8 * i)); | ||
| 26 | } | ||
| 27 | |||
| 28 | static leonida::cached_pso::Identity identity() { | ||
| 29 | leonida::cached_pso::Identity id; | ||
| 30 | id.vendor = 0x10de; | ||
| 31 | id.device = 0x2782; | ||
| 32 | for (int i = 0; i < 16; ++i) id.cache_uuid[i] = static_cast<std::uint8_t>(0xa0 + i); | ||
| 33 | return id; | ||
| 34 | } | ||
| 35 | |||
| 36 | // A VkPipelineCacheHeaderVersionOne for `id` followed by `payload` bytes. | ||
| 37 | static std::vector<char> blob(const leonida::cached_pso::Identity& id, std::size_t payload) { | ||
| 38 | std::vector<char> out(store::header_bytes + payload, '\x5a'); | ||
| 39 | auto* p = reinterpret_cast<std::uint8_t*>(out.data()); | ||
| 40 | put32(p, store::header_bytes); | ||
| 41 | put32(p + 4, store::header_version_one); | ||
| 42 | put32(p + 8, id.vendor); | ||
| 43 | put32(p + 12, id.device); | ||
| 44 | std::memcpy(p + 16, id.cache_uuid, sizeof(id.cache_uuid)); | ||
| 45 | return out; | ||
| 46 | } | ||
| 47 | |||
| 48 | static int test_hash() { | ||
| 49 | const std::uint32_t words[] = {0x07230203, 0x00010600, 1, 2, 3}; | ||
| 50 | journal::Hasher a, b, c; | ||
| 51 | a.text("cs"); | ||
| 52 | a.bytes(words, sizeof(words)); | ||
| 53 | a.value(std::uint32_t(32)); | ||
| 54 | b.text("cs"); | ||
| 55 | b.bytes(words, sizeof(words)); | ||
| 56 | b.value(std::uint32_t(32)); | ||
| 57 | CHECK(a.digest() == b.digest()); // deterministic: the next boot finds the same file | ||
| 58 | c.text("cs"); | ||
| 59 | c.bytes(words, sizeof(words)); | ||
| 60 | c.value(std::uint32_t(64)); // another subgroup size is another pipeline | ||
| 61 | CHECK(a.digest() != c.digest()); | ||
| 62 | journal::Hasher d, e; | ||
| 63 | d.text("ab"); | ||
| 64 | d.text("c"); | ||
| 65 | e.text("a"); | ||
| 66 | e.text("bc"); | ||
| 67 | CHECK(d.digest() != e.digest()); // text is length-prefixed | ||
| 68 | return 0; | ||
| 69 | } | ||
| 70 | |||
| 71 | static int test_path() { | ||
| 72 | const auto path = journal::entry_path("dir", "cs", 0x0123456789abcdefull); | ||
| 73 | CHECK(path.filename().string() == "cs-0123456789abcdef.bin"); | ||
| 74 | CHECK(journal::entry_path("dir", "cs", 1).filename().string() == "cs-0000000000000001.bin"); | ||
| 75 | return 0; | ||
| 76 | } | ||
| 77 | |||
| 78 | static int test_files(const fs::path& dir) { | ||
| 79 | const auto id = identity(); | ||
| 80 | const auto path = journal::entry_path(dir / "pipeline_cache.d", "cs", 42); | ||
| 81 | CHECK(journal::read_entry(path, id).empty()); // missing | ||
| 82 | |||
| 83 | // write_entry creates the directory and publishes the whole blob. | ||
| 84 | const auto data = blob(id, 1000); | ||
| 85 | CHECK(!journal::write_entry(path, data.data(), data.size())); | ||
| 86 | CHECK(journal::read_entry(path, id) == data); | ||
| 87 | |||
| 88 | // A second write replaces the first. | ||
| 89 | const auto next = blob(id, 10); | ||
| 90 | CHECK(!journal::write_entry(path, next.data(), next.size())); | ||
| 91 | CHECK(journal::read_entry(path, id) == next); | ||
| 92 | |||
| 93 | // Another device or driver (pipeline-cache UUID): not read, so the build starts over and rewrites it. | ||
| 94 | auto other = id; | ||
| 95 | other.cache_uuid[3] ^= 1; | ||
| 96 | CHECK(journal::read_entry(path, other).empty()); | ||
| 97 | other = id; | ||
| 98 | other.device = 0x1234; | ||
| 99 | CHECK(journal::read_entry(path, other).empty()); | ||
| 100 | |||
| 101 | // Truncated to less than a header, or over the read limit: not read. | ||
| 102 | { | ||
| 103 | std::ofstream(path, std::ios::binary | std::ios::trunc).write(next.data(), 16); | ||
| 104 | } | ||
| 105 | CHECK(journal::read_entry(path, id).empty()); | ||
| 106 | CHECK(!journal::write_entry(path, data.data(), data.size())); | ||
| 107 | CHECK(journal::read_entry(path, id, data.size() - 1).empty()); | ||
| 108 | CHECK(journal::read_entry(path, id, data.size()) == data); | ||
| 109 | |||
| 110 | CHECK(journal::directory_bytes(path.parent_path()) == data.size()); | ||
| 111 | CHECK(journal::directory_bytes(dir / "missing") == 0); | ||
| 112 | |||
| 113 | // No staging files are left behind. | ||
| 114 | std::size_t files = 0; | ||
| 115 | for (const auto& item : fs::directory_iterator(path.parent_path())) { | ||
| 116 | (void)item; | ||
| 117 | ++files; | ||
| 118 | } | ||
| 119 | CHECK(files == 1); | ||
| 120 | return 0; | ||
| 121 | } | ||
| 122 | |||
| 123 | // When a build writes its file, and when the shared cache's answer was a compile. | ||
| 124 | static int test_policy() { | ||
| 125 | // No file (or one the driver declined): always written, whatever the feedback or time. | ||
| 126 | CHECK(journal::should_write(false, 1, 0)); | ||
| 127 | CHECK(journal::should_write(false, -1, 0)); | ||
| 128 | CHECK(journal::should_write(false, 0, 0)); | ||
| 129 | // From the file: the feedback decides; without feedback, the length of the driver call. | ||
| 130 | CHECK(!journal::should_write(true, 1, 5000)); | ||
| 131 | CHECK(journal::should_write(true, 0, 1)); | ||
| 132 | CHECK(!journal::should_write(true, -1, journal::unreported_compile_ms - 1)); | ||
| 133 | CHECK(journal::should_write(true, -1, journal::unreported_compile_ms)); | ||
| 134 | // FAIL_ON_PIPELINE_COMPILE_REQUIRED: a slow pipeline without the hit bit was compiled; a fast one came out of | ||
| 135 | // the driver's own disk cache, and a hit or no feedback is never taken for a compile. | ||
| 136 | CHECK(journal::probe_compiled(0, journal::probe_compile_ms)); | ||
| 137 | CHECK(!journal::probe_compiled(0, journal::probe_compile_ms - 1)); | ||
| 138 | CHECK(!journal::probe_compiled(1, 60000)); | ||
| 139 | CHECK(!journal::probe_compiled(-1, 60000)); | ||
| 140 | return 0; | ||
| 141 | } | ||
| 142 | |||
| 143 | static int test_accounting() { | ||
| 144 | CHECK(journal::replace_bytes(100, 0, 30) == 130); // a new file | ||
| 145 | CHECK(journal::replace_bytes(100, 40, 30) == 90); // a rewrite replaces the old size | ||
| 146 | CHECK(journal::replace_bytes(10, 40, 30) == 30); // never below zero | ||
| 147 | const auto t0 = fs::file_time_type::clock::now(); | ||
| 148 | using std::chrono::hours; | ||
| 149 | const std::vector<journal::EntryInfo> entries = { | ||
| 150 | {"a", 40, t0 - hours(3)}, {"b", 40, t0 - hours(1)}, {"c", 40, t0 - hours(2)}, {"d", 40, t0}}; | ||
| 151 | CHECK(journal::plan_eviction(entries, 160, 120).empty()); // at the budget: nothing goes | ||
| 152 | // Over it: least recently used first (a, then c), until the target holds. | ||
| 153 | const auto out = journal::plan_eviction(entries, 150, 100); | ||
| 154 | CHECK(out.size() == 2 && out[0] == 0 && out[1] == 2); | ||
| 155 | CHECK(journal::plan_eviction(entries, 0, 0).size() == 4); | ||
| 156 | return 0; | ||
| 157 | } | ||
| 158 | |||
| 159 | static int test_names() { | ||
| 160 | CHECK(journal::entry_name("cs-0123456789abcdef.bin")); | ||
| 161 | CHECK(!journal::entry_name("cs-0123456789abcde.bin")); // 15 digits | ||
| 162 | CHECK(!journal::entry_name("cs-0123456789ABCDEF.bin")); // entry_path writes lowercase | ||
| 163 | CHECK(!journal::entry_name("-0123456789abcdef.bin")); | ||
| 164 | CHECK(!journal::entry_name("pipeline_cache.session.bin")); | ||
| 165 | CHECK(journal::staging_name("cs-0123456789abcdef.bin.tmp.123456.0")); | ||
| 166 | CHECK(!journal::staging_name("cs-0123456789abcdef.bin.tmp.123456")); | ||
| 167 | CHECK(!journal::staging_name("cs-0123456789abcdef.bin.tmp.12x.0")); | ||
| 168 | CHECK(!journal::staging_name("pipeline_cache.session.bin.tmp.1.0")); // the session file's, swept elsewhere | ||
| 169 | return 0; | ||
| 170 | } | ||
| 171 | |||
| 172 | static void put_file(const fs::path& path, std::size_t bytes, fs::file_time_type when) { | ||
| 173 | std::ofstream(path, std::ios::binary | std::ios::trunc) << std::string(bytes, 'x'); | ||
| 174 | fs::last_write_time(path, when); | ||
| 175 | } | ||
| 176 | |||
| 177 | static int test_tidy(const fs::path& root) { | ||
| 178 | const auto dir = root / "tidy"; | ||
| 179 | fs::create_directories(dir); | ||
| 180 | const auto now = fs::file_time_type::clock::now(); | ||
| 181 | using std::chrono::hours; | ||
| 182 | using std::chrono::minutes; | ||
| 183 | const auto a = journal::entry_path(dir, "cs", 0xa), b = journal::entry_path(dir, "cs", 0xb), | ||
| 184 | c = journal::entry_path(dir, "cs", 0xc); | ||
| 185 | put_file(a, 400, now - hours(5)); | ||
| 186 | put_file(b, 400, now - hours(1)); | ||
| 187 | put_file(c, 400, now - hours(3)); | ||
| 188 | const fs::path old_stage = a.string() + ".tmp.111.0", new_stage = b.string() + ".tmp.222.1"; | ||
| 189 | put_file(old_stage, 50, now - minutes(30)); | ||
| 190 | put_file(new_stage, 50, now - minutes(2)); | ||
| 191 | put_file(dir / "notes.txt", 999, now - hours(9)); | ||
| 192 | |||
| 193 | // Under the budget: only the old staging file goes; the young one may still be being written. | ||
| 194 | auto result = journal::tidy(dir, 2000, minutes(10), now); | ||
| 195 | CHECK(result.swept == 1 && result.evicted == 0 && result.entries == 3 && result.bytes == 1200); | ||
| 196 | CHECK(!fs::exists(old_stage) && fs::exists(new_stage) && fs::exists(dir / "notes.txt")); | ||
| 197 | |||
| 198 | // Over it: the least recently used go until three quarters is left (1200 > 1000; 750 holds b alone). | ||
| 199 | result = journal::tidy(dir, 1000, minutes(10), now); | ||
| 200 | CHECK(result.evicted == 2 && result.entries == 1 && result.bytes == 400); | ||
| 201 | CHECK(!fs::exists(a) && !fs::exists(c) && fs::exists(b)); | ||
| 202 | |||
| 203 | // A hit refreshes a file's last use, which keeps it over older ones. | ||
| 204 | put_file(a, 400, now - hours(5)); | ||
| 205 | journal::touch(a, now); | ||
| 206 | put_file(c, 400, now - hours(3)); | ||
| 207 | result = journal::tidy(dir, 1000, minutes(10), now); // 1200 again: c (3 h) is now the oldest, then b (1 h) | ||
| 208 | CHECK(fs::exists(a) && !fs::exists(c) && !fs::exists(b) && result.entries == 1); | ||
| 209 | CHECK(journal::tidy(root / "missing", 1000).entries == 0); | ||
| 210 | return 0; | ||
| 211 | } | ||
| 212 | |||
| 213 | static int test_entry_file(const fs::path& dir) { | ||
| 214 | const auto id = identity(); | ||
| 215 | const auto path = journal::entry_path(dir, "cs", 77); | ||
| 216 | auto missing = journal::read_entry_file(path, id); | ||
| 217 | CHECK(missing.data.empty() && missing.bytes == 0); | ||
| 218 | // A foreign file still reports its size, which its rewrite replaces in the budget. | ||
| 219 | auto other = id; | ||
| 220 | other.device ^= 1; | ||
| 221 | const auto data = blob(other, 100); | ||
| 222 | CHECK(!journal::write_entry(path, data.data(), data.size())); | ||
| 223 | const auto foreign = journal::read_entry_file(path, id); | ||
| 224 | CHECK(foreign.data.empty() && foreign.bytes == data.size()); | ||
| 225 | const auto own = journal::read_entry_file(path, other); | ||
| 226 | CHECK(own.data == data && own.bytes == data.size()); | ||
| 227 | return 0; | ||
| 228 | } | ||
| 229 | |||
| 230 | static int test_overlay(const fs::path& dir) { | ||
| 231 | using std::chrono::hours; | ||
| 232 | const auto local = dir / "overlay" / "pipeline_cache.d", seed = dir / "seed"; | ||
| 233 | const auto dst = journal::entry_path(local, "cs", 1), src = journal::entry_path(seed, "cs", 1); | ||
| 234 | const auto id = identity(); | ||
| 235 | auto wrong = id; | ||
| 236 | wrong.cache_uuid[0] ^= 1; | ||
| 237 | const auto donor = blob(id, 32), rebuilt = blob(id, 53), stale = blob(wrong, 45); | ||
| 238 | CHECK(!journal::write_entry(src, donor.data(), donor.size())); | ||
| 239 | const auto now = fs::file_time_type::clock::now(); | ||
| 240 | fs::last_write_time(src, now - hours(8)); | ||
| 241 | const auto donor_time = fs::last_write_time(src); | ||
| 242 | const auto roots = journal::resolve_roots(local, seed); | ||
| 243 | CHECK(!roots.writable.empty() && fs::equivalent(roots.seed, seed)); | ||
| 244 | |||
| 245 | // No local entry: donor bytes may seed the driver, but do not count against the writable budget. | ||
| 246 | constexpr auto runtime = journal::ReadRole::runtime; | ||
| 247 | constexpr auto builder = journal::ReadRole::materialize_local; | ||
| 248 | auto entry = journal::read_with_seed(dst, roots.seed, id, runtime); | ||
| 249 | CHECK(entry.from_seed && entry.data == donor && entry.bytes == 0 && entry.used == fs::file_time_type{}); | ||
| 250 | // Same roots, but the host building a requested local file must still see a miss. | ||
| 251 | CHECK(!journal::entry_usable(dst, id) && journal::entry_usable(src, id)); | ||
| 252 | const auto missing_build = journal::read_with_seed(dst, roots.seed, id, builder); | ||
| 253 | CHECK(missing_build.data.empty() && !missing_build.from_seed && missing_build.bytes == 0); | ||
| 254 | journal::touch_local_hit(dst, entry, now); | ||
| 255 | CHECK(!fs::exists(local) && fs::last_write_time(src) == donor_time); | ||
| 256 | CHECK(journal::replace_bytes(1000, entry.bytes, rebuilt.size()) == 1000 + rebuilt.size()); | ||
| 257 | CHECK(journal::read_with_seed(dst, {}, id, runtime).data.empty()); | ||
| 258 | CHECK(journal::read_with_seed(dst, seed, wrong, runtime).data.empty()); | ||
| 259 | CHECK(journal::read_with_seed(dst, seed, id, runtime, donor.size() - 1).data.empty()); | ||
| 260 | CHECK(journal::read_with_seed(dst, seed, id, runtime, donor.size()).data == donor); | ||
| 261 | CHECK(journal::read_with_seed(journal::entry_path(local, "cs", 2), seed, id, runtime).data.empty()); | ||
| 262 | |||
| 263 | // Even with a stale local object the recorded byte count and LRU timestamp belong to that object. | ||
| 264 | CHECK(!journal::write_entry(dst, stale.data(), stale.size())); | ||
| 265 | fs::last_write_time(dst, now - hours(3)); | ||
| 266 | const auto stale_time = fs::last_write_time(dst); | ||
| 267 | entry = journal::read_with_seed(dst, seed, id, runtime); | ||
| 268 | CHECK(entry.from_seed && entry.data == donor && entry.bytes == stale.size() && entry.used == stale_time); | ||
| 269 | const auto stale_build = journal::read_with_seed(dst, roots.seed, id, builder); | ||
| 270 | CHECK(stale_build.data.empty() && !stale_build.from_seed && stale_build.bytes == stale.size() && | ||
| 271 | stale_build.used == stale_time && !journal::entry_usable(dst, id)); | ||
| 272 | journal::touch_local_hit(dst, entry, now); | ||
| 273 | CHECK(fs::last_write_time(dst) == stale_time && fs::last_write_time(src) == donor_time); | ||
| 274 | CHECK(journal::read_entry(dst, wrong) == stale); // neither promoted nor rewritten by the hit | ||
| 275 | auto used = journal::tidy(roots.writable, stale.size()); | ||
| 276 | CHECK(used.entries == 1 && used.bytes == stale.size() && used.evicted == 0); | ||
| 277 | CHECK(journal::replace_bytes(used.bytes, entry.bytes, rebuilt.size()) == rebuilt.size()); | ||
| 278 | |||
| 279 | CHECK(!journal::write_entry(dst, rebuilt.data(), 3)); // truncated local is not a seed hit on the local file | ||
| 280 | entry = journal::read_with_seed(dst, seed, id, runtime); | ||
| 281 | CHECK(entry.from_seed && entry.data == donor && entry.bytes == 3 && fs::file_size(dst) == 3); | ||
| 282 | CHECK(!journal::write_entry(dst, rebuilt.data(), rebuilt.size())); | ||
| 283 | fs::last_write_time(dst, now - hours(3)); | ||
| 284 | entry = journal::read_with_seed(dst, seed, id, runtime); | ||
| 285 | CHECK(!entry.from_seed && entry.data == rebuilt && entry.bytes == rebuilt.size()); | ||
| 286 | CHECK(journal::entry_usable(dst, id)); | ||
| 287 | CHECK(!journal::entry_usable(dst, id, rebuilt.size() - 1) && journal::entry_usable(dst, id, rebuilt.size())); | ||
| 288 | const auto ready_build = journal::read_with_seed(dst, roots.seed, id, builder); | ||
| 289 | CHECK(!ready_build.from_seed && ready_build.data == rebuilt && ready_build.bytes == rebuilt.size()); | ||
| 290 | journal::touch_local_hit(dst, entry, now); | ||
| 291 | const auto refreshed = fs::last_write_time(dst); | ||
| 292 | CHECK(refreshed > entry.used); | ||
| 293 | entry = journal::read_with_seed(dst, seed, id, runtime); | ||
| 294 | journal::touch_local_hit(dst, entry, now + std::chrono::minutes(30)); | ||
| 295 | CHECK(fs::last_write_time(dst) == refreshed); | ||
| 296 | used = journal::tidy(roots.writable, 0); | ||
| 297 | CHECK(used.evicted == 1 && used.bytes == 0 && !fs::exists(dst)); | ||
| 298 | CHECK(journal::read_entry(src, id) == donor && fs::last_write_time(src) == donor_time); | ||
| 299 | |||
| 300 | const auto unset = journal::resolve_roots(local, {}); | ||
| 301 | CHECK(unset.writable == local && unset.seed.empty()); | ||
| 302 | const auto disabled = [](const fs::path& sink, const fs::path& source) { | ||
| 303 | const auto r = journal::resolve_roots(sink, source); | ||
| 304 | return r.writable.empty() && r.seed.empty(); | ||
| 305 | }; | ||
| 306 | CHECK(disabled({}, seed) && disabled(local, "relative") && disabled(local, dir / "no-seed")); | ||
| 307 | CHECK(disabled(local, src) && disabled(src, seed)); | ||
| 308 | CHECK(disabled(seed / ".", seed) && disabled(seed / "missing" / "journal", seed) && disabled(dir, seed)); | ||
| 309 | #ifdef _WIN32 | ||
| 310 | if (fs::exists(dir / "SEED")) CHECK(disabled(dir / "SEED", seed)); | ||
| 311 | #endif | ||
| 312 | return 0; | ||
| 313 | } | ||
| 314 | |||
| 315 | int main() { | ||
| 316 | const auto dir = fs::temp_directory_path() / | ||
| 317 | ("leonida_pipeline_journal_test_" + std::to_string(std::chrono::steady_clock::now().time_since_epoch().count())); | ||
| 318 | std::error_code ec; | ||
| 319 | fs::create_directories(dir, ec); | ||
| 320 | if (ec) { | ||
| 321 | std::fprintf(stderr, "cannot create %s\n", dir.string().c_str()); | ||
| 322 | return 1; | ||
| 323 | } | ||
| 324 | int failed = test_hash(); | ||
| 325 | if (!failed) failed = test_path(); | ||
| 326 | if (!failed) failed = test_files(dir); | ||
| 327 | if (!failed) failed = test_policy(); | ||
| 328 | if (!failed) failed = test_accounting(); | ||
| 329 | if (!failed) failed = test_names(); | ||
| 330 | if (!failed) failed = test_tidy(dir); | ||
| 331 | if (!failed) failed = test_entry_file(dir); | ||
| 332 | if (!failed) failed = test_overlay(dir); | ||
| 333 | fs::remove_all(dir, ec); | ||
| 334 | if (failed) return failed; | ||
| 335 | std::printf("pipeline_cache_journal_test: ok\n"); | ||
| 336 | return 0; | ||
| 337 | } | ||
diff --git a/runtime/test/replay_pipeline_compile_unlock_test.cpp b/runtime/test/replay_pipeline_compile_unlock_test.cpp new file mode 100644 index 000000000..045f81864 --- /dev/null +++ b/runtime/test/replay_pipeline_compile_unlock_test.cpp | |||
| @@ -0,0 +1,291 @@ | |||
| 1 | // VulkanQueue::execute_now() releases resource_mutex_ and tracker_mutex_ while compiling unbuilt pipelines under | ||
| 2 | // pipeline_mutex_ alone, so add_resource()/remove_resource() and other queues do not stall behind shader compiles, | ||
| 3 | // remove_pipeline() still waits until compilation finishes, failed non-strict dispatches build only once, and | ||
| 4 | // pass-1 re-preparation observes resource updates made while resource_mutex_ was unlocked. No GPU or game data. | ||
| 5 | #include "../src/vulkan_backend.h" | ||
| 6 | |||
| 7 | #include <atomic> | ||
| 8 | #include <chrono> | ||
| 9 | #include <condition_variable> | ||
| 10 | #include <cstdint> | ||
| 11 | #include <cstdio> | ||
| 12 | #include <memory> | ||
| 13 | #include <mutex> | ||
| 14 | #include <string_view> | ||
| 15 | #include <thread> | ||
| 16 | #include <vector> | ||
| 17 | |||
| 18 | #define EXPECT(condition) do { \ | ||
| 19 | if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ | ||
| 20 | } while (0) | ||
| 21 | |||
| 22 | namespace { | ||
| 23 | |||
| 24 | using namespace leonida; | ||
| 25 | |||
| 26 | template<class T> | ||
| 27 | T handle(std::uintptr_t n) { | ||
| 28 | return reinterpret_cast<T>(n); | ||
| 29 | } | ||
| 30 | |||
| 31 | VulkanDeviceFunctions driver{}; | ||
| 32 | std::atomic<std::uintptr_t> next_handle{10}; | ||
| 33 | std::mutex record_mutex; | ||
| 34 | std::vector<std::pair<VkBuffer, VkBuffer>> recorded_copies; | ||
| 35 | |||
| 36 | PFN_vkVoidFunction VKAPI_CALL mock_get_device_proc(VkDevice, const char* name) { | ||
| 37 | #define MOCK_DEVICE_FUNCTION(n) \ | ||
| 38 | if (std::string_view(name) == #n) return reinterpret_cast<PFN_vkVoidFunction>(driver.n); | ||
| 39 | LEONIDA_VK_DEVICE_FUNCTIONS(MOCK_DEVICE_FUNCTION) | ||
| 40 | #undef MOCK_DEVICE_FUNCTION | ||
| 41 | return nullptr; | ||
| 42 | } | ||
| 43 | |||
| 44 | void init_mock_driver() { | ||
| 45 | driver = {}; | ||
| 46 | driver.vkCreateCommandPool = +[](VkDevice, const VkCommandPoolCreateInfo*, const VkAllocationCallbacks*, | ||
| 47 | VkCommandPool* out) { | ||
| 48 | *out = handle<VkCommandPool>(next_handle.fetch_add(1)); | ||
| 49 | return VK_SUCCESS; | ||
| 50 | }; | ||
| 51 | driver.vkDestroyCommandPool = +[](VkDevice, VkCommandPool, const VkAllocationCallbacks*) {}; | ||
| 52 | driver.vkCreateSemaphore = +[](VkDevice, const VkSemaphoreCreateInfo*, const VkAllocationCallbacks*, | ||
| 53 | VkSemaphore* out) { | ||
| 54 | *out = handle<VkSemaphore>(next_handle.fetch_add(1)); | ||
| 55 | return VK_SUCCESS; | ||
| 56 | }; | ||
| 57 | driver.vkDestroySemaphore = +[](VkDevice, VkSemaphore, const VkAllocationCallbacks*) {}; | ||
| 58 | driver.vkGetSemaphoreCounterValue = +[](VkDevice, VkSemaphore, std::uint64_t* value) { | ||
| 59 | *value = UINT64_MAX; | ||
| 60 | return VK_SUCCESS; | ||
| 61 | }; | ||
| 62 | driver.vkQueueWaitIdle = +[](VkQueue) { return VK_SUCCESS; }; | ||
| 63 | driver.vkAllocateCommandBuffers = +[](VkDevice, const VkCommandBufferAllocateInfo* info, VkCommandBuffer* out) { | ||
| 64 | for (std::uint32_t i = 0; i < info->commandBufferCount; ++i) | ||
| 65 | out[i] = handle<VkCommandBuffer>(next_handle.fetch_add(1)); | ||
| 66 | return VK_SUCCESS; | ||
| 67 | }; | ||
| 68 | driver.vkResetCommandBuffer = +[](VkCommandBuffer, VkCommandBufferResetFlags) { return VK_SUCCESS; }; | ||
| 69 | driver.vkBeginCommandBuffer = +[](VkCommandBuffer, const VkCommandBufferBeginInfo*) { return VK_SUCCESS; }; | ||
| 70 | driver.vkEndCommandBuffer = +[](VkCommandBuffer) { return VK_SUCCESS; }; | ||
| 71 | driver.vkQueueSubmit = +[](VkQueue, std::uint32_t, const VkSubmitInfo*, VkFence) { return VK_SUCCESS; }; | ||
| 72 | driver.vkCmdPipelineBarrier = +[](VkCommandBuffer, VkPipelineStageFlags, VkPipelineStageFlags, VkDependencyFlags, | ||
| 73 | std::uint32_t, const VkMemoryBarrier*, std::uint32_t, | ||
| 74 | const VkBufferMemoryBarrier*, std::uint32_t, const VkImageMemoryBarrier*) {}; | ||
| 75 | driver.vkCmdBindPipeline = +[](VkCommandBuffer, VkPipelineBindPoint, VkPipeline) {}; | ||
| 76 | driver.vkCmdPushConstants = +[](VkCommandBuffer, VkPipelineLayout, VkShaderStageFlags, std::uint32_t, | ||
| 77 | std::uint32_t, const void*) {}; | ||
| 78 | driver.vkCmdDispatch = +[](VkCommandBuffer, std::uint32_t, std::uint32_t, std::uint32_t) {}; | ||
| 79 | driver.vkCmdCopyBuffer = +[](VkCommandBuffer, VkBuffer src, VkBuffer dst, std::uint32_t, const VkBufferCopy*) { | ||
| 80 | std::lock_guard lock(record_mutex); | ||
| 81 | recorded_copies.emplace_back(src, dst); | ||
| 82 | }; | ||
| 83 | driver.vkCmdCopyBufferToImage = +[](VkCommandBuffer, VkBuffer, VkImage, VkImageLayout, std::uint32_t, | ||
| 84 | const VkBufferImageCopy*) {}; | ||
| 85 | driver.vkCmdCopyImageToBuffer = +[](VkCommandBuffer, VkImage, VkImageLayout, VkBuffer, std::uint32_t, | ||
| 86 | const VkBufferImageCopy*) {}; | ||
| 87 | driver.vkCmdCopyImage = +[](VkCommandBuffer, VkImage, VkImageLayout, VkImage, VkImageLayout, std::uint32_t, | ||
| 88 | const VkImageCopy*) {}; | ||
| 89 | } | ||
| 90 | |||
| 91 | struct SlowPipeline { | ||
| 92 | std::mutex mutex; | ||
| 93 | std::condition_variable cv; | ||
| 94 | bool entered = false; | ||
| 95 | bool allow_finish = false; | ||
| 96 | bool fail = false; | ||
| 97 | std::atomic<int> builds{0}; | ||
| 98 | VkPipeline handle_out = VK_NULL_HANDLE; | ||
| 99 | |||
| 100 | VkPipeline build() { | ||
| 101 | builds.fetch_add(1, std::memory_order_relaxed); | ||
| 102 | { | ||
| 103 | std::unique_lock lock(mutex); | ||
| 104 | entered = true; | ||
| 105 | cv.notify_all(); | ||
| 106 | cv.wait(lock, [this] { return allow_finish; }); | ||
| 107 | if (!fail) handle_out = handle<VkPipeline>(0x7001); | ||
| 108 | return handle_out; | ||
| 109 | } | ||
| 110 | } | ||
| 111 | |||
| 112 | VkPipeline find() { | ||
| 113 | std::unique_lock lock(mutex, std::try_to_lock); | ||
| 114 | return lock.owns_lock() ? handle_out : VK_NULL_HANDLE; | ||
| 115 | } | ||
| 116 | |||
| 117 | void release() { | ||
| 118 | std::lock_guard lock(mutex); | ||
| 119 | allow_finish = true; | ||
| 120 | cv.notify_all(); | ||
| 121 | } | ||
| 122 | }; | ||
| 123 | |||
| 124 | // Exercises concurrent add_resource/remove_resource, a second queue submission, resource replacement observed on | ||
| 125 | // pass-1 re-prepare, and remove_pipeline() waiting on pipeline_mutex_ while a slow compile runs. | ||
| 126 | int test_unlocks_resources_during_compile(bool with_workers) { | ||
| 127 | { | ||
| 128 | std::lock_guard lock(record_mutex); | ||
| 129 | recorded_copies.clear(); | ||
| 130 | } | ||
| 131 | VulkanContext context(mock_get_device_proc, handle<VkDevice>(1), false); | ||
| 132 | if (with_workers) context.set_pipeline_workers(std::make_unique<PipelineWorkers>(2)); | ||
| 133 | |||
| 134 | ResourceBinding src{}; | ||
| 135 | src.buffer = handle<VkBuffer>(101); | ||
| 136 | src.size = 64; | ||
| 137 | ResourceBinding dst_old{}; | ||
| 138 | dst_old.buffer = handle<VkBuffer>(102); | ||
| 139 | dst_old.size = 64; | ||
| 140 | ResourceBinding dst_new{}; | ||
| 141 | dst_new.buffer = handle<VkBuffer>(202); | ||
| 142 | dst_new.size = 64; | ||
| 143 | context.add_resource(1, src); | ||
| 144 | context.add_resource(2, dst_old); | ||
| 145 | |||
| 146 | SlowPipeline slow; | ||
| 147 | constexpr std::uintptr_t slow_id = 0x100; | ||
| 148 | constexpr std::uintptr_t fast_id = 0x200; | ||
| 149 | |||
| 150 | ComputePipeline slow_pso{}; | ||
| 151 | slow_pso.layout = handle<VkPipelineLayout>(5); | ||
| 152 | slow_pso.build_context = &slow; | ||
| 153 | slow_pso.build = [](void* ctx) { return static_cast<SlowPipeline*>(ctx)->build(); }; | ||
| 154 | slow_pso.built = [](void* ctx) { return static_cast<SlowPipeline*>(ctx)->find(); }; | ||
| 155 | context.add_pipeline(slow_id, slow_pso); | ||
| 156 | |||
| 157 | ComputePipeline fast_pso{}; | ||
| 158 | fast_pso.layout = handle<VkPipelineLayout>(5); | ||
| 159 | fast_pso.pipeline = handle<VkPipeline>(0x8001); | ||
| 160 | context.add_pipeline(fast_id, fast_pso); | ||
| 161 | |||
| 162 | VulkanQueue queue_a(context, handle<VkQueue>(1), 0, VulkanQueue::QueueKind::compute); | ||
| 163 | VulkanQueue queue_b(context, handle<VkQueue>(2), 0, VulkanQueue::QueueKind::compute); | ||
| 164 | EXPECT(queue_a.ok() && queue_b.ok()); | ||
| 165 | |||
| 166 | CommandList list_a; | ||
| 167 | EXPECT(list_a.dispatch({slow_id, {}, 1, 1, 1})); | ||
| 168 | EXPECT(list_a.copy_buffer({2, 0, 1, 0, 64})); | ||
| 169 | EXPECT(list_a.close()); | ||
| 170 | |||
| 171 | CommandList list_b; | ||
| 172 | EXPECT(list_b.dispatch({fast_id, {}, 1, 1, 1})); | ||
| 173 | EXPECT(list_b.close()); | ||
| 174 | |||
| 175 | ReplayResult result_a = ReplayResult::unsupported; | ||
| 176 | std::thread thread_a([&] { | ||
| 177 | const CommandList* ptr = &list_a; | ||
| 178 | result_a = queue_a.execute({&ptr, 1}); | ||
| 179 | }); | ||
| 180 | |||
| 181 | // Wait for thread_a (or a PipelineWorkers thread) to enter slow.build(). | ||
| 182 | { | ||
| 183 | std::unique_lock lock(slow.mutex); | ||
| 184 | const bool entered = slow.cv.wait_for(lock, std::chrono::seconds(5), [&] { return slow.entered; }); | ||
| 185 | if (!entered) { | ||
| 186 | slow.allow_finish = true; | ||
| 187 | slow.cv.notify_all(); | ||
| 188 | lock.unlock(); | ||
| 189 | thread_a.join(); | ||
| 190 | EXPECT(false); | ||
| 191 | } | ||
| 192 | } | ||
| 193 | |||
| 194 | // While compilation is paused: | ||
| 195 | // 1. add_resource() / remove_resource() and a second queue submission must complete without blocking. | ||
| 196 | std::atomic<bool> resources_unblocked{false}; | ||
| 197 | ReplayResult result_b = ReplayResult::unsupported; | ||
| 198 | std::thread resource_thread([&] { | ||
| 199 | ResourceBinding temp{}; | ||
| 200 | temp.buffer = handle<VkBuffer>(303); | ||
| 201 | temp.size = 64; | ||
| 202 | context.add_resource(3, temp); | ||
| 203 | context.remove_resource(3); | ||
| 204 | // Replace resource 2 while resource_mutex_ is unlocked so pass-1 re-prepare must bind dst_new. | ||
| 205 | context.remove_resource(2); | ||
| 206 | context.add_resource(2, dst_new); | ||
| 207 | const CommandList* ptr = &list_b; | ||
| 208 | result_b = queue_b.execute({&ptr, 1}); | ||
| 209 | resources_unblocked.store(true, std::memory_order_release); | ||
| 210 | }); | ||
| 211 | |||
| 212 | const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(2); | ||
| 213 | while (!resources_unblocked.load(std::memory_order_acquire) && std::chrono::steady_clock::now() < deadline) | ||
| 214 | std::this_thread::sleep_for(std::chrono::milliseconds(5)); | ||
| 215 | |||
| 216 | if (!resources_unblocked.load(std::memory_order_acquire)) { | ||
| 217 | slow.release(); | ||
| 218 | resource_thread.join(); | ||
| 219 | thread_a.join(); | ||
| 220 | EXPECT(false); | ||
| 221 | } | ||
| 222 | resource_thread.join(); | ||
| 223 | EXPECT(result_b == ReplayResult::success); | ||
| 224 | |||
| 225 | // 2. remove_pipeline() must wait on pipeline_mutex_ until compilation finishes (protecting ComputePipeline*). | ||
| 226 | std::atomic<bool> remove_started{false}; | ||
| 227 | std::atomic<bool> remove_finished{false}; | ||
| 228 | std::thread remove_thread([&] { | ||
| 229 | remove_started.store(true, std::memory_order_release); | ||
| 230 | context.remove_pipeline(slow_id); | ||
| 231 | remove_finished.store(true, std::memory_order_release); | ||
| 232 | }); | ||
| 233 | while (!remove_started.load(std::memory_order_acquire)) | ||
| 234 | std::this_thread::sleep_for(std::chrono::milliseconds(1)); | ||
| 235 | std::this_thread::sleep_for(std::chrono::milliseconds(30)); | ||
| 236 | const bool removed_early = remove_finished.load(std::memory_order_acquire); | ||
| 237 | |||
| 238 | slow.release(); | ||
| 239 | thread_a.join(); | ||
| 240 | remove_thread.join(); | ||
| 241 | |||
| 242 | EXPECT(!removed_early); | ||
| 243 | EXPECT(remove_finished.load(std::memory_order_acquire)); | ||
| 244 | EXPECT(result_a == ReplayResult::success); | ||
| 245 | EXPECT(slow.builds.load() == 1); | ||
| 246 | { | ||
| 247 | std::lock_guard lock(record_mutex); | ||
| 248 | EXPECT(recorded_copies.size() == 1); | ||
| 249 | EXPECT(recorded_copies[0].first == src.buffer && recorded_copies[0].second == dst_new.buffer); | ||
| 250 | } | ||
| 251 | return 0; | ||
| 252 | } | ||
| 253 | |||
| 254 | // A non-strict failed compute dispatch must not invoke build() a second time on pass-1 re-prepare. | ||
| 255 | int test_failed_compute_dispatch_built_once() { | ||
| 256 | VulkanContext context(mock_get_device_proc, handle<VkDevice>(1), false); | ||
| 257 | SlowPipeline failing; | ||
| 258 | failing.fail = true; | ||
| 259 | failing.allow_finish = true; | ||
| 260 | |||
| 261 | constexpr std::uintptr_t fail_id = 0x300; | ||
| 262 | ComputePipeline pso{}; | ||
| 263 | pso.layout = handle<VkPipelineLayout>(5); | ||
| 264 | pso.build_context = &failing; | ||
| 265 | pso.build = [](void* ctx) { return static_cast<SlowPipeline*>(ctx)->build(); }; | ||
| 266 | pso.built = [](void* ctx) { return static_cast<SlowPipeline*>(ctx)->find(); }; | ||
| 267 | context.add_pipeline(fail_id, pso); | ||
| 268 | |||
| 269 | VulkanQueue queue(context, handle<VkQueue>(3), 0, VulkanQueue::QueueKind::compute); | ||
| 270 | EXPECT(queue.ok()); | ||
| 271 | |||
| 272 | CommandList list; | ||
| 273 | EXPECT(list.dispatch({fail_id, {}, 1, 1, 1})); | ||
| 274 | EXPECT(list.close()); | ||
| 275 | const CommandList* ptr = &list; | ||
| 276 | const ReplayResult r = queue.execute({&ptr, 1}); | ||
| 277 | EXPECT(r == (strict_replay() ? ReplayResult::unresolved_resource : ReplayResult::success)); | ||
| 278 | EXPECT(failing.builds.load() == 1); | ||
| 279 | return 0; | ||
| 280 | } | ||
| 281 | |||
| 282 | } // namespace | ||
| 283 | |||
| 284 | int main() { | ||
| 285 | init_mock_driver(); | ||
| 286 | if (test_unlocks_resources_during_compile(true) != 0) return 1; | ||
| 287 | if (test_unlocks_resources_during_compile(false) != 0) return 1; | ||
| 288 | if (test_failed_compute_dispatch_built_once() != 0) return 1; | ||
| 289 | std::printf("replay_pipeline_compile_unlock_test: passed\n"); | ||
| 290 | return 0; | ||
| 291 | } | ||
diff --git a/runtime/test/replay_pipeline_compiles_test.cpp b/runtime/test/replay_pipeline_compiles_test.cpp index 35b6057ed..a8983f7ce 100644 --- a/runtime/test/replay_pipeline_compiles_test.cpp +++ b/runtime/test/replay_pipeline_compiles_test.cpp | |||
| @@ -2,13 +2,16 @@ | |||
| 2 | // prepared twice, once with every pipeline built where prepare() meets it and once with them left to PipelineCompiles | 2 | // prepared twice, once with every pipeline built where prepare() meets it and once with them left to PipelineCompiles |
| 3 | // and built on PipelineWorkers. Both have to give the same result, the same pipeline to every draw and dispatch, the same | 3 | // and built on PipelineWorkers. Both have to give the same result, the same pipeline to every draw and dispatch, the same |
| 4 | // commands dropped, and the same pipelines built, each once. Fixed cases, then random ones. Run a second time with | 4 | // commands dropped, and the same pipelines built, each once. Fixed cases, then random ones. Run a second time with |
| 5 | // LEONIDA_STRICT_REPLAY=1, where a dispatch without a pipeline fails its list. No GPU: pipelines and resources are fakes. | 5 | // LEONIDA_STRICT_REPLAY=1, where a dispatch without a pipeline fails its list. Also which large pipelines compile at once |
| 6 | // within a budget (PipelineCompiles::build). No GPU: pipelines and resources are fakes. | ||
| 7 | #include "../src/large_module_gate.h" | ||
| 6 | #include "../src/pipeline_workers.h" | 8 | #include "../src/pipeline_workers.h" |
| 7 | #include "../src/vulkan_replay.h" | 9 | #include "../src/vulkan_replay.h" |
| 8 | 10 | ||
| 9 | #include <algorithm> | 11 | #include <algorithm> |
| 10 | #include <atomic> | 12 | #include <atomic> |
| 11 | #include <chrono> | 13 | #include <chrono> |
| 14 | #include <condition_variable> | ||
| 12 | #include <cstdint> | 15 | #include <cstdint> |
| 13 | #include <cstdio> | 16 | #include <cstdio> |
| 14 | #include <functional> | 17 | #include <functional> |
| @@ -39,9 +42,10 @@ T handle(std::uintptr_t n) { | |||
| 39 | constexpr ResourceId color_id = 1, depth_id = 2, arguments_id = 3; | 42 | constexpr ResourceId color_id = 1, depth_id = 2, arguments_id = 3; |
| 40 | constexpr std::uint64_t bad_va = 0xbad0000; | 43 | constexpr std::uint64_t bad_va = 0xbad0000; |
| 41 | 44 | ||
| 42 | // The large pipelines being built now, and how often there were two. | 45 | // The large pipelines being built now, and how often there were two, where they are to compile one after another. |
| 43 | std::atomic<int> large_now = 0; | 46 | std::atomic<int> large_now = 0; |
| 44 | std::atomic<int> large_together = 0; | 47 | std::atomic<int> large_together = 0; |
| 48 | std::atomic<bool> large_one_at_a_time = true; | ||
| 45 | 49 | ||
| 46 | // What a pipeline state owns: its variants, built on demand under its own lock, and what was asked of it. | 50 | // What a pipeline state owns: its variants, built on demand under its own lock, and what was asked of it. |
| 47 | struct Owner { | 51 | struct Owner { |
| @@ -60,7 +64,7 @@ struct Owner { | |||
| 60 | if (failed && compute) return VK_NULL_HANDLE; // a refused compute pipeline is not tried again | 64 | if (failed && compute) return VK_NULL_HANDLE; // a refused compute pipeline is not tried again |
| 61 | attempts.push_back(flags); | 65 | attempts.push_back(flags); |
| 62 | if (large) { | 66 | if (large) { |
| 63 | if (++large_now > 1) ++large_together; | 67 | if (++large_now > 1 && large_one_at_a_time) ++large_together; |
| 64 | const auto end = std::chrono::steady_clock::now() + std::chrono::microseconds(20); | 68 | const auto end = std::chrono::steady_clock::now() + std::chrono::microseconds(20); |
| 65 | while (std::chrono::steady_clock::now() < end) std::this_thread::yield(); | 69 | while (std::chrono::steady_clock::now() < end) std::this_thread::yield(); |
| 66 | --large_now; | 70 | --large_now; |
| @@ -84,6 +88,7 @@ struct PipelineSpec { | |||
| 84 | bool fails = false; | 88 | bool fails = false; |
| 85 | bool with_built = true; | 89 | bool with_built = true; |
| 86 | bool large = false; | 90 | bool large = false; |
| 91 | std::uint64_t estimate = 0; | ||
| 87 | bool skipped = false; // compute: never built, its dispatches are dropped | 92 | bool skipped = false; // compute: never built, its dispatches are dropped |
| 88 | bool bindless = false; // compute: needs a set 0, which these functions cannot bind | 93 | bool bindless = false; // compute: needs a set 0, which these functions cannot bind |
| 89 | bool async = false; // its null handle may be waiting for another worker: never left to PipelineCompiles | 94 | bool async = false; // its null handle may be waiting for another worker: never left to PipelineCompiles |
| @@ -114,6 +119,7 @@ struct Registry { | |||
| 114 | ComputePipeline p{}; | 119 | ComputePipeline p{}; |
| 115 | p.layout = handle<VkPipelineLayout>(7); | 120 | p.layout = handle<VkPipelineLayout>(7); |
| 116 | p.large = spec.large; | 121 | p.large = spec.large; |
| 122 | p.estimate = spec.estimate; | ||
| 117 | p.async_build = spec.async; | 123 | p.async_build = spec.async; |
| 118 | p.skipped = spec.skipped; | 124 | p.skipped = spec.skipped; |
| 119 | if (spec.bindless) p.bindless_set = handle<VkDescriptorSet>(6); | 125 | if (spec.bindless) p.bindless_set = handle<VkDescriptorSet>(6); |
| @@ -138,6 +144,7 @@ struct Registry { | |||
| 138 | } | 144 | } |
| 139 | p.mesh = spec.mesh; | 145 | p.mesh = spec.mesh; |
| 140 | p.large = spec.large; | 146 | p.large = spec.large; |
| 147 | p.estimate = spec.estimate; | ||
| 141 | p.vertex_slots = spec.vertices ? 1 : 0; | 148 | p.vertex_slots = spec.vertices ? 1 : 0; |
| 142 | if (spec.rectangle) p.rectangle_variant_topology = 17; | 149 | if (spec.rectangle) p.rectangle_variant_topology = 17; |
| 143 | p.variant = [&owner](std::uint32_t flags) { return owner.build(flags); }; | 150 | p.variant = [&owner](std::uint32_t flags) { return owner.build(flags); }; |
| @@ -273,12 +280,12 @@ struct Outcome { | |||
| 273 | std::multiset<std::pair<std::uintptr_t, std::uint32_t>> built; | 280 | std::multiset<std::pair<std::uintptr_t, std::uint32_t>> built; |
| 274 | std::size_t jobs = 0; | 281 | std::size_t jobs = 0; |
| 275 | std::size_t runs = 0; | 282 | std::size_t runs = 0; |
| 276 | std::size_t units = 0; // what run() was given: the large pipelines together are one | 283 | std::size_t units = 0; // what run() was given: the large pipelines together are one (no budget) |
| 277 | }; | 284 | }; |
| 278 | 285 | ||
| 279 | // `workers` null: prepare() builds each pipeline itself, as without workers. | 286 | // `workers` null: prepare() builds each pipeline itself, as without workers. |
| 280 | Outcome prepare_all(const std::vector<CommandList>& lists, const std::vector<PipelineSpec>& specs, | 287 | Outcome prepare_all(const std::vector<CommandList>& lists, const std::vector<PipelineSpec>& specs, |
| 281 | PipelineWorkers* workers) { | 288 | PipelineWorkers* workers, const std::function<std::uint64_t()>& budget = {}) { |
| 282 | Registry registry(specs); | 289 | Registry registry(specs); |
| 283 | ReplayFunctions vk = functions(registry); | 290 | ReplayFunctions vk = functions(registry); |
| 284 | PipelineCompiles compiles; | 291 | PipelineCompiles compiles; |
| @@ -294,7 +301,8 @@ Outcome prepare_all(const std::vector<CommandList>& lists, const std::vector<Pip | |||
| 294 | ++out.runs; | 301 | ++out.runs; |
| 295 | out.units = count; | 302 | out.units = count; |
| 296 | workers->run(count, job); | 303 | workers->run(count, job); |
| 297 | }); | 304 | }, |
| 305 | budget); | ||
| 298 | if (out.result == ReplayResult::success) | 306 | if (out.result == ReplayResult::success) |
| 299 | for (std::size_t i = 0; i < lists.size(); ++i) { | 307 | for (std::size_t i = 0; i < lists.size(); ++i) { |
| 300 | for (std::size_t c = 0; c < prepared[i].commands.size(); ++c) { | 308 | for (std::size_t c = 0; c < prepared[i].commands.size(); ++c) { |
| @@ -312,10 +320,13 @@ Outcome prepare_all(const std::vector<CommandList>& lists, const std::vector<Pip | |||
| 312 | } | 320 | } |
| 313 | 321 | ||
| 314 | Outcome compare(const std::string& name, const std::vector<PipelineSpec>& specs, | 322 | Outcome compare(const std::string& name, const std::vector<PipelineSpec>& specs, |
| 315 | const std::vector<std::vector<CommandSpec>>& commands, PipelineWorkers& workers) { | 323 | const std::vector<std::vector<CommandSpec>>& commands, PipelineWorkers& workers, |
| 324 | const std::function<std::uint64_t()>& budget = {}) { | ||
| 316 | const auto lists = record(commands); | 325 | const auto lists = record(commands); |
| 317 | const Outcome serial = prepare_all(lists, specs, nullptr); | 326 | const Outcome serial = prepare_all(lists, specs, nullptr); |
| 318 | const Outcome together = prepare_all(lists, specs, &workers); | 327 | large_one_at_a_time = !budget; |
| 328 | const Outcome together = prepare_all(lists, specs, &workers, budget); | ||
| 329 | large_one_at_a_time = true; | ||
| 319 | check(serial.result == together.result, name + ": another result"); | 330 | check(serial.result == together.result, name + ": another result"); |
| 320 | check(serial.pipelines == together.pipelines, name + ": another pipeline for a draw or dispatch"); | 331 | check(serial.pipelines == together.pipelines, name + ": another pipeline for a draw or dispatch"); |
| 321 | if (serial.result == ReplayResult::success) | 332 | if (serial.result == ReplayResult::success) |
| @@ -516,6 +527,7 @@ void random_submissions(PipelineWorkers& workers) { | |||
| 516 | s.with_built = chance(90); | 527 | s.with_built = chance(90); |
| 517 | s.async = chance(8); | 528 | s.async = chance(8); |
| 518 | s.large = chance(15); | 529 | s.large = chance(15); |
| 530 | s.estimate = rng() % 12; | ||
| 519 | s.bindless = chance(2); | 531 | s.bindless = chance(2); |
| 520 | s.skipped = s.compute && chance(4); | 532 | s.skipped = s.compute && chance(4); |
| 521 | if (s.skipped) s.fails = s.pending = true; | 533 | if (s.skipped) s.fails = s.pending = true; |
| @@ -540,13 +552,352 @@ void random_submissions(PipelineWorkers& workers) { | |||
| 540 | c.mesh = c.pipeline <= specs.size() && specs[c.pipeline - 1].mesh; | 552 | c.mesh = c.pipeline <= specs.size() && specs[c.pipeline - 1].mesh; |
| 541 | list.push_back(c); | 553 | list.push_back(c); |
| 542 | } | 554 | } |
| 543 | succeeded += compare("random submission " + std::to_string(round), specs, commands, workers).result == | 555 | const std::uint64_t memory = rng() % 24; // 0: no budget |
| 544 | ReplayResult::success; | 556 | const auto budget = [memory] { return memory; }; |
| 557 | const bool limited = chance(50); | ||
| 558 | succeeded += compare("random submission " + std::to_string(round), specs, commands, workers, | ||
| 559 | limited ? std::function<std::uint64_t()>(budget) : std::function<std::uint64_t()>{}) | ||
| 560 | .result == ReplayResult::success; | ||
| 545 | } | 561 | } |
| 546 | check(succeeded > 1000 && succeeded < 2900, "the random submissions both succeed and fail: " + | 562 | check(succeeded > 1000 && succeeded < 2900, "the random submissions both succeed and fail: " + |
| 547 | std::to_string(succeeded)); | 563 | std::to_string(succeeded)); |
| 548 | } | 564 | } |
| 549 | 565 | ||
| 566 | // Re-preparing after a prior compile pass reuses prior outcomes (both built handles and non-strict failed compute | ||
| 567 | // dispatches) without re-invoking build() or failing the submission. | ||
| 568 | void prior_compiles_reuse(PipelineWorkers& workers) { | ||
| 569 | Registry registry({ | ||
| 570 | {.compute = true, .pending = true, .fails = false, .with_built = true}, | ||
| 571 | {.compute = true, .pending = true, .fails = true, .with_built = true}, | ||
| 572 | }); | ||
| 573 | const std::vector<CommandList> lists = record({{ | ||
| 574 | CommandSpec{.kind = CommandSpec::dispatch, .pipeline = 1}, | ||
| 575 | CommandSpec{.kind = CommandSpec::dispatch, .pipeline = 2}, | ||
| 576 | }}); | ||
| 577 | std::vector<PreparedList> prepared(1); | ||
| 578 | ReplayFunctions vk = functions(registry); | ||
| 579 | PipelineCompiles first; | ||
| 580 | vk.compiles = &first; | ||
| 581 | const ReplayResult r0 = prepare(lists[0], resolve, vk, prepared[0]); | ||
| 582 | check(r0 == ReplayResult::success && first.size() == 2, "prior_compiles_reuse: pass 0 collected both"); | ||
| 583 | first.build([&](std::size_t count, const std::function<void(std::size_t)>& job) { workers.run(count, job); }); | ||
| 584 | const ReplayResult c0 = check_compiled_pipelines(first, r0); | ||
| 585 | if (strict_replay()) { | ||
| 586 | check(c0 == ReplayResult::unresolved_resource, "prior_compiles_reuse: strict fails on failed dispatch"); | ||
| 587 | return; | ||
| 588 | } | ||
| 589 | check(c0 == ReplayResult::success, "prior_compiles_reuse: non-strict tolerates failed dispatch"); | ||
| 590 | check(registry.owners[0]->attempts.size() == 1 && registry.owners[1]->attempts.size() == 1, | ||
| 591 | "prior_compiles_reuse: each pipeline built once on pass 0"); | ||
| 592 | // Reset the failed flag on owner 2 so any redundant build() call on pass 1 would be caught in attempts. | ||
| 593 | registry.owners[1]->failed = false; | ||
| 594 | |||
| 595 | PipelineCompiles second; | ||
| 596 | vk.compiles = &second; | ||
| 597 | const ReplayResult r1 = prepare(lists[0], resolve, vk, prepared[0]); | ||
| 598 | const ReplayResult b1 = build_pipelines( | ||
| 599 | second, std::span(prepared), r1, | ||
| 600 | [&](std::size_t count, const std::function<void(std::size_t)>& job) { workers.run(count, job); }, | ||
| 601 | {}, &first); | ||
| 602 | check(b1 == ReplayResult::success, "prior_compiles_reuse: pass 1 succeeded"); | ||
| 603 | check(registry.owners[0]->attempts.size() == 1 && registry.owners[1]->attempts.size() == 1, | ||
| 604 | "prior_compiles_reuse: pass 1 did not re-invoke build() on prior failure"); | ||
| 605 | check(prepared[0].commands[0].pipeline.pipeline == handle<VkPipeline>(0x1001), | ||
| 606 | "prior_compiles_reuse: built compute handle attached"); | ||
| 607 | check(prepared[0].commands[1].pipeline.pipeline == VK_NULL_HANDLE, | ||
| 608 | "prior_compiles_reuse: failed compute dispatch stays dropped"); | ||
| 609 | } | ||
| 610 | |||
| 611 | // Serial compilation stops at the first refused graphics draw (matching pre-unlock serial semantics and | ||
| 612 | // d3d12_pipeline_workers::refused_graphics) instead of compiling later pipelines in the same submission. | ||
| 613 | void serial_stops_at_refused_draw() { | ||
| 614 | Registry registry({ | ||
| 615 | {.compute = false, .pending = true, .fails = false}, | ||
| 616 | {.compute = false, .pending = true, .fails = true}, | ||
| 617 | {.compute = false, .pending = true, .fails = false}, | ||
| 618 | {.compute = false, .pending = true, .fails = false}, | ||
| 619 | }); | ||
| 620 | const std::vector<CommandList> lists = record({{ | ||
| 621 | CommandSpec{.kind = CommandSpec::draw, .pipeline = 1}, | ||
| 622 | CommandSpec{.kind = CommandSpec::draw, .pipeline = 2}, | ||
| 623 | CommandSpec{.kind = CommandSpec::draw, .pipeline = 3}, | ||
| 624 | CommandSpec{.kind = CommandSpec::draw, .pipeline = 4}, | ||
| 625 | }}); | ||
| 626 | std::vector<PreparedList> prepared(1); | ||
| 627 | ReplayFunctions vk = functions(registry); | ||
| 628 | PipelineCompiles compiles; | ||
| 629 | vk.compiles = &compiles; | ||
| 630 | const ReplayResult r = prepare(lists[0], resolve, vk, prepared[0]); | ||
| 631 | check(r == ReplayResult::success && compiles.size() == 4, "serial_stops: collected all 4 draws"); | ||
| 632 | const ReplayResult out = build_pipelines_serial(compiles, std::span(prepared), r); | ||
| 633 | check(out == ReplayResult::unsupported, "serial_stops: refused draw returns unsupported"); | ||
| 634 | check(registry.owners[0]->attempts.size() == 1 && registry.owners[1]->attempts.size() == 1, | ||
| 635 | "serial_stops: built first draw and attempted refused second draw"); | ||
| 636 | check(registry.owners[2]->attempts.empty() && registry.owners[3]->attempts.empty(), | ||
| 637 | "serial_stops: did not compile draws past the first refused draw"); | ||
| 638 | } | ||
| 639 | |||
| 640 | // ---- Large pipelines within a budget. ---- | ||
| 641 | |||
| 642 | // Pipelines that note the order they start in. One with `hold` does not end before `release` is called. | ||
| 643 | struct Shop { | ||
| 644 | struct Item { | ||
| 645 | Shop* shop = nullptr; | ||
| 646 | ComputePipeline pipeline{}; | ||
| 647 | std::string name; | ||
| 648 | bool hold = false; | ||
| 649 | }; | ||
| 650 | std::mutex mutex; | ||
| 651 | std::condition_variable changed; | ||
| 652 | std::vector<std::string> started; | ||
| 653 | std::vector<std::unique_ptr<Item>> items; | ||
| 654 | bool released = false; | ||
| 655 | int large_in = 0, most_large_in = 0; | ||
| 656 | LargeModuleGate* gate = nullptr; // set: a large one takes its place there, as in the layer | ||
| 657 | |||
| 658 | ComputePipeline& add(const std::string& name, std::uint64_t estimate, bool large, bool hold = false) { | ||
| 659 | auto& item = *items.emplace_back(std::make_unique<Item>()); | ||
| 660 | item.shop = this; | ||
| 661 | item.name = name; | ||
| 662 | item.hold = hold; | ||
| 663 | item.pipeline.large = large; | ||
| 664 | item.pipeline.estimate = estimate; | ||
| 665 | item.pipeline.build_context = &item; | ||
| 666 | item.pipeline.build = [](void* context) { | ||
| 667 | auto& i = *static_cast<Item*>(context); | ||
| 668 | Shop& shop = *i.shop; | ||
| 669 | LargeModuleGate::Ticket place; | ||
| 670 | if (shop.gate && i.pipeline.large) place = LargeModuleGate::Ticket(*shop.gate, i.pipeline.estimate); | ||
| 671 | std::unique_lock lock(shop.mutex); | ||
| 672 | shop.started.push_back(i.name); | ||
| 673 | if (i.pipeline.large) shop.most_large_in = std::max(shop.most_large_in, ++shop.large_in); | ||
| 674 | shop.changed.notify_all(); | ||
| 675 | if (i.hold) shop.changed.wait_for(lock, std::chrono::seconds(10), [&] { return shop.released; }); | ||
| 676 | if (i.pipeline.large) --shop.large_in; | ||
| 677 | return handle<VkPipeline>(std::uintptr_t(&i) | 1); | ||
| 678 | }; | ||
| 679 | return item.pipeline; | ||
| 680 | } | ||
| 681 | void fill(PipelineCompiles& compiles) { | ||
| 682 | for (auto& item : items) compiles.add(item->pipeline, PipelineCompiles::User::dispatch); | ||
| 683 | } | ||
| 684 | // Whether `count` have started, within 10 s. | ||
| 685 | bool wait_started(std::size_t count) { | ||
| 686 | std::unique_lock lock(mutex); | ||
| 687 | return changed.wait_for(lock, std::chrono::seconds(10), [&] { return started.size() >= count; }); | ||
| 688 | } | ||
| 689 | void release() { | ||
| 690 | std::lock_guard lock(mutex); | ||
| 691 | released = true; | ||
| 692 | changed.notify_all(); | ||
| 693 | } | ||
| 694 | }; | ||
| 695 | |||
| 696 | // On `threads` threads, which take the jobs in order. | ||
| 697 | void on_threads(unsigned threads, std::size_t count, const std::function<void(std::size_t)>& job) { | ||
| 698 | std::atomic<std::size_t> next = 0; | ||
| 699 | std::vector<std::thread> workers; | ||
| 700 | for (unsigned t = 0; t < threads; ++t) | ||
| 701 | workers.emplace_back([&] { | ||
| 702 | for (std::size_t i; (i = next++) < count;) job(i); | ||
| 703 | }); | ||
| 704 | for (auto& w : workers) w.join(); | ||
| 705 | } | ||
| 706 | |||
| 707 | using Names = std::vector<std::string>; | ||
| 708 | |||
| 709 | // The order and the jobs of the run, on one thread: the largest first, then the others, and the budget read once. | ||
| 710 | void budget_order() { | ||
| 711 | struct Case { | ||
| 712 | std::vector<std::uint64_t> large; | ||
| 713 | std::uint64_t budget; | ||
| 714 | std::size_t lanes; | ||
| 715 | Names order; // of the large ones | ||
| 716 | }; | ||
| 717 | for (const Case& c : {Case{{5, 2, 3, 2, 1}, 5, 3, {"5", "3", "2", "2", "1"}}, | ||
| 718 | Case{{5, 2, 3, 2, 1}, 4, 2, {"5", "3", "2", "2", "1"}}, | ||
| 719 | Case{{5, 2, 3, 2, 1}, 0, 1, {"5", "2", "3", "2", "1"}}, // no budget: in the order they came | ||
| 720 | Case{{5, 2, 3, 2, 1}, 100, 5, {"5", "3", "2", "2", "1"}}, | ||
| 721 | Case{{9}, 5, 1, {"9"}}, // more than the budget: one, alone | ||
| 722 | Case{{9, 9}, 5, 1, {"9", "9"}}, | ||
| 723 | Case{{9, 1}, 5, 1, {"9", "1"}}, | ||
| 724 | Case{{4, 4}, 8, 2, {"4", "4"}}}) { | ||
| 725 | Shop shop; | ||
| 726 | for (const auto size : c.large) shop.add(std::to_string(size), size, true); | ||
| 727 | for (int i = 0; i < 3; ++i) shop.add("s" + std::to_string(i), 0, false); | ||
| 728 | PipelineCompiles compiles; | ||
| 729 | shop.fill(compiles); | ||
| 730 | std::size_t units = 0; | ||
| 731 | unsigned reads = 0; | ||
| 732 | compiles.build([&](std::size_t count, const std::function<void(std::size_t)>& job) { | ||
| 733 | units = count; | ||
| 734 | for (std::size_t i = 0; i < count; ++i) job(i); | ||
| 735 | }, [&] { ++reads; return c.budget; }); | ||
| 736 | Names want = c.order; | ||
| 737 | for (int i = 0; i < 3; ++i) want.push_back("s" + std::to_string(i)); | ||
| 738 | const std::string name = "budget " + std::to_string(c.budget) + " of " + std::to_string(c.large.size()); | ||
| 739 | check(shop.started == want, name + ": another order"); | ||
| 740 | check(units == c.lanes + 3, name + ": " + std::to_string(units) + " jobs, not " + std::to_string(c.lanes + 3)); | ||
| 741 | check(reads == 1, name + ": the budget read " + std::to_string(reads) + " times"); | ||
| 742 | for (std::size_t i = 0; i < shop.items.size(); ++i) | ||
| 743 | check(compiles.built(PipelineCompiles::Ticket(i + 1)) != VK_NULL_HANDLE, name + ": not built"); | ||
| 744 | } | ||
| 745 | // Without a large pipeline the budget is not read, and the jobs are the pipelines. | ||
| 746 | Shop shop; | ||
| 747 | for (int i = 0; i < 3; ++i) shop.add("s" + std::to_string(i), 0, false); | ||
| 748 | PipelineCompiles compiles; | ||
| 749 | shop.fill(compiles); | ||
| 750 | std::size_t units = 0; | ||
| 751 | unsigned reads = 0; | ||
| 752 | compiles.build([&](std::size_t count, const std::function<void(std::size_t)>& job) { | ||
| 753 | units = count; | ||
| 754 | for (std::size_t i = 0; i < count; ++i) job(i); | ||
| 755 | }, [&] { ++reads; return 100u; }); | ||
| 756 | check(units == 3 && reads == 0, "the budget read for pipelines that are not large"); | ||
| 757 | } | ||
| 758 | |||
| 759 | // A large one that does not fit beside the one in is not waited for while others are left: they come first. | ||
| 760 | void budget_others_first() { | ||
| 761 | Shop shop; | ||
| 762 | shop.add("8", 8, true, true); | ||
| 763 | shop.add("4a", 4, true); | ||
| 764 | shop.add("4b", 4, true); | ||
| 765 | for (int i = 0; i < 3; ++i) shop.add("s" + std::to_string(i), 0, false); | ||
| 766 | PipelineCompiles compiles; | ||
| 767 | shop.fill(compiles); | ||
| 768 | std::thread building([&] { | ||
| 769 | compiles.build([&](std::size_t count, const std::function<void(std::size_t)>& job) { | ||
| 770 | check(count == 2 + 3, "two lanes: the two of 4 fit 8 together"); | ||
| 771 | on_threads(2, count, job); | ||
| 772 | }, [] { return 8; }); | ||
| 773 | }); | ||
| 774 | const bool all = shop.wait_started(6); // "8" is held: the other lane does the rest | ||
| 775 | Names seen; | ||
| 776 | { | ||
| 777 | std::lock_guard lock(shop.mutex); | ||
| 778 | seen = shop.started; | ||
| 779 | } | ||
| 780 | shop.release(); | ||
| 781 | building.join(); | ||
| 782 | check(all && seen.size() == 6 && seen[0] == "8", "the large one first"); | ||
| 783 | check(all && std::set<std::string>(seen.begin() + 1, seen.begin() + 4) == std::set<std::string>{"s0", "s1", "s2"}, | ||
| 784 | "the others before the large ones that do not fit"); | ||
| 785 | check(all && seen[4] == "4a" && seen[5] == "4b", "then the next large ones"); | ||
| 786 | } | ||
| 787 | |||
| 788 | // Those that fit together start together, before the others. | ||
| 789 | void budget_fits_together() { | ||
| 790 | Shop shop; | ||
| 791 | shop.add("3", 3, true, true); | ||
| 792 | shop.add("5", 5, true, true); | ||
| 793 | for (int i = 0; i < 2; ++i) shop.add("s" + std::to_string(i), 0, false); | ||
| 794 | PipelineCompiles compiles; | ||
| 795 | shop.fill(compiles); | ||
| 796 | std::thread building([&] { | ||
| 797 | compiles.build([&](std::size_t count, const std::function<void(std::size_t)>& job) { on_threads(2, count, job); }, | ||
| 798 | [] { return 8; }); | ||
| 799 | }); | ||
| 800 | const bool both = shop.wait_started(2); | ||
| 801 | Names seen; | ||
| 802 | { | ||
| 803 | std::lock_guard lock(shop.mutex); | ||
| 804 | seen = shop.started; | ||
| 805 | } | ||
| 806 | shop.release(); | ||
| 807 | building.join(); | ||
| 808 | check(both && std::set<std::string>(seen.begin(), seen.begin() + 2) == std::set<std::string>{"3", "5"}, | ||
| 809 | "two that fit the budget are in together"); | ||
| 810 | check(shop.most_large_in == 2, "two that fit the budget at once"); | ||
| 811 | } | ||
| 812 | |||
| 813 | // The room that a large one leaves is the next large one's, before the others. | ||
| 814 | void budget_room_is_given_back() { | ||
| 815 | Shop shop; | ||
| 816 | shop.add("5", 5, true, true); | ||
| 817 | for (const char* name : {"3a", "3b", "3c"}) shop.add(name, 3, true); | ||
| 818 | for (int i = 0; i < 3; ++i) shop.add("s" + std::to_string(i), 0, false); | ||
| 819 | PipelineCompiles compiles; | ||
| 820 | shop.fill(compiles); | ||
| 821 | std::thread building([&] { | ||
| 822 | compiles.build([&](std::size_t count, const std::function<void(std::size_t)>& job) { | ||
| 823 | check(count == 2 + 3, "two lanes: two of 3 fit 8, three do not"); | ||
| 824 | on_threads(2, count, job); | ||
| 825 | }, [] { return 8; }); | ||
| 826 | }); | ||
| 827 | const bool all = shop.wait_started(7); // "5" is held: the other lane has room for one of 3 at a time | ||
| 828 | Names seen; | ||
| 829 | { | ||
| 830 | std::lock_guard lock(shop.mutex); | ||
| 831 | seen = shop.started; | ||
| 832 | } | ||
| 833 | shop.release(); | ||
| 834 | building.join(); | ||
| 835 | check(all && Names(seen.begin(), seen.begin() + 4) == Names{"5", "3a", "3b", "3c"}, | ||
| 836 | "a large one does not leave its room"); | ||
| 837 | } | ||
| 838 | |||
| 839 | // Graphics and compute pipelines share the budget: what each is expected to take counts alike. | ||
| 840 | void budget_graphics_and_compute() { | ||
| 841 | Shop shop; | ||
| 842 | shop.add("3", 3, true); | ||
| 843 | shop.add("4", 4, true); | ||
| 844 | GraphicsPipeline graphics{}; | ||
| 845 | graphics.large = true; | ||
| 846 | graphics.estimate = 5; | ||
| 847 | graphics.variant = [&](std::uint32_t) { | ||
| 848 | std::lock_guard lock(shop.mutex); | ||
| 849 | shop.started.push_back("5"); | ||
| 850 | return handle<VkPipeline>(5); | ||
| 851 | }; | ||
| 852 | PipelineCompiles compiles; | ||
| 853 | shop.fill(compiles); | ||
| 854 | compiles.add(graphics, 0); | ||
| 855 | std::size_t units = 0; | ||
| 856 | compiles.build([&](std::size_t count, const std::function<void(std::size_t)>& job) { | ||
| 857 | units = count; | ||
| 858 | for (std::size_t i = 0; i < count; ++i) job(i); | ||
| 859 | }, [] { return 8; }); | ||
| 860 | check(shop.started == Names{"5", "4", "3"}, "the largest first, graphics or compute"); | ||
| 861 | check(units == 2, "3 and 4 fit 8, and 5 does not beside them"); | ||
| 862 | } | ||
| 863 | |||
| 864 | // The lanes are no more than could be in: a thread is not kept waiting for room there is none of. | ||
| 865 | void budget_lanes_are_bounded() { | ||
| 866 | Shop shop; | ||
| 867 | for (int i = 0; i < 3; ++i) shop.add("5" + std::to_string(i), 5, true); | ||
| 868 | for (int i = 0; i < 6; ++i) shop.add("s" + std::to_string(i), 0, false); | ||
| 869 | PipelineCompiles compiles; | ||
| 870 | shop.fill(compiles); | ||
| 871 | compiles.build([&](std::size_t count, const std::function<void(std::size_t)>& job) { | ||
| 872 | check(count == 2 + 6, "10 bytes hold two of 5"); | ||
| 873 | on_threads(4, count, job); | ||
| 874 | }, [] { return 10; }); | ||
| 875 | check(shop.started.size() == 9 && shop.most_large_in <= 2, "no more than two large ones at once"); | ||
| 876 | } | ||
| 877 | |||
| 878 | // Every one of them is built once, with the gate of the runtime holding what does not fit, whatever sizes and budget. | ||
| 879 | void budget_random(PipelineWorkers& workers) { | ||
| 880 | std::mt19937 rng(20251127); | ||
| 881 | for (int round = 0; round < 300; ++round) { | ||
| 882 | Shop shop; | ||
| 883 | const std::uint64_t budget = rng() % 20; | ||
| 884 | LargeModuleGate gate([budget] { return budget; }); | ||
| 885 | shop.gate = &gate; | ||
| 886 | const unsigned large = rng() % 10, others = rng() % 10; | ||
| 887 | for (unsigned i = 0; i < large; ++i) shop.add("l" + std::to_string(i), rng() % 12, true); | ||
| 888 | for (unsigned i = 0; i < others; ++i) shop.add("s" + std::to_string(i), 0, false); | ||
| 889 | PipelineCompiles compiles; | ||
| 890 | shop.fill(compiles); | ||
| 891 | compiles.build([&](std::size_t count, const std::function<void(std::size_t)>& job) { workers.run(count, job); }, | ||
| 892 | [budget] { return budget; }); | ||
| 893 | Names names = shop.started; | ||
| 894 | std::sort(names.begin(), names.end()); | ||
| 895 | check(std::adjacent_find(names.begin(), names.end()) == names.end() && names.size() == large + others, | ||
| 896 | "random budget " + std::to_string(round) + ": a pipeline built twice or not at all"); | ||
| 897 | check(gate.inflight() == 0, "random budget " + std::to_string(round) + ": a place not given back"); | ||
| 898 | } | ||
| 899 | } | ||
| 900 | |||
| 550 | } // namespace | 901 | } // namespace |
| 551 | 902 | ||
| 552 | int main() { | 903 | int main() { |
| @@ -555,8 +906,17 @@ int main() { | |||
| 555 | cases(workers); | 906 | cases(workers); |
| 556 | if (threads) many(workers); | 907 | if (threads) many(workers); |
| 557 | reused_lists(workers); | 908 | reused_lists(workers); |
| 909 | prior_compiles_reuse(workers); | ||
| 558 | random_submissions(workers); | 910 | random_submissions(workers); |
| 911 | budget_random(workers); | ||
| 559 | } | 912 | } |
| 913 | serial_stops_at_refused_draw(); | ||
| 914 | budget_order(); | ||
| 915 | budget_others_first(); | ||
| 916 | budget_fits_together(); | ||
| 917 | budget_room_is_given_back(); | ||
| 918 | budget_graphics_and_compute(); | ||
| 919 | budget_lanes_are_bounded(); | ||
| 560 | check(large_together == 0, "two large pipelines were built at once"); | 920 | check(large_together == 0, "two large pipelines were built at once"); |
| 561 | if (failures) return 1; | 921 | if (failures) return 1; |
| 562 | std::printf("replay_pipeline_compiles_test: passed\n"); | 922 | std::printf("replay_pipeline_compiles_test: passed\n"); |
diff --git a/runtime/test/replay_query_predication_test.cpp b/runtime/test/replay_query_predication_test.cpp index 87056a499..352067bca 100644 --- a/runtime/test/replay_query_predication_test.cpp +++ b/runtime/test/replay_query_predication_test.cpp | |||
| @@ -7,7 +7,8 @@ | |||
| 7 | // inside ordinary, the composite sum-and-normalize binary resolve, helper dispatches inside overlapping statistics | 7 | // inside ordinary, the composite sum-and-normalize binary resolve, helper dispatches inside overlapping statistics |
| 8 | // queries, the single-list refusal (D3D-252) and, with a pool, its replay (D3D-399). Cases 15 and 16 check queries | 8 | // queries, the single-list refusal (D3D-252) and, with a pool, its replay (D3D-399). Cases 15 and 16 check queries |
| 9 | // that hold mesh draws, split between the full and the mesh-compatible pool, alone and overlapping (D3D-291). No GPU or | 9 | // that hold mesh draws, split between the full and the mesh-compatible pool, alone and overlapping (D3D-291). No GPU or |
| 10 | // game data. | 10 | // game data. Case 18 checks SO_STATISTICS: overlapping queries on one stream are refused |
| 11 | // (VUID-vkCmdBeginQueryIndexedEXT-queryPool-04753) and streams past maxTransformFeedbackStreams resolve zero (D3D-302). | ||
| 11 | #include "../src/vulkan_replay.h" | 12 | #include "../src/vulkan_replay.h" |
| 12 | #include <cstdint> | 13 | #include <cstdint> |
| 13 | #include <cstdio> | 14 | #include <cstdio> |
| @@ -774,6 +775,105 @@ int main() { | |||
| 774 | "the mesh pool counts the fragment and compute invocations"); | 775 | "the mesh pool counts the fragment and compute invocations"); |
| 775 | } | 776 | } |
| 776 | 777 | ||
| 778 | // 18. D3D-302: two overlapping SO_STATISTICS queries on one stream would be two active indexed queries in one | ||
| 779 | // pool (VUID-vkCmdBeginQueryIndexedEXT-queryPool-04753). prepare() refuses them; different streams are fine. | ||
| 780 | // A stream past the pool's maxTransformFeedbackStreams runs nothing and resolves zero. | ||
| 781 | { | ||
| 782 | QueryPool so{handle<VkQueryPool>(8), d3d12_query_heap::so_statistics, 4, false, | ||
| 783 | std::vector<bool>(4, false), {}, 4}; | ||
| 784 | ReplayFunctions indexed = vk; | ||
| 785 | indexed.query_pool = [&](QueryHeapId id) -> QueryPool* { return id == 8 ? &so : nullptr; }; | ||
| 786 | indexed.begin_query_indexed = +[](VkCommandBuffer, VkQueryPool pool, std::uint32_t index, | ||
| 787 | std::uint32_t stream, VkQueryControlFlags) { | ||
| 788 | g_trace->events.push_back(query_event("begin_indexed", pool, index) + "/" + std::to_string(stream)); | ||
| 789 | }; | ||
| 790 | indexed.end_query_indexed = +[](VkCommandBuffer, VkQueryPool pool, std::uint32_t index, | ||
| 791 | std::uint32_t stream) { | ||
| 792 | g_trace->events.push_back(query_event("end_indexed", pool, index) + "/" + std::to_string(stream)); | ||
| 793 | }; | ||
| 794 | |||
| 795 | { | ||
| 796 | CommandList list; | ||
| 797 | expect(list.begin_query({8, d3d12_query::so_statistics_stream0, 0}), "record SO begin stream 0"); | ||
| 798 | expect(list.begin_query({8, d3d12_query::so_statistics_stream0, 1}), "record second SO begin stream 0"); | ||
| 799 | expect(list.end_query({8, d3d12_query::so_statistics_stream0, 1}), "record second SO end stream 0"); | ||
| 800 | expect(list.end_query({8, d3d12_query::so_statistics_stream0, 0}), "record SO end stream 0"); | ||
| 801 | expect(list.close(), "close overlapping SO stream list"); | ||
| 802 | PreparedList prepared; | ||
| 803 | expect(prepare(list, resolve, indexed, prepared) == ReplayResult::invalid_query, | ||
| 804 | "two overlapping SO_STATISTICS queries on one stream are refused"); | ||
| 805 | } | ||
| 806 | { | ||
| 807 | CommandList list; | ||
| 808 | expect(list.begin_query({8, d3d12_query::so_statistics_stream0, 0}), "record SO begin stream 0"); | ||
| 809 | expect(list.begin_query({8, d3d12_query::so_statistics_stream0 + 1, 1}), "record SO begin stream 1"); | ||
| 810 | expect(list.end_query({8, d3d12_query::so_statistics_stream0 + 1, 1}), "record SO end stream 1"); | ||
| 811 | expect(list.end_query({8, d3d12_query::so_statistics_stream0, 0}), "record SO end stream 0"); | ||
| 812 | expect(list.close(), "close two-stream SO list"); | ||
| 813 | PreparedList prepared; | ||
| 814 | expect(prepare(list, resolve, indexed, prepared) == ReplayResult::success, | ||
| 815 | "overlapping SO_STATISTICS queries on different streams are fine"); | ||
| 816 | } | ||
| 817 | // The VUID holds per command buffer, not per pool: one stream in two heaps is refused too, while queries that | ||
| 818 | // take turns on that stream are fine. | ||
| 819 | QueryPool so2{handle<VkQueryPool>(9), d3d12_query_heap::so_statistics, 4, false, | ||
| 820 | std::vector<bool>(4, false), {}, 4}; | ||
| 821 | ReplayFunctions two_heaps = indexed; | ||
| 822 | two_heaps.query_pool = [&](QueryHeapId id) -> QueryPool* { | ||
| 823 | return id == 8 ? &so : id == 9 ? &so2 : nullptr; | ||
| 824 | }; | ||
| 825 | { | ||
| 826 | CommandList list; | ||
| 827 | expect(list.begin_query({8, d3d12_query::so_statistics_stream0, 0}), "record SO begin stream 0, heap 8"); | ||
| 828 | expect(list.begin_query({9, d3d12_query::so_statistics_stream0, 0}), "record SO begin stream 0, heap 9"); | ||
| 829 | expect(list.end_query({9, d3d12_query::so_statistics_stream0, 0}), "record SO end stream 0, heap 9"); | ||
| 830 | expect(list.end_query({8, d3d12_query::so_statistics_stream0, 0}), "record SO end stream 0, heap 8"); | ||
| 831 | expect(list.close(), "close two-heap SO stream list"); | ||
| 832 | PreparedList prepared; | ||
| 833 | expect(prepare(list, resolve, two_heaps, prepared) == ReplayResult::invalid_query, | ||
| 834 | "overlapping SO_STATISTICS queries on one stream in two heaps are refused"); | ||
| 835 | } | ||
| 836 | { | ||
| 837 | CommandList list; | ||
| 838 | expect(list.begin_query({8, d3d12_query::so_statistics_stream0, 0}), "record SO begin stream 0, heap 8"); | ||
| 839 | expect(list.end_query({8, d3d12_query::so_statistics_stream0, 0}), "record SO end stream 0, heap 8"); | ||
| 840 | expect(list.begin_query({9, d3d12_query::so_statistics_stream0, 0}), "record SO begin stream 0, heap 9"); | ||
| 841 | expect(list.end_query({9, d3d12_query::so_statistics_stream0, 0}), "record SO end stream 0, heap 9"); | ||
| 842 | expect(list.close(), "close two-heap SO stream list in turn"); | ||
| 843 | PreparedList prepared; | ||
| 844 | expect(prepare(list, resolve, two_heaps, prepared) == ReplayResult::success, | ||
| 845 | "SO_STATISTICS queries on one stream in two heaps, one after the other, are fine"); | ||
| 846 | } | ||
| 847 | // A one-stream pool: stream 0 runs, stream 1 is zero-filled and emits nothing. | ||
| 848 | so.streams = 1; | ||
| 849 | { | ||
| 850 | Trace trace; | ||
| 851 | g_trace = &trace; | ||
| 852 | CommandList list; | ||
| 853 | expect(list.begin_query({8, d3d12_query::so_statistics_stream0 + 1, 0}), "record unsupported SO begin"); | ||
| 854 | expect(list.end_query({8, d3d12_query::so_statistics_stream0 + 1, 0}), "record unsupported SO end"); | ||
| 855 | expect(list.resolve_queries({8, d3d12_query::so_statistics_stream0 + 1, 0, 1, 1, 0}), | ||
| 856 | "record unsupported SO resolve"); | ||
| 857 | expect(list.close(), "close unsupported stream list"); | ||
| 858 | expect(replay(list, VK_NULL_HANDLE, resolve, indexed) == ReplayResult::success, | ||
| 859 | "a stream past maxTransformFeedbackStreams replays"); | ||
| 860 | expect(trace.fills == 1 && trace.events == std::vector<std::string>{"fill"}, | ||
| 861 | "a stream past maxTransformFeedbackStreams emits no query and resolves zero"); | ||
| 862 | } | ||
| 863 | { | ||
| 864 | Trace trace; | ||
| 865 | g_trace = &trace; | ||
| 866 | CommandList list; | ||
| 867 | expect(list.begin_query({8, d3d12_query::so_statistics_stream0, 0}), "record supported SO begin"); | ||
| 868 | expect(list.end_query({8, d3d12_query::so_statistics_stream0, 0}), "record supported SO end"); | ||
| 869 | expect(list.close(), "close supported stream list"); | ||
| 870 | expect(replay(list, VK_NULL_HANDLE, resolve, indexed) == ReplayResult::success, | ||
| 871 | "stream 0 on a one-stream pool replays"); | ||
| 872 | expect(trace.events == std::vector<std::string>{"begin_indexed 8:0/0", "end_indexed 8:0/0"}, | ||
| 873 | "stream 0 on a one-stream pool begins and ends indexed on stream 0"); | ||
| 874 | } | ||
| 875 | } | ||
| 876 | |||
| 777 | if (failures) return 1; | 877 | if (failures) return 1; |
| 778 | std::puts("replay_query_predication_test: query resolves suspend conditional rendering around fills, copies and dispatches"); | 878 | std::puts("replay_query_predication_test: query resolves suspend conditional rendering around fills, copies and dispatches"); |
| 779 | return 0; | 879 | return 0; |
diff --git a/runtime/test/replay_uav_clear_offset_test.cpp b/runtime/test/replay_uav_clear_offset_test.cpp index a11da272a..65247e08c 100644 --- a/runtime/test/replay_uav_clear_offset_test.cpp +++ b/runtime/test/replay_uav_clear_offset_test.cpp | |||
| @@ -14,6 +14,7 @@ struct Write { | |||
| 14 | char kind; // 'f' fill, 'u' update, 'c' copy (dst; src in from) | 14 | char kind; // 'f' fill, 'u' update, 'c' copy (dst; src in from) |
| 15 | VkDeviceSize offset, size, from; | 15 | VkDeviceSize offset, size, from; |
| 16 | VkBuffer buffer = VK_NULL_HANDLE, source = VK_NULL_HANDLE; | 16 | VkBuffer buffer = VK_NULL_HANDLE, source = VK_NULL_HANDLE; |
| 17 | std::uint32_t word = 0; | ||
| 17 | }; | 18 | }; |
| 18 | std::vector<Write> writes; | 19 | std::vector<Write> writes; |
| 19 | 20 | ||
| @@ -38,8 +39,8 @@ void reset_texture_capture() { | |||
| 38 | VKAPI_ATTR void VKAPI_CALL barrier(VkCommandBuffer, VkPipelineStageFlags, VkPipelineStageFlags, VkDependencyFlags, | 39 | VKAPI_ATTR void VKAPI_CALL barrier(VkCommandBuffer, VkPipelineStageFlags, VkPipelineStageFlags, VkDependencyFlags, |
| 39 | std::uint32_t, const VkMemoryBarrier*, std::uint32_t, const VkBufferMemoryBarrier*, | 40 | std::uint32_t, const VkMemoryBarrier*, std::uint32_t, const VkBufferMemoryBarrier*, |
| 40 | std::uint32_t, const VkImageMemoryBarrier*) {} | 41 | std::uint32_t, const VkImageMemoryBarrier*) {} |
| 41 | VKAPI_ATTR void VKAPI_CALL fill(VkCommandBuffer, VkBuffer buffer, VkDeviceSize offset, VkDeviceSize size, std::uint32_t) { | 42 | VKAPI_ATTR void VKAPI_CALL fill(VkCommandBuffer, VkBuffer buffer, VkDeviceSize offset, VkDeviceSize size, std::uint32_t word) { |
| 42 | writes.push_back({'f', offset, size, 0, buffer}); | 43 | writes.push_back({'f', offset, size, 0, buffer, VK_NULL_HANDLE, word}); |
| 43 | } | 44 | } |
| 44 | VKAPI_ATTR void VKAPI_CALL update(VkCommandBuffer, VkBuffer, VkDeviceSize offset, VkDeviceSize size, const void*) { | 45 | VKAPI_ATTR void VKAPI_CALL update(VkCommandBuffer, VkBuffer, VkDeviceSize offset, VkDeviceSize size, const void*) { |
| 45 | writes.push_back({'u', offset, size, 0}); | 46 | writes.push_back({'u', offset, size, 0}); |
| @@ -447,7 +448,264 @@ int main() { | |||
| 447 | expect(image_clears == 1 && attachment_clears == 0, | 448 | expect(image_clears == 1 && attachment_clears == 0, |
| 448 | "non-attachable view format whole-view clear uses vkCmdClearColorImage"); | 449 | "non-attachable view format whole-view clear uses vkCmdClearColorImage"); |
| 449 | 450 | ||
| 451 | // ---- 3D volume partial-W and XY rectangle UAV clears (direct and compute queues) ---- | ||
| 452 | { | ||
| 453 | ResourceBinding vol{}; | ||
| 454 | vol.image = reinterpret_cast<VkImage>(std::uintptr_t{0x4000}); | ||
| 455 | vol.format = VK_FORMAT_R8G8B8A8_UNORM; | ||
| 456 | vol.aspects = VK_IMAGE_ASPECT_COLOR_BIT; | ||
| 457 | vol.width = 8; | ||
| 458 | vol.height = 6; | ||
| 459 | vol.depth = 4; | ||
| 460 | vol.mip_levels = 2; | ||
| 461 | vol.array_layers = 1; | ||
| 462 | vol.volume = true; | ||
| 463 | vol.color_attachment = false; | ||
| 464 | |||
| 465 | static std::vector<VkBufferImageCopy> vol_copies; | ||
| 466 | VkDeviceSize last_scratch_req = 0; | ||
| 467 | unsigned scratch_allocs = 0; | ||
| 468 | unsigned prepared_predicates = 0; | ||
| 469 | bool resolved_volume = false; | ||
| 470 | bool scratch_ok = true; | ||
| 471 | VkDeviceSize scratch_offset_out = 256; | ||
| 472 | |||
| 473 | auto make_vol_vk = [&](bool compute_queue) { | ||
| 474 | ReplayFunctions v = tex_vk; | ||
| 475 | v.graphics_family = !compute_queue; | ||
| 476 | v.queue_stages = compute_queue ? detail::queue_stages_compute : 0; | ||
| 477 | if (compute_queue) { | ||
| 478 | v.begin_rendering = nullptr; | ||
| 479 | v.image_view = {}; | ||
| 480 | } | ||
| 481 | v.begin_conditional_rendering = [](VkCommandBuffer, const VkConditionalRenderingBeginInfoEXT*) {}; | ||
| 482 | v.end_conditional_rendering = [](VkCommandBuffer) {}; | ||
| 483 | v.prepare_predicate = [&](VkBuffer source, VkDeviceSize offset, PredicateCapture& out) { | ||
| 484 | ++prepared_predicates; | ||
| 485 | out = {source, offset, scratch, 0, VK_NULL_HANDLE}; | ||
| 486 | return true; | ||
| 487 | }; | ||
| 488 | v.capture_predicate = [](VkCommandBuffer, const PredicateCapture&) {}; | ||
| 489 | v.copy_scratch = [&](VkDeviceSize size, VkBuffer& buffer, VkDeviceSize& offset) { | ||
| 490 | ++scratch_allocs; | ||
| 491 | last_scratch_req = size; | ||
| 492 | if (!scratch_ok) return false; | ||
| 493 | buffer = scratch; | ||
| 494 | offset = scratch_offset_out; | ||
| 495 | return true; | ||
| 496 | }; | ||
| 497 | v.copy_buffer_to_image = [](VkCommandBuffer, VkBuffer, VkImage, VkImageLayout layout, | ||
| 498 | std::uint32_t count, const VkBufferImageCopy* regions) { | ||
| 499 | expect(layout == VK_IMAGE_LAYOUT_GENERAL && count == 1, "3D clear copy uses GENERAL and count 1"); | ||
| 500 | vol_copies.push_back(regions[0]); | ||
| 501 | }; | ||
| 502 | return v; | ||
| 503 | }; | ||
| 504 | |||
| 505 | auto run_vol = [&](const ResourceBinding& b, const UavView& view, bool is_float, | ||
| 506 | std::array<std::uint32_t, 4> values, std::span<const Rect> rects, | ||
| 507 | const ReplayFunctions& v, bool predicate = false) { | ||
| 508 | writes.clear(); | ||
| 509 | vol_copies.clear(); | ||
| 510 | reset_texture_capture(); | ||
| 511 | last_scratch_req = 0; | ||
| 512 | scratch_allocs = 0; | ||
| 513 | prepared_predicates = 0; | ||
| 514 | resolved_volume = false; | ||
| 515 | CommandList list; | ||
| 516 | ResourceBinding pred_buf{}; | ||
| 517 | pred_buf.buffer = reinterpret_cast<VkBuffer>(std::uintptr_t{0x5000}); | ||
| 518 | pred_buf.size = 64; | ||
| 519 | if (predicate) expect(list.set_predication({9, 0, d3d12_predication::equal_zero}), "record predicate"); | ||
| 520 | expect(list.clear_unordered_access(view, is_float, values, rects), "record volume clear"); | ||
| 521 | expect(list.close(), "close volume clear list"); | ||
| 522 | return replay(list, VK_NULL_HANDLE, | ||
| 523 | [&](ResourceId id) -> const ResourceBinding* { | ||
| 524 | if (id == 2) { resolved_volume = true; return &b; } | ||
| 525 | if (id == 9) return &pred_buf; | ||
| 526 | return nullptr; | ||
| 527 | }, | ||
| 528 | v); | ||
| 529 | }; | ||
| 530 | |||
| 531 | const auto direct_vol = make_vol_vk(false); | ||
| 532 | const auto compute_vol = make_vol_vk(true); | ||
| 533 | |||
| 534 | // Whole-mip, non-rect 3D clear stays on vkCmdClearColorImage with zero scratch. | ||
| 535 | expect(run_vol(vol, {2, false, VK_FORMAT_R8G8B8A8_UNORM, 0, 0, 0, 0, 0, 4, true}, false, {1, 2, 3, 4}, {}, | ||
| 536 | direct_vol) == ReplayResult::success && | ||
| 537 | image_clears == 1 && scratch_allocs == 0 && vol_copies.empty(), | ||
| 538 | "whole-mip 3D clear keeps vkCmdClearColorImage fast path"); | ||
| 539 | |||
| 540 | // Partial W slice on mip 0 (FirstWSlice=1, WSize=2) on both direct and compute queues. | ||
| 541 | for (bool comp : {false, true}) { | ||
| 542 | const auto& v = comp ? compute_vol : direct_vol; | ||
| 543 | expect(run_vol(vol, {2, false, VK_FORMAT_R8G8B8A8_UNORM, 0, 0, 0, 0, 1, 2, true}, false, {1, 2, 3, 4}, {}, | ||
| 544 | v) == ReplayResult::success, | ||
| 545 | comp ? "partial 3D clear replays on compute queue" : "partial 3D clear replays on direct queue"); | ||
| 546 | expect(image_clears == 0 && scratch_allocs == 1 && last_scratch_req == 8 * 6 * 4 && | ||
| 547 | writes.size() == 1 && writes[0].kind == 'f' && vol_copies.size() == 2, | ||
| 548 | "partial 3D clear fills one 2D slice and emits 2 depth-1 copies"); | ||
| 549 | if (vol_copies.size() == 2) { | ||
| 550 | expect(vol_copies[0].imageSubresource.mipLevel == 0 && | ||
| 551 | vol_copies[0].imageSubresource.baseArrayLayer == 0 && | ||
| 552 | vol_copies[0].imageSubresource.layerCount == 1 && | ||
| 553 | vol_copies[0].imageOffset.z == 1 && vol_copies[0].imageExtent.depth == 1 && | ||
| 554 | vol_copies[1].imageOffset.z == 2 && vol_copies[1].imageExtent.depth == 1 && | ||
| 555 | vol_copies[0].bufferOffset == 256 && vol_copies[1].bufferOffset == 256, | ||
| 556 | "partial 3D copies target Z=1 and Z=2 on array layer 0"); | ||
| 557 | } | ||
| 558 | } | ||
| 559 | |||
| 560 | // Non-zero mip (mip 1 -> 4x3x2), partial W (FirstWSlice=1, WSize=1) with clipped & overlapping rects. | ||
| 561 | const std::array<Rect, 2> overlap{{{-2, 1, 3, 4}, {1, 0, 5, 2}}}; | ||
| 562 | expect(run_vol(vol, {2, false, VK_FORMAT_R8G8B8A8_UNORM, 0, 0, 0, 1, 1, 1, true}, false, {9, 8, 7, 6}, | ||
| 563 | overlap, direct_vol) == ReplayResult::success && | ||
| 564 | vol_copies.size() == 2 && last_scratch_req == 3 * 2 * 4, | ||
| 565 | "mip-1 partial 3D overlapping rects clip to 4x3 and emit separate copies"); | ||
| 566 | if (vol_copies.size() == 2) { | ||
| 567 | expect(vol_copies[0].imageSubresource.mipLevel == 1 && vol_copies[0].imageOffset.x == 0 && | ||
| 568 | vol_copies[0].imageOffset.y == 1 && vol_copies[0].imageOffset.z == 1 && | ||
| 569 | vol_copies[0].imageExtent.width == 3 && vol_copies[0].imageExtent.height == 2 && | ||
| 570 | vol_copies[1].imageOffset.x == 1 && vol_copies[1].imageOffset.y == 0 && | ||
| 571 | vol_copies[1].imageOffset.z == 1 && vol_copies[1].imageExtent.width == 3 && | ||
| 572 | vol_copies[1].imageExtent.height == 2, | ||
| 573 | "mip-1 clipped rect offsets and extents match"); | ||
| 574 | } | ||
| 575 | |||
| 576 | // Empty clipped rect skips without allocating scratch or emitting commands. | ||
| 577 | const Rect offscreen{10, 10, 12, 12}; | ||
| 578 | expect(run_vol(vol, {2, false, VK_FORMAT_R8G8B8A8_UNORM, 0, 0, 0, 0, 1, 2, true}, false, {1, 2, 3, 4}, | ||
| 579 | std::span<const Rect>(&offscreen, 1), direct_vol) == ReplayResult::success && | ||
| 580 | scratch_allocs == 0 && writes.empty() && vol_copies.empty(), | ||
| 581 | "empty clipped 3D rect skips without scratch"); | ||
| 582 | |||
| 583 | // Tiny 1..3-byte payloads pad fill to 4 bytes and copy exact texel extent. | ||
| 584 | ResourceBinding vol_r8 = vol; | ||
| 585 | vol_r8.format = VK_FORMAT_R8_UINT; | ||
| 586 | const Rect one_px{2, 2, 3, 3}; | ||
| 587 | for (int width : {1, 2, 3}) { | ||
| 588 | const Rect tiny{2, 2, 2 + width, 3}; | ||
| 589 | expect(run_vol(vol_r8, {2, false, VK_FORMAT_R8_UINT, 0, 0, 0, 0, 2, 1, true}, false, {0x5a, 0, 0, 0}, | ||
| 590 | std::span<const Rect>(&tiny, 1), direct_vol) == ReplayResult::success && | ||
| 591 | last_scratch_req == 4 && writes.size() == 1 && writes[0].kind == 'f' && | ||
| 592 | writes[0].word == 0x5a5a5a5au && writes[0].size == 4 && vol_copies.size() == 1 && | ||
| 593 | vol_copies[0].imageExtent.width == std::uint32_t(width) && | ||
| 594 | vol_copies[0].imageExtent.height == 1 && vol_copies[0].imageOffset.z == 2, | ||
| 595 | "1/2/3-byte R8 volume clear fills one private word and copies the exact extent"); | ||
| 596 | } | ||
| 597 | auto vol_r16 = vol; | ||
| 598 | vol_r16.format = VK_FORMAT_R16_UINT; | ||
| 599 | expect(run_vol(vol_r16, {2, false, VK_FORMAT_R16_UINT, 0, 0, 0, 0, 2, 1, true}, false, {0xcdef, 0, 0, 0}, | ||
| 600 | std::span<const Rect>(&one_px, 1), direct_vol) == ReplayResult::success && | ||
| 601 | writes.size() == 1 && writes[0].word == 0xcdefcdefu && writes[0].size == 4 && | ||
| 602 | vol_copies.size() == 1 && vol_copies[0].imageExtent.width == 1, | ||
| 603 | "one R16 texel uses padded scratch without widening the copy"); | ||
| 604 | |||
| 605 | // Wide 16-byte format exceeding 64 KiB per slice tiles cleanly with single vkCmdUpdateBuffer <= 65536 B. | ||
| 606 | ResourceBinding big_vol = vol; | ||
| 607 | big_vol.format = VK_FORMAT_R32G32B32A32_UINT; | ||
| 608 | big_vol.width = 128; | ||
| 609 | big_vol.height = 64; | ||
| 610 | big_vol.depth = 3; | ||
| 611 | big_vol.mip_levels = 1; | ||
| 612 | expect(run_vol(big_vol, {2, false, VK_FORMAT_R32G32B32A32_UINT, 0, 0, 0, 0, 1, 2, true}, false, | ||
| 613 | {1, 2, 3, 4}, {}, direct_vol) == ReplayResult::success && | ||
| 614 | scratch_allocs == 1 && last_scratch_req == 65536 && writes.size() == 1 && | ||
| 615 | writes[0].kind == 'u' && writes[0].size == 65536 && vol_copies.size() == 4, | ||
| 616 | "128x64x2 RGBA32_UINT partial 3D clear tiles into 64 KiB update_buffer chunks"); | ||
| 617 | if (vol_copies.size() == 4) { | ||
| 618 | expect(vol_copies[0].imageOffset.y == 0 && vol_copies[0].imageExtent.height == 32 && | ||
| 619 | vol_copies[0].imageOffset.z == 1 && vol_copies[1].imageOffset.y == 32 && | ||
| 620 | vol_copies[1].imageExtent.height == 32 && vol_copies[1].imageOffset.z == 1 && | ||
| 621 | vol_copies[2].imageOffset.y == 0 && vol_copies[2].imageOffset.z == 2 && | ||
| 622 | vol_copies[3].imageOffset.y == 32 && vol_copies[3].imageOffset.z == 2, | ||
| 623 | "tiled 3D copies cover full 128x64 across both slices"); | ||
| 624 | } | ||
| 625 | |||
| 626 | // Emulated R9G9B9E5_SHAREDEXP on R32_UINT 3D backing replays partial W slice. | ||
| 627 | ResourceBinding vol_e5 = vol; | ||
| 628 | vol_e5.format = VK_FORMAT_R32_UINT; | ||
| 629 | expect(run_vol(vol_e5, {2, false, VK_FORMAT_E5B9G9R9_UFLOAT_PACK32, 0, 0, 0, 0, 1, 2, true}, true, | ||
| 630 | {fbits(1.0f), fbits(2.0f), fbits(4.0f), 0}, {}, direct_vol) == ReplayResult::success && | ||
| 631 | vol_copies.size() == 2 && writes.size() == 1 && writes[0].kind == 'f' && writes[0].word == 0x94010040u, | ||
| 632 | "emulated RGB9E5 volume float clear packs RGB 1, 2, 4 into one shared-exponent word"); | ||
| 633 | expect(run_vol(vol_e5, {2, false, VK_FORMAT_E5B9G9R9_UFLOAT_PACK32, 0, 0, 0, 0, 1, 2, true}, false, | ||
| 634 | {1, 2, 4, 8}, {}, direct_vol) == ReplayResult::success && | ||
| 635 | vol_copies.size() == 2 && writes.size() == 1 && writes[0].word == 0, | ||
| 636 | "emulated RGB9E5 volume uint clear writes zero even for nonzero inputs"); | ||
| 637 | |||
| 638 | // Error and safety contracts: zero commands emitted on any rejection. | ||
| 639 | // Out-of-range W slices. | ||
| 640 | expect(run_vol(vol, {2, false, VK_FORMAT_R8G8B8A8_UNORM, 0, 0, 0, 0, 2, 3, true}, false, {1, 2, 3, 4}, {}, | ||
| 641 | direct_vol) == ReplayResult::invalid_subresource && | ||
| 642 | writes.empty() && vol_copies.empty(), | ||
| 643 | "out-of-range 3D W slice range is rejected as invalid_subresource"); | ||
| 644 | expect(run_vol(vol, {2, false, VK_FORMAT_R8G8B8A8_UNORM, 0, 0, 0, 1, 2, 1, true}, false, {1, 2, 3, 4}, {}, | ||
| 645 | direct_vol) == ReplayResult::invalid_subresource && | ||
| 646 | writes.empty() && vol_copies.empty(), | ||
| 647 | "out-of-range mip-1 3D FirstWSlice is rejected as invalid_subresource"); | ||
| 648 | CommandList invalid; | ||
| 649 | expect(!invalid.clear_unordered_access({2, false, VK_FORMAT_R8G8B8A8_UNORM, 0, 0, 0, 0, 0, 0, true}, false, | ||
| 650 | {1, 2, 3, 4}) && invalid.commands().empty(), | ||
| 651 | "zero 3D WSize is rejected while recording"); | ||
| 652 | |||
| 653 | // Typeless 3D format mismatch refused (both exact_clear_format true and false on staged path). | ||
| 654 | ResourceBinding vol_f32 = vol; | ||
| 655 | vol_f32.format = VK_FORMAT_R32_SFLOAT; | ||
| 656 | expect(run_vol(vol_f32, {2, false, VK_FORMAT_R32_UINT, 0, 0, 0, 0, 1, 2, true}, false, {1, 0, 0, 0}, {}, | ||
| 657 | direct_vol) == ReplayResult::unsupported && | ||
| 658 | writes.empty() && vol_copies.empty(), | ||
| 659 | "typeless 3D format mismatch is refused"); | ||
| 660 | expect(run_vol(vol_f32, {2, false, VK_FORMAT_R32_UINT, 0, 0, 0, 0, 1, 2, false}, false, {1, 0, 0, 0}, {}, | ||
| 661 | direct_vol) == ReplayResult::unsupported && | ||
| 662 | writes.empty() && vol_copies.empty(), | ||
| 663 | "staged 3D format mismatch without exact_clear_format is also refused"); | ||
| 664 | |||
| 665 | // Predicated partial 3D / 3D rect clear refused on BOTH direct and compute lists. | ||
| 666 | expect(run_vol(vol, {2, false, VK_FORMAT_R8G8B8A8_UNORM, 0, 0, 0, 0, 1, 2, true}, false, {1, 2, 3, 4}, {}, | ||
| 667 | direct_vol, true) == ReplayResult::unsupported && | ||
| 668 | prepared_predicates == 1 && resolved_volume && scratch_allocs == 0 && writes.empty() && vol_copies.empty(), | ||
| 669 | "predicated partial 3D clear is refused on direct list"); | ||
| 670 | expect(run_vol(vol, {2, false, VK_FORMAT_R8G8B8A8_UNORM, 0, 0, 0, 0, 0, 4, true}, false, {1, 2, 3, 4}, | ||
| 671 | std::span<const Rect>(&one_px, 1), compute_vol, true) == ReplayResult::unsupported && | ||
| 672 | prepared_predicates == 1 && resolved_volume && scratch_allocs == 0 && writes.empty() && vol_copies.empty(), | ||
| 673 | "predicated 3D rect clear is refused on compute list"); | ||
| 674 | |||
| 675 | // Failed scratch allocation, misaligned offset for 16-byte / 4-byte formats, and offset overflow. | ||
| 676 | scratch_ok = false; | ||
| 677 | expect(run_vol(vol, {2, false, VK_FORMAT_R8G8B8A8_UNORM, 0, 0, 0, 0, 1, 2, true}, false, {1, 2, 3, 4}, {}, | ||
| 678 | direct_vol) == ReplayResult::unsupported && | ||
| 679 | writes.empty() && vol_copies.empty(), | ||
| 680 | "3D staged clear rejects failed scratch allocation"); | ||
| 681 | scratch_ok = true; | ||
| 682 | scratch_offset_out = 8; // 8-byte aligned, NOT 16-byte aligned for RGBA32_UINT | ||
| 683 | expect(run_vol(big_vol, {2, false, VK_FORMAT_R32G32B32A32_UINT, 0, 0, 0, 0, 1, 1, true}, false, {1, 2, 3, 4}, | ||
| 684 | std::span<const Rect>(&one_px, 1), direct_vol) == ReplayResult::unsupported && | ||
| 685 | writes.empty() && vol_copies.empty(), | ||
| 686 | "16-byte 3D clear rejects 8-byte-only aligned scratch offset"); | ||
| 687 | scratch_offset_out = 2; // not 4-byte aligned | ||
| 688 | expect(run_vol(vol, {2, false, VK_FORMAT_R8G8B8A8_UNORM, 0, 0, 0, 0, 1, 1, true}, false, {1, 2, 3, 4}, {}, | ||
| 689 | direct_vol) == ReplayResult::unsupported && | ||
| 690 | writes.empty() && vol_copies.empty(), | ||
| 691 | "4-byte 3D clear rejects 2-byte aligned scratch offset"); | ||
| 692 | scratch_offset_out = UINT64_MAX - 15; // aligned to 16, but the exclusive end is unrepresentable | ||
| 693 | expect(run_vol(big_vol, {2, false, VK_FORMAT_R32G32B32A32_UINT, 0, 0, 0, 0, 1, 1, true}, false, {1, 2, 3, 4}, | ||
| 694 | std::span<const Rect>(&one_px, 1), direct_vol) == ReplayResult::unsupported && | ||
| 695 | writes.empty() && vol_copies.empty(), | ||
| 696 | "3D clear rejects scratch offset + fill_bytes overflow"); | ||
| 697 | scratch_offset_out = 256; | ||
| 698 | |||
| 699 | // Missing update_buffer callback for 16-byte 3D staged clear. | ||
| 700 | ReplayFunctions no_update = direct_vol; | ||
| 701 | no_update.update_buffer = nullptr; | ||
| 702 | expect(run_vol(big_vol, {2, false, VK_FORMAT_R32G32B32A32_UINT, 0, 0, 0, 0, 1, 1, true}, false, {1, 2, 3, 4}, | ||
| 703 | std::span<const Rect>(&one_px, 1), no_update) == ReplayResult::unsupported && | ||
| 704 | writes.empty() && vol_copies.empty(), | ||
| 705 | "16-byte 3D clear without vkCmdUpdateBuffer is rejected"); | ||
| 706 | } | ||
| 707 | |||
| 450 | if (failures) return 1; | 708 | if (failures) return 1; |
| 451 | std::printf("replay_uav_clear_offset: buffer offsets and typeless texture view-format clears all passed\n"); | 709 | std::printf("replay_uav_clear_offset: buffer offsets, typeless texture view-format clears, and 3D sliced/rect clears all passed\n"); |
| 452 | return 0; | 710 | return 0; |
| 453 | } | 711 | } |
diff --git a/runtime/test/root_sig_public_flags_test.cpp b/runtime/test/root_sig_public_flags_test.cpp new file mode 100644 index 000000000..8b8c5d76e --- /dev/null +++ b/runtime/test/root_sig_public_flags_test.cpp | |||
| @@ -0,0 +1,443 @@ | |||
| 1 | // The d3d12_xs root-signature flag mask leaves every public D3D12_ROOT_SIGNATURE_FLAGS value alone (old upstream | ||
| 2 | // PR 7140). | ||
| 3 | // | ||
| 4 | // The shims clear bits 24-31 (kXboxRootSignatureFlagHighByte) of a root signature's flags before the host serializer | ||
| 5 | // or deserializer sees them, on every descriptor and every RTS0 blob, whoever built it. Every public flag in d3d12.h | ||
| 6 | // is in the low 16 bits (the highest is SAMPLER_HEAP_DIRECTLY_INDEXED, 0x800), so a descriptor whose flags fit in 16 | ||
| 7 | // bits must come out of the shims exactly as it went in. That is the case for the retail executable's root | ||
| 8 | // signatures (old upstream PR 7140: a 1.1 descriptor with Flags 0x80, and a decoder whose Flags is a zero-extended | ||
| 9 | // 16-bit read). | ||
| 10 | // | ||
| 11 | // Checked here: | ||
| 12 | // - the helpers, for every flag value in [0, 0xFFFF]: versioned 1.0/1.1/1.2 and legacy descriptors keep the value, and | ||
| 13 | // an RTS0 blob carrying it is not rewritten; | ||
| 14 | // - the registered shims against the host d3d12.dll, for each public flag, 0x80 alone and all of them: the serializers | ||
| 15 | // give the host's result byte for byte (1.0 and 1.1) wherever the host takes the description, the deserializer | ||
| 16 | // returns the same flags. Where the host refuses a description only for the heap-indexed flags (Windows 10's in-box | ||
| 17 | // d3d12.dll, kDirectlyIndexedFlags), the shims serialize it on purpose: their blob is the host's blob for the | ||
| 18 | // flags without those bits, with the full flags in RTS0 and a valid container hash; | ||
| 19 | // - a blob carrying 0x03000000 on top of 0x80 has exactly those two bits cleared and nothing else changed. | ||
| 20 | #include <windows.h> | ||
| 21 | #include <d3d12.h> | ||
| 22 | |||
| 23 | #include <cstdint> | ||
| 24 | #include <cstdio> | ||
| 25 | #include <cstring> | ||
| 26 | #include <vector> | ||
| 27 | |||
| 28 | #include "d3d12_xs_rootsig.h" | ||
| 29 | #include "shims.h" | ||
| 30 | |||
| 31 | namespace { | ||
| 32 | |||
| 33 | int g_failures = 0; | ||
| 34 | |||
| 35 | void check(bool condition, const char* what) { | ||
| 36 | std::printf("%s %s\n", condition ? "PASS" : "FAIL", what); | ||
| 37 | if (!condition) ++g_failures; | ||
| 38 | } | ||
| 39 | |||
| 40 | struct Blobs { | ||
| 41 | ID3DBlob* blob = nullptr; | ||
| 42 | ID3DBlob* error = nullptr; | ||
| 43 | ~Blobs() { | ||
| 44 | if (blob) blob->Release(); | ||
| 45 | if (error) error->Release(); | ||
| 46 | } | ||
| 47 | }; | ||
| 48 | |||
| 49 | // Every D3D12_ROOT_SIGNATURE_FLAGS value in d3d12.h (Windows SDK 10.0.26100, DirectX-Headers 1.721). | ||
| 50 | constexpr D3D12_ROOT_SIGNATURE_FLAGS kPublicFlags[] = { | ||
| 51 | D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT, | ||
| 52 | D3D12_ROOT_SIGNATURE_FLAG_DENY_VERTEX_SHADER_ROOT_ACCESS, | ||
| 53 | D3D12_ROOT_SIGNATURE_FLAG_DENY_HULL_SHADER_ROOT_ACCESS, | ||
| 54 | D3D12_ROOT_SIGNATURE_FLAG_DENY_DOMAIN_SHADER_ROOT_ACCESS, | ||
| 55 | D3D12_ROOT_SIGNATURE_FLAG_DENY_GEOMETRY_SHADER_ROOT_ACCESS, | ||
| 56 | D3D12_ROOT_SIGNATURE_FLAG_DENY_PIXEL_SHADER_ROOT_ACCESS, | ||
| 57 | D3D12_ROOT_SIGNATURE_FLAG_ALLOW_STREAM_OUTPUT, | ||
| 58 | D3D12_ROOT_SIGNATURE_FLAG_LOCAL_ROOT_SIGNATURE, | ||
| 59 | D3D12_ROOT_SIGNATURE_FLAG_DENY_AMPLIFICATION_SHADER_ROOT_ACCESS, | ||
| 60 | D3D12_ROOT_SIGNATURE_FLAG_DENY_MESH_SHADER_ROOT_ACCESS, | ||
| 61 | D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED, | ||
| 62 | D3D12_ROOT_SIGNATURE_FLAG_SAMPLER_HEAP_DIRECTLY_INDEXED, | ||
| 63 | }; | ||
| 64 | |||
| 65 | constexpr uint32_t all_public_flags() { | ||
| 66 | uint32_t all = 0; | ||
| 67 | for (D3D12_ROOT_SIGNATURE_FLAGS f : kPublicFlags) all |= static_cast<uint32_t>(f); | ||
| 68 | return all; | ||
| 69 | } | ||
| 70 | |||
| 71 | static_assert(all_public_flags() == 0xFFFu, "the public flags are the twelve bits 0x1..0x800"); | ||
| 72 | static_assert((all_public_flags() & rt::d3d12_xs::kXboxRootSignatureFlagHighByte) == 0, | ||
| 73 | "no public root-signature flag is in the byte the shims clear"); | ||
| 74 | |||
| 75 | // The executable's direct call site (old upstream PR 7140): version 1.1, no parameters, no samplers, Flags 0x80. | ||
| 76 | constexpr uint32_t kExecutableFlags = 0x80u; | ||
| 77 | static_assert(kExecutableFlags == D3D12_ROOT_SIGNATURE_FLAG_LOCAL_ROOT_SIGNATURE, "0x80 is a public flag"); | ||
| 78 | |||
| 79 | constexpr uint32_t kXboxFlags = 0x03000000u; | ||
| 80 | |||
| 81 | D3D12_ROOT_SIGNATURE_FLAGS as_flags(uint32_t v) { return static_cast<D3D12_ROOT_SIGNATURE_FLAGS>(v); } | ||
| 82 | |||
| 83 | D3D12_VERSIONED_ROOT_SIGNATURE_DESC versioned(D3D_ROOT_SIGNATURE_VERSION version, uint32_t flags) { | ||
| 84 | D3D12_VERSIONED_ROOT_SIGNATURE_DESC d{}; | ||
| 85 | d.Version = version; | ||
| 86 | switch (version) { | ||
| 87 | case D3D_ROOT_SIGNATURE_VERSION_1_0: d.Desc_1_0.Flags = as_flags(flags); break; | ||
| 88 | case D3D_ROOT_SIGNATURE_VERSION_1_1: d.Desc_1_1.Flags = as_flags(flags); break; | ||
| 89 | default: d.Desc_1_2.Flags = as_flags(flags); break; | ||
| 90 | } | ||
| 91 | return d; | ||
| 92 | } | ||
| 93 | |||
| 94 | uint32_t flags_of(const D3D12_VERSIONED_ROOT_SIGNATURE_DESC& d) { | ||
| 95 | switch (d.Version) { | ||
| 96 | case D3D_ROOT_SIGNATURE_VERSION_1_0: return static_cast<uint32_t>(d.Desc_1_0.Flags); | ||
| 97 | case D3D_ROOT_SIGNATURE_VERSION_1_1: return static_cast<uint32_t>(d.Desc_1_1.Flags); | ||
| 98 | default: return static_cast<uint32_t>(d.Desc_1_2.Flags); | ||
| 99 | } | ||
| 100 | } | ||
| 101 | |||
| 102 | // Version and every member of the descriptor the version selects (the union arms share their layout up to Flags). | ||
| 103 | bool same_fields(const D3D12_VERSIONED_ROOT_SIGNATURE_DESC& a, const D3D12_VERSIONED_ROOT_SIGNATURE_DESC& b) { | ||
| 104 | if (a.Version != b.Version) return false; | ||
| 105 | switch (a.Version) { | ||
| 106 | case D3D_ROOT_SIGNATURE_VERSION_1_0: | ||
| 107 | return a.Desc_1_0.NumParameters == b.Desc_1_0.NumParameters && | ||
| 108 | a.Desc_1_0.pParameters == b.Desc_1_0.pParameters && | ||
| 109 | a.Desc_1_0.NumStaticSamplers == b.Desc_1_0.NumStaticSamplers && | ||
| 110 | a.Desc_1_0.pStaticSamplers == b.Desc_1_0.pStaticSamplers && a.Desc_1_0.Flags == b.Desc_1_0.Flags; | ||
| 111 | case D3D_ROOT_SIGNATURE_VERSION_1_1: | ||
| 112 | return a.Desc_1_1.NumParameters == b.Desc_1_1.NumParameters && | ||
| 113 | a.Desc_1_1.pParameters == b.Desc_1_1.pParameters && | ||
| 114 | a.Desc_1_1.NumStaticSamplers == b.Desc_1_1.NumStaticSamplers && | ||
| 115 | a.Desc_1_1.pStaticSamplers == b.Desc_1_1.pStaticSamplers && a.Desc_1_1.Flags == b.Desc_1_1.Flags; | ||
| 116 | default: | ||
| 117 | return a.Desc_1_2.NumParameters == b.Desc_1_2.NumParameters && | ||
| 118 | a.Desc_1_2.pParameters == b.Desc_1_2.pParameters && | ||
| 119 | a.Desc_1_2.NumStaticSamplers == b.Desc_1_2.NumStaticSamplers && | ||
| 120 | a.Desc_1_2.pStaticSamplers == b.Desc_1_2.pStaticSamplers && a.Desc_1_2.Flags == b.Desc_1_2.Flags; | ||
| 121 | } | ||
| 122 | } | ||
| 123 | |||
| 124 | // Byte offset of the RTS0 flags dword in a DXBC container, or 0 when there is none. | ||
| 125 | size_t rts0_flags_offset(const std::vector<uint8_t>& blob) { | ||
| 126 | if (blob.size() < 32 || std::memcmp(blob.data(), "DXBC", 4) != 0) return 0; | ||
| 127 | uint32_t count = 0; | ||
| 128 | std::memcpy(&count, blob.data() + 28, 4); | ||
| 129 | for (uint32_t i = 0; i < count && 32 + i * 4 + 4 <= blob.size(); ++i) { | ||
| 130 | uint32_t off = 0; | ||
| 131 | std::memcpy(&off, blob.data() + 32 + i * 4, 4); | ||
| 132 | if (off <= blob.size() && blob.size() - off >= 8 + 24 && std::memcmp(blob.data() + off, "RTS0", 4) == 0) | ||
| 133 | return off + 8 + 20; | ||
| 134 | } | ||
| 135 | return 0; | ||
| 136 | } | ||
| 137 | |||
| 138 | std::vector<uint8_t> bytes_of(ID3DBlob* blob) { | ||
| 139 | const auto* p = static_cast<const uint8_t*>(blob->GetBufferPointer()); | ||
| 140 | return {p, p + blob->GetBufferSize()}; | ||
| 141 | } | ||
| 142 | |||
| 143 | void rehash(std::vector<uint8_t>& blob) { | ||
| 144 | uint32_t hash[4]; | ||
| 145 | rt::d3d12_xs::dxbc_checksum(blob.data(), blob.size(), hash); | ||
| 146 | std::memcpy(blob.data() + 4, hash, sizeof(hash)); | ||
| 147 | } | ||
| 148 | |||
| 149 | // The host refused flags `f` and took them without kDirectlyIndexedFlags (`host_plain`, its blob for those). The shims | ||
| 150 | // serialize again without the two bits and put them back (serialize_*_keeping_heap_flags, d3d12_xs_rootsig.h), so | ||
| 151 | // their blob must be `host_plain` byte for byte except the RTS0 flags dword, which holds all of `f`, and the | ||
| 152 | // container hash, which must be valid. | ||
| 153 | bool is_heap_flag_fallback(const std::vector<uint8_t>& host_plain, const std::vector<uint8_t>& ours, uint32_t f) { | ||
| 154 | const size_t at = rts0_flags_offset(ours); | ||
| 155 | if (!at || ours.size() != host_plain.size() || rts0_flags_offset(host_plain) != at) return false; | ||
| 156 | uint32_t stored = 0; | ||
| 157 | std::memcpy(&stored, ours.data() + at, 4); | ||
| 158 | if (stored != f) return false; | ||
| 159 | for (size_t i = 0; i < ours.size(); ++i) | ||
| 160 | if ((i < 4 || i >= 20) && (i < at || i >= at + 4) && ours[i] != host_plain[i]) return false; | ||
| 161 | uint32_t hash[4]; | ||
| 162 | rt::d3d12_xs::dxbc_checksum(ours.data(), ours.size(), hash); | ||
| 163 | return std::memcmp(hash, ours.data() + 4, sizeof(hash)) == 0; | ||
| 164 | } | ||
| 165 | |||
| 166 | // The helpers, over the whole range the executable's decoder can produce. | ||
| 167 | void test_helpers_keep_16_bit_flags(const std::vector<uint8_t>& clean_blob) { | ||
| 168 | const D3D_ROOT_SIGNATURE_VERSION versions[] = {D3D_ROOT_SIGNATURE_VERSION_1_0, D3D_ROOT_SIGNATURE_VERSION_1_1, | ||
| 169 | D3D_ROOT_SIGNATURE_VERSION_1_2}; | ||
| 170 | const char* names[] = {"1.0", "1.1", "1.2"}; | ||
| 171 | for (int v = 0; v < 3; ++v) { | ||
| 172 | uint32_t changed = 0; | ||
| 173 | for (uint32_t f = 0; f <= 0xFFFFu; ++f) { | ||
| 174 | const D3D12_VERSIONED_ROOT_SIGNATURE_DESC in = versioned(versions[v], f); | ||
| 175 | D3D12_VERSIONED_ROOT_SIGNATURE_DESC out{}; | ||
| 176 | const bool known = rt::d3d12_xs::copy_versioned_root_signature_desc_clear_xbox_flags(in, out); | ||
| 177 | if (!known || !same_fields(in, out) || flags_of(out) != f) ++changed; | ||
| 178 | } | ||
| 179 | char what[160]; | ||
| 180 | std::snprintf(what, sizeof(what), | ||
| 181 | "versioned %s helper: all 65536 flag values in [0, 0xFFFF] come out unchanged (%u changed)", | ||
| 182 | names[v], changed); | ||
| 183 | check(changed == 0, what); | ||
| 184 | } | ||
| 185 | |||
| 186 | uint32_t legacy_changed = 0; | ||
| 187 | for (uint32_t f = 0; f <= 0xFFFFu; ++f) { | ||
| 188 | D3D12_ROOT_SIGNATURE_DESC in{}; | ||
| 189 | in.Flags = as_flags(f); | ||
| 190 | D3D12_ROOT_SIGNATURE_DESC out{}; | ||
| 191 | rt::d3d12_xs::copy_root_signature_desc_clear_xbox_flags(in, out); | ||
| 192 | if (out.NumParameters != in.NumParameters || out.pParameters != in.pParameters || | ||
| 193 | out.NumStaticSamplers != in.NumStaticSamplers || out.pStaticSamplers != in.pStaticSamplers || | ||
| 194 | out.Flags != in.Flags) | ||
| 195 | ++legacy_changed; | ||
| 196 | } | ||
| 197 | check(legacy_changed == 0, "legacy helper: all 65536 flag values in [0, 0xFFFF] come out unchanged"); | ||
| 198 | |||
| 199 | const size_t at = rts0_flags_offset(clean_blob); | ||
| 200 | check(at != 0, "the host serializer's blob has an RTS0 part"); | ||
| 201 | if (!at) return; | ||
| 202 | std::vector<uint8_t> blob = clean_blob; | ||
| 203 | uint32_t rewritten = 0; | ||
| 204 | for (uint32_t f = 0; f <= 0xFFFFu; ++f) { | ||
| 205 | std::memcpy(blob.data() + at, &f, 4); | ||
| 206 | std::vector<uint8_t> out; | ||
| 207 | if (rt::d3d12_xs::copy_rts0_blob_clear_xbox_flags(blob.data(), blob.size(), out) || !out.empty()) ++rewritten; | ||
| 208 | } | ||
| 209 | check(rewritten == 0, "blob helper: an RTS0 blob with flags in [0, 0xFFFF] is never rewritten"); | ||
| 210 | } | ||
| 211 | |||
| 212 | void test_serializer_shim_matches_host() { | ||
| 213 | using SerializeFn = HRESULT(WINAPI*)(const D3D12_VERSIONED_ROOT_SIGNATURE_DESC*, ID3DBlob**, ID3DBlob**); | ||
| 214 | using LegacyFn = HRESULT(WINAPI*)(const D3D12_ROOT_SIGNATURE_DESC*, D3D_ROOT_SIGNATURE_VERSION, ID3DBlob**, | ||
| 215 | ID3DBlob**); | ||
| 216 | auto shim = reinterpret_cast<SerializeFn>(rt::shims::find("d3d12_xs.dll", "D3D12SerializeVersionedRootSignature")); | ||
| 217 | auto legacy = reinterpret_cast<LegacyFn>(rt::shims::find("d3d12_xs.dll", "D3D12SerializeRootSignature")); | ||
| 218 | check(shim && legacy, "shim registry exposes both d3d12_xs serializers"); | ||
| 219 | if (!shim || !legacy) return; | ||
| 220 | |||
| 221 | std::vector<uint32_t> values; | ||
| 222 | for (D3D12_ROOT_SIGNATURE_FLAGS f : kPublicFlags) values.push_back(static_cast<uint32_t>(f)); | ||
| 223 | values.push_back(all_public_flags()); | ||
| 224 | values.push_back(0); | ||
| 225 | |||
| 226 | // Probed once, as the shim does: does the host serialize an empty 1.2 description? | ||
| 227 | bool host_serializes_1_2 = false; | ||
| 228 | { | ||
| 229 | const D3D12_VERSIONED_ROOT_SIGNATURE_DESC empty12 = versioned(D3D_ROOT_SIGNATURE_VERSION_1_2, 0); | ||
| 230 | Blobs b; | ||
| 231 | host_serializes_1_2 = SUCCEEDED(D3D12SerializeVersionedRootSignature(&empty12, &b.blob, &b.error)); | ||
| 232 | std::printf("host serializer %s root signature 1.2\n", host_serializes_1_2 ? "takes" : "refuses"); | ||
| 233 | } | ||
| 234 | |||
| 235 | const D3D_ROOT_SIGNATURE_VERSION versions[] = {D3D_ROOT_SIGNATURE_VERSION_1_0, D3D_ROOT_SIGNATURE_VERSION_1_1, | ||
| 236 | D3D_ROOT_SIGNATURE_VERSION_1_2}; | ||
| 237 | const char* names[] = {"1.0", "1.1", "1.2"}; | ||
| 238 | for (int v = 0; v < 3; ++v) { | ||
| 239 | int differ = 0, same_bytes = 0, host_refused = 0, heap_fallback = 0, lost_flags = 0, touched_input = 0; | ||
| 240 | for (uint32_t f : values) { | ||
| 241 | const D3D12_VERSIONED_ROOT_SIGNATURE_DESC desc = versioned(versions[v], f); | ||
| 242 | const D3D12_VERSIONED_ROOT_SIGNATURE_DESC before = desc; | ||
| 243 | Blobs host, ours; | ||
| 244 | const HRESULT hr_host = D3D12SerializeVersionedRootSignature(&desc, &host.blob, &host.error); | ||
| 245 | const HRESULT hr_ours = shim(&desc, &ours.blob, &ours.error); | ||
| 246 | if (!same_fields(desc, before)) ++touched_input; | ||
| 247 | if (SUCCEEDED(hr_host)) { | ||
| 248 | if (FAILED(hr_ours) || !ours.blob || !host.blob || bytes_of(host.blob) != bytes_of(ours.blob)) ++differ; | ||
| 249 | else ++same_bytes; | ||
| 250 | } else { | ||
| 251 | ++host_refused; | ||
| 252 | // A host that serializes only up to 1.1 refuses every 1.2 description, and the shim rewrites those | ||
| 253 | // as 1.1. A host that refuses the heap-indexed flags (Windows 10) gets them serialized anyway when it | ||
| 254 | // takes the description without them. Otherwise (1.0, 1.1, or 1.2 on a host that takes 1.2) the shim | ||
| 255 | // must refuse what the host refuses. | ||
| 256 | const bool rewritten_as_1_1 = versions[v] == D3D_ROOT_SIGNATURE_VERSION_1_2 && !host_serializes_1_2; | ||
| 257 | const uint32_t plain_flags = f & ~rt::d3d12_xs::kDirectlyIndexedFlags; | ||
| 258 | bool host_takes_plain = false; | ||
| 259 | if (!rewritten_as_1_1 && plain_flags != f) { | ||
| 260 | const D3D12_VERSIONED_ROOT_SIGNATURE_DESC plain = versioned(versions[v], plain_flags); | ||
| 261 | Blobs host_plain; | ||
| 262 | host_takes_plain = | ||
| 263 | SUCCEEDED(D3D12SerializeVersionedRootSignature(&plain, &host_plain.blob, &host_plain.error)) && | ||
| 264 | host_plain.blob; | ||
| 265 | if (host_takes_plain) { | ||
| 266 | ++heap_fallback; | ||
| 267 | if (hr_ours != S_OK || !ours.blob || | ||
| 268 | !is_heap_flag_fallback(bytes_of(host_plain.blob), bytes_of(ours.blob), f)) | ||
| 269 | ++differ; | ||
| 270 | } | ||
| 271 | } | ||
| 272 | if (!rewritten_as_1_1 && !host_takes_plain && SUCCEEDED(hr_ours)) ++differ; | ||
| 273 | } | ||
| 274 | if (SUCCEEDED(hr_ours) && ours.blob) { | ||
| 275 | ID3D12VersionedRootSignatureDeserializer* de = nullptr; | ||
| 276 | if (FAILED(D3D12CreateVersionedRootSignatureDeserializer(ours.blob->GetBufferPointer(), | ||
| 277 | ours.blob->GetBufferSize(), | ||
| 278 | IID_PPV_ARGS(&de))) || !de) { | ||
| 279 | ++lost_flags; | ||
| 280 | } else { | ||
| 281 | const D3D12_VERSIONED_ROOT_SIGNATURE_DESC* got = de->GetUnconvertedRootSignatureDesc(); | ||
| 282 | if (!got || flags_of(*got) != f) ++lost_flags; | ||
| 283 | de->Release(); | ||
| 284 | } | ||
| 285 | } | ||
| 286 | } | ||
| 287 | char what[240]; | ||
| 288 | std::snprintf(what, sizeof(what), | ||
| 289 | "versioned %s: the shim serializes each public flag, 0x80 and all of them as the host does " | ||
| 290 | "(%d byte-identical, %d refused by the host, %d of those kept with the heap-indexed flags, " | ||
| 291 | "%d different)", | ||
| 292 | names[v], same_bytes, host_refused, heap_fallback, differ); | ||
| 293 | check(differ == 0, what); | ||
| 294 | std::snprintf(what, sizeof(what), "versioned %s: every blob the shim returns deserializes with the same flags", | ||
| 295 | names[v]); | ||
| 296 | check(lost_flags == 0, what); | ||
| 297 | std::snprintf(what, sizeof(what), "versioned %s: the caller's descriptor is never modified", names[v]); | ||
| 298 | check(touched_input == 0, what); | ||
| 299 | } | ||
| 300 | |||
| 301 | // The legacy entry point, 1.0 only (it has no 1.1 descriptor), with the same heap-indexed fallback. | ||
| 302 | int differ = 0, legacy_fallback = 0; | ||
| 303 | for (uint32_t f : values) { | ||
| 304 | D3D12_ROOT_SIGNATURE_DESC desc{}; | ||
| 305 | desc.Flags = as_flags(f); | ||
| 306 | Blobs host, ours; | ||
| 307 | const HRESULT hr_host = D3D12SerializeRootSignature(&desc, D3D_ROOT_SIGNATURE_VERSION_1_0, &host.blob, | ||
| 308 | &host.error); | ||
| 309 | const HRESULT hr_ours = legacy(&desc, D3D_ROOT_SIGNATURE_VERSION_1_0, &ours.blob, &ours.error); | ||
| 310 | if (SUCCEEDED(hr_host)) { | ||
| 311 | if (FAILED(hr_ours) || !host.blob || !ours.blob || bytes_of(host.blob) != bytes_of(ours.blob)) ++differ; | ||
| 312 | continue; | ||
| 313 | } | ||
| 314 | const uint32_t plain_flags = f & ~rt::d3d12_xs::kDirectlyIndexedFlags; | ||
| 315 | bool host_takes_plain = false; | ||
| 316 | if (plain_flags != f) { | ||
| 317 | D3D12_ROOT_SIGNATURE_DESC plain{}; | ||
| 318 | plain.Flags = as_flags(plain_flags); | ||
| 319 | Blobs host_plain; | ||
| 320 | host_takes_plain = SUCCEEDED(D3D12SerializeRootSignature(&plain, D3D_ROOT_SIGNATURE_VERSION_1_0, | ||
| 321 | &host_plain.blob, &host_plain.error)) && | ||
| 322 | host_plain.blob; | ||
| 323 | if (host_takes_plain) { | ||
| 324 | ++legacy_fallback; | ||
| 325 | if (hr_ours != S_OK || !ours.blob || | ||
| 326 | !is_heap_flag_fallback(bytes_of(host_plain.blob), bytes_of(ours.blob), f)) | ||
| 327 | ++differ; | ||
| 328 | } | ||
| 329 | } | ||
| 330 | if (!host_takes_plain && SUCCEEDED(hr_ours)) ++differ; | ||
| 331 | } | ||
| 332 | char legacy_what[200]; | ||
| 333 | std::snprintf(legacy_what, sizeof(legacy_what), | ||
| 334 | "legacy serializer shim gives the host's result for each public flag, 0x80 and all of them " | ||
| 335 | "(%d kept with the heap-indexed flags the host refuses)", | ||
| 336 | legacy_fallback); | ||
| 337 | check(differ == 0, legacy_what); | ||
| 338 | |||
| 339 | // Call site 1 of old upstream PR 7140, by name. | ||
| 340 | const D3D12_VERSIONED_ROOT_SIGNATURE_DESC exe = versioned(D3D_ROOT_SIGNATURE_VERSION_1_1, kExecutableFlags); | ||
| 341 | Blobs host, ours; | ||
| 342 | const HRESULT hr_host = D3D12SerializeVersionedRootSignature(&exe, &host.blob, &host.error); | ||
| 343 | const HRESULT hr_ours = shim(&exe, &ours.blob, &ours.error); | ||
| 344 | check(SUCCEEDED(hr_host) && SUCCEEDED(hr_ours) && host.blob && ours.blob && | ||
| 345 | bytes_of(host.blob) == bytes_of(ours.blob), | ||
| 346 | "1.1, no parameters, Flags 0x80 (the executable's direct call): the shim's blob is the host's, byte for byte"); | ||
| 347 | if (ours.blob) { | ||
| 348 | const std::vector<uint8_t> b = bytes_of(ours.blob); | ||
| 349 | const size_t at = rts0_flags_offset(b); | ||
| 350 | uint32_t stored = 0; | ||
| 351 | if (at) std::memcpy(&stored, b.data() + at, 4); | ||
| 352 | check(at && stored == kExecutableFlags, "the shim's blob stores RTS0 flags 0x80"); | ||
| 353 | } | ||
| 354 | } | ||
| 355 | |||
| 356 | void test_deserializer(const std::vector<uint8_t>& clean_blob) { | ||
| 357 | using DeserializeFn = HRESULT(WINAPI*)(const void*, SIZE_T, REFIID, void**); | ||
| 358 | auto shim = reinterpret_cast<DeserializeFn>(rt::shims::find("d3d12_xs.dll", "D3D12CreateRootSignatureDeserializer")); | ||
| 359 | check(shim != nullptr, "shim registry exposes d3d12_xs!D3D12CreateRootSignatureDeserializer"); | ||
| 360 | const size_t at = rts0_flags_offset(clean_blob); | ||
| 361 | if (!shim || !at) return; | ||
| 362 | |||
| 363 | auto flags_through = [&](const std::vector<uint8_t>& blob, bool through_shim, uint32_t& flags) { | ||
| 364 | ID3D12RootSignatureDeserializer* de = nullptr; | ||
| 365 | const HRESULT hr = through_shim ? shim(blob.data(), blob.size(), IID_PPV_ARGS(&de)) | ||
| 366 | : D3D12CreateRootSignatureDeserializer(blob.data(), blob.size(), | ||
| 367 | IID_PPV_ARGS(&de)); | ||
| 368 | if (FAILED(hr) || !de) return false; | ||
| 369 | flags = static_cast<uint32_t>(de->GetRootSignatureDesc()->Flags); | ||
| 370 | de->Release(); | ||
| 371 | return true; | ||
| 372 | }; | ||
| 373 | |||
| 374 | // Each public flag, 0x80 and all of them, written into a correctly hashed 1.1 blob. | ||
| 375 | int differ = 0; | ||
| 376 | std::vector<uint32_t> values; | ||
| 377 | for (D3D12_ROOT_SIGNATURE_FLAGS f : kPublicFlags) values.push_back(static_cast<uint32_t>(f)); | ||
| 378 | values.push_back(all_public_flags()); | ||
| 379 | for (uint32_t f : values) { | ||
| 380 | std::vector<uint8_t> blob = clean_blob; | ||
| 381 | std::memcpy(blob.data() + at, &f, 4); | ||
| 382 | rehash(blob); | ||
| 383 | uint32_t host_flags = 0, shim_flags = 0; | ||
| 384 | const bool host_ok = flags_through(blob, false, host_flags); | ||
| 385 | const bool shim_ok = flags_through(blob, true, shim_flags); | ||
| 386 | if (host_ok != shim_ok || (shim_ok && (shim_flags != f || host_flags != f))) ++differ; | ||
| 387 | } | ||
| 388 | check(differ == 0, "the deserializer shim returns each public flag, 0x80 and all of them as the host does"); | ||
| 389 | |||
| 390 | // A blob carrying the Xbox bits on top of 0x80: exactly 0x03000000 is cleared, nothing else changes. | ||
| 391 | std::vector<uint8_t> xbox = clean_blob; | ||
| 392 | const uint32_t xbox_flags = kXboxFlags | kExecutableFlags; | ||
| 393 | std::memcpy(xbox.data() + at, &xbox_flags, 4); | ||
| 394 | rehash(xbox); | ||
| 395 | std::vector<uint8_t> cleared; | ||
| 396 | const bool rewritten = rt::d3d12_xs::copy_rts0_blob_clear_xbox_flags(xbox.data(), xbox.size(), cleared); | ||
| 397 | check(rewritten && cleared.size() == xbox.size(), "a blob with flags 0x03000080 is rewritten"); | ||
| 398 | if (!rewritten || cleared.size() != xbox.size()) return; | ||
| 399 | uint32_t got = 0; | ||
| 400 | std::memcpy(&got, cleared.data() + at, 4); | ||
| 401 | check(got == kExecutableFlags && (xbox_flags ^ got) == kXboxFlags, | ||
| 402 | "0x03000080 becomes 0x80: only bits 24 and 25 are cleared"); | ||
| 403 | bool rest_same = true; | ||
| 404 | for (size_t i = 0; i < xbox.size(); ++i) | ||
| 405 | if ((i < 4 || i >= 20) && (i < at || i >= at + 4) && xbox[i] != cleared[i]) rest_same = false; | ||
| 406 | check(rest_same, "every byte outside the flags dword and the container hash is unchanged"); | ||
| 407 | uint32_t hash[4]; | ||
| 408 | rt::d3d12_xs::dxbc_checksum(cleared.data(), cleared.size(), hash); | ||
| 409 | check(std::memcmp(hash, cleared.data() + 4, sizeof(hash)) == 0, "the rewritten blob carries a valid container hash"); | ||
| 410 | uint32_t shim_flags = 0; | ||
| 411 | check(flags_through(xbox, true, shim_flags) && shim_flags == kExecutableFlags, | ||
| 412 | "the deserializer shim hands back 0x80 for a blob with flags 0x03000080"); | ||
| 413 | |||
| 414 | // The mask is the documented byte (d3d12_xs_rootsig.h): the other high bits go too, the low 24 stay. | ||
| 415 | const uint32_t high_and_low = 0xFC000000u | 0x00FF0000u | kExecutableFlags; | ||
| 416 | std::memcpy(xbox.data() + at, &high_and_low, 4); | ||
| 417 | rehash(xbox); | ||
| 418 | const uint32_t low_kept = 0x00FF0000u | kExecutableFlags; | ||
| 419 | check(rt::d3d12_xs::copy_rts0_blob_clear_xbox_flags(xbox.data(), xbox.size(), cleared) && | ||
| 420 | std::memcmp(cleared.data() + at, &low_kept, 4) == 0, | ||
| 421 | "flags 0xFCFF0080 become 0x00FF0080: bits 24-31 are cleared, bits 0-23 kept"); | ||
| 422 | } | ||
| 423 | |||
| 424 | } // namespace | ||
| 425 | |||
| 426 | int main() { | ||
| 427 | std::printf("root_sig_public_flags_test: the d3d12_xs flag mask keeps every public root-signature flag\n"); | ||
| 428 | // A clean 1.1 blob from the host serializer: no parameters, no samplers, flags 0. | ||
| 429 | std::vector<uint8_t> clean; | ||
| 430 | { | ||
| 431 | const D3D12_VERSIONED_ROOT_SIGNATURE_DESC empty = versioned(D3D_ROOT_SIGNATURE_VERSION_1_1, 0); | ||
| 432 | Blobs b; | ||
| 433 | const HRESULT hr = D3D12SerializeVersionedRootSignature(&empty, &b.blob, &b.error); | ||
| 434 | check(SUCCEEDED(hr) && b.blob, "the host serializes an empty 1.1 root signature"); | ||
| 435 | if (b.blob) clean = bytes_of(b.blob); | ||
| 436 | } | ||
| 437 | if (!clean.empty()) test_helpers_keep_16_bit_flags(clean); | ||
| 438 | test_serializer_shim_matches_host(); | ||
| 439 | if (!clean.empty()) test_deserializer(clean); | ||
| 440 | std::printf("root_sig_public_flags_test: %s (%d failure%s)\n", g_failures ? "FAILED" : "OK", g_failures, | ||
| 441 | g_failures == 1 ? "" : "s"); | ||
| 442 | return g_failures ? 1 : 0; | ||
| 443 | } | ||
diff --git a/runtime/test/root_signature_test.cpp b/runtime/test/root_signature_test.cpp index c7f726599..8ecf580ef 100644 --- a/runtime/test/root_signature_test.cpp +++ b/runtime/test/root_signature_test.cpp | |||
| @@ -131,6 +131,39 @@ int main() { | |||
| 131 | check(!r.ok && r.error.find("64-dword") != std::string::npos, | 131 | check(!r.ok && r.error.find("64-dword") != std::string::npos, |
| 132 | "65 constants refused by cost limit"); | 132 | "65 constants refused by cost limit"); |
| 133 | } | 133 | } |
| 134 | // 64 constants are within the cost limit, as on the host: pack() and the graphics stages refuse them only for | ||
| 135 | // the spill past the user SGPRs, and that is what the error says; compute spills them whole. | ||
| 136 | { | ||
| 137 | RootSignature sig; | ||
| 138 | sig.params = {consts(64)}; | ||
| 139 | const PackResult r = pack(sig); | ||
| 140 | check(!r.ok && r.error.find("64-dword") == std::string::npos && r.error.find("spill") != std::string::npos, | ||
| 141 | "64 constants pass the cost limit (refused only as a spill)"); | ||
| 142 | const StagePackResult p = pack_stage(sig, Stage::Pixel); | ||
| 143 | check(!p.ok && p.error.find("64-dword") == std::string::npos && p.error.find("spill") != std::string::npos, | ||
| 144 | "pack_stage: 64 constants pass the cost limit for a pixel shader (refused only as a spill)"); | ||
| 145 | const StagePackResult c = pack_stage(sig, Stage::Compute); | ||
| 146 | check(c.ok && c.d3d12_cost == 64 && c.spill_dword == std::vector<uint32_t>({0}) && c.spill_dwords == 64, | ||
| 147 | "pack_stage: 64 constants pass the cost limit for compute, spilled whole"); | ||
| 148 | sig.params = {consts(32), consts(0), consts(32)}; | ||
| 149 | check(pack(sig).error.find("spill") != std::string::npos, "32 + 0 + 32 constants cost 64, not more"); | ||
| 150 | } | ||
| 151 | // A constant parameter of 0 values is valid on the host (the serializer warns, CreateRootSignature answers | ||
| 152 | // S_OK). It takes no dwords and no cost: the parameters around it pack as if it were absent. | ||
| 153 | { | ||
| 154 | RootSignature sig; | ||
| 155 | sig.params = {consts(0), consts(2), consts(0), view(), consts(0)}; | ||
| 156 | const PackResult r = pack(sig); | ||
| 157 | check(r.ok && r.dword_count == 2 + 2 && r.d3d12_cost == 2 + 2, "zero-value constants pack to no dwords"); | ||
| 158 | check(r.provenance.size() == 4 && r.provenance[0].param_index == 1 && r.provenance[1].param_index == 1 && | ||
| 159 | r.provenance[2].param_index == 3 && r.provenance[2].sub_index == 0 && | ||
| 160 | r.provenance[3].param_index == 3 && r.provenance[3].sub_index == 1, | ||
| 161 | "zero-value constants leave no provenance; their neighbours keep their dwords"); | ||
| 162 | RootSignature alone; | ||
| 163 | alone.params = {consts(0)}; | ||
| 164 | const PackResult a = pack(alone); | ||
| 165 | check(a.ok && a.dword_count == 0 && a.d3d12_cost == 0, "a lone zero-value constant parameter packs"); | ||
| 166 | } | ||
| 134 | // A count that wraps a 32-bit sum (1 + 0xFFFFFFFF) is still refused, not packed past dwords[32]. | 167 | // A count that wraps a 32-bit sum (1 + 0xFFFFFFFF) is still refused, not packed past dwords[32]. |
| 135 | { | 168 | { |
| 136 | rt::rootsig::RootSignature sig; | 169 | rt::rootsig::RootSignature sig; |
| @@ -188,6 +221,19 @@ int main() { | |||
| 188 | const PackResult r = pack(d.sig); | 221 | const PackResult r = pack(d.sig); |
| 189 | check(r.ok && r.dword_count == 3 + 2, "parsed RTS0 packs to 5 dwords"); | 222 | check(r.ok && r.dword_count == 3 + 2, "parsed RTS0 packs to 5 dwords"); |
| 190 | } | 223 | } |
| 224 | // The same blob with 0 values in its constant parameter: parsed and packed, the CBV taking the first dwords. | ||
| 225 | { | ||
| 226 | std::vector<uint8_t> payload = build_payload(); | ||
| 227 | payload[56] = 0; // the constants' value count (payload at 48: register, space, count) | ||
| 228 | const DecodeResult d = parse_rts0(payload.data(), payload.size()); | ||
| 229 | check(d.ok && d.sig.params.size() == 2 && d.sig.params[0].num_values == 0, | ||
| 230 | "RTS0 with a zero-value constant parameter parses"); | ||
| 231 | const PackResult r = pack(d.sig); | ||
| 232 | check(r.ok && r.dword_count == 2 && r.provenance[0].param_index == 1, "zero-value RTS0 packs the CBV at 0"); | ||
| 233 | const StagePackResult c = pack_stage(d.sig, Stage::Compute); | ||
| 234 | check(c.ok && c.first_sgpr.size() == 2 && c.first_sgpr[0] == 4 && c.first_sgpr[1] == 4 && c.end_sgpr == 6, | ||
| 235 | "pack_stage: zero-value RTS0 puts the CBV at s4"); | ||
| 236 | } | ||
| 191 | 237 | ||
| 192 | // RTS0 controls: unknown version, wild offsets and truncation fail loudly. | 238 | // RTS0 controls: unknown version, wild offsets and truncation fail loudly. |
| 193 | { | 239 | { |
| @@ -541,9 +587,26 @@ int main() { | |||
| 541 | bad_param.type = static_cast<ParamType>(0xffffffffu); | 587 | bad_param.type = static_cast<ParamType>(0xffffffffu); |
| 542 | invalid_sig.params = {bad_param}; | 588 | invalid_sig.params = {bad_param}; |
| 543 | check(!pack_stage(invalid_sig, Stage::Compute).ok, "pack_stage: invalid parameter enum rejected"); | 589 | check(!pack_stage(invalid_sig, Stage::Compute).ok, "pack_stage: invalid parameter enum rejected"); |
| 590 | // Zero-value constants are accepted (the host takes them) and take no SGPRs: the next parameter starts where | ||
| 591 | // they would have. | ||
| 544 | RootSignature zero; | 592 | RootSignature zero; |
| 545 | zero.params = {consts(0)}; | 593 | zero.params = {consts(0)}; |
| 546 | check(!pack_stage(zero, Stage::Compute).ok, "pack_stage: zero-value constants rejected"); | 594 | const StagePackResult lone = pack_stage(zero, Stage::Compute); |
| 595 | check(lone.ok && lone.first_sgpr.size() == 1 && lone.first_sgpr[0] == 4 && lone.end_sgpr == 4 && | ||
| 596 | lone.spill_dwords == 0, | ||
| 597 | "pack_stage: zero-value constants accepted"); | ||
| 598 | zero.params = {consts(1), consts(0), table(), consts(0), consts(26)}; | ||
| 599 | const StagePackResult mixed = pack_stage(zero, Stage::Compute); | ||
| 600 | check(mixed.ok && mixed.first_sgpr.size() == 5 && mixed.first_sgpr[0] == 4 && mixed.first_sgpr[1] == 5 && | ||
| 601 | mixed.first_sgpr[2] == 5 && mixed.first_sgpr[3] == 6 && mixed.first_sgpr[4] == 6 && | ||
| 602 | mixed.end_sgpr == 32 && mixed.spill_dwords == 0 && mixed.d3d12_cost == 1 + 1 + 26, | ||
| 603 | "pack_stage: zero-value constants between others fill compute exactly, offsets unchanged"); | ||
| 604 | // In the compute spill array a zero-value constant takes no dwords either: the next parameter shares its offset. | ||
| 605 | zero.params = {consts(28), table(), consts(0), consts(1)}; | ||
| 606 | const StagePackResult spilled = pack_stage(zero, Stage::Compute); | ||
| 607 | check(spilled.ok && spilled.end_sgpr == 32 && | ||
| 608 | spilled.spill_dword == std::vector<uint32_t>({kNoSpill, 0, 1, 1}) && spilled.spill_dwords == 2, | ||
| 609 | "pack_stage: zero-value constants in the compute spill array take no dwords"); | ||
| 547 | RootSignature costly; | 610 | RootSignature costly; |
| 548 | costly.params = {consts(32), consts(33)}; | 611 | costly.params = {consts(32), consts(33)}; |
| 549 | const StagePackResult costly_r = pack_stage(costly, Stage::Compute); | 612 | const StagePackResult costly_r = pack_stage(costly, Stage::Compute); |
diff --git a/runtime/test/shader_library_test.cpp b/runtime/test/shader_library_test.cpp index 2448ab7b8..ee49c48eb 100644 --- a/runtime/test/shader_library_test.cpp +++ b/runtime/test/shader_library_test.cpp | |||
| @@ -820,6 +820,80 @@ int main() { | |||
| 820 | std::filesystem::remove_all(dir); | 820 | std::filesystem::remove_all(dir); |
| 821 | } | 821 | } |
| 822 | 822 | ||
| 823 | // The descriptor-table layout marker (`descriptor_table` in each module's meta, descriptor_table.h): absent is | ||
| 824 | // the old plain layout. The kind word is additive - a tagged module reads it, a plain one ignores it and reads | ||
| 825 | // the index at the same place - so one tagged module needs the tagged layout however many plain ones a merged or | ||
| 826 | // partial index holds; counting entries would let a plain majority hand every tagged module an all-zero kind, and | ||
| 827 | // every image read through another dimension's array would fall back. LEONIDA_DESCRIPTOR_TABLE overrides in the | ||
| 828 | // device, through descriptor_table_layout_from_env. | ||
| 829 | { | ||
| 830 | const auto root = dir / "table_layouts"; | ||
| 831 | const auto write_index = [](const std::filesystem::path& folder, const std::string& modules) { | ||
| 832 | std::filesystem::create_directories(folder); | ||
| 833 | std::ofstream index(folder / "index.json", std::ios::binary); | ||
| 834 | index << "{" << modules << "}"; | ||
| 835 | }; | ||
| 836 | const auto module = [](const char* name, const char* marker) { | ||
| 837 | std::string out = "{\"stage\": \"vs\", \"fssm_sha256\": \"" + std::string(name) + "\""; | ||
| 838 | if (marker) out += ", \"descriptor_table\": \"" + std::string(marker) + "\""; | ||
| 839 | return out + "}"; | ||
| 840 | }; | ||
| 841 | const auto census = [](const ShaderLibrary& library, std::size_t tagged, std::size_t plain) { | ||
| 842 | return library.descriptor_table_census().tagged == tagged && | ||
| 843 | library.descriptor_table_census().plain == plain; | ||
| 844 | }; | ||
| 845 | |||
| 846 | // A library translated before the kind word (or with --descriptor-table plain) is plain. | ||
| 847 | write_index(root, "\"a\": " + module("aa", nullptr) + ", \"b\": " + module("bb", nullptr)); | ||
| 848 | ShaderLibrary all_plain; | ||
| 849 | CHECK(all_plain.load(root.string(), &error)); | ||
| 850 | CHECK(census(all_plain, 0, 2) && | ||
| 851 | all_plain.descriptor_table_layout() == DescriptorTableLayout::plain); | ||
| 852 | |||
| 853 | write_index(root, "\"a\": " + module("aa", "tagged") + ", \"b\": " + module("bb", "tagged")); | ||
| 854 | ShaderLibrary all_tagged; | ||
| 855 | CHECK(all_tagged.load(root.string(), &error)); | ||
| 856 | CHECK(census(all_tagged, 2, 0) && | ||
| 857 | all_tagged.descriptor_table_layout() == DescriptorTableLayout::tagged); | ||
| 858 | |||
| 859 | // One tagged module among plain ones: the tagged layout (the old vote gave the plain majority's choice and | ||
| 860 | // every image of another dimension fell back). | ||
| 861 | write_index(root, "\"a\": " + module("aa", "tagged") + ", \"b\": " + module("bb", nullptr) + ", \"c\": " + | ||
| 862 | module("cc", "plain") + ", \"d\": " + module("dd", nullptr)); | ||
| 863 | ShaderLibrary tagged_minority; | ||
| 864 | CHECK(tagged_minority.load(root.string(), &error)); | ||
| 865 | CHECK(census(tagged_minority, 1, 3) && | ||
| 866 | tagged_minority.descriptor_table_layout() == DescriptorTableLayout::tagged); | ||
| 867 | |||
| 868 | write_index(root, "\"a\": " + module("aa", nullptr) + ", \"b\": " + module("bb", "tagged")); | ||
| 869 | ShaderLibrary tied; | ||
| 870 | CHECK(tied.load(root.string(), &error)); | ||
| 871 | CHECK(census(tied, 1, 1) && tied.descriptor_table_layout() == DescriptorTableLayout::tagged); | ||
| 872 | |||
| 873 | // A sub-index's marker counts too, and loading a folder replaces the census rather than adding to it. | ||
| 874 | write_index(root, "\"a\": " + module("aa", nullptr) + ", \"b\": " + module("bb", nullptr)); | ||
| 875 | write_index(root / "fspx", "\"upscaler\": " + module("cc", "tagged")); | ||
| 876 | ShaderLibrary sub_index; | ||
| 877 | CHECK(sub_index.load(root.string(), &error)); | ||
| 878 | CHECK(census(sub_index, 1, 2) && sub_index.descriptor_table_layout() == DescriptorTableLayout::tagged); | ||
| 879 | CHECK(sub_index.load(root.string(), &error) && census(sub_index, 1, 2)); // reload, not accumulate | ||
| 880 | std::filesystem::remove_all(root / "fspx"); | ||
| 881 | CHECK(sub_index.load(root.string(), &error) && census(sub_index, 0, 2) && | ||
| 882 | sub_index.descriptor_table_layout() == DescriptorTableLayout::plain); | ||
| 883 | |||
| 884 | // LEONIDA_DESCRIPTOR_TABLE: an exact layout name wins over the vote; anything else is ignored, and a refused | ||
| 885 | // value leaves the caller's layout alone. | ||
| 886 | DescriptorTableLayout chosen = DescriptorTableLayout::tagged; | ||
| 887 | CHECK(descriptor_table_layout_from_env("plain", &chosen) && chosen == DescriptorTableLayout::plain); | ||
| 888 | CHECK(descriptor_table_layout_from_env("tagged", &chosen) && chosen == DescriptorTableLayout::tagged); | ||
| 889 | CHECK(!descriptor_table_layout_from_env(nullptr, &chosen)); | ||
| 890 | CHECK(!descriptor_table_layout_from_env("", &chosen)); | ||
| 891 | CHECK(!descriptor_table_layout_from_env("Plain", &chosen)); | ||
| 892 | CHECK(!descriptor_table_layout_from_env("other", &chosen)); | ||
| 893 | CHECK(chosen == DescriptorTableLayout::tagged); | ||
| 894 | std::filesystem::remove_all(dir); | ||
| 895 | } | ||
| 896 | |||
| 823 | if (const int line = fspx_checks()) return line; | 897 | if (const int line = fspx_checks()) return line; |
| 824 | 898 | ||
| 825 | // FSPX entries: found by fspx_code_sha256, in the main index or in <dir>/fspx/index.json (named "fspx/<name>"). | 899 | // FSPX entries: found by fspx_code_sha256, in the main index or in <dir>/fspx/index.json (named "fspx/<name>"). |
diff --git a/runtime/test/shaders/build.py b/runtime/test/shaders/build.py index 03a7ecd22..377f7025e 100644 --- a/runtime/test/shaders/build.py +++ b/runtime/test/shaders/build.py | |||
| @@ -198,6 +198,10 @@ def translate_tests(work, names): | |||
| 198 | # 128-byte push constants: the tail in a set-1 uniform block. The values the test programs accept (vk_pc_tail.h). | 198 | # 128-byte push constants: the tail in a set-1 uniform block. The values the test programs accept (vk_pc_tail.h). |
| 199 | if (os.environ.get("LEONIDA_PC_TAIL_UBO") or "").strip().lower() in ("1", "true", "yes", "on"): | 199 | if (os.environ.get("LEONIDA_PC_TAIL_UBO") or "").strip().lower() in ("1", "true", "yes", "on"): |
| 200 | cmd.append("--pc-tail-ubo") | 200 | cmd.append("--pc-tail-ubo") |
| 201 | # The descriptor-table entry layout: tagged (the default) is what the runtime fills. plain is the old one, for a | ||
| 202 | # module translated before the kind word existed (and for the runtime test that must show the old behaviour). | ||
| 203 | if os.environ.get("LEONIDA_DESCRIPTOR_TABLE"): | ||
| 204 | cmd += ["--descriptor-table", os.environ["LEONIDA_DESCRIPTOR_TABLE"]] | ||
| 201 | return subprocess.run(cmd).returncode | 205 | return subprocess.run(cmd).returncode |
| 202 | 206 | ||
| 203 | 207 | ||
diff --git a/runtime/test/shaders/check.py b/runtime/test/shaders/check.py index 4653a37f2..39a3179a4 100644 --- a/runtime/test/shaders/check.py +++ b/runtime/test/shaders/check.py | |||
| @@ -108,7 +108,7 @@ WAVE32_DUMPS = ("cs_store", "cs_signed_zero_nan", "cs_smem_soffset_imm", "cs_wqm | |||
| 108 | "cs_barrier_divergent", "cs_barrier_early_end", "cs_barrier_loop", "cs_w32_lds_u8_d16", "cs_bpermute32", | 108 | "cs_barrier_divergent", "cs_barrier_early_end", "cs_barrier_loop", "cs_w32_lds_u8_d16", "cs_bpermute32", |
| 109 | "cs_w32_lds_subdword", "cs_w32_lds_wide", | 109 | "cs_w32_lds_subdword", "cs_w32_lds_wide", |
| 110 | "cs_w32_partial_scmp", "cs_w32_partial_permute", "cs_exec_const", "cs_w32_mask_imm", "cs_w32_int_ext", | 110 | "cs_w32_partial_scmp", "cs_w32_partial_permute", "cs_exec_const", "cs_w32_mask_imm", "cs_w32_int_ext", |
| 111 | "cs_w32_salu64", "cs_w32_misc_ext", "cs_w32_new_ops", "cs_w32_sincos", "cs_lds_b64_cmpst", "cs_lds_xchg64_ext", "cs_lds_atomics_ext", "cs_w32_andn2_exec", | 111 | "cs_w32_salu64", "cs_w32_misc_ext", "cs_w32_new_ops", "cs_w32_sincos", "cs_lds_b64_cmpst", "cs_lds_xchg64_ext", "cs_lds_atomics_ext", "cs_w32_wrxchg2_ext", "cs_w32_wrxchg2st64", "cs_w32_andn2_exec", |
| 112 | "cs_mask_vgpr_exec", "cs_w32_buffer_sub16", "cs_w32_buffer_store_sub", "cs_w32_fcmpswap", "cs_w32_permlane_fi", | 112 | "cs_mask_vgpr_exec", "cs_w32_buffer_sub16", "cs_w32_buffer_store_sub", "cs_w32_fcmpswap", "cs_w32_permlane_fi", |
| 113 | "cs_w32_exec_computed") | 113 | "cs_w32_exec_computed") |
| 114 | # Wave32 lane-mask dumps: their EXEC/VCC masks and lane selects cover 32 lanes, so a device whose widest subgroup is | 114 | # Wave32 lane-mask dumps: their EXEC/VCC masks and lane selects cover 32 lanes, so a device whose widest subgroup is |
| @@ -117,7 +117,7 @@ WAVE32_DUMPS = ("cs_store", "cs_signed_zero_nan", "cs_smem_soffset_imm", "cs_wqm | |||
| 117 | # otherwise pick a narrower size and return different words (#774). | 117 | # otherwise pick a narrower size and return different words (#774). |
| 118 | WAVE32_LANE_ENV = {"VKC_SUBGROUP_SIZE": "32"} | 118 | WAVE32_LANE_ENV = {"VKC_SUBGROUP_SIZE": "32"} |
| 119 | WAVE32_LANE_DUMPS = ("cs_wqm_w32", "cs_w32_lane_wrap", "cs_w32_permute", "cs_bpermute32", "cs_w32_partial_scmp", "cs_w32_partial_permute", "cs_exec_const", | 119 | WAVE32_LANE_DUMPS = ("cs_wqm_w32", "cs_w32_lane_wrap", "cs_w32_permute", "cs_bpermute32", "cs_w32_partial_scmp", "cs_w32_partial_permute", "cs_exec_const", |
| 120 | "cs_w32_mask_imm", "cs_lds_b64_cmpst", "cs_lds_xchg64_ext", "cs_lds_atomics_ext", "cs_w32_andn2_exec", "cs_mask_vgpr_exec", "cs_w32_permlane_fi", | 120 | "cs_w32_mask_imm", "cs_lds_b64_cmpst", "cs_lds_xchg64_ext", "cs_lds_atomics_ext", "cs_w32_wrxchg2_ext", "cs_w32_wrxchg2st64", "cs_w32_andn2_exec", "cs_mask_vgpr_exec", "cs_w32_permlane_fi", |
| 121 | "cs_w32_exec_computed") | 121 | "cs_w32_exec_computed") |
| 122 | CS_DPP = [("cs_dpp", [1, 0, 3, 2, 5, 4, 7, 6]), | 122 | CS_DPP = [("cs_dpp", [1, 0, 3, 2, 5, 4, 7, 6]), |
| 123 | ("cs_dpp_row", [0, 0, 1, 2, 3, 4, 5, 6]), | 123 | ("cs_dpp_row", [0, 0, 1, 2, 3, 4, 5, 6]), |
| @@ -164,6 +164,12 @@ CS_DUMPS = [*CS_DPP, ("cs_smem_vcc_base", CS_SMEM_VCC), ("cs_store", CS_STORE), | |||
| 164 | # ds_wrxchg*_rtn_b64, ds_or_rtn_b64, ds_min_f32, ds_max_rtn_f32 (cs_lds_xchg64_ext.asm header) | 164 | # ds_wrxchg*_rtn_b64, ds_or_rtn_b64, ds_min_f32, ds_max_rtn_f32 (cs_lds_xchg64_ext.asm header) |
| 165 | ("cs_lds_xchg64_ext", [0x11110003, 0x33333333, 0xF00FF000, 0x04030201, | 165 | ("cs_lds_xchg64_ext", [0x11110003, 0x33333333, 0xF00FF000, 0x04030201, |
| 166 | 0x40302010, 0x70500705, 0x3FC00000, 0x80000000]), | 166 | 0x40302010, 0x70500705, 0x3FC00000, 0x80000000]), |
| 167 | # ds_wrxchg2_rtn_b32's pair cases and ds_wrxchg2st64_rtn_b32 | ||
| 168 | # (cs_w32_wrxchg2_ext.asm / cs_w32_wrxchg2st64.asm headers) | ||
| 169 | ("cs_w32_wrxchg2_ext", [0x77777777, 0x88880008, 0x99990009, 0xDEADBEEF, | ||
| 170 | 0xAAAAAAAA, 0xBBBBBBBB, 0x12341234, 0x56785678]), | ||
| 171 | ("cs_w32_wrxchg2st64", [0x33333333, 0x44444444, 0x55550005, 0x66660006, | ||
| 172 | 0xB0B00084, 0xB0B00088, 0xB0B00140, 0xB0B002C0]), | ||
| 167 | # ds_mskor, ds_and/xor_b64, ds_add_rtn_f32, ds_inc/dec/rsub_u32 (cs_lds_atomics_ext.asm header) | 173 | # ds_mskor, ds_and/xor_b64, ds_add_rtn_f32, ds_inc/dec/rsub_u32 (cs_lds_atomics_ext.asm header) |
| 168 | ("cs_lds_atomics_ext", [0xF0F11234, 0xAB34CD78, 0x12345678, 0xF0F00F0F, | 174 | ("cs_lds_atomics_ext", [0xF0F11234, 0xAB34CD78, 0x12345678, 0xF0F00F0F, |
| 169 | 0xA5A55A5A, 0x00AA00AA, 0x7FB00000, 0xFE090700]), | 175 | 0xA5A55A5A, 0x00AA00AA, 0x7FB00000, 0xFE090700]), |
| @@ -776,7 +782,8 @@ W64X_DUMPS = [("cs_dpp_w64", [1, 0, 3, 2, 5, 4, 7, 6]), | |||
| 776 | ("cs_w64x_cmp_sdst", [10240, 6144, 2053, 8224, 7714, 6184, 4144, 5])] | 782 | ("cs_w64x_cmp_sdst", [10240, 6144, 2053, 8224, 7714, 6184, 4144, 5])] |
| 777 | # A 40-thread group (one partial wave) cannot use --require-wave64 (full subgroups), so it asks for subgroup size 64. | 783 | # A 40-thread group (one partial wave) cannot use --require-wave64 (full subgroups), so it asks for subgroup size 64. |
| 778 | W64X_PARTIAL = [("cs_w64x_partial", [40, 40, 528, 0, 0, 532, 539, 524820]), | 784 | W64X_PARTIAL = [("cs_w64x_partial", [40, 40, 528, 0, 0, 532, 539, 524820]), |
| 779 | ("cs_w64x_partial_scmp", [0, 1, 0, 1, 1, 1, 1, 0])] | 785 | ("cs_w64x_partial_scmp", [0, 1, 0, 1, 1, 1, 1, 0]), |
| 786 | ("cs_w64x_partial_swizzle", [508, 523, 0, 0, 528, 0, 531, 0])] | ||
| 780 | PIXEL_BITS = {"ps_clip_color": (0x3e800000, 0x3f000000, 0x3f400000, 0x3f800000), | 787 | PIXEL_BITS = {"ps_clip_color": (0x3e800000, 0x3f000000, 0x3f400000, 0x3f800000), |
| 781 | # exp mrt0 done (no vm) with every lane on, EXEC off afterwards: written (.asm header, measured on gfx1036) | 788 | # exp mrt0 done (no vm) with every lane on, EXEC off afterwards: written (.asm header, measured on gfx1036) |
| 782 | "ps_exp_color_mask": (0x40000000, 0x40800000, 0x40000000, 0x40800000), | 789 | "ps_exp_color_mask": (0x40000000, 0x40800000, 0x40000000, 0x40800000), |
diff --git a/runtime/test/shaders/cs_w32_wrxchg2_ext.asm b/runtime/test/shaders/cs_w32_wrxchg2_ext.asm new file mode 100644 index 000000000..8744ddeca --- /dev/null +++ b/runtime/test/shaders/cs_w32_wrxchg2_ext.asm | |||
| @@ -0,0 +1,91 @@ | |||
| 1 | ; GPU test for ds_wrxchg2_rtn_b32, part two: the four cases cs_w32_new_ops.asm leaves out | ||
| 2 | ; (docs/design.md "ds_wrxchg2_rtn_b32, ds_wrxchg2st64_rtn_b32" row). cs_w32_new_ops covers the first | ||
| 3 | ; returned word and data1 in LDS with offset0:2 offset1:5; this fixture covers: | ||
| 4 | ; | ||
| 5 | ; - the SECOND returned word of the pair, which is data0 when both offsets name one dword | ||
| 6 | ; - both offsets on one dword (the second exchange reads back what the first wrote) | ||
| 7 | ; - vdst aliasing the data VGPRs (the data must be read before vdst is written) | ||
| 8 | ; - that an exchange at one base leaves a neighbouring LDS word alone | ||
| 9 | ; | ||
| 10 | ; LDS 4 KiB (RSRC2 0x40088), group 32x1x1, only lane 0 runs (32 lanes on one LDS address would race: | ||
| 11 | ; which lane's exchange runs first is up to the hardware). LDS is seeded by ds_write_b32 before each case. | ||
| 12 | ; Every word is stored raw, in this order: | ||
| 13 | ; | ||
| 14 | ; out[0] both offsets on one dword: ds_wrxchg2_rtn_b32 at base 0x200, offset0:1 offset1:1 | ||
| 15 | ; (both = element 0x204). Seeded M[0x204]=0x77777777, data0=0x88880008, data1=0x99990009. | ||
| 16 | ; vdst[0] = the word the first exchange took out of M -> 0x77777777 | ||
| 17 | ; out[1] vdst[1] = the second exchange's return, which is data0, not the | ||
| 18 | ; word the first exchange wrote -> 0x88880008 | ||
| 19 | ; out[2] M[0x204] after both: data1 landed -> 0x99990009 | ||
| 20 | ; out[3] M[0x700], seeded 0xDEADBEEF before the exchange and read after it: | ||
| 21 | ; the exchange touched only 0x204 -> 0xDEADBEEF | ||
| 22 | ; out[4] vdst aliases the data VGPRs: ds_wrxchg2_rtn_b32 v[4:5], ... with v4=0x12341234 v5=0x56785678 | ||
| 23 | ; at base 0x300, offset0:0 offset1:2, M[0x300]=0xAAAAAAAA, M[0x308]=0xBBBBBBBB. | ||
| 24 | ; vdst[0] = the old word, so the data was read before the write -> 0xAAAAAAAA | ||
| 25 | ; out[5] vdst[1] = the old word at 0x308 -> 0xBBBBBBBB | ||
| 26 | ; out[6] M[0x300] after: data0 -> 0x12341234 | ||
| 27 | ; out[7] M[0x308] after: data1 -> 0x56785678 | ||
| 28 | ; | ||
| 29 | ; Run: vk_compute_test cs_w32_wrxchg2_ext.spv 1 dump | ||
| 30 | ; -> out[0..7] = 0x77777777 0x88880008 0x99990009 0xDEADBEEF | ||
| 31 | ; 0xAAAAAAAA 0xBBBBBBBB 0x12341234 0x56785678 | ||
| 32 | ; rsrc2: 0x40088 | ||
| 33 | ; group: 32,1,1 | ||
| 34 | ; mattr: +wavefrontsize32,-wavefrontsize64 | ||
| 35 | v_cmpx_eq_u32_e32 0, v0 | ||
| 36 | |||
| 37 | ; --- both offsets on one dword (element 0x204) --- | ||
| 38 | v_mov_b32_e32 v1, 0x204 | ||
| 39 | v_mov_b32_e32 v4, 0x77777777 | ||
| 40 | ds_write_b32 v1, v4 | ||
| 41 | v_mov_b32_e32 v2, 0x700 | ||
| 42 | v_mov_b32_e32 v5, 0xDEADBEEF | ||
| 43 | ds_write_b32 v2, v5 | ||
| 44 | s_waitcnt lgkmcnt(0) | ||
| 45 | v_mov_b32_e32 v1, 0x200 | ||
| 46 | v_mov_b32_e32 v4, 0x88880008 | ||
| 47 | v_mov_b32_e32 v5, 0x99990009 | ||
| 48 | ds_wrxchg2_rtn_b32 v[12:13], v1, v4, v5 offset0:1 offset1:1 | ||
| 49 | s_waitcnt lgkmcnt(0) | ||
| 50 | v_mov_b32_e32 v21, 0 | ||
| 51 | buffer_store_dword v12, v21, s[0:3], 0 offen | ||
| 52 | v_mov_b32_e32 v21, 4 | ||
| 53 | buffer_store_dword v13, v21, s[0:3], 0 offen | ||
| 54 | v_mov_b32_e32 v1, 0x204 | ||
| 55 | ds_read_b32 v10, v1 | ||
| 56 | v_mov_b32_e32 v2, 0x700 | ||
| 57 | ds_read_b32 v11, v2 | ||
| 58 | s_waitcnt lgkmcnt(0) | ||
| 59 | v_mov_b32_e32 v21, 8 | ||
| 60 | buffer_store_dword v10, v21, s[0:3], 0 offen | ||
| 61 | v_mov_b32_e32 v21, 12 | ||
| 62 | buffer_store_dword v11, v21, s[0:3], 0 offen | ||
| 63 | |||
| 64 | ; --- vdst aliases the data VGPRs --- | ||
| 65 | v_mov_b32_e32 v1, 0x300 | ||
| 66 | v_mov_b32_e32 v4, 0xAAAAAAAA | ||
| 67 | ds_write_b32 v1, v4 | ||
| 68 | v_mov_b32_e32 v2, 0x308 | ||
| 69 | v_mov_b32_e32 v5, 0xBBBBBBBB | ||
| 70 | ds_write_b32 v2, v5 | ||
| 71 | s_waitcnt lgkmcnt(0) | ||
| 72 | v_mov_b32_e32 v1, 0x300 | ||
| 73 | v_mov_b32_e32 v4, 0x12341234 | ||
| 74 | v_mov_b32_e32 v5, 0x56785678 | ||
| 75 | ds_wrxchg2_rtn_b32 v[4:5], v1, v4, v5 offset0:0 offset1:2 | ||
| 76 | s_waitcnt lgkmcnt(0) | ||
| 77 | v_mov_b32_e32 v21, 16 | ||
| 78 | buffer_store_dword v4, v21, s[0:3], 0 offen | ||
| 79 | v_mov_b32_e32 v21, 20 | ||
| 80 | buffer_store_dword v5, v21, s[0:3], 0 offen | ||
| 81 | ds_read_b32 v10, v1 | ||
| 82 | s_waitcnt lgkmcnt(0) | ||
| 83 | v_mov_b32_e32 v21, 24 | ||
| 84 | buffer_store_dword v10, v21, s[0:3], 0 offen | ||
| 85 | v_mov_b32_e32 v1, 0x308 | ||
| 86 | ds_read_b32 v11, v1 | ||
| 87 | s_waitcnt lgkmcnt(0) | ||
| 88 | v_mov_b32_e32 v21, 28 | ||
| 89 | buffer_store_dword v11, v21, s[0:3], 0 offen | ||
| 90 | |||
| 91 | s_endpgm | ||
diff --git a/runtime/test/shaders/cs_w32_wrxchg2st64.asm b/runtime/test/shaders/cs_w32_wrxchg2st64.asm new file mode 100644 index 000000000..2f2b25a9a --- /dev/null +++ b/runtime/test/shaders/cs_w32_wrxchg2st64.asm | |||
| @@ -0,0 +1,93 @@ | |||
| 1 | ; GPU test for ds_wrxchg2st64_rtn_b32 (docs/design.md "ds_wrxchg2_rtn_b32, ds_wrxchg2st64_rtn_b32" | ||
| 2 | ; row). Neither this form nor the row's st64 step is covered by a GPU fixture on main: cs_w32_new_ops | ||
| 3 | ; runs ds_wrxchg2_rtn_b32 only, and cs_lds_xchg64_ext runs the _b64 pair forms. The row and the gfx1100 | ||
| 4 | ; measurement both say the st64 unit is 64 dwords = 256 bytes, i.e. offset0:1 and offset1:2 address | ||
| 5 | ; vaddr + 256 and vaddr + 512; this fixture pins that on a GPU. | ||
| 6 | ; | ||
| 7 | ; LDS 4 KiB (RSRC2 0x40088), group 32x1x1, only lane 0 runs. Base 0x80, so the two elements are at | ||
| 8 | ; 0x180 and 0x280 and neither is where a non-st64 unit would have put them (0x84 and 0x88) - those two | ||
| 9 | ; words are seeded too and must come back untouched, which is what proves the step size. | ||
| 10 | ; Every word is stored raw, in this order: | ||
| 11 | ; | ||
| 12 | ; out[0] vdst[0] = the old word at 0x180 -> 0x33333333 | ||
| 13 | ; out[1] vdst[1] = the old word at 0x280 -> 0x44444444 | ||
| 14 | ; out[2] M[0x180] after: data0 -> 0x55550005 | ||
| 15 | ; out[3] M[0x280] after: data1 -> 0x66660006 | ||
| 16 | ; out[4] M[0x84], where a 4-byte step would have written data0: untouched -> 0xB0B00084 | ||
| 17 | ; out[5] M[0x88], where a 4-byte step would have written data1: untouched -> 0xB0B00088 | ||
| 18 | ; out[6] M[0x140], one 256-byte step short of 0x180: untouched -> 0xB0B00140 | ||
| 19 | ; out[7] M[0x2c0], one 256-byte step past 0x280: untouched -> 0xB0B002C0 | ||
| 20 | ; | ||
| 21 | ; Run: vk_compute_test cs_w32_wrxchg2st64.spv 1 dump | ||
| 22 | ; -> out[0..7] = 0x33333333 0x44444444 0x55550005 0x66660006 | ||
| 23 | ; 0xB0B00084 0xB0B00088 0xB0B00140 0xB0B002C0 | ||
| 24 | ; rsrc2: 0x40088 | ||
| 25 | ; group: 32,1,1 | ||
| 26 | ; mattr: +wavefrontsize32,-wavefrontsize64 | ||
| 27 | v_cmpx_eq_u32_e32 0, v0 | ||
| 28 | |||
| 29 | ; --- seed the two real elements and the four words the exchange must not touch --- | ||
| 30 | v_mov_b32_e32 v1, 0x180 | ||
| 31 | v_mov_b32_e32 v4, 0x33333333 | ||
| 32 | ds_write_b32 v1, v4 | ||
| 33 | v_mov_b32_e32 v1, 0x280 | ||
| 34 | v_mov_b32_e32 v4, 0x44444444 | ||
| 35 | ds_write_b32 v1, v4 | ||
| 36 | v_mov_b32_e32 v1, 0x84 | ||
| 37 | v_mov_b32_e32 v4, 0xB0B00084 | ||
| 38 | ds_write_b32 v1, v4 | ||
| 39 | v_mov_b32_e32 v1, 0x88 | ||
| 40 | v_mov_b32_e32 v4, 0xB0B00088 | ||
| 41 | ds_write_b32 v1, v4 | ||
| 42 | v_mov_b32_e32 v1, 0x140 | ||
| 43 | v_mov_b32_e32 v4, 0xB0B00140 | ||
| 44 | ds_write_b32 v1, v4 | ||
| 45 | v_mov_b32_e32 v1, 0x2C0 | ||
| 46 | v_mov_b32_e32 v4, 0xB0B002C0 | ||
| 47 | ds_write_b32 v1, v4 | ||
| 48 | s_waitcnt lgkmcnt(0) | ||
| 49 | |||
| 50 | ; --- the st64 pair exchange: base 0x80, offset0:1 offset1:2 --- | ||
| 51 | v_mov_b32_e32 v4, 0x55550005 | ||
| 52 | v_mov_b32_e32 v5, 0x66660006 | ||
| 53 | v_mov_b32_e32 v1, 0x80 | ||
| 54 | ds_wrxchg2st64_rtn_b32 v[12:13], v1, v4, v5 offset0:1 offset1:2 | ||
| 55 | s_waitcnt lgkmcnt(0) | ||
| 56 | |||
| 57 | v_mov_b32_e32 v21, 0 | ||
| 58 | buffer_store_dword v12, v21, s[0:3], 0 offen | ||
| 59 | v_mov_b32_e32 v21, 4 | ||
| 60 | buffer_store_dword v13, v21, s[0:3], 0 offen | ||
| 61 | |||
| 62 | ; --- read back the two elements and the four words that must be untouched --- | ||
| 63 | v_mov_b32_e32 v1, 0x180 | ||
| 64 | ds_read_b32 v10, v1 | ||
| 65 | v_mov_b32_e32 v2, 0x280 | ||
| 66 | ds_read_b32 v11, v2 | ||
| 67 | s_waitcnt lgkmcnt(0) | ||
| 68 | v_mov_b32_e32 v21, 8 | ||
| 69 | buffer_store_dword v10, v21, s[0:3], 0 offen | ||
| 70 | v_mov_b32_e32 v21, 12 | ||
| 71 | buffer_store_dword v11, v21, s[0:3], 0 offen | ||
| 72 | |||
| 73 | v_mov_b32_e32 v1, 0x84 | ||
| 74 | ds_read_b32 v3, v1 | ||
| 75 | v_mov_b32_e32 v1, 0x88 | ||
| 76 | ds_read_b32 v6, v1 | ||
| 77 | s_waitcnt lgkmcnt(0) | ||
| 78 | v_mov_b32_e32 v21, 16 | ||
| 79 | buffer_store_dword v3, v21, s[0:3], 0 offen | ||
| 80 | v_mov_b32_e32 v21, 20 | ||
| 81 | buffer_store_dword v6, v21, s[0:3], 0 offen | ||
| 82 | |||
| 83 | v_mov_b32_e32 v1, 0x140 | ||
| 84 | ds_read_b32 v3, v1 | ||
| 85 | v_mov_b32_e32 v1, 0x2C0 | ||
| 86 | ds_read_b32 v6, v1 | ||
| 87 | s_waitcnt lgkmcnt(0) | ||
| 88 | v_mov_b32_e32 v21, 24 | ||
| 89 | buffer_store_dword v3, v21, s[0:3], 0 offen | ||
| 90 | v_mov_b32_e32 v21, 28 | ||
| 91 | buffer_store_dword v6, v21, s[0:3], 0 offen | ||
| 92 | |||
| 93 | s_endpgm | ||
diff --git a/runtime/test/shaders/cs_w64x_partial_swizzle.asm b/runtime/test/shaders/cs_w64x_partial_swizzle.asm new file mode 100644 index 000000000..44ac9061d --- /dev/null +++ b/runtime/test/shaders/cs_w64x_partial_swizzle.asm | |||
| @@ -0,0 +1,78 @@ | |||
| 1 | ; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm | ||
| 2 | ; Partial wave64, ds_swizzle_b32 / ds_bpermute_b32 from a lane that doesn't exist: a 40x1x1 group is one wave with | ||
| 3 | ; lanes 0-39 running and 40-63 missing. A source lane that doesn't exist reads 0 (RDNA2 ISA, ds_swizzle/ds_bpermute of | ||
| 4 | ; a lane that isn't running; on gfx1036 through tools/hw_oracle, 40 threads, native wave64: lanes 32-39 of SWAP 8 and | ||
| 5 | ; of BROADCAST 16,15 read 0). The exchange sits after a vote and an s_cbranch_execz, as in the crosslane_fuzz | ||
| 6 | ; programs that found it (seed 48315): with --wave64-emulate, RADV (Mesa 26.3.1) turned the store, barrier and load of | ||
| 7 | ; the exchange slot into a subgroup swizzle that fetched the missing lane's register, so lanes 32-39 read garbage | ||
| 8 | ; that changed between runs although the slot was zeroed. | ||
| 9 | ; v1 = lane, v2 = 500 + lane, s8 = s_bcnt1 of EXEC (40, an exchange before the branch). | ||
| 10 | ; v3 = ds_swizzle SWAP 8 of v2 (source lane ^ 8): lane 0 -> 8 -> 508, lane 31 -> 23 -> 523, lane 33 -> 41 -> 0, | ||
| 11 | ; lane 39 -> 47 -> 0. | ||
| 12 | ; v4 = ds_bpermute with addr = (lane ^ 8) * 4 (each half its own 32 lanes): lane 20 -> 28 -> 528, lane 33 -> 41 -> 0. | ||
| 13 | ; v5 = ds_swizzle BROADCAST 16,15 (lane 15 of each group of 16): lane 20 -> 31 -> 531, lane 35 -> 47 -> 0. | ||
| 14 | ; Stores: out[0] lane 0 v3, out[1] lane 31 v3, out[2] lane 33 v3, out[3] lane 39 v3, out[4] lane 20 v4, | ||
| 15 | ; out[5] lane 33 v4, out[6] lane 20 v5, out[7] lane 35 v5. | ||
| 16 | ; As for cs_w64x_partial, 40 threads can't have full subgroups: check.py asks for subgroup size 64 (32 when emulated). | ||
| 17 | ; Run: VKC_SUBGROUP_SIZE=64 vk_compute_test cs_w64x_partial_swizzle.spv 1 dump | ||
| 18 | ; -> out[0..7] = 508 523 0 0 528 0 531 0 | ||
| 19 | ; mattr: +wavefrontsize64,-wavefrontsize32 | ||
| 20 | ; group: 40,1,1 | ||
| 21 | v_mbcnt_lo_u32_b32 v1, -1, 0 | ||
| 22 | v_mbcnt_hi_u32_b32 v1, -1, v1 | ||
| 23 | v_add_nc_u32_e32 v2, 500, v1 | ||
| 24 | v_mov_b32_e32 v3, 99 | ||
| 25 | v_mov_b32_e32 v4, 99 | ||
| 26 | v_mov_b32_e32 v5, 99 | ||
| 27 | s_mov_b64 s[6:7], exec | ||
| 28 | s_bcnt1_i32_b64 s8, exec | ||
| 29 | v_cmp_gt_u32_e64 s[4:5], 48, v1 | ||
| 30 | s_and_saveexec_b64 s[10:11], s[4:5] | ||
| 31 | s_cbranch_execz 9 | ||
| 32 | ds_swizzle_b32 v3, v2 offset:swizzle(SWAP,8) | ||
| 33 | ds_swizzle_b32 v5, v2 offset:swizzle(BROADCAST,16,15) | ||
| 34 | v_xor_b32_e32 v6, 8, v1 | ||
| 35 | v_lshlrev_b32_e32 v6, 2, v6 | ||
| 36 | ds_bpermute_b32 v4, v6, v2 | ||
| 37 | s_waitcnt lgkmcnt(0) | ||
| 38 | s_mov_b64 exec, s[6:7] | ||
| 39 | v_cmpx_eq_u32_e32 0, v1 | ||
| 40 | v_mov_b32_e32 v20, v3 | ||
| 41 | v_mov_b32_e32 v21, 0 | ||
| 42 | buffer_store_dword v20, v21, s[0:3], 0 offen | ||
| 43 | s_mov_b64 exec, s[6:7] | ||
| 44 | v_cmpx_eq_u32_e32 31, v1 | ||
| 45 | v_mov_b32_e32 v20, v3 | ||
| 46 | v_mov_b32_e32 v21, 4 | ||
| 47 | buffer_store_dword v20, v21, s[0:3], 0 offen | ||
| 48 | s_mov_b64 exec, s[6:7] | ||
| 49 | v_cmpx_eq_u32_e32 33, v1 | ||
| 50 | v_mov_b32_e32 v20, v3 | ||
| 51 | v_mov_b32_e32 v21, 8 | ||
| 52 | buffer_store_dword v20, v21, s[0:3], 0 offen | ||
| 53 | s_mov_b64 exec, s[6:7] | ||
| 54 | v_cmpx_eq_u32_e32 39, v1 | ||
| 55 | v_mov_b32_e32 v20, v3 | ||
| 56 | v_mov_b32_e32 v21, 12 | ||
| 57 | buffer_store_dword v20, v21, s[0:3], 0 offen | ||
| 58 | s_mov_b64 exec, s[6:7] | ||
| 59 | v_cmpx_eq_u32_e32 20, v1 | ||
| 60 | v_mov_b32_e32 v20, v4 | ||
| 61 | v_mov_b32_e32 v21, 16 | ||
| 62 | buffer_store_dword v20, v21, s[0:3], 0 offen | ||
| 63 | s_mov_b64 exec, s[6:7] | ||
| 64 | v_cmpx_eq_u32_e32 33, v1 | ||
| 65 | v_mov_b32_e32 v20, v4 | ||
| 66 | v_mov_b32_e32 v21, 20 | ||
| 67 | buffer_store_dword v20, v21, s[0:3], 0 offen | ||
| 68 | s_mov_b64 exec, s[6:7] | ||
| 69 | v_cmpx_eq_u32_e32 20, v1 | ||
| 70 | v_mov_b32_e32 v20, v5 | ||
| 71 | v_mov_b32_e32 v21, 24 | ||
| 72 | buffer_store_dword v20, v21, s[0:3], 0 offen | ||
| 73 | s_mov_b64 exec, s[6:7] | ||
| 74 | v_cmpx_eq_u32_e32 35, v1 | ||
| 75 | v_mov_b32_e32 v20, v5 | ||
| 76 | v_mov_b32_e32 v21, 28 | ||
| 77 | buffer_store_dword v20, v21, s[0:3], 0 offen | ||
| 78 | s_endpgm | ||
diff --git a/runtime/test/shaders/w64_graphics.py b/runtime/test/shaders/w64_graphics.py index e28d03d2f..35936afe8 100644 --- a/runtime/test/shaders/w64_graphics.py +++ b/runtime/test/shaders/w64_graphics.py | |||
| @@ -30,8 +30,15 @@ The vs_w64_* fixtures (TEST-251) are vertex shaders: Vulkan cannot require a ver | |||
| 30 | come from RADV, which runs the VS stage as wave64 by default and as wave32 with RADV_PERFTEST=gewave32 (GFX10+). | 30 | come from RADV, which runs the VS stage as wave64 by default and as wave32 with RADV_PERFTEST=gewave32 (GFX10+). |
| 31 | Each draws 960 vertices with zero area (VKH_VERTICES) and stores four words per vertex to the heap; vs_w64_c_lane_id | 31 | Each draws 960 vertices with zero area (VKH_VERTICES) and stores four words per vertex to the heap; vs_w64_c_lane_id |
| 32 | doubles as the probe that the wave size really changed, and without RADV only the default-size checks run. RADV packs | 32 | doubles as the probe that the wave size really changed, and without RADV only the default-size checks run. RADV packs |
| 33 | 62 or 64 vertices into a wave64 and 30 or 32 into a wave32, so the 32-lane run is a repacking, not the two halves of | 33 | 62 or 64 vertices into a wave64 and 30 or 32 into a wave32, and the wave32 waves are the two halves of the wave64 ones: |
| 34 | the 64-lane waves: a stricter test of tiers A and B, which key every word on the vertex index. | 34 | waves of 64, 62, 64, 62 ... vertices starting at vertices 0, 64, 126, 190 ... at wave64, and of 32, 32, 32, 30 ... |
| 35 | starting at 0, 32, 64, 96, 126 ... at wave32 (a period of 126 vertices both ways). Each vertex's wave32 lane is its | ||
| 36 | wave64 lane & 31 (vs_w64_c_lane_id, all 960 vertices; RADV Mesa 26.3.1 on a gfx1036 iGPU (Raphael) and an RX 7900 XTX | ||
| 37 | (NAVI31, RDNA3); TEST-1700). GFX12 gives the same waves and starts, with every wave32 wave inside one half of a wave64 | ||
| 38 | wave (RX 9070 XT, GFX1201, RDNA4, RADV Mesa 26.2.6; from sperm's old upstream PR 7354). So the 32-lane run is the | ||
| 39 | cut into halves the tiers describe, not a repacking: it does not move a vertex into another wave or lane group. Mind | ||
| 40 | it when writing a VS fixture: waves start at even vertices that are not all multiples of 4 (126, 252, ...), so the | ||
| 41 | lane ^ 1 of a vertex v holds vertex v ^ 1, but lane ^ 2, ^ 3 or ^ 16 need not hold v ^ 2, v ^ 3 or v ^ 16. | ||
| 35 | 42 | ||
| 36 | The gs_w64_* fixtures are legacy geometry shaders, switched the same way (gewave32 covers the whole NGG stage). Each is | 43 | The gs_w64_* fixtures are legacy geometry shaders, switched the same way (gewave32 covers the whole NGG stage). Each is |
| 37 | drawn after vs_ids with VKH_GS, finds its triangle from the vertex number vs_ids passes in TEXCOORD0, and stores four | 44 | drawn after vs_ids with VKH_GS, finds its triangle from the vertex number vs_ids passes in TEXCOORD0, and stores four |
diff --git a/runtime/test/spirv_f16_halves_test.cpp b/runtime/test/spirv_f16_halves_test.cpp index 61604f14a..8cd2c4796 100644 --- a/runtime/test/spirv_f16_halves_test.cpp +++ b/runtime/test/spirv_f16_halves_test.cpp | |||
| @@ -419,6 +419,25 @@ int main() { | |||
| 419 | CHECK(vs_w == vs_orig && ps_w == ps_orig); | 419 | CHECK(vs_w == vs_orig && ps_w == ps_orig); |
| 420 | } | 420 | } |
| 421 | 421 | ||
| 422 | // 11. Custom top_location relocates halves into <= top_location. | ||
| 423 | { | ||
| 424 | ShaderEntry vs_e, ps_e; | ||
| 425 | vs_e.f16_halves = {}; | ||
| 426 | ps_e.f16_halves = {{0, {28, 29}}}; | ||
| 427 | // 10 raw VS outputs (0..9); top_location = 14 leaves slots 10..14 free. | ||
| 428 | auto vs_w = build_vs(0x00010500u, 10, vs_e.f16_halves); | ||
| 429 | auto ps_w = build_ps(0x00010500u, {0}, ps_e.f16_halves); | ||
| 430 | std::string err; | ||
| 431 | CHECK(link_f16_halves(vs_w, vs_e, ps_w, ps_e, &err, 14)); | ||
| 432 | std::map<std::uint32_t, std::uint32_t> vs_locs; | ||
| 433 | int unpacks = 0, privs = 0; | ||
| 434 | std::set<std::uint32_t> ep_iface; | ||
| 435 | CHECK(verify_spirv_structure(vs_w, kStorageOutput, vs_locs, unpacks, privs, ep_iface)); | ||
| 436 | for (const auto& [loc, var] : vs_locs) { | ||
| 437 | CHECK(loc <= 14); | ||
| 438 | } | ||
| 439 | } | ||
| 440 | |||
| 422 | std::printf("spirv_f16_halves_test: all checks passed\n"); | 441 | std::printf("spirv_f16_halves_test: all checks passed\n"); |
| 423 | return 0; | 442 | return 0; |
| 424 | } | 443 | } |
diff --git a/runtime/test/startup_trace_test.cpp b/runtime/test/startup_trace_test.cpp index 170ea39d5..2b8671099 100644 --- a/runtime/test/startup_trace_test.cpp +++ b/runtime/test/startup_trace_test.cpp | |||
| @@ -7,7 +7,8 @@ | |||
| 7 | // 0x1220 reads address 0 (an access violation the test catches) | 7 | // 0x1220 reads address 0 (an access violation the test catches) |
| 8 | // The loader maps it with the trace open, the test calls the three functions, closes the trace and checks the lines: | 8 | // The loader maps it with the trace open, the test calls the three functions, closes the trace and checks the lines: |
| 9 | // map, unimplemented_call with the caller as module+RVA, debug_string with the text, exception with the faulting | 9 | // map, unimplemented_call with the caller as module+RVA, debug_string with the text, exception with the faulting |
| 10 | // RVA and access kind. No game data and no GPU are involved. | 10 | // RVA and access kind. A second image with delay imports checks delay_import_unimplemented (make_delay_image). |
| 11 | // No game data and no GPU are involved. | ||
| 11 | // LEONIDA_TEST_DIR names the folder for the image and the trace, as for loader_test; the default is the temp folder. | 12 | // LEONIDA_TEST_DIR names the folder for the image and the trace, as for loader_test; the default is the temp folder. |
| 12 | #include <windows.h> | 13 | #include <windows.h> |
| 13 | 14 | ||
| @@ -279,6 +280,102 @@ void test_trace(const fs::path& dir) { | |||
| 279 | check(find_line(lines, "exit") == &lines.back(), "exit comes last"); | 280 | check(find_line(lines, "exit") == &lines.back(), "exit comes last"); |
| 280 | } | 281 | } |
| 281 | 282 | ||
| 283 | // A DLL image with no code: one ordinary import that binds to nothing, and two delay-import descriptors, one naming a | ||
| 284 | // function nothing serves and one naming kernel32!GetTickCount (bound to the host). Delay imports are bound when the | ||
| 285 | // image is loaded, so the trace names the missing one then; the ordinary missing import and the bound delay import | ||
| 286 | // give no such event. | ||
| 287 | constexpr const char* kDelayImageName = "delay_image.bin"; | ||
| 288 | |||
| 289 | std::vector<uint8_t> make_delay_image() { | ||
| 290 | std::vector<uint8_t> b(0x600, 0); | ||
| 291 | auto* dos = reinterpret_cast<IMAGE_DOS_HEADER*>(b.data()); | ||
| 292 | dos->e_magic = IMAGE_DOS_SIGNATURE; | ||
| 293 | dos->e_lfanew = 0x80; | ||
| 294 | auto* nt = reinterpret_cast<IMAGE_NT_HEADERS64*>(b.data() + dos->e_lfanew); | ||
| 295 | nt->Signature = IMAGE_NT_SIGNATURE; | ||
| 296 | nt->FileHeader.Machine = IMAGE_FILE_MACHINE_AMD64; | ||
| 297 | nt->FileHeader.NumberOfSections = 1; | ||
| 298 | nt->FileHeader.SizeOfOptionalHeader = sizeof(IMAGE_OPTIONAL_HEADER64); | ||
| 299 | nt->FileHeader.Characteristics = IMAGE_FILE_EXECUTABLE_IMAGE | IMAGE_FILE_DLL | IMAGE_FILE_LARGE_ADDRESS_AWARE; | ||
| 300 | nt->OptionalHeader.Magic = IMAGE_NT_OPTIONAL_HDR64_MAGIC; | ||
| 301 | nt->OptionalHeader.ImageBase = 0x1a0000000; | ||
| 302 | nt->OptionalHeader.SizeOfHeaders = 0x200; | ||
| 303 | nt->OptionalHeader.SizeOfImage = 0x2000; | ||
| 304 | nt->OptionalHeader.Subsystem = IMAGE_SUBSYSTEM_WINDOWS_CUI; | ||
| 305 | nt->OptionalHeader.NumberOfRvaAndSizes = IMAGE_NUMBEROF_DIRECTORY_ENTRIES; | ||
| 306 | auto* sec = IMAGE_FIRST_SECTION(nt); | ||
| 307 | std::memcpy(sec->Name, ".data", 6); | ||
| 308 | sec->VirtualAddress = kTextRva; | ||
| 309 | sec->Misc.VirtualSize = 0x400; | ||
| 310 | sec->PointerToRawData = 0x200; | ||
| 311 | sec->SizeOfRawData = 0x400; | ||
| 312 | sec->Characteristics = IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_WRITE; | ||
| 313 | |||
| 314 | uint8_t* data = b.data() + 0x200; | ||
| 315 | auto put_string = [&](uint32_t off, const char* s) { std::strcpy(reinterpret_cast<char*>(data + off), s); }; | ||
| 316 | // One name table entry and its terminator at `lookup_off`, the import's hint/name at `hint_off`. | ||
| 317 | auto put_thunk = [&](uint32_t lookup_off, uint32_t hint_off, const char* name) { | ||
| 318 | *reinterpret_cast<uint64_t*>(data + lookup_off) = kTextRva + hint_off; | ||
| 319 | put_string(hint_off + 2, name); | ||
| 320 | }; | ||
| 321 | put_string(0x100, "leonida_trace_probe.dll"); | ||
| 322 | put_string(0x120, "kernel32.dll"); | ||
| 323 | |||
| 324 | auto* d = reinterpret_cast<IMAGE_IMPORT_DESCRIPTOR*>(data); | ||
| 325 | d->Name = kTextRva + 0x100; | ||
| 326 | d->OriginalFirstThunk = kTextRva + 0x140; | ||
| 327 | d->FirstThunk = kTextRva + 0x160; | ||
| 328 | put_thunk(0x140, 0x180, "NormalProbeMissing"); | ||
| 329 | |||
| 330 | const struct { | ||
| 331 | uint32_t dll_off, int_off, iat_off, hint_off; | ||
| 332 | const char* name; | ||
| 333 | } delayed[2] = {{0x100, 0x1A0, 0x1C0, 0x1E0, "DelayProbeMissing"}, {0x120, 0x200, 0x220, 0x240, "GetTickCount"}}; | ||
| 334 | for (int i = 0; i < 2; ++i) { | ||
| 335 | auto* dd = reinterpret_cast<IMAGE_DELAYLOAD_DESCRIPTOR*>(data + 0x40) + i; | ||
| 336 | dd->Attributes.AllAttributes = 1; // dlattrRva | ||
| 337 | dd->DllNameRVA = kTextRva + delayed[i].dll_off; | ||
| 338 | dd->ImportNameTableRVA = kTextRva + delayed[i].int_off; | ||
| 339 | dd->ImportAddressTableRVA = kTextRva + delayed[i].iat_off; | ||
| 340 | put_thunk(delayed[i].int_off, delayed[i].hint_off, delayed[i].name); | ||
| 341 | } | ||
| 342 | |||
| 343 | auto& dir = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]; | ||
| 344 | dir.VirtualAddress = kTextRva; | ||
| 345 | dir.Size = 2 * sizeof(IMAGE_IMPORT_DESCRIPTOR); | ||
| 346 | auto& ddir = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT]; | ||
| 347 | ddir.VirtualAddress = kTextRva + 0x40; | ||
| 348 | ddir.Size = 3 * sizeof(IMAGE_DELAYLOAD_DESCRIPTOR); | ||
| 349 | return b; | ||
| 350 | } | ||
| 351 | |||
| 352 | void test_delay_import_trace(const fs::path& dir) { | ||
| 353 | const fs::path image = write_file(dir / kDelayImageName, make_delay_image()); | ||
| 354 | const fs::path trace = dir / "delay_trace.jsonl"; | ||
| 355 | check(rt::startup_trace::open(trace.c_str()), "open the delay-import trace file"); | ||
| 356 | { | ||
| 357 | rt::Loader loader(dir); | ||
| 358 | rt::Module& m = loader.load(image); | ||
| 359 | int unimplemented = 0, host = 0; | ||
| 360 | for (const auto& r : m.imports) { | ||
| 361 | unimplemented += r.binding == rt::Binding::Unimplemented; | ||
| 362 | host += r.binding == rt::Binding::Host; | ||
| 363 | } | ||
| 364 | check(m.imports.size() == 3 && unimplemented == 2 && host == 1, | ||
| 365 | "the delay image binds 3 imports: 2 unimplemented, 1 host"); | ||
| 366 | } | ||
| 367 | rt::startup_trace::close(); | ||
| 368 | |||
| 369 | const auto lines = read_lines(trace); | ||
| 370 | int events = 0; | ||
| 371 | for (auto& l : lines) events += l.find("\"kind\":\"delay_import_unimplemented\"") != std::string::npos; | ||
| 372 | const std::string* e = find_line(lines, "delay_import_unimplemented"); | ||
| 373 | check(events == 1, "one delay_import_unimplemented event (got " + std::to_string(events) + ")"); | ||
| 374 | check(has(e, "\"module\":\"" + std::string(kDelayImageName) + "\"") && | ||
| 375 | has(e, "\"import\":\"leonida_trace_probe.dll!DelayProbeMissing\""), | ||
| 376 | "delay_import_unimplemented names the module and the delay import"); | ||
| 377 | } | ||
| 378 | |||
| 282 | } // namespace | 379 | } // namespace |
| 283 | 380 | ||
| 284 | int wmain() { | 381 | int wmain() { |
| @@ -287,6 +384,7 @@ int wmain() { | |||
| 287 | test_disabled_is_silent(); | 384 | test_disabled_is_silent(); |
| 288 | test_existing_file_is_kept(dir); | 385 | test_existing_file_is_kept(dir); |
| 289 | test_trace(dir); | 386 | test_trace(dir); |
| 387 | test_delay_import_trace(dir); | ||
| 290 | std::error_code ec; | 388 | std::error_code ec; |
| 291 | fs::remove_all(dir, ec); | 389 | fs::remove_all(dir, ec); |
| 292 | } catch (const std::exception& e) { | 390 | } catch (const std::exception& e) { |
diff --git a/runtime/test/submit_mutex_test.cpp b/runtime/test/submit_mutex_test.cpp new file mode 100644 index 000000000..345f30887 --- /dev/null +++ b/runtime/test/submit_mutex_test.cpp | |||
| @@ -0,0 +1,209 @@ | |||
| 1 | // leonida::SubmitMutex (src/vulkan_device_fault.h), on the CPU: the submit lock's owner and hold tracking, its waiter | ||
| 2 | // count, let_submit_finish (the handoff a pipeline create makes to submits before entering the driver) and the | ||
| 3 | // compile gate between pipeline creates and queue submissions. Windows only: the owner is a Win32 thread id. No GPU, | ||
| 4 | // no game data. | ||
| 5 | #include "../src/vulkan_device_fault.h" | ||
| 6 | |||
| 7 | #include <windows.h> | ||
| 8 | |||
| 9 | #include <atomic> | ||
| 10 | #include <chrono> | ||
| 11 | #include <cstdio> | ||
| 12 | #include <mutex> | ||
| 13 | #include <thread> | ||
| 14 | |||
| 15 | #define EXPECT(condition) do { \ | ||
| 16 | if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ | ||
| 17 | } while (0) | ||
| 18 | |||
| 19 | namespace { | ||
| 20 | |||
| 21 | using leonida::SubmitMutex; | ||
| 22 | using namespace std::chrono_literals; | ||
| 23 | |||
| 24 | std::int64_t now_ms() { return leonida::diagnostic_ms(); } | ||
| 25 | |||
| 26 | // Polls `done` for up to two seconds. | ||
| 27 | template<class Done> bool eventually(Done&& done) { | ||
| 28 | for (int i = 0; i < 2000; ++i) { | ||
| 29 | if (done()) return true; | ||
| 30 | std::this_thread::sleep_for(1ms); | ||
| 31 | } | ||
| 32 | return done(); | ||
| 33 | } | ||
| 34 | |||
| 35 | int owner_tracking() { | ||
| 36 | SubmitMutex m; | ||
| 37 | EXPECT(m.owner() == 0 && m.waiting() == 0); | ||
| 38 | const std::int64_t before = now_ms(); | ||
| 39 | m.lock(); | ||
| 40 | EXPECT(m.owner() == GetCurrentThreadId()); | ||
| 41 | EXPECT(m.since_ms() >= before && m.since_ms() <= now_ms()); | ||
| 42 | // The holder's own thread: nothing to let through, no wait (it would deadlock on the lock it holds). | ||
| 43 | EXPECT(m.let_submit_finish(true) == 0); | ||
| 44 | EXPECT(m.let_submit_finish(false) == 0); | ||
| 45 | m.unlock(); | ||
| 46 | EXPECT(m.owner() == 0); | ||
| 47 | EXPECT(m.try_lock()); | ||
| 48 | EXPECT(m.owner() == GetCurrentThreadId()); | ||
| 49 | m.unlock(); | ||
| 50 | // Free: no wait at all. | ||
| 51 | EXPECT(m.let_submit_finish(true) == 0); | ||
| 52 | std::printf("owner and hold tracking, holder's own thread returns at once\n"); | ||
| 53 | return 0; | ||
| 54 | } | ||
| 55 | |||
| 56 | int waits_for_holder() { | ||
| 57 | SubmitMutex m; | ||
| 58 | std::atomic<bool> held{false}, released{false}; | ||
| 59 | std::thread holder([&] { | ||
| 60 | m.lock(); | ||
| 61 | held = true; | ||
| 62 | std::this_thread::sleep_for(200ms); | ||
| 63 | released = true; | ||
| 64 | m.unlock(); | ||
| 65 | }); | ||
| 66 | EXPECT(eventually([&] { return held.load(); })); | ||
| 67 | EXPECT(m.owner() != 0 && m.owner() != GetCurrentThreadId()); | ||
| 68 | const std::int64_t waited = m.let_submit_finish(false); | ||
| 69 | const bool after_release = released.load(); | ||
| 70 | holder.join(); | ||
| 71 | EXPECT(after_release); | ||
| 72 | EXPECT(waited >= 100); | ||
| 73 | std::printf("let_submit_finish(false) waited %lld ms for another thread's hold\n", static_cast<long long>(waited)); | ||
| 74 | return 0; | ||
| 75 | } | ||
| 76 | |||
| 77 | int waits_for_queued_submitter() { | ||
| 78 | // A holds the lock, B queues behind it in lock(); the worker's handoff returns only after B has had its turn. | ||
| 79 | SubmitMutex m; | ||
| 80 | std::atomic<bool> a_held{false}, b_done{false}; | ||
| 81 | std::atomic<std::int64_t> b_released_at{0}; | ||
| 82 | std::thread a([&] { | ||
| 83 | m.lock(); | ||
| 84 | a_held = true; | ||
| 85 | std::this_thread::sleep_for(150ms); | ||
| 86 | m.unlock(); | ||
| 87 | }); | ||
| 88 | EXPECT(eventually([&] { return a_held.load(); })); | ||
| 89 | std::thread b([&] { | ||
| 90 | m.lock(); | ||
| 91 | std::this_thread::sleep_for(100ms); | ||
| 92 | b_released_at = now_ms(); | ||
| 93 | b_done = true; | ||
| 94 | m.unlock(); | ||
| 95 | }); | ||
| 96 | EXPECT(eventually([&] { return m.waiting() == 1; })); // B is counted while it waits | ||
| 97 | const std::int64_t waited = m.let_submit_finish(true); | ||
| 98 | const bool b_had_turn = b_done.load(); | ||
| 99 | const std::int64_t returned_at = now_ms(); | ||
| 100 | a.join(); | ||
| 101 | b.join(); | ||
| 102 | EXPECT(b_had_turn); | ||
| 103 | EXPECT(returned_at >= b_released_at.load()); | ||
| 104 | EXPECT(m.waiting() == 0 && m.owner() == 0); | ||
| 105 | std::printf("let_submit_finish(true) let a queued submitter go first (%lld ms)\n", static_cast<long long>(waited)); | ||
| 106 | return 0; | ||
| 107 | } | ||
| 108 | |||
| 109 | int handoff_is_capped() { | ||
| 110 | // Two threads keep the lock busy back to back (one always queued): the worker still gets its turn after the cap. | ||
| 111 | SubmitMutex m; | ||
| 112 | std::atomic<bool> stop{false}; | ||
| 113 | auto churn = [&] { | ||
| 114 | while (!stop) { | ||
| 115 | m.lock(); | ||
| 116 | std::this_thread::sleep_for(10ms); | ||
| 117 | m.unlock(); | ||
| 118 | } | ||
| 119 | }; | ||
| 120 | std::thread a(churn), b(churn); | ||
| 121 | EXPECT(eventually([&] { return m.owner() != 0 && m.waiting() != 0; })); | ||
| 122 | const std::int64_t waited = m.let_submit_finish(true, 100); | ||
| 123 | stop = true; | ||
| 124 | a.join(); | ||
| 125 | b.join(); | ||
| 126 | std::printf("capped handoff: %lld ms\n", static_cast<long long>(waited)); | ||
| 127 | EXPECT(waited >= 90 && waited < 600); | ||
| 128 | std::printf("let_submit_finish(true, 100) under a steady stream of submits returned after %lld ms\n", | ||
| 129 | static_cast<long long>(waited)); | ||
| 130 | return 0; | ||
| 131 | } | ||
| 132 | |||
| 133 | int compile_gate() { | ||
| 134 | if (!SubmitMutex::compile_gate_enabled()) { | ||
| 135 | std::printf("compile gate off (LEONIDA_COMPILE_GATE=0): not checked\n"); | ||
| 136 | return 0; | ||
| 137 | } | ||
| 138 | SubmitMutex m; | ||
| 139 | // Nothing in the driver: a submission passes at once. | ||
| 140 | { | ||
| 141 | const std::int64_t start = now_ms(); | ||
| 142 | const SubmitMutex::SubmitTurn turn(m); | ||
| 143 | EXPECT(now_ms() - start < 50); | ||
| 144 | } | ||
| 145 | // A submission waits for the create in the driver; a create arriving meanwhile waits behind the submission. | ||
| 146 | std::atomic<bool> creating{false}; | ||
| 147 | std::atomic<std::int64_t> create_left_at{0}, submit_entered_at{0}, submit_left_at{0}, second_entered_at{0}; | ||
| 148 | std::atomic<std::int64_t> second_waited{-1}; | ||
| 149 | std::thread create([&] { | ||
| 150 | const SubmitMutex::CompileTurn turn(m); | ||
| 151 | creating = true; | ||
| 152 | std::this_thread::sleep_for(250ms); | ||
| 153 | create_left_at = now_ms(); | ||
| 154 | }); | ||
| 155 | EXPECT(eventually([&] { return creating.load(); })); | ||
| 156 | std::thread submit([&] { | ||
| 157 | m.lock(); // as a submitter does: the submit lock, then the gate around vkQueueSubmit | ||
| 158 | { | ||
| 159 | const SubmitMutex::SubmitTurn turn(m); | ||
| 160 | submit_entered_at = now_ms(); | ||
| 161 | std::this_thread::sleep_for(100ms); | ||
| 162 | submit_left_at = now_ms(); | ||
| 163 | } | ||
| 164 | m.unlock(); | ||
| 165 | }); | ||
| 166 | EXPECT(eventually([&] { return m.gate_waiter() != 0; })); // waiting at the gate, with the submit lock held | ||
| 167 | EXPECT(m.owner() == m.gate_waiter()); | ||
| 168 | std::thread second([&] { | ||
| 169 | const SubmitMutex::CompileTurn turn(m); | ||
| 170 | second_entered_at = now_ms(); | ||
| 171 | second_waited = turn.waited_ms(); | ||
| 172 | }); | ||
| 173 | create.join(); | ||
| 174 | submit.join(); | ||
| 175 | second.join(); | ||
| 176 | EXPECT(submit_entered_at.load() >= create_left_at.load()); // never in the driver together with a create | ||
| 177 | EXPECT(second_entered_at.load() >= submit_left_at.load()); // the waiting submission went first | ||
| 178 | EXPECT(second_waited.load() >= 50); | ||
| 179 | EXPECT(m.gate_waiter() == 0); | ||
| 180 | const SubmitMutex::GateStats stats = m.gate_stats(); | ||
| 181 | EXPECT(stats.submits == 1 && stats.submit_max_ms >= 100); | ||
| 182 | EXPECT(stats.creates == 1 && stats.create_max_ms >= 50); | ||
| 183 | std::printf("compile gate: submission waited %lld ms for a create, a later create waited %lld ms behind it\n", | ||
| 184 | static_cast<long long>(stats.submit_max_ms), static_cast<long long>(stats.create_max_ms)); | ||
| 185 | // Creates share the gate. | ||
| 186 | { | ||
| 187 | const SubmitMutex::CompileTurn first(m); | ||
| 188 | std::atomic<std::int64_t> other_waited{-1}; | ||
| 189 | std::thread other([&] { | ||
| 190 | const SubmitMutex::CompileTurn turn(m); | ||
| 191 | other_waited = turn.waited_ms(); | ||
| 192 | }); | ||
| 193 | other.join(); | ||
| 194 | EXPECT(other_waited.load() == 0); | ||
| 195 | } | ||
| 196 | std::printf("compile gate: creates pass it together\n"); | ||
| 197 | return 0; | ||
| 198 | } | ||
| 199 | |||
| 200 | } // namespace | ||
| 201 | |||
| 202 | int main() { | ||
| 203 | std::setvbuf(stdout, nullptr, _IONBF, 0); | ||
| 204 | if (owner_tracking() || waits_for_holder() || waits_for_queued_submitter() || handoff_is_capped() || | ||
| 205 | compile_gate()) | ||
| 206 | return 1; | ||
| 207 | std::printf("submit_mutex_test: all passed\n"); | ||
| 208 | return 0; | ||
| 209 | } | ||
diff --git a/runtime/test/title_hud_test.cpp b/runtime/test/title_hud_test.cpp new file mode 100644 index 000000000..661f4d30c --- /dev/null +++ b/runtime/test/title_hud_test.cpp | |||
| @@ -0,0 +1,190 @@ | |||
| 1 | // shims/title_hud.h: LEONIDA_TITLE_HUD's counters reach the title bar of a window owned by another thread, and a | ||
| 2 | // window that stops pumping messages does not hold the HUD thread. The memory figures: VK_EXT_memory_budget's heaps | ||
| 3 | // summed, DXGI's as the fallback, "n/a" where neither has one, and the private bytes Wine reports. A real Win32 | ||
| 4 | // window and made-up budgets; no GPU needed (d3d12_vram_budget_test reads a real device's). | ||
| 5 | #include "title_hud.h" | ||
| 6 | #include "../src/vulkan_memory_budget.h" | ||
| 7 | |||
| 8 | #include <windows.h> | ||
| 9 | |||
| 10 | #include <atomic> | ||
| 11 | #include <cstdint> | ||
| 12 | #include <cstdio> | ||
| 13 | #include <string> | ||
| 14 | |||
| 15 | #define CHECK(condition) do { \ | ||
| 16 | if (!(condition)) { \ | ||
| 17 | std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); \ | ||
| 18 | return 1; \ | ||
| 19 | } \ | ||
| 20 | } while (0) | ||
| 21 | |||
| 22 | static std::wstring title_of(HWND window) { | ||
| 23 | wchar_t text[512] = {}; | ||
| 24 | InternalGetWindowText(window, text, 512); // no message: the window's own thread may be busy | ||
| 25 | return text; | ||
| 26 | } | ||
| 27 | |||
| 28 | // Pumps this thread's messages for `ms`, presenting every 16 ms when `present` is set. | ||
| 29 | static void pump(DWORD ms, rt::d3d12_xs::TitleHud* present) { | ||
| 30 | const ULONGLONG end = GetTickCount64() + ms; | ||
| 31 | while (GetTickCount64() < end) { | ||
| 32 | MSG msg; | ||
| 33 | while (PeekMessageW(&msg, nullptr, 0, 0, PM_REMOVE)) { | ||
| 34 | TranslateMessage(&msg); | ||
| 35 | DispatchMessageW(&msg); | ||
| 36 | } | ||
| 37 | if (present) present->note_present(); | ||
| 38 | Sleep(16); | ||
| 39 | } | ||
| 40 | } | ||
| 41 | |||
| 42 | constexpr std::uint64_t kGiB = 1ull << 30; | ||
| 43 | |||
| 44 | // The memory figures without a window: VK_EXT_memory_budget's heaps summed, DXGI's answer as the fallback, and this | ||
| 45 | // process's own private bytes. Made-up values except the last. The text and the private-bytes choice are | ||
| 46 | // src/memory_figures.h's, shared with the dev overlay; dev_overlay_test checks them. | ||
| 47 | static int check_figures() { | ||
| 48 | using rt::d3d12_xs::TitleHud; | ||
| 49 | namespace mf = leonida::memory_figures; | ||
| 50 | |||
| 51 | // Two device-local heaps (VRAM and a BAR window) and system memory. | ||
| 52 | VkPhysicalDeviceMemoryProperties heaps{}; | ||
| 53 | heaps.memoryHeapCount = 3; | ||
| 54 | heaps.memoryHeaps[0] = {16 * kGiB, VK_MEMORY_HEAP_DEVICE_LOCAL_BIT}; | ||
| 55 | heaps.memoryHeaps[1] = {32 * kGiB, 0}; | ||
| 56 | heaps.memoryHeaps[2] = {kGiB / 4, VK_MEMORY_HEAP_DEVICE_LOCAL_BIT}; | ||
| 57 | VkPhysicalDeviceMemoryBudgetPropertiesEXT budget{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MEMORY_BUDGET_PROPERTIES_EXT}; | ||
| 58 | budget.heapUsage[0] = 3 * kGiB + kGiB / 4; | ||
| 59 | budget.heapBudget[0] = 15 * kGiB + kGiB * 3 / 4; | ||
| 60 | budget.heapUsage[1] = kGiB / 2; | ||
| 61 | budget.heapBudget[1] = 24 * kGiB; | ||
| 62 | budget.heapUsage[2] = kGiB / 4; | ||
| 63 | budget.heapBudget[2] = kGiB / 4; | ||
| 64 | budget.heapUsage[3] = 7 * kGiB; // past memoryHeapCount: not counted | ||
| 65 | budget.heapBudget[3] = 7 * kGiB; | ||
| 66 | const leonida::VramBudget summed = leonida::sum_vram_budget(heaps, budget); | ||
| 67 | CHECK(summed.available); | ||
| 68 | CHECK(summed.local_usage == 3 * kGiB + kGiB / 2 && summed.local_budget == 16 * kGiB); | ||
| 69 | CHECK(summed.shared_usage == kGiB / 2); | ||
| 70 | CHECK(mf::vram_text(summed) == "VRAM 3.5/16.0 GB +0.5 shared"); | ||
| 71 | |||
| 72 | // A device that reports no budget for its device-local heaps has no figure, not a 0. | ||
| 73 | const VkPhysicalDeviceMemoryBudgetPropertiesEXT empty{ | ||
| 74 | VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MEMORY_BUDGET_PROPERTIES_EXT}; | ||
| 75 | CHECK(!leonida::sum_vram_budget(heaps, empty).available); | ||
| 76 | |||
| 77 | // DXGI: Wine's QueryVideoMemoryInfo answers S_OK with no usage, which is not a figure; Windows' is. | ||
| 78 | DXGI_QUERY_VIDEO_MEMORY_INFO local{}, non_local{}; | ||
| 79 | local.Budget = 24 * kGiB; | ||
| 80 | CHECK(!TitleHud::dxgi_budget(local, non_local).available); | ||
| 81 | local.CurrentUsage = 2 * kGiB; | ||
| 82 | non_local.CurrentUsage = kGiB; | ||
| 83 | const leonida::VramBudget dxgi = TitleHud::dxgi_budget(local, non_local); | ||
| 84 | CHECK(dxgi.available && dxgi.local_usage == 2 * kGiB && dxgi.local_budget == 24 * kGiB && | ||
| 85 | dxgi.shared_usage == kGiB); | ||
| 86 | |||
| 87 | // This process's own counters: its private bytes are never 0, on Windows or under Wine (where only PagefileUsage | ||
| 88 | // is filled). | ||
| 89 | const mf::ProcessMemory own = mf::process_memory(); | ||
| 90 | std::fprintf(stderr, "own counters: PrivateUsage %llu, PagefileUsage %llu, WorkingSetSize %llu\n", | ||
| 91 | (unsigned long long)own.private_usage, (unsigned long long)own.pagefile_usage, | ||
| 92 | (unsigned long long)own.working_set); | ||
| 93 | CHECK(own.read && mf::private_bytes(own) > 0); | ||
| 94 | return 0; | ||
| 95 | } | ||
| 96 | |||
| 97 | int main() { | ||
| 98 | if (const int failed = check_figures()) return failed; | ||
| 99 | WNDCLASSW cls{}; | ||
| 100 | cls.lpfnWndProc = DefWindowProcW; | ||
| 101 | cls.hInstance = GetModuleHandleW(nullptr); | ||
| 102 | cls.lpszClassName = L"LeonidaTitleHudTest"; | ||
| 103 | CHECK(RegisterClassW(&cls)); | ||
| 104 | HWND window = CreateWindowExW(WS_EX_NOACTIVATE, cls.lpszClassName, L"before", WS_OVERLAPPEDWINDOW, 0, 0, 64, 64, | ||
| 105 | nullptr, nullptr, cls.hInstance, nullptr); | ||
| 106 | CHECK(window); | ||
| 107 | { | ||
| 108 | rt::d3d12_xs::TitleHud hud(window); | ||
| 109 | // Presents at ~60 Hz for 1.5 s: the title shows a frame rate and the counters. | ||
| 110 | pump(1500, &hud); | ||
| 111 | const std::wstring text = title_of(window); | ||
| 112 | std::fwprintf(stderr, L"title: %ls\n", text.c_str()); | ||
| 113 | CHECK(text.rfind(L"Leonida | ", 0) == 0); | ||
| 114 | CHECK(text.find(L" fps ") != std::wstring::npos && text.find(L" ms (worst ") != std::wstring::npos); | ||
| 115 | CHECK(text.find(L"RAM ") != std::wstring::npos && text.find(L"VRAM ") != std::wstring::npos); | ||
| 116 | // The private bytes are read under Wine as well ("VRAM n/a" may show: no device behind this HUD). | ||
| 117 | CHECK(text.find(L"| RAM n/a") == std::wstring::npos); | ||
| 118 | CHECK(text.find(L"PSO -") != std::wstring::npos); // no LEONIDA_MEM_PROBE: no pipeline counters | ||
| 119 | const int fps = _wtoi(text.c_str() + 10); | ||
| 120 | CHECK(fps >= 10 && fps <= 120); // a loose band: Sleep(16) on a loaded machine is not 60 Hz | ||
| 121 | |||
| 122 | // Presents stop while the window still pumps: the title says how long since the last frame. | ||
| 123 | pump(1300, nullptr); | ||
| 124 | const std::wstring stalled = title_of(window); | ||
| 125 | std::fwprintf(stderr, L"title: %ls\n", stalled.c_str()); | ||
| 126 | CHECK(stalled.find(L"0 fps, no frame for ") != std::wstring::npos); | ||
| 127 | |||
| 128 | // The window's thread stops pumping: the HUD's SendMessageTimeout gives up and the HUD thread is not stuck, | ||
| 129 | // so the destructor below returns. | ||
| 130 | Sleep(1200); | ||
| 131 | } | ||
| 132 | { | ||
| 133 | // A VRAM source (the device's VK_EXT_memory_budget in the runtime) is what the title shows, and it is read | ||
| 134 | // at most once per refresh, on the HUD's thread. | ||
| 135 | std::atomic<unsigned> reads{0}; | ||
| 136 | rt::d3d12_xs::TitleHud hud(window, [&reads] { | ||
| 137 | ++reads; | ||
| 138 | leonida::VramBudget fake; | ||
| 139 | fake.available = true; | ||
| 140 | fake.local_usage = 3 * kGiB + kGiB / 2; | ||
| 141 | fake.local_budget = 20 * kGiB; | ||
| 142 | fake.shared_usage = kGiB / 2; | ||
| 143 | return fake; | ||
| 144 | }); | ||
| 145 | pump(1300, &hud); | ||
| 146 | const std::wstring text = title_of(window); | ||
| 147 | std::fwprintf(stderr, L"title: %ls\n", text.c_str()); | ||
| 148 | CHECK(text.find(L"| VRAM 3.5/20.0 GB +0.5 shared |") != std::wstring::npos); | ||
| 149 | CHECK(reads.load() >= 1 && reads.load() <= 3); // 1.3 s at one refresh per 500 ms | ||
| 150 | } | ||
| 151 | { | ||
| 152 | // No source of its own: the HUD shows what a device published (src/memory_figures.h), the figure the dev | ||
| 153 | // overlay shows as well. | ||
| 154 | static const int device = 0; | ||
| 155 | leonida::memory_figures::publish_vram_reader( | ||
| 156 | [](const void*) { | ||
| 157 | leonida::VramBudget fake; | ||
| 158 | fake.available = true; | ||
| 159 | fake.local_usage = 5 * kGiB; | ||
| 160 | fake.local_budget = 12 * kGiB; | ||
| 161 | return fake; | ||
| 162 | }, | ||
| 163 | &device); | ||
| 164 | { | ||
| 165 | rt::d3d12_xs::TitleHud hud(window); | ||
| 166 | pump(700, &hud); | ||
| 167 | const std::wstring text = title_of(window); | ||
| 168 | std::fwprintf(stderr, L"title: %ls\n", text.c_str()); | ||
| 169 | CHECK(text.find(L"| VRAM 5.0/12.0 GB +0.0 shared |") != std::wstring::npos); | ||
| 170 | } | ||
| 171 | leonida::memory_figures::withdraw_vram_reader(&device); | ||
| 172 | } | ||
| 173 | { | ||
| 174 | // A source with no figure (a device without VK_EXT_memory_budget): DXGI's figure where it has one (Windows), | ||
| 175 | // else "n/a" (Wine, whose DXGI answers 0; check_figures covers that choice). | ||
| 176 | rt::d3d12_xs::TitleHud hud(window, [] { return leonida::VramBudget{}; }); | ||
| 177 | pump(700, &hud); | ||
| 178 | const std::wstring text = title_of(window); | ||
| 179 | std::fwprintf(stderr, L"title: %ls\n", text.c_str()); | ||
| 180 | CHECK(text.find(L"| VRAM ") != std::wstring::npos && text.find(L"VRAM 3.5/20.0") == std::wstring::npos); | ||
| 181 | } | ||
| 182 | const ULONGLONG before = GetTickCount64(); | ||
| 183 | { | ||
| 184 | rt::d3d12_xs::TitleHud quick(window); | ||
| 185 | } // stops at once, without waiting a whole interval | ||
| 186 | CHECK(GetTickCount64() - before < 1000); | ||
| 187 | DestroyWindow(window); | ||
| 188 | std::printf("title_hud: counters in the title bar of another thread's window; a busy window does not hold it\n"); | ||
| 189 | return 0; | ||
| 190 | } | ||
diff --git a/runtime/test/title_va_alias_test.cpp b/runtime/test/title_va_alias_test.cpp index fe378a3bf..f2f869391 100644 --- a/runtime/test/title_va_alias_test.cpp +++ b/runtime/test/title_va_alias_test.cpp | |||
| @@ -85,6 +85,44 @@ int main() { | |||
| 85 | a.remove(title, arena); | 85 | a.remove(title, arena); |
| 86 | a.remove(title + 0x40000, 0x7000000); | 86 | a.remove(title + 0x40000, 0x7000000); |
| 87 | EXPECT(a.size() == 0); | 87 | EXPECT(a.size() == 0); |
| 88 | // Replacing part of an alias removes the entire old interval. Other heaps read independently. | ||
| 89 | std::uint64_t cursor = 0; | ||
| 90 | leonida::DescriptorRanges past; | ||
| 91 | EXPECT(a.changed_ranges(cursor, past)); | ||
| 92 | auto second = cursor; | ||
| 93 | EXPECT(a.add(title, size, arena)); | ||
| 94 | EXPECT(a.add(title+16, 32, arena+4096)); | ||
| 95 | for (auto* reader : {&cursor, &second}) { | ||
| 96 | leonida::DescriptorRanges delta; | ||
| 97 | EXPECT(a.changed_ranges(*reader, delta)); | ||
| 98 | delta.merge(); | ||
| 99 | EXPECT(delta.overlaps(title+size-1, 1) && delta.overlaps(title-16, 17)); | ||
| 100 | EXPECT(!delta.overlaps(title+size, 1) && !delta.overlaps(title-16, 16)); | ||
| 101 | } | ||
| 102 | leonida::DescriptorRangeChanges backing; | ||
| 103 | for (unsigned i = 0; i < 4097; ++i) backing.record(UINT64_MAX-3, 4); | ||
| 104 | cursor = 0; | ||
| 105 | EXPECT(!backing.read(cursor, past)); | ||
| 106 | backing.record(UINT64_MAX-3, 4); | ||
| 107 | leonida::DescriptorRanges last; | ||
| 108 | EXPECT(backing.read(cursor,last)); | ||
| 109 | last.merge(); | ||
| 110 | EXPECT(last.overlaps(UINT64_MAX,1) && !last.overlaps(0,1)); | ||
| 111 | // shader_side: whether an address is one the layer wrote for the title (inside some range's copy), so a scan that | ||
| 112 | // sees an already rewritten V# again leaves it alone rather than taking it for an unmapped address. | ||
| 113 | EXPECT(!a.shader_side(arena)); | ||
| 114 | EXPECT(a.add(title, size, arena) && a.add_twin(title + 0x200000, title + 0x400000, 0x1000, 0x9000000)); | ||
| 115 | EXPECT(a.shader_side(arena) && a.shader_side(arena + size - 1) && !a.shader_side(arena + size)); | ||
| 116 | EXPECT(a.shader_side(0x9000fff) && !a.shader_side(0x9001000) && !a.shader_side(title)); | ||
| 117 | a.remove(title + 0x200000, 0x9000000); | ||
| 118 | EXPECT(a.shader_side(0x9000000)); // the twin still names it | ||
| 119 | a.remove(title + 0x400000, 0x9000000); | ||
| 120 | EXPECT(!a.shader_side(0x9000000)); | ||
| 121 | // A range replaced by an overlapping one leaves the index with the new copy only. | ||
| 122 | EXPECT(a.add(title + 0x100, 0x100, 0xA000000)); | ||
| 123 | EXPECT(!a.shader_side(arena) && a.shader_side(0xA0000ff) && !a.shader_side(0xA000100)); | ||
| 124 | a.remove(title + 0x100, 0xA000000); | ||
| 125 | EXPECT(a.size() == 0 && !a.shader_side(0xA000000)); | ||
| 88 | std::printf("title_va_alias: translation inside a title-placed range, identity outside it and after release\n"); | 126 | std::printf("title_va_alias: translation inside a title-placed range, identity outside it and after release\n"); |
| 89 | return 0; | 127 | return 0; |
| 90 | } | 128 | } |
diff --git a/runtime/test/vk_bindless_test.cpp b/runtime/test/vk_bindless_test.cpp index 194df74a9..dc33e7d91 100644 --- a/runtime/test/vk_bindless_test.cpp +++ b/runtime/test/vk_bindless_test.cpp | |||
| @@ -738,6 +738,222 @@ int main(int argc, char** argv) { | |||
| 738 | return submit() == VK_SUCCESS && ok; | 738 | return submit() == VK_SUCCESS && ok; |
| 739 | }; | 739 | }; |
| 740 | 740 | ||
| 741 | const float orange_pixel[4] = {1.0f, 128.0f / 255.0f, 0.0f, 1.0f}; | ||
| 742 | const float fallback_pixels[4] = {0.0f, 0.0f, 0.0f, 0.0f}; | ||
| 743 | |||
| 744 | // The mirror (BindlessSet::MirrorViews): a 2D-array T# read by a 2D op finds its slice 0 bound in the 2D | ||
| 745 | // arrays at the T#'s own index. The index spaces are per dimension and dense, so slot N of one dimension | ||
| 746 | // and a 2D-array image's mirror slot N coincide: the set records which image owns a mirror slot, not just | ||
| 747 | // that it is used. | ||
| 748 | { | ||
| 749 | // A 2D-array image of two layers (layer 0 orange, layer 1 blue) with its own 2D-array and storage views | ||
| 750 | // plus a 2D view of layer 0, which is what a mirror binds. The storage view puts the index in the | ||
| 751 | // storage range, as in the index-space checks below. | ||
| 752 | const auto make_layered = [&](VkImage* image, VkImageView* layers, VkImageView* layer0) { | ||
| 753 | VkImageCreateInfo ii{VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO}; | ||
| 754 | ii.imageType = VK_IMAGE_TYPE_2D; | ||
| 755 | ii.format = VK_FORMAT_R8G8B8A8_UNORM; | ||
| 756 | ii.extent = {1, 1, 1}; | ||
| 757 | ii.mipLevels = 1; | ||
| 758 | ii.arrayLayers = 2; | ||
| 759 | ii.samples = VK_SAMPLE_COUNT_1_BIT; | ||
| 760 | ii.tiling = VK_IMAGE_TILING_OPTIMAL; | ||
| 761 | ii.usage = sampled_usage | VK_IMAGE_USAGE_STORAGE_BIT; | ||
| 762 | VkResult r = vkCreateImage(dev, &ii, nullptr, image); | ||
| 763 | if (r) return r; | ||
| 764 | VkMemoryRequirements mr; | ||
| 765 | vkGetImageMemoryRequirements(dev, *image, &mr); | ||
| 766 | VkMemoryAllocateInfo ai{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; | ||
| 767 | ai.allocationSize = mr.size; | ||
| 768 | ai.memoryTypeIndex = memtype(mr.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); | ||
| 769 | VkDeviceMemory m = VK_NULL_HANDLE; | ||
| 770 | if ((r = vkAllocateMemory(dev, &ai, nullptr, &m))) return r; | ||
| 771 | allocations.push_back(m); | ||
| 772 | if ((r = vkBindImageMemory(dev, *image, m, 0))) return r; | ||
| 773 | VkImageViewCreateInfo vi{VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO}; | ||
| 774 | vi.image = *image; | ||
| 775 | vi.viewType = VK_IMAGE_VIEW_TYPE_2D_ARRAY; | ||
| 776 | vi.format = VK_FORMAT_R8G8B8A8_UNORM; | ||
| 777 | vi.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 2}; | ||
| 778 | if ((r = vkCreateImageView(dev, &vi, nullptr, layers))) return r; | ||
| 779 | vi.viewType = VK_IMAGE_VIEW_TYPE_2D; | ||
| 780 | vi.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; | ||
| 781 | return vkCreateImageView(dev, &vi, nullptr, layer0); | ||
| 782 | }; | ||
| 783 | const auto upload_layered = [&](VkImage image) { | ||
| 784 | constexpr std::uint32_t blue = 0xffff0000u; // r = 0, g = 0, b = 255, a = 255 | ||
| 785 | std::memcpy(static_cast<char*>(upload_map) + 1028, &blue, 4); | ||
| 786 | VkResult r = vkResetCommandBuffer(cmd, 0); | ||
| 787 | if (r) return r; | ||
| 788 | if ((r = vkBeginCommandBuffer(cmd, &begin))) return r; | ||
| 789 | VkImageMemoryBarrier b{VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER}; | ||
| 790 | b.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED; | ||
| 791 | b.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; | ||
| 792 | b.image = image; | ||
| 793 | b.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 2}; | ||
| 794 | b.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; | ||
| 795 | b.srcQueueFamilyIndex = b.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; | ||
| 796 | vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, | ||
| 797 | nullptr, 0, nullptr, 1, &b); | ||
| 798 | for (std::uint32_t layer = 0; layer < 2; ++layer) { | ||
| 799 | VkBufferImageCopy c{}; | ||
| 800 | c.bufferOffset = 1024 + layer * 4; | ||
| 801 | c.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, layer, 1}; | ||
| 802 | c.imageExtent = {1, 1, 1}; | ||
| 803 | vkCmdCopyBufferToImage(cmd, upload, image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &c); | ||
| 804 | } | ||
| 805 | b.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; | ||
| 806 | b.newLayout = VK_IMAGE_LAYOUT_GENERAL; // sampled and storage | ||
| 807 | b.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; | ||
| 808 | b.dstAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT; | ||
| 809 | vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, 0, 0, | ||
| 810 | nullptr, 0, nullptr, 1, &b); | ||
| 811 | return submit(); | ||
| 812 | }; | ||
| 813 | // A 3D image with a storage view: its own index space, whose slot numbers are the 2D arrays' too. | ||
| 814 | const auto make_volume = [&](VkImage* image, VkImageView* view) { | ||
| 815 | VkImageCreateInfo ii{VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO}; | ||
| 816 | ii.imageType = VK_IMAGE_TYPE_3D; | ||
| 817 | ii.format = VK_FORMAT_R8G8B8A8_UNORM; | ||
| 818 | ii.extent = {1, 1, 1}; | ||
| 819 | ii.mipLevels = 1; | ||
| 820 | ii.arrayLayers = 1; | ||
| 821 | ii.samples = VK_SAMPLE_COUNT_1_BIT; | ||
| 822 | ii.tiling = VK_IMAGE_TILING_OPTIMAL; | ||
| 823 | ii.usage = sampled_usage | VK_IMAGE_USAGE_STORAGE_BIT; | ||
| 824 | VkResult r = vkCreateImage(dev, &ii, nullptr, image); | ||
| 825 | if (r) return r; | ||
| 826 | VkMemoryRequirements mr; | ||
| 827 | vkGetImageMemoryRequirements(dev, *image, &mr); | ||
| 828 | VkMemoryAllocateInfo ai{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; | ||
| 829 | ai.allocationSize = mr.size; | ||
| 830 | ai.memoryTypeIndex = memtype(mr.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); | ||
| 831 | VkDeviceMemory m = VK_NULL_HANDLE; | ||
| 832 | if ((r = vkAllocateMemory(dev, &ai, nullptr, &m))) return r; | ||
| 833 | allocations.push_back(m); | ||
| 834 | if ((r = vkBindImageMemory(dev, *image, m, 0))) return r; | ||
| 835 | VkImageViewCreateInfo vi{VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO}; | ||
| 836 | vi.image = *image; | ||
| 837 | vi.viewType = VK_IMAGE_VIEW_TYPE_3D; | ||
| 838 | vi.format = VK_FORMAT_R8G8B8A8_UNORM; | ||
| 839 | vi.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; | ||
| 840 | return vkCreateImageView(dev, &vi, nullptr, view); | ||
| 841 | }; | ||
| 842 | const auto add_mirrored = [&](VkImageView layers, VkImageView layer0, std::uint32_t* index, | ||
| 843 | std::uint32_t* kind) { | ||
| 844 | StorageViews storage; | ||
| 845 | storage.as_float = layers; | ||
| 846 | BindlessSet::MirrorViews mirror{}; | ||
| 847 | mirror.sampled = layer0; | ||
| 848 | mirror.sampled_layout = VK_IMAGE_LAYOUT_GENERAL; | ||
| 849 | mirror.storage.as_float = layer0; | ||
| 850 | *index = set.add_image(ImageDimension::dim_2d_array, layers, VK_IMAGE_LAYOUT_GENERAL, storage, 0, | ||
| 851 | &mirror, kind); | ||
| 852 | return *index != 0; | ||
| 853 | }; | ||
| 854 | const auto draw_with = [&](const DescriptorKey& key) { | ||
| 855 | std::memcpy(static_cast<char*>(heap_map) + table_va, key.data(), 32); | ||
| 856 | return draw(); | ||
| 857 | }; | ||
| 858 | |||
| 859 | const std::uint32_t free_2d = set.free_images(ImageDimension::dim_2d); | ||
| 860 | const std::uint32_t free_array = set.free_images(ImageDimension::dim_2d_array); | ||
| 861 | VkImage layered = VK_NULL_HANDLE; | ||
| 862 | VkImageView layered_view = VK_NULL_HANDLE, layer0 = VK_NULL_HANDLE; | ||
| 863 | CHECK(make_layered(&layered, &layered_view, &layer0)); | ||
| 864 | CHECK(upload_layered(layered)); | ||
| 865 | |||
| 866 | std::uint32_t index = 0, kind = 0; | ||
| 867 | EXPECT(add_mirrored(layered_view, layer0, &index, &kind)); | ||
| 868 | // The allocation is in both index spaces: the T#'s dimension and the 2D arrays (the mirror's slot). | ||
| 869 | EXPECT(set.free_images(ImageDimension::dim_2d) == free_2d - 1); | ||
| 870 | EXPECT(set.free_images(ImageDimension::dim_2d_array) == free_array - 1); | ||
| 871 | // The entry names the 2D-array arrays and their storage arrays, and the 2D ones the mirror is bound in. | ||
| 872 | EXPECT(kind == (kind_sampled_bit(1) | kind_storage_bit(1) | kind_sampled_bit(0) | kind_storage_bit(0))); | ||
| 873 | EXPECT(set.image_kind_at(ImageDimension::dim_2d_array, index) == kind); | ||
| 874 | EXPECT(set.image_kind_at(ImageDimension::dim_2d, index) == | ||
| 875 | (kind_sampled_bit(0) | kind_storage_bit(0))); | ||
| 876 | EXPECT(set.insert_key(tsharp, index, kind)); | ||
| 877 | EXPECT(flush()); | ||
| 878 | CHECK(draw()); | ||
| 879 | compare("mirror: a 2D-array T# read by a 2D op", orange_pixel); | ||
| 880 | // Removing the image puts the 2D slot back to its fallback. Its entry still names 2D (the kind it had), | ||
| 881 | // so a 2D op reads that slot: it must hold zeros, not the removed mirror. | ||
| 882 | EXPECT(set.erase_key(tsharp)); | ||
| 883 | set.remove_image(ImageDimension::dim_2d_array, index); | ||
| 884 | EXPECT(flush()); | ||
| 885 | EXPECT((set.image_kind_at(ImageDimension::dim_2d_array, index) & kind_sampled_bit(0)) == 0); | ||
| 886 | EXPECT(set.free_images(ImageDimension::dim_2d) == free_2d); | ||
| 887 | EXPECT(set.free_images(ImageDimension::dim_2d_array) == free_array); | ||
| 888 | EXPECT(set.insert_key(tsharp, index, kind)); | ||
| 889 | EXPECT(flush()); | ||
| 890 | CHECK(draw()); | ||
| 891 | compare("mirror: removed, the 2D slot holds the fallback", fallback_pixels); | ||
| 892 | EXPECT(set.erase_key(tsharp)); | ||
| 893 | |||
| 894 | // The aliasing scenario the owner records: a 2D-array image with its mirror at slot N and a 3D image at | ||
| 895 | // its own index N (both index spaces are dense, so both take the lowest storage slot). Neither may claim | ||
| 896 | // the other's slot, and removing either must leave the other's binding alone. | ||
| 897 | VkImage layered2 = VK_NULL_HANDLE; | ||
| 898 | VkImageView layered2_view = VK_NULL_HANDLE, layer0_2 = VK_NULL_HANDLE; | ||
| 899 | CHECK(make_layered(&layered2, &layered2_view, &layer0_2)); | ||
| 900 | CHECK(upload_layered(layered2)); | ||
| 901 | std::uint32_t array_index = 0, array_kind = 0; | ||
| 902 | EXPECT(add_mirrored(layered2_view, layer0_2, &array_index, &array_kind)); | ||
| 903 | VkImage volume = VK_NULL_HANDLE; | ||
| 904 | VkImageView volume_view = VK_NULL_HANDLE; | ||
| 905 | CHECK(make_volume(&volume, &volume_view)); | ||
| 906 | StorageViews volume_storage; | ||
| 907 | volume_storage.as_float = volume_view; | ||
| 908 | const std::uint32_t volume_index = set.add_image(ImageDimension::dim_3d, volume_view, | ||
| 909 | VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, volume_storage); | ||
| 910 | EXPECT(volume_index != 0 && volume_index == array_index); // the same slot number, two index spaces | ||
| 911 | const std::uint32_t volume_kind = set.image_kind_at(ImageDimension::dim_3d, volume_index); | ||
| 912 | // The 3D image does not own the 2D mirror: a 2D op reading its T# takes the 2D fallback. | ||
| 913 | EXPECT(volume_kind == (kind_sampled_bit(2) | kind_storage_bit(2))); | ||
| 914 | EXPECT((volume_kind & kind_sampled_bit(0)) == 0); | ||
| 915 | EXPECT(set.image_kind_at(ImageDimension::dim_2d_array, array_index) == array_kind); | ||
| 916 | DescriptorKey volume_key = tsharp; // the same FORMAT (word 1), a different key | ||
| 917 | volume_key[7] ^= 0x10u; | ||
| 918 | EXPECT(set.insert_key(tsharp, array_index, array_kind)); | ||
| 919 | EXPECT(set.insert_key(volume_key, volume_index, volume_kind)); | ||
| 920 | EXPECT(flush()); | ||
| 921 | CHECK(draw_with(volume_key)); | ||
| 922 | compare("alias: a 3D T# at another image's mirror slot", fallback_pixels); | ||
| 923 | CHECK(draw_with(tsharp)); | ||
| 924 | compare("alias: the mirror, with the 3D image at the same slot", orange_pixel); | ||
| 925 | // Removing the 3D image must not take the 2D-array image's mirror with it. | ||
| 926 | EXPECT(set.erase_key(volume_key)); | ||
| 927 | set.remove_image(ImageDimension::dim_3d, volume_index); | ||
| 928 | EXPECT(flush()); | ||
| 929 | EXPECT(set.image_kind_at(ImageDimension::dim_2d_array, array_index) == array_kind); | ||
| 930 | CHECK(draw_with(tsharp)); | ||
| 931 | compare("alias: the mirror survives the 3D image's removal", orange_pixel); | ||
| 932 | // And removing the 2D-array image frees the 2D slot: a 3D image at that slot number names no mirror. | ||
| 933 | const std::uint32_t volume_again = set.add_image(ImageDimension::dim_3d, volume_view, | ||
| 934 | VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, volume_storage); | ||
| 935 | EXPECT(volume_again == volume_index); | ||
| 936 | EXPECT(set.insert_key(volume_key, volume_again, set.image_kind_at(ImageDimension::dim_3d, volume_again))); | ||
| 937 | EXPECT(set.erase_key(tsharp)); | ||
| 938 | set.remove_image(ImageDimension::dim_2d_array, array_index); | ||
| 939 | EXPECT(flush()); | ||
| 940 | EXPECT((set.image_kind_at(ImageDimension::dim_3d, volume_again) & kind_sampled_bit(0)) == 0); | ||
| 941 | EXPECT(set.free_images(ImageDimension::dim_2d) == free_2d); | ||
| 942 | CHECK(draw_with(volume_key)); | ||
| 943 | compare("alias: no mirror once the 2D-array image is gone", fallback_pixels); | ||
| 944 | EXPECT(set.erase_key(volume_key)); | ||
| 945 | set.remove_image(ImageDimension::dim_3d, volume_again); | ||
| 946 | EXPECT(flush()); | ||
| 947 | // The steps below expect tsharp at the heap's T# again. | ||
| 948 | std::memcpy(static_cast<char*>(heap_map) + table_va, tsharp.data(), 32); | ||
| 949 | vkDestroyImageView(dev, volume_view, nullptr); | ||
| 950 | vkDestroyImage(dev, volume, nullptr); | ||
| 951 | for (const VkImageView view : {layered_view, layer0, layered2_view, layer0_2}) | ||
| 952 | vkDestroyImageView(dev, view, nullptr); | ||
| 953 | vkDestroyImage(dev, layered, nullptr); | ||
| 954 | vkDestroyImage(dev, layered2, nullptr); | ||
| 955 | } | ||
| 956 | |||
| 741 | // Index spaces. An image with storage views gets an index the storage arrays hold; one without goes above | 957 | // Index spaces. An image with storage views gets an index the storage arrays hold; one without goes above |
| 742 | // them where the dimension has room. A dimension that is full gives 0, and removed indices come back. | 958 | // them where the dimension has room. A dimension that is full gives 0, and removed indices come back. |
| 743 | StorageViews as_storage; | 959 | StorageViews as_storage; |
| @@ -763,6 +979,61 @@ int main(int argc, char** argv) { | |||
| 763 | const std::uint32_t sampler_index = set.add_sampler(nearest); | 979 | const std::uint32_t sampler_index = set.add_sampler(nearest); |
| 764 | EXPECT(decoy_sampler == 1 && sampler_index == 2 && set.free_samplers() == set.sampler_capacity() - 3); | 980 | EXPECT(decoy_sampler == 1 && sampler_index == 2 && set.free_samplers() == set.sampler_capacity() - 3); |
| 765 | 981 | ||
| 982 | // The T#'s own type is the truth. This shader samples in 2D; the 3D image's index is 1 in the 3D arrays, | ||
| 983 | // and index 1 of the 2D arrays is `stored_view` (its own image, a red texel). The entry says the index is | ||
| 984 | // bound in the 3D arrays only, so the 2D read must use the 2D array's fallback and read zeros - not | ||
| 985 | // `stored_view`, which is what indexing the instruction's array with the other dimension's index would do. | ||
| 986 | { | ||
| 987 | EXPECT(stored_index == 1); | ||
| 988 | VkImage volume = VK_NULL_HANDLE; | ||
| 989 | VkImageView volume_view = VK_NULL_HANDLE; | ||
| 990 | { | ||
| 991 | const VkImageUsageFlags usage = | ||
| 992 | VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_STORAGE_BIT; | ||
| 993 | VkImageCreateInfo ii{VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO}; | ||
| 994 | ii.imageType = VK_IMAGE_TYPE_3D; | ||
| 995 | ii.format = VK_FORMAT_R8G8B8A8_UNORM; | ||
| 996 | ii.extent = {2, 2, 2}; | ||
| 997 | ii.mipLevels = 1; | ||
| 998 | ii.arrayLayers = 1; | ||
| 999 | ii.samples = VK_SAMPLE_COUNT_1_BIT; | ||
| 1000 | ii.tiling = VK_IMAGE_TILING_OPTIMAL; | ||
| 1001 | ii.usage = usage; | ||
| 1002 | CHECK(vkCreateImage(dev, &ii, nullptr, &volume)); | ||
| 1003 | VkMemoryRequirements mr; | ||
| 1004 | vkGetImageMemoryRequirements(dev, volume, &mr); | ||
| 1005 | VkMemoryAllocateInfo ai{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; | ||
| 1006 | ai.allocationSize = mr.size; | ||
| 1007 | ai.memoryTypeIndex = memtype(mr.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); | ||
| 1008 | VkDeviceMemory memory = VK_NULL_HANDLE; | ||
| 1009 | CHECK(vkAllocateMemory(dev, &ai, nullptr, &memory)); | ||
| 1010 | allocations.push_back(memory); | ||
| 1011 | CHECK(vkBindImageMemory(dev, volume, memory, 0)); | ||
| 1012 | VkImageViewCreateInfo vi{VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO}; | ||
| 1013 | vi.image = volume; | ||
| 1014 | vi.viewType = VK_IMAGE_VIEW_TYPE_3D; | ||
| 1015 | vi.format = VK_FORMAT_R8G8B8A8_UNORM; | ||
| 1016 | vi.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; | ||
| 1017 | CHECK(vkCreateImageView(dev, &vi, nullptr, &volume_view)); | ||
| 1018 | } | ||
| 1019 | // A storage view puts it in the low index region, so its index is 1: the same slot number as | ||
| 1020 | // `stored_view` in the 2D arrays, which a dimension-blind read would pick up. | ||
| 1021 | StorageViews volume_storage; | ||
| 1022 | volume_storage.as_float = volume_view; | ||
| 1023 | const std::uint32_t volume_index = set.add_image(ImageDimension::dim_3d, volume_view, | ||
| 1024 | VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, volume_storage); | ||
| 1025 | EXPECT(volume_index == stored_index); // the same slot number, a different index space | ||
| 1026 | EXPECT(set.insert_key(tsharp, volume_index, ImageDimension::dim_3d)); | ||
| 1027 | EXPECT(flush()); | ||
| 1028 | EXPECT(draw() == VK_SUCCESS); | ||
| 1029 | const float zeros[4] = {0.0f, 0.0f, 0.0f, 0.0f}; | ||
| 1030 | compare("a 3D T# read by a 2D op", zeros); | ||
| 1031 | EXPECT(set.erase_key(tsharp)); | ||
| 1032 | set.remove_image(ImageDimension::dim_3d, volume_index); | ||
| 1033 | vkDestroyImageView(dev, volume_view, nullptr); | ||
| 1034 | vkDestroyImage(dev, volume, nullptr); | ||
| 1035 | } | ||
| 1036 | |||
| 766 | if (atomic_mode) { | 1037 | if (atomic_mode) { |
| 767 | // ps_imgatomic.asm: image_atomic_umax/umin/or on three 8x8 r32ui images and umax on a 4x4x4 one, from | 1038 | // ps_imgatomic.asm: image_atomic_umax/umin/or on three 8x8 r32ui images and umax on a 4x4x4 one, from |
| 768 | // every pixel of the 64x64 draw (64 pixels per 2D texel), each found through its own T# key. Odd | 1039 | // every pixel of the 64x64 draw (64 pixels per 2D texel), each found through its own T# key. Odd |
| @@ -815,7 +1086,8 @@ int main(int argc, char** argv) { | |||
| 815 | indices[k] = set.add_image(k == 3 ? ImageDimension::dim_3d : ImageDimension::dim_2d, views[k], | 1086 | indices[k] = set.add_image(k == 3 ? ImageDimension::dim_3d : ImageDimension::dim_2d, views[k], |
| 816 | VK_IMAGE_LAYOUT_GENERAL, storage); | 1087 | VK_IMAGE_LAYOUT_GENERAL, storage); |
| 817 | EXPECT(indices[k] != 0); | 1088 | EXPECT(indices[k] != 0); |
| 818 | EXPECT(set.insert_key(keys[k], indices[k])); | 1089 | EXPECT(set.insert_key(keys[k], indices[k], |
| 1090 | k == 3 ? ImageDimension::dim_3d : ImageDimension::dim_2d)); | ||
| 819 | } | 1091 | } |
| 820 | EXPECT(flush()); | 1092 | EXPECT(flush()); |
| 821 | 1093 | ||
| @@ -963,9 +1235,10 @@ int main(int argc, char** argv) { | |||
| 963 | const auto target = (slots - 4 + i % kDescriptorProbes) & (slots - 1); | 1235 | const auto target = (slots - 4 + i % kDescriptorProbes) & (slots - 1); |
| 964 | while ((hash_descriptor_key(key) & (slots - 1)) != target) ++key[7]; | 1236 | while ((hash_descriptor_key(key) & (slots - 1)) != target) ++key[7]; |
| 965 | } | 1237 | } |
| 966 | for (std::uint32_t i = 0; i < kDescriptorProbes; ++i) set.insert_key(keys[i], decoy_index); | 1238 | for (std::uint32_t i = 0; i < kDescriptorProbes; ++i) |
| 1239 | set.insert_key(keys[i], decoy_index, ImageDimension::dim_2d); | ||
| 967 | EXPECT(!set.flush_replaces_table() && flush()); | 1240 | EXPECT(!set.flush_replaces_table() && flush()); |
| 968 | EXPECT(set.insert_key(keys.back(), gradient_index)); | 1241 | EXPECT(set.insert_key(keys.back(), gradient_index, ImageDimension::dim_2d)); |
| 969 | EXPECT(slot_count() == slots && set.flush_replaces_table()); | 1242 | EXPECT(slot_count() == slots && set.flush_replaces_table()); |
| 970 | EXPECT(flush() && !set.flush_replaces_table()); | 1243 | EXPECT(flush() && !set.flush_replaces_table()); |
| 971 | for (const auto& key : keys) { | 1244 | for (const auto& key : keys) { |
| @@ -979,12 +1252,13 @@ int main(int argc, char** argv) { | |||
| 979 | std::uint32_t ahead = 0; | 1252 | std::uint32_t ahead = 0; |
| 980 | for (std::uint32_t k = 1; ahead < 3; ++k) { | 1253 | for (std::uint32_t k = 1; ahead < 3; ++k) { |
| 981 | if ((hash_descriptor_key(numbered(k)) & (slots - 1)) != home) continue; | 1254 | if ((hash_descriptor_key(numbered(k)) & (slots - 1)) != home) continue; |
| 982 | set.insert_key(numbered(k), decoy_index); | 1255 | set.insert_key(numbered(k), decoy_index, ImageDimension::dim_2d); |
| 983 | ++ahead; | 1256 | ++ahead; |
| 984 | } | 1257 | } |
| 985 | set.insert_key(tsharp, gradient_index); | 1258 | set.insert_key(tsharp, gradient_index, ImageDimension::dim_2d); |
| 986 | set.insert_key(make_ssharp_key(ssharp.data()), sampler_index); | 1259 | set.insert_key(make_ssharp_key(ssharp.data()), sampler_index); |
| 987 | for (std::uint32_t k = 100000; k < 100006; ++k) set.insert_key(numbered(k), decoy_index); | 1260 | for (std::uint32_t k = 100000; k < 100006; ++k) |
| 1261 | set.insert_key(numbered(k), decoy_index, ImageDimension::dim_2d); | ||
| 988 | const std::uint32_t depth = probe_depth(table.build_gpu_buffer(), tsharp); | 1262 | const std::uint32_t depth = probe_depth(table.build_gpu_buffer(), tsharp); |
| 989 | EXPECT(slot_count() == slots && depth == 3 && !set.flush_replaces_table()); | 1263 | EXPECT(slot_count() == slots && depth == 3 && !set.flush_replaces_table()); |
| 990 | EXPECT(flush()); | 1264 | EXPECT(flush()); |
| @@ -1000,9 +1274,10 @@ int main(int argc, char** argv) { | |||
| 1000 | compare("2 miss", zeros); | 1274 | compare("2 miss", zeros); |
| 1001 | 1275 | ||
| 1002 | // 3. The table grows: a new, larger buffer behind binding 2. | 1276 | // 3. The table grows: a new, larger buffer behind binding 2. |
| 1003 | set.insert_key(tsharp, gradient_index); | 1277 | set.insert_key(tsharp, gradient_index, ImageDimension::dim_2d); |
| 1004 | EXPECT(!set.flush_replaces_table()); // one more entry, in place | 1278 | EXPECT(!set.flush_replaces_table()); // one more entry, in place |
| 1005 | for (std::uint32_t k = 200000; k < 200200; ++k) set.insert_key(numbered(k), decoy_index); | 1279 | for (std::uint32_t k = 200000; k < 200200; ++k) |
| 1280 | set.insert_key(numbered(k), decoy_index, ImageDimension::dim_2d); | ||
| 1006 | EXPECT(slot_count() > slots && table.lookup(tsharp) == gradient_index && set.flush_replaces_table()); | 1281 | EXPECT(slot_count() > slots && table.lookup(tsharp) == gradient_index && set.flush_replaces_table()); |
| 1007 | const VkDescriptorSet before_growth = set.set(); | 1282 | const VkDescriptorSet before_growth = set.set(); |
| 1008 | const std::uint64_t made_before = set.generations_made(); | 1283 | const std::uint64_t made_before = set.generations_made(); |
| @@ -1020,12 +1295,13 @@ int main(int argc, char** argv) { | |||
| 1020 | const float orange_colour[4] = {1.0f, 128.0f / 255.0f, 0.0f, 1.0f}; | 1295 | const float orange_colour[4] = {1.0f, 128.0f / 255.0f, 0.0f, 1.0f}; |
| 1021 | // Rewriting the same mapping is a no-op. Changing it makes a new generation even with no table growth. | 1296 | // Rewriting the same mapping is a no-op. Changing it makes a new generation even with no table growth. |
| 1022 | const std::uint32_t grown_slots = slot_count(); | 1297 | const std::uint32_t grown_slots = slot_count(); |
| 1023 | EXPECT(set.insert_key(tsharp, gradient_index) && !set.flush_replaces_table()); | 1298 | EXPECT(set.insert_key(tsharp, gradient_index, ImageDimension::dim_2d) && !set.flush_replaces_table()); |
| 1024 | EXPECT(set.insert_key(tsharp, decoy_index) && slot_count() == grown_slots && set.flush_replaces_table()); | 1299 | EXPECT(set.insert_key(tsharp, decoy_index, ImageDimension::dim_2d) && slot_count() == grown_slots && |
| 1300 | set.flush_replaces_table()); | ||
| 1025 | EXPECT(flush() && !set.flush_replaces_table()); | 1301 | EXPECT(flush() && !set.flush_replaces_table()); |
| 1026 | CHECK(draw()); | 1302 | CHECK(draw()); |
| 1027 | compare("4 rebound", orange_colour); | 1303 | compare("4 rebound", orange_colour); |
| 1028 | EXPECT(set.insert_key(tsharp, gradient_index) && set.flush_replaces_table()); | 1304 | EXPECT(set.insert_key(tsharp, gradient_index, ImageDimension::dim_2d) && set.flush_replaces_table()); |
| 1029 | EXPECT(flush()); | 1305 | EXPECT(flush()); |
| 1030 | CHECK(draw()); | 1306 | CHECK(draw()); |
| 1031 | compare("5 restored", nullptr); | 1307 | compare("5 restored", nullptr); |
| @@ -1033,7 +1309,7 @@ int main(int argc, char** argv) { | |||
| 1033 | // A submit that never reached the queue must keep the table upload pending: the retry has to see the new | 1309 | // A submit that never reached the queue must keep the table upload pending: the retry has to see the new |
| 1034 | // mapping instead of the fallback or the old index (a recovered submit failure, the case a device reports | 1310 | // mapping instead of the fallback or the old index (a recovered submit failure, the case a device reports |
| 1035 | // through table_upload_result(false)). | 1311 | // through table_upload_result(false)). |
| 1036 | EXPECT(set.insert_key(tsharp, decoy_index) && set.flush_replaces_table()); | 1312 | EXPECT(set.insert_key(tsharp, decoy_index, ImageDimension::dim_2d) && set.flush_replaces_table()); |
| 1037 | vkResetCommandBuffer(cmd, 0); | 1313 | vkResetCommandBuffer(cmd, 0); |
| 1038 | CHECK(vkBeginCommandBuffer(cmd, &begin)); | 1314 | CHECK(vkBeginCommandBuffer(cmd, &begin)); |
| 1039 | EXPECT(set.flush(cmd, 1)); // recorded in a command buffer that is never submitted | 1315 | EXPECT(set.flush(cmd, 1)); // recorded in a command buffer that is never submitted |
| @@ -1043,7 +1319,7 @@ int main(int argc, char** argv) { | |||
| 1043 | EXPECT(flush()); | 1319 | EXPECT(flush()); |
| 1044 | CHECK(draw()); | 1320 | CHECK(draw()); |
| 1045 | compare("6 rebound after a failed submit", orange_colour); | 1321 | compare("6 rebound after a failed submit", orange_colour); |
| 1046 | EXPECT(set.insert_key(tsharp, gradient_index) && set.flush_replaces_table()); | 1322 | EXPECT(set.insert_key(tsharp, gradient_index, ImageDimension::dim_2d) && set.flush_replaces_table()); |
| 1047 | EXPECT(flush()); | 1323 | EXPECT(flush()); |
| 1048 | 1324 | ||
| 1049 | // Another view at the same index, then removal of the index. | 1325 | // Another view at the same index, then removal of the index. |
| @@ -1066,7 +1342,7 @@ int main(int argc, char** argv) { | |||
| 1066 | far_image = set.add_image(ImageDimension::dim_2d, gradient_view, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); | 1342 | far_image = set.add_image(ImageDimension::dim_2d, gradient_view, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); |
| 1067 | for (std::uint32_t i = 0; i < 2100; ++i) far_sampler = set.add_sampler(nearest); | 1343 | for (std::uint32_t i = 0; i < 2100; ++i) far_sampler = set.add_sampler(nearest); |
| 1068 | EXPECT(far_image > 5000 && far_sampler > 2100); | 1344 | EXPECT(far_image > 5000 && far_sampler > 2100); |
| 1069 | set.insert_key(tsharp, far_image); | 1345 | set.insert_key(tsharp, far_image, ImageDimension::dim_2d); |
| 1070 | set.insert_key(make_ssharp_key(ssharp.data()), far_sampler); | 1346 | set.insert_key(make_ssharp_key(ssharp.data()), far_sampler); |
| 1071 | EXPECT(flush()); | 1347 | EXPECT(flush()); |
| 1072 | CHECK(draw()); | 1348 | CHECK(draw()); |
| @@ -1087,7 +1363,7 @@ int main(int argc, char** argv) { | |||
| 1087 | const float blue[4] = {0, 0, 128.0f / 255.0f, 1}; // stored image uses the first gradient texel | 1363 | const float blue[4] = {0, 0, 128.0f / 255.0f, 1}; // stored image uses the first gradient texel |
| 1088 | compare("11 reused high slot", blue); | 1364 | compare("11 reused high slot", blue); |
| 1089 | 1365 | ||
| 1090 | EXPECT(set.insert_key(tsharp, neighbour)); | 1366 | EXPECT(set.insert_key(tsharp, neighbour, ImageDimension::dim_2d)); |
| 1091 | EXPECT(flush()); | 1367 | EXPECT(flush()); |
| 1092 | CHECK(draw()); | 1368 | CHECK(draw()); |
| 1093 | compare("12 live neighbour", orange_colour); | 1369 | compare("12 live neighbour", orange_colour); |
diff --git a/runtime/test/vk_console_heap_gpu_test.cpp b/runtime/test/vk_console_heap_gpu_test.cpp new file mode 100644 index 000000000..9ac34f52b --- /dev/null +++ b/runtime/test/vk_console_heap_gpu_test.cpp | |||
| @@ -0,0 +1,584 @@ | |||
| 1 | // The console heap translation pass (src/console_heap_fix.comp, src/console_heap_gpu.h) against its CPU reference: | ||
| 2 | // synthetic descriptor words only (no game data). Checks the key table mirror on the CPU first, then that the GPU | ||
| 3 | // writes every slot exactly as console_heap_translate_slot does and records the same misses, through key table | ||
| 4 | // updates, a new range table, a submission that failed (its work queued again) and a miss list that overflows. | ||
| 5 | // Exits 77 without a Vulkan device with bufferDeviceAddress. | ||
| 6 | #include "vk_test_device.h" | ||
| 7 | #include "../src/console_heap_gpu.h" | ||
| 8 | |||
| 9 | #include <cstdio> | ||
| 10 | #include <cstring> | ||
| 11 | #include <random> | ||
| 12 | #include <array> | ||
| 13 | #include <set> | ||
| 14 | #include <vector> | ||
| 15 | |||
| 16 | #define EXPECT(x) \ | ||
| 17 | do { \ | ||
| 18 | if (!(x)) { \ | ||
| 19 | std::fprintf(stderr, "line %d: %s\n", __LINE__, #x); \ | ||
| 20 | return 1; \ | ||
| 21 | } \ | ||
| 22 | } while (0) | ||
| 23 | |||
| 24 | namespace { | ||
| 25 | |||
| 26 | using leonida::ConsoleHeapKeys; | ||
| 27 | using leonida::ConsoleHeapRange; | ||
| 28 | using leonida::ConsoleHeapTables; | ||
| 29 | |||
| 30 | // A buffer V# half: base, stride, records and dword 3 with TYPE bits 30-31 clear. | ||
| 31 | void vsharp(std::uint32_t* w, std::uint64_t base, std::uint32_t stride, std::uint32_t records, std::uint32_t dword3) { | ||
| 32 | w[0] = std::uint32_t(base); | ||
| 33 | w[1] = std::uint32_t((base >> 32) & 0xffff) | (stride << 16); | ||
| 34 | w[2] = records; | ||
| 35 | w[3] = dword3 & 0x3fffffffu; | ||
| 36 | } | ||
| 37 | |||
| 38 | int keys_on_cpu() { | ||
| 39 | ConsoleHeapKeys keys(6); // 64 entries: probe chains overlap | ||
| 40 | const ConsoleHeapKeys::Key a{1, 2, 3, 4}, b{5, 6, 7, 8}; | ||
| 41 | EXPECT(keys.find(a) < 0); | ||
| 42 | EXPECT(keys.put(a, 0x1000, 0x100, false)); | ||
| 43 | EXPECT(keys.put(b, 0, 0x40, true)); | ||
| 44 | std::uint64_t to = 0; | ||
| 45 | bool none = true; | ||
| 46 | EXPECT(keys.lookup(a, to, none) && to == 0x1000 && !none); | ||
| 47 | EXPECT(keys.lookup(b, to, none) && none); | ||
| 48 | EXPECT(keys.size() == 2); | ||
| 49 | // Only positive answers fall in a released shader range; the edge is exclusive. | ||
| 50 | EXPECT(keys.erase_overlapping(0x1100, 0x2000) == 0); | ||
| 51 | EXPECT(keys.erase_overlapping(0x10ff, 0x1100) == 1); | ||
| 52 | EXPECT(keys.find(a) < 0 && keys.find(b) >= 0); | ||
| 53 | // Replacing an answer keeps one entry and moves its index. | ||
| 54 | EXPECT(keys.put(b, 0x5000, 0x10, false)); | ||
| 55 | EXPECT(keys.size() == 1); | ||
| 56 | EXPECT(keys.erase_overlapping(0x5008, 0x5009) == 1); | ||
| 57 | EXPECT(keys.size() == 0); | ||
| 58 | // Fill one probe chain: the 17th key with the same start finds no slot. | ||
| 59 | // V#s whose words differ only in high bits (bases megabytes apart): the hash must still spread them. Bare FNV-1a | ||
| 60 | // put all of these in one probe chain. | ||
| 61 | { | ||
| 62 | ConsoleHeapKeys big(20); | ||
| 63 | for (std::uint32_t i = 0; i < 20000; ++i) { | ||
| 64 | const ConsoleHeapKeys::Key k{(i & 0xfffu) << 20, ((i >> 12) << 8) | (64u << 16), 256, 0x2000}; | ||
| 65 | EXPECT(big.put(k, 0x100000ull * i, 256, false)); | ||
| 66 | } | ||
| 67 | EXPECT(big.size() == 20000); | ||
| 68 | } | ||
| 69 | std::vector<ConsoleHeapKeys::Key> same; | ||
| 70 | for (std::uint32_t i = 0; same.size() < ConsoleHeapKeys::kProbes + 1 && i < 1u << 20; ++i) { | ||
| 71 | const ConsoleHeapKeys::Key k{i, 0, 1, 0}; | ||
| 72 | if ((ConsoleHeapKeys::hash(k) & keys.mask()) == 7) same.push_back(k); | ||
| 73 | } | ||
| 74 | EXPECT(same.size() == ConsoleHeapKeys::kProbes + 1); | ||
| 75 | for (std::size_t i = 0; i < ConsoleHeapKeys::kProbes; ++i) EXPECT(keys.put(same[i], 0x100 * i, 1, false)); | ||
| 76 | EXPECT(!keys.put(same.back(), 1, 1, false)); | ||
| 77 | std::vector<std::uint32_t> updates; | ||
| 78 | keys.take_updates(updates); | ||
| 79 | EXPECT(!updates.empty() && updates.size() % ConsoleHeapKeys::kUpdateWords == 0); | ||
| 80 | EXPECT(!keys.has_updates()); | ||
| 81 | // The reference: ranges first (checked only), then keys, else a miss. | ||
| 82 | ConsoleHeapTables ranges; | ||
| 83 | ranges.ranges = {{0x10000, 0x20000, 0x400000, true}, {0x30000, 0x40000, 0x500000, false}}; | ||
| 84 | ConsoleHeapKeys k2(8); | ||
| 85 | std::uint32_t w[8] = {}; | ||
| 86 | vsharp(w, 0x10100, 16, 4, 0); | ||
| 87 | EXPECT(leonida::console_heap_translate_slot(w, ranges, k2) == 0); | ||
| 88 | EXPECT(w[0] == 0x400100 && (w[1] & 0xffff) == 0 && w[2] == 4); | ||
| 89 | vsharp(w, 0x1ff00, 16, 32, 0); // 512 bytes past a range with 256 left: no records | ||
| 90 | EXPECT(leonida::console_heap_translate_slot(w, ranges, k2) == 0 && !w[0] && !w[1] && !w[2]); | ||
| 91 | vsharp(w, 0x30000, 0, 64, 0); // an unchecked range: the key table, then a miss | ||
| 92 | EXPECT(leonida::console_heap_translate_slot(w, ranges, k2) == 1 && !w[2]); | ||
| 93 | // Backed spans leave a base as it is (before the key table); outside the ask table nothing is a miss. | ||
| 94 | ranges.backed = {{0x80000, 0x90000}}; | ||
| 95 | ranges.ask = {{0x30000, 0x40000}}; | ||
| 96 | ranges.use_ask = true; | ||
| 97 | vsharp(w, 0x80100, 0, 64, 0); | ||
| 98 | EXPECT(leonida::console_heap_translate_slot(w, ranges, k2) == 0 && w[0] == 0x80100 && w[2] == 64); | ||
| 99 | vsharp(w, 0x8ffc0, 0, 128, 0); // runs past the span: not backed, outside ask: no records, no miss | ||
| 100 | EXPECT(leonida::console_heap_translate_slot(w, ranges, k2) == 0 && !w[2]); | ||
| 101 | vsharp(w, 0x30000, 0, 64, 0); // in ask: a miss | ||
| 102 | EXPECT(leonida::console_heap_translate_slot(w, ranges, k2) == 1); | ||
| 103 | // Signed offsets: a base with bit 47 set is the negative shader VA it names. | ||
| 104 | ranges.signed_offsets = true; | ||
| 105 | ranges.backed = {{0xffff800000000000ull, 0xffff800000010000ull}}; | ||
| 106 | vsharp(w, 0x800000000100ull, 0, 64, 0); | ||
| 107 | EXPECT(leonida::console_heap_translate_slot(w, ranges, k2) == 0 && w[2] == 64); | ||
| 108 | std::vector<std::pair<std::uint64_t, std::uint64_t>> spans{{10, 20}, {15, 30}, {30, 40}, {50, 60}, {5, 5}}; | ||
| 109 | leonida::merge_console_heap_spans(spans); | ||
| 110 | EXPECT(spans.size() == 2 && spans[0].first == 10 && spans[0].second == 40 && spans[1].first == 50); | ||
| 111 | return 0; | ||
| 112 | } | ||
| 113 | |||
| 114 | struct Case { | ||
| 115 | ConsoleHeapTables t; | ||
| 116 | std::vector<ConsoleHeapRange>& ranges = t.ranges; | ||
| 117 | ConsoleHeapKeys keys{14}; | ||
| 118 | }; | ||
| 119 | |||
| 120 | // Random slot words over a mix of classes; bases drawn from the ranges and keys so every path is taken. | ||
| 121 | void make_slots(std::mt19937& rng, std::uint32_t* words, std::size_t slots, Case& c, | ||
| 122 | std::vector<ConsoleHeapKeys::Key>& entered) { | ||
| 123 | std::uniform_int_distribution<std::uint32_t> any; | ||
| 124 | for (std::size_t s = 0; s < slots; ++s) { | ||
| 125 | std::uint32_t* w = words + 8 * s; | ||
| 126 | for (int i = 0; i < 8; ++i) w[i] = any(rng); | ||
| 127 | const std::uint32_t kind = any(rng) % 10; | ||
| 128 | if (kind == 0) { // T#: TYPE >= 8 | ||
| 129 | w[3] = (w[3] & 0x0fffffffu) | 0x80000000u; | ||
| 130 | continue; | ||
| 131 | } | ||
| 132 | if (kind == 1) { // other words with bits 30-31 set | ||
| 133 | w[3] |= 0x40000000u; | ||
| 134 | continue; | ||
| 135 | } | ||
| 136 | if (kind == 2) { | ||
| 137 | std::memset(w, 0, 32); | ||
| 138 | continue; | ||
| 139 | } | ||
| 140 | for (int half = 0; half < 2; ++half) { | ||
| 141 | std::uint32_t* k = w + 4 * half; | ||
| 142 | const std::uint32_t pick = any(rng) % 8; | ||
| 143 | const std::uint32_t stride = any(rng) % 3 == 0 ? 0 : any(rng) % 64; | ||
| 144 | const std::uint32_t records = 1 + any(rng) % 256; | ||
| 145 | if (pick < 3 && !c.ranges.empty()) { | ||
| 146 | const auto& r = c.ranges[any(rng) % c.ranges.size()]; | ||
| 147 | vsharp(k, r.title_va + any(rng) % (r.end - r.title_va), stride, records, any(rng)); | ||
| 148 | } else if (pick < 5) { | ||
| 149 | vsharp(k, 0x200000000ull + (any(rng) % 4096) * 64, stride, records, any(rng)); | ||
| 150 | if (pick == 3) { | ||
| 151 | const ConsoleHeapKeys::Key key{k[0], k[1], k[2], k[3]}; | ||
| 152 | const bool none = any(rng) % 4 == 0; | ||
| 153 | if (c.keys.put(key, 0x10000000ull + (any(rng) % 65536) * 256, 4096, none)) entered.push_back(key); | ||
| 154 | } | ||
| 155 | } else if (pick == 5) { | ||
| 156 | vsharp(k, 0, stride, records, any(rng)); | ||
| 157 | } else if (pick == 6) { | ||
| 158 | vsharp(k, 0x300000000ull + any(rng), stride, 0, any(rng)); // no records: left as it is | ||
| 159 | } else if (half == 1) { | ||
| 160 | k[3] |= 0x40000000u; // a counter half that is no V# | ||
| 161 | } else { | ||
| 162 | vsharp(k, 0x400000000ull + any(rng), stride, records, any(rng)); // nowhere: a miss | ||
| 163 | } | ||
| 164 | } | ||
| 165 | } | ||
| 166 | } | ||
| 167 | |||
| 168 | } // namespace | ||
| 169 | |||
| 170 | int main() { | ||
| 171 | if (const int failed = keys_on_cpu()) return failed; | ||
| 172 | std::puts("console heap keys (CPU): ok"); | ||
| 173 | |||
| 174 | vktest::Device d; | ||
| 175 | d.request_buffer_device_address = true; | ||
| 176 | const auto status = d.initialize(); | ||
| 177 | if (status == vktest::DeviceStatus::unavailable || (status == vktest::DeviceStatus::ready && !d.buffer_device_address)) { | ||
| 178 | std::printf("vk_console_heap_gpu_test: no Vulkan device with bufferDeviceAddress, skipped\n"); | ||
| 179 | return 77; | ||
| 180 | } | ||
| 181 | if (status != vktest::DeviceStatus::ready) return 1; | ||
| 182 | VkPhysicalDeviceMemoryProperties memory{}; | ||
| 183 | d.instance_fn<PFN_vkGetPhysicalDeviceMemoryProperties>("vkGetPhysicalDeviceMemoryProperties")(d.physical, &memory); | ||
| 184 | |||
| 185 | leonida::ConsoleHeapGpu gpu(d.device_proc, d.device, memory, 14); | ||
| 186 | EXPECT(gpu.init()); | ||
| 187 | |||
| 188 | constexpr std::uint32_t kSlots = 6000; | ||
| 189 | void* input_data = nullptr; | ||
| 190 | void* copy_data = nullptr; | ||
| 191 | const VkBuffer input = d.buffer(VkDeviceSize(kSlots) * 32, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, &input_data); | ||
| 192 | const VkBuffer copy = d.buffer(VkDeviceSize(kSlots) * 32, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, ©_data); | ||
| 193 | EXPECT(input && copy && input_data && copy_data); | ||
| 194 | const int heap = gpu.add_heap(d.device_address(input), d.device_address(copy), kSlots); | ||
| 195 | EXPECT(heap >= 0); | ||
| 196 | auto* in = static_cast<std::uint32_t*>(input_data); | ||
| 197 | auto* out = static_cast<std::uint32_t*>(copy_data); | ||
| 198 | |||
| 199 | std::mt19937 rng(1234); | ||
| 200 | Case c; | ||
| 201 | c.ranges = {{0x10000, 0x30000, 0x100000, true}, | ||
| 202 | {0x40000, 0x48000, 0x0000ffff00000000ull, true}, // bits 32-47 of the answer | ||
| 203 | {0x50000, 0x60000, 0x200000, false}, | ||
| 204 | {0x100000000ull, 0x100100000ull, 0x300000, true}}; | ||
| 205 | std::vector<ConsoleHeapKeys::Key> entered; | ||
| 206 | make_slots(rng, in, kSlots, c, entered); | ||
| 207 | // The GPU's mirror gets the same keys. | ||
| 208 | gpu.with_keys([&](ConsoleHeapKeys& k) { | ||
| 209 | for (const auto& key : entered) { | ||
| 210 | std::uint64_t to = 0; | ||
| 211 | bool none = false; | ||
| 212 | c.keys.lookup(key, to, none); | ||
| 213 | k.put(key, to, 4096, none); | ||
| 214 | } | ||
| 215 | return 0; | ||
| 216 | }); | ||
| 217 | gpu.set_ranges(c.ranges); | ||
| 218 | |||
| 219 | // One round: the listed slots are written as the reference says, the others keep the marker, and the misses | ||
| 220 | // are the reference's. | ||
| 221 | auto round = [&](const std::vector<std::uint32_t>& listed, std::uint64_t ticket, bool expect_overflow) -> int { | ||
| 222 | std::memset(out, 0xcd, std::size_t(kSlots) * 32); | ||
| 223 | gpu.queue(heap, listed.begin(), listed.end()); | ||
| 224 | bool recorded = false; | ||
| 225 | EXPECT(d.run([&](VkCommandBuffer cb) { return recorded = gpu.record(cb); })); | ||
| 226 | EXPECT(recorded); | ||
| 227 | gpu.commit(true, ticket); | ||
| 228 | std::set<std::uint32_t> misses; | ||
| 229 | bool overflowed = false; | ||
| 230 | gpu.drain(ticket, [&](int h, std::uint32_t slot, std::uint32_t half) { | ||
| 231 | if (h == heap) misses.insert(slot * 2 + half); | ||
| 232 | }, [&](int) { overflowed = true; }); | ||
| 233 | EXPECT(gpu.in_flight() == 0); | ||
| 234 | EXPECT(overflowed == expect_overflow); | ||
| 235 | std::set<std::uint32_t> expected_misses; | ||
| 236 | std::vector<std::uint8_t> is_listed(kSlots, 0); | ||
| 237 | for (const std::uint32_t s : listed) is_listed[s] = 1; | ||
| 238 | for (std::uint32_t s = 0; s < kSlots; ++s) { | ||
| 239 | std::uint32_t w[8]; | ||
| 240 | std::memcpy(w, in + 8 * s, 32); | ||
| 241 | if (!is_listed[s]) { | ||
| 242 | for (int i = 0; i < 8; ++i) EXPECT(out[8 * s + i] == 0xcdcdcdcdu); | ||
| 243 | continue; | ||
| 244 | } | ||
| 245 | const unsigned missed = leonida::console_heap_translate_slot(w, c.t, c.keys); | ||
| 246 | if (missed & 1) expected_misses.insert(s * 2); | ||
| 247 | if (missed & 2) expected_misses.insert(s * 2 + 1); | ||
| 248 | if (std::memcmp(w, out + 8 * s, 32)) { | ||
| 249 | std::fprintf(stderr, "slot %u: in %08x %08x %08x %08x %08x %08x %08x %08x\n", s, in[8 * s], | ||
| 250 | in[8 * s + 1], in[8 * s + 2], in[8 * s + 3], in[8 * s + 4], in[8 * s + 5], in[8 * s + 6], | ||
| 251 | in[8 * s + 7]); | ||
| 252 | std::fprintf(stderr, " gpu %08x %08x %08x %08x %08x %08x %08x %08x\n", out[8 * s], out[8 * s + 1], | ||
| 253 | out[8 * s + 2], out[8 * s + 3], out[8 * s + 4], out[8 * s + 5], out[8 * s + 6], | ||
| 254 | out[8 * s + 7]); | ||
| 255 | std::fprintf(stderr, " cpu %08x %08x %08x %08x %08x %08x %08x %08x\n", w[0], w[1], w[2], w[3], w[4], | ||
| 256 | w[5], w[6], w[7]); | ||
| 257 | return 1; | ||
| 258 | } | ||
| 259 | } | ||
| 260 | if (!expect_overflow) EXPECT(misses == expected_misses); | ||
| 261 | else EXPECT(misses.size() == leonida::ConsoleHeapGpu::kMissCapacity); | ||
| 262 | std::printf(" %zu slots, %zu misses\n", listed.size(), misses.size()); | ||
| 263 | return 0; | ||
| 264 | }; | ||
| 265 | |||
| 266 | std::vector<std::uint32_t> all(kSlots); | ||
| 267 | for (std::uint32_t s = 0; s < kSlots; ++s) all[s] = s; | ||
| 268 | EXPECT(round(all, 1, false) == 0); | ||
| 269 | std::puts("console heap pass, every slot: ok"); | ||
| 270 | |||
| 271 | // Key table updates and a new range table: erase some keys, enter answers for some misses, move a range. | ||
| 272 | std::vector<std::uint32_t> some; | ||
| 273 | for (std::uint32_t s = 0; s < kSlots; s += 3) some.push_back(s); | ||
| 274 | std::size_t erased = 0, added = 0; | ||
| 275 | for (std::size_t i = 0; i < entered.size(); i += 2) { | ||
| 276 | c.keys.erase(entered[i]); | ||
| 277 | gpu.with_keys([&](ConsoleHeapKeys& k) { return k.erase(entered[i]); }); | ||
| 278 | ++erased; | ||
| 279 | } | ||
| 280 | for (std::uint32_t s = 0; s < kSlots && added < 200; ++s) { | ||
| 281 | std::uint32_t w[8]; | ||
| 282 | std::memcpy(w, in + 8 * s, 32); | ||
| 283 | std::uint32_t copy_w[8]; | ||
| 284 | std::memcpy(copy_w, w, 32); | ||
| 285 | const unsigned missed = leonida::console_heap_translate_slot(copy_w, c.t, c.keys); | ||
| 286 | if (!(missed & 1)) continue; | ||
| 287 | const ConsoleHeapKeys::Key key{w[0], w[1], w[2], w[3]}; | ||
| 288 | c.keys.put(key, 0x7000000000ull + added * 64, 64, added % 5 == 0); | ||
| 289 | gpu.with_keys([&](ConsoleHeapKeys& k) { return k.put(key, 0x7000000000ull + added * 64, 64, added % 5 == 0); }); | ||
| 290 | ++added; | ||
| 291 | } | ||
| 292 | c.ranges[0].shader_va = 0x900000; | ||
| 293 | c.ranges[2].checked = true; | ||
| 294 | gpu.set_ranges(c.ranges); | ||
| 295 | EXPECT(round(some, 2, false) == 0); | ||
| 296 | std::printf("console heap pass, %zu keys erased, %zu entered, ranges moved: ok\n", erased, added); | ||
| 297 | |||
| 298 | // A submission that did not reach the queue: its slots and updates come back for the next pass. | ||
| 299 | { | ||
| 300 | const ConsoleHeapKeys::Key key{in[8 * 5], in[8 * 5 + 1], in[8 * 5 + 2], in[8 * 5 + 3]}; | ||
| 301 | gpu.queue(heap, 5); | ||
| 302 | bool recorded = false; | ||
| 303 | EXPECT(d.run([&](VkCommandBuffer cb) { return recorded = gpu.record(cb); })); | ||
| 304 | EXPECT(recorded && !gpu.pending()); | ||
| 305 | gpu.commit(false, 0); | ||
| 306 | EXPECT(gpu.pending() && gpu.in_flight() == 0); | ||
| 307 | (void)key; | ||
| 308 | } | ||
| 309 | EXPECT(round({5}, 3, false) == 0); | ||
| 310 | // Backed and ask tables: part of the keyed bases become backed (answered before the key table), and only bases | ||
| 311 | // in the ask span miss. | ||
| 312 | c.t.backed = {{0x200000000ull, 0x200008000ull}, {0x10000ull, 0x18000ull}}; | ||
| 313 | c.t.ask = {{0x400000000ull, 0x500000000ull}}; | ||
| 314 | c.t.use_ask = true; | ||
| 315 | gpu.set_spans(leonida::ConsoleHeapGpu::backed_table, c.t.backed); | ||
| 316 | gpu.set_spans(leonida::ConsoleHeapGpu::ask_table, c.t.ask); | ||
| 317 | EXPECT(round(all, 7, false) == 0); | ||
| 318 | std::puts("console heap pass, backed and ask tables: ok"); | ||
| 319 | { | ||
| 320 | // kZeroFirst: words that are no buffer pair and no T# get dwords 0-3 zeroed; the last queue() decides. | ||
| 321 | std::vector<std::uint32_t> flagged; | ||
| 322 | for (std::uint32_t s2 = 0; s2 < kSlots && flagged.size() < 64; ++s2) | ||
| 323 | if (in[8 * s2 + 3] >> 30) flagged.push_back(s2); | ||
| 324 | EXPECT(flagged.size() == 64); | ||
| 325 | std::memset(out, 0xcd, std::size_t(kSlots) * 32); | ||
| 326 | for (std::size_t i = 0; i < flagged.size(); ++i) { | ||
| 327 | gpu.queue(heap, flagged[i] | leonida::ConsoleHeapGpu::kZeroFirst); | ||
| 328 | if (i % 2) gpu.queue(heap, flagged[i]); // queued again without the bit: copied as it is | ||
| 329 | } | ||
| 330 | bool recorded = false; | ||
| 331 | EXPECT(d.run([&](VkCommandBuffer cb) { return recorded = gpu.record(cb); })); | ||
| 332 | gpu.commit(true, 8); | ||
| 333 | gpu.drain(8, [](int, std::uint32_t, std::uint32_t) {}, [](int) {}); | ||
| 334 | EXPECT(recorded); | ||
| 335 | for (std::size_t i = 0; i < flagged.size(); ++i) { | ||
| 336 | std::uint32_t w[8]; | ||
| 337 | std::memcpy(w, in + 8 * flagged[i], 32); | ||
| 338 | leonida::console_heap_translate_slot(w, c.t, c.keys, i % 2 == 0); | ||
| 339 | EXPECT(!std::memcmp(w, out + 8 * flagged[i], 32)); | ||
| 340 | if (i % 2 == 0) EXPECT(!out[8 * flagged[i]] && !out[8 * flagged[i] + 3]); | ||
| 341 | } | ||
| 342 | } | ||
| 343 | std::puts("console heap pass, words that are no descriptor: ok"); | ||
| 344 | { | ||
| 345 | // rescan(): one range dispatch rewrites the buffer pairs of [0, n) and leaves every other slot as it was. | ||
| 346 | constexpr std::uint32_t n = 4000; | ||
| 347 | std::memset(out, 0xcd, std::size_t(kSlots) * 32); | ||
| 348 | gpu.rescan(heap, n); | ||
| 349 | EXPECT(gpu.pending()); | ||
| 350 | bool recorded = false; | ||
| 351 | EXPECT(d.run([&](VkCommandBuffer cb) { return recorded = gpu.record(cb); })); | ||
| 352 | gpu.commit(true, 9); | ||
| 353 | std::set<std::uint32_t> misses; | ||
| 354 | gpu.drain(9, [&](int h, std::uint32_t slot, std::uint32_t half) { if (h == heap) misses.insert(slot * 2 + half); }, | ||
| 355 | [](int) {}); | ||
| 356 | EXPECT(recorded); | ||
| 357 | std::set<std::uint32_t> expected; | ||
| 358 | std::size_t pairs = 0; | ||
| 359 | for (std::uint32_t s2 = 0; s2 < kSlots; ++s2) { | ||
| 360 | std::uint32_t w[8]; | ||
| 361 | std::memcpy(w, in + 8 * s2, 32); | ||
| 362 | if (s2 >= n || (w[3] >> 30)) { | ||
| 363 | for (int i = 0; i < 8; ++i) EXPECT(out[8 * s2 + i] == 0xcdcdcdcdu); | ||
| 364 | continue; | ||
| 365 | } | ||
| 366 | ++pairs; | ||
| 367 | const unsigned missed = leonida::console_heap_translate_slot(w, c.t, c.keys); | ||
| 368 | if (missed & 1) expected.insert(s2 * 2); | ||
| 369 | if (missed & 2) expected.insert(s2 * 2 + 1); | ||
| 370 | EXPECT(!std::memcmp(w, out + 8 * s2, 32)); | ||
| 371 | } | ||
| 372 | EXPECT(misses == expected && pairs > 1000); | ||
| 373 | EXPECT(!gpu.pending()); | ||
| 374 | } | ||
| 375 | std::puts("console heap pass, range rescan: ok"); | ||
| 376 | { | ||
| 377 | // rescan_filtered(): only the slots whose metadata (left by the last pass over them, the rescan above) meets a | ||
| 378 | // change span are translated again: a title span holding one slot's base, a shader span holding another's | ||
| 379 | // result. The rest keep what they hold, without the title's words being read. | ||
| 380 | constexpr std::uint32_t n = 4000; | ||
| 381 | struct Half { | ||
| 382 | std::uint64_t base, to, span; | ||
| 383 | }; | ||
| 384 | std::vector<std::array<Half, 2>> meta(n); | ||
| 385 | std::vector<bool> pair(n, false); | ||
| 386 | for (std::uint32_t s2 = 0; s2 < n; ++s2) { | ||
| 387 | std::uint32_t w[8]; | ||
| 388 | std::memcpy(w, in + 8 * s2, 32); | ||
| 389 | if (w[3] >> 30) continue; | ||
| 390 | pair[s2] = true; | ||
| 391 | std::uint32_t before[8]; | ||
| 392 | std::memcpy(before, w, 32); | ||
| 393 | leonida::console_heap_translate_slot(w, c.t, c.keys); | ||
| 394 | for (int h = 0; h < 2; ++h) { | ||
| 395 | const std::uint32_t* b = before + 4 * h; | ||
| 396 | const std::uint32_t* a = w + 4 * h; | ||
| 397 | if (!b[2]) { | ||
| 398 | meta[s2][h] = {}; | ||
| 399 | continue; | ||
| 400 | } | ||
| 401 | const std::uint64_t stride = (b[1] >> 16) & 0x3fff; | ||
| 402 | const std::uint64_t span = std::min<std::uint64_t>(std::uint64_t(b[2]) * std::max<std::uint64_t>(stride, 1), | ||
| 403 | 0xffffffffull); | ||
| 404 | meta[s2][h] = {b[0] | (std::uint64_t(b[1] & 0xffff) << 32), | ||
| 405 | a[2] ? a[0] | (std::uint64_t(a[1] & 0xffff) << 32) : 0, span}; | ||
| 406 | } | ||
| 407 | } | ||
| 408 | std::uint32_t by_title = UINT32_MAX, by_result = UINT32_MAX; | ||
| 409 | for (std::uint32_t s2 = 0; s2 < n; ++s2) { | ||
| 410 | if (!pair[s2] || !meta[s2][0].span) continue; | ||
| 411 | if (by_title == UINT32_MAX) by_title = s2; | ||
| 412 | else if (meta[s2][0].to && meta[s2][0].to != meta[by_title][0].base) { | ||
| 413 | by_result = s2; | ||
| 414 | break; | ||
| 415 | } | ||
| 416 | } | ||
| 417 | EXPECT(by_title != UINT32_MAX && by_result != UINT32_MAX); | ||
| 418 | const leonida::ConsoleHeapSpans title{{meta[by_title][0].base, meta[by_title][0].base + 1}}; | ||
| 419 | const leonida::ConsoleHeapSpans shader{{meta[by_result][0].to, meta[by_result][0].to + 1}}; | ||
| 420 | const auto meets = [](const leonida::ConsoleHeapSpans& spans, std::uint64_t v, std::uint64_t bytes) { | ||
| 421 | for (const auto& [a, b] : spans) | ||
| 422 | if (v < b && a < v + bytes) return true; | ||
| 423 | return false; | ||
| 424 | }; | ||
| 425 | std::set<std::uint32_t> touched; | ||
| 426 | for (std::uint32_t s2 = 0; s2 < n; ++s2) | ||
| 427 | for (const Half& h : meta[s2]) { | ||
| 428 | if (!pair[s2] || !h.span) continue; | ||
| 429 | if (meets(title, h.base, 1) || meets(shader, h.base, h.span) || (h.to && meets(shader, h.to, h.span))) | ||
| 430 | touched.insert(s2); | ||
| 431 | } | ||
| 432 | EXPECT(touched.count(by_title) && touched.count(by_result) && touched.size() < 1000); | ||
| 433 | std::memset(out, 0xcd, std::size_t(kSlots) * 32); | ||
| 434 | const auto before = gpu.take_stats(); | ||
| 435 | (void)before; | ||
| 436 | gpu.rescan_filtered(heap, n, shader, title); | ||
| 437 | EXPECT(gpu.pending()); | ||
| 438 | bool recorded = false; | ||
| 439 | EXPECT(d.run([&](VkCommandBuffer cb) { return recorded = gpu.record(cb); })); | ||
| 440 | gpu.commit(true, 10); | ||
| 441 | gpu.drain(10, [](int, std::uint32_t, std::uint32_t) {}, [](int) {}); | ||
| 442 | EXPECT(recorded && !gpu.pending()); | ||
| 443 | for (std::uint32_t s2 = 0; s2 < kSlots; ++s2) { | ||
| 444 | if (!touched.count(s2)) { | ||
| 445 | for (int i = 0; i < 8; ++i) EXPECT(out[8 * s2 + i] == 0xcdcdcdcdu); | ||
| 446 | continue; | ||
| 447 | } | ||
| 448 | std::uint32_t w[8]; | ||
| 449 | std::memcpy(w, in + 8 * s2, 32); | ||
| 450 | leonida::console_heap_translate_slot(w, c.t, c.keys); | ||
| 451 | EXPECT(!std::memcmp(w, out + 8 * s2, 32)); | ||
| 452 | } | ||
| 453 | EXPECT(gpu.take_stats().filtered == n); | ||
| 454 | // A failed submission: the filtered rescan and its spans come back, and the next pass does them. | ||
| 455 | std::memset(out, 0xcd, std::size_t(kSlots) * 32); | ||
| 456 | gpu.rescan_filtered(heap, n, shader, title); | ||
| 457 | EXPECT(d.run([&](VkCommandBuffer cb) { return recorded = gpu.record(cb); })); | ||
| 458 | gpu.commit(false, 0); | ||
| 459 | EXPECT(gpu.pending()); | ||
| 460 | EXPECT(d.run([&](VkCommandBuffer cb) { return recorded = gpu.record(cb); })); | ||
| 461 | gpu.commit(true, 11); | ||
| 462 | gpu.drain(11, [](int, std::uint32_t, std::uint32_t) {}, [](int) {}); | ||
| 463 | std::size_t rewritten = 0; | ||
| 464 | for (std::uint32_t s2 = 0; s2 < n; ++s2) rewritten += out[8 * s2] != 0xcdcdcdcdu || out[8 * s2 + 3] != 0xcdcdcdcdu; | ||
| 465 | EXPECT(rewritten == touched.size()); | ||
| 466 | std::printf("console heap pass, filtered rescan: ok (%zu of %u slots)\n", touched.size(), n); | ||
| 467 | } | ||
| 468 | { | ||
| 469 | // queue_copy(): buffer copies recorded at the start of the pass; their keepalive goes once the pass retires. | ||
| 470 | constexpr VkDeviceSize kBytes = 64 * 1024; | ||
| 471 | void* src_data = nullptr; | ||
| 472 | void* dst_data = nullptr; | ||
| 473 | const VkBuffer src = d.buffer(kBytes, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, &src_data); | ||
| 474 | const VkBuffer dst = d.buffer(kBytes, VK_BUFFER_USAGE_TRANSFER_DST_BIT, &dst_data); | ||
| 475 | EXPECT(src && dst && src_data && dst_data); | ||
| 476 | auto* sw = static_cast<std::uint32_t*>(src_data); | ||
| 477 | for (std::size_t i = 0; i < kBytes / 4; ++i) sw[i] = std::uint32_t(i * 2654435761u); | ||
| 478 | std::memset(dst_data, 0, kBytes); | ||
| 479 | auto keep = std::make_shared<int>(7); | ||
| 480 | std::weak_ptr<int> watch = keep; | ||
| 481 | gpu.queue_copy(src, 4096, dst, 0, 8192, keep); | ||
| 482 | gpu.queue_copy(src, 0, dst, 32768, 4096, keep); | ||
| 483 | keep.reset(); | ||
| 484 | EXPECT(gpu.pending() && !watch.expired()); | ||
| 485 | bool recorded = false; | ||
| 486 | EXPECT(d.run([&](VkCommandBuffer cb) { return recorded = gpu.record(cb); })); | ||
| 487 | EXPECT(recorded && !watch.expired()); | ||
| 488 | gpu.commit(true, 10); | ||
| 489 | gpu.drain(10, [](int, std::uint32_t, std::uint32_t) {}, [](int) {}); | ||
| 490 | EXPECT(watch.expired()); | ||
| 491 | const auto* dw = static_cast<const std::uint8_t*>(dst_data); | ||
| 492 | EXPECT(!std::memcmp(dw, static_cast<const std::uint8_t*>(src_data) + 4096, 8192)); | ||
| 493 | EXPECT(!std::memcmp(dw + 32768, src_data, 4096)); | ||
| 494 | EXPECT(dw[8192] == 0 && dw[32768 + 4096] == 0); | ||
| 495 | } | ||
| 496 | std::puts("console heap pass, queued copies: ok"); | ||
| 497 | c.t.backed.clear(); | ||
| 498 | c.t.ask = {{0, ~0ull}}; // everything asks again: the overflow cases below need their misses | ||
| 499 | gpu.set_spans(leonida::ConsoleHeapGpu::backed_table, c.t.backed); | ||
| 500 | gpu.set_spans(leonida::ConsoleHeapGpu::ask_table, c.t.ask); | ||
| 501 | std::puts("console heap pass, failed submission queued again: ok"); | ||
| 502 | |||
| 503 | // More misses than the list holds: the overflow is reported, and the slots are still written. | ||
| 504 | { | ||
| 505 | constexpr std::uint32_t kStride = 0; | ||
| 506 | for (std::uint32_t s = 0; s < kSlots; ++s) { | ||
| 507 | vsharp(in + 8 * s, 0x500000000ull + s * 0x100, kStride, 16, 0); | ||
| 508 | vsharp(in + 8 * s + 4, 0x600000000ull + s * 0x100, kStride, 16, 0); | ||
| 509 | } | ||
| 510 | std::vector<std::uint32_t> many; | ||
| 511 | for (std::uint32_t s = 0; s < kSlots; ++s) many.push_back(s); | ||
| 512 | // 12,000 misses fit; list them twice over with a second heap view of the same buffers to pass 65,536. | ||
| 513 | const int heap2 = gpu.add_heap(d.device_address(input), d.device_address(copy), kSlots); | ||
| 514 | EXPECT(heap2 >= 0); | ||
| 515 | std::size_t total = 0; | ||
| 516 | for (int h = 0; h < 6; ++h) { // 6 x 12,000 = 72,000 misses in one pass over the two heaps | ||
| 517 | gpu.queue(h % 2 ? heap2 : heap, many.begin(), many.end()); | ||
| 518 | total += 2 * many.size(); | ||
| 519 | } | ||
| 520 | (void)total; | ||
| 521 | bool recorded = false; | ||
| 522 | EXPECT(d.run([&](VkCommandBuffer cb) { return recorded = gpu.record(cb); })); | ||
| 523 | // Queued twice per heap only counts once: 2 heaps x 12,000 = 24,000 misses, under the list. Queue a heap of | ||
| 524 | // its own instead to pass it. | ||
| 525 | gpu.commit(true, 4); | ||
| 526 | std::size_t misses = 0; | ||
| 527 | bool overflowed = false; | ||
| 528 | gpu.drain(4, [&](int, std::uint32_t, std::uint32_t) { ++misses; }, [&](int) { overflowed = true; }); | ||
| 529 | EXPECT(recorded && misses == 24000 && !overflowed); | ||
| 530 | gpu.remove_heap(heap2); | ||
| 531 | } | ||
| 532 | std::puts("console heap pass, a slot queued twice is translated once: ok"); | ||
| 533 | { | ||
| 534 | // Six heap views of the same buffers: 6 x 12,000 = 72,000 misses, past the list's 65,536. | ||
| 535 | std::vector<int> views; | ||
| 536 | for (int i = 0; i < 5; ++i) views.push_back(gpu.add_heap(d.device_address(input), d.device_address(copy), kSlots)); | ||
| 537 | std::vector<std::uint32_t> many; | ||
| 538 | for (std::uint32_t s = 0; s < kSlots; ++s) many.push_back(s); | ||
| 539 | gpu.queue(heap, many.begin(), many.end()); | ||
| 540 | for (const int v : views) { | ||
| 541 | EXPECT(v >= 0); | ||
| 542 | gpu.queue(v, many.begin(), many.end()); | ||
| 543 | } | ||
| 544 | bool recorded = false; | ||
| 545 | EXPECT(d.run([&](VkCommandBuffer cb) { return recorded = gpu.record(cb); })); | ||
| 546 | gpu.commit(true, 5); | ||
| 547 | std::size_t misses = 0; | ||
| 548 | bool overflowed = false; | ||
| 549 | gpu.drain(5, [&](int, std::uint32_t, std::uint32_t) { ++misses; }, [&](int) { overflowed = true; }); | ||
| 550 | EXPECT(recorded && overflowed && misses == leonida::ConsoleHeapGpu::kMissCapacity); | ||
| 551 | for (std::uint32_t s = 0; s < kSlots; ++s) EXPECT(out[8 * s] == 0 && out[8 * s + 2] == 0); | ||
| 552 | for (const int v : views) gpu.remove_heap(v); | ||
| 553 | } | ||
| 554 | std::puts("console heap pass, miss list overflow: ok"); | ||
| 555 | { | ||
| 556 | // Clustered words (bases a megabyte apart) entered in both tables: every slot answered, none missed. | ||
| 557 | Case clustered; | ||
| 558 | for (std::uint32_t s2 = 0; s2 < 3000; ++s2) { | ||
| 559 | for (int half = 0; half < 2; ++half) { | ||
| 560 | const std::uint32_t i = 2 * s2 + std::uint32_t(half); | ||
| 561 | std::uint32_t* k = in + 8 * s2 + 4 * half; | ||
| 562 | vsharp(k, 0x700000000ull + (std::uint64_t(i) << 20), 16, 8, 0x2000); | ||
| 563 | const ConsoleHeapKeys::Key key{k[0], k[1], k[2], k[3]}; | ||
| 564 | EXPECT(clustered.keys.put(key, 0x1000000ull + i * 256ull, 128, (i % 7) == 0)); | ||
| 565 | EXPECT(gpu.with_keys([&](ConsoleHeapKeys& keys) { | ||
| 566 | return keys.put(key, 0x1000000ull + i * 256ull, 128, (i % 7) == 0); | ||
| 567 | })); | ||
| 568 | } | ||
| 569 | } | ||
| 570 | std::swap(c.keys, clustered.keys); | ||
| 571 | c.ranges.clear(); | ||
| 572 | gpu.set_ranges(c.ranges); | ||
| 573 | EXPECT(round(all, 6, false) == 0); | ||
| 574 | } | ||
| 575 | std::puts("console heap pass, clustered words: ok"); | ||
| 576 | const auto stats = gpu.take_stats(); | ||
| 577 | std::printf("console heap pass: %llu passes, %llu slots, %llu updates, %llu misses, %llu overflows, %llu failed\n", | ||
| 578 | (unsigned long long)stats.passes, (unsigned long long)stats.slots, (unsigned long long)stats.updates, | ||
| 579 | (unsigned long long)stats.misses, (unsigned long long)stats.overflows, | ||
| 580 | (unsigned long long)stats.failed); | ||
| 581 | EXPECT(d.validation_errors() == 0); | ||
| 582 | std::puts("vk_console_heap_gpu_test: ok"); | ||
| 583 | return 0; | ||
| 584 | } | ||
diff --git a/runtime/test/vk_descriptor_bench.cpp b/runtime/test/vk_descriptor_bench.cpp index 3dd179268..c048f3745 100644 --- a/runtime/test/vk_descriptor_bench.cpp +++ b/runtime/test/vk_descriptor_bench.cpp | |||
| @@ -710,7 +710,8 @@ bool build_dataset(std::uint32_t entry_count, TableDataset& out) { | |||
| 710 | 710 | ||
| 711 | for (std::uint32_t i = 0; i < out.t_count; ++i) { | 711 | for (std::uint32_t i = 0; i < out.t_count; ++i) { |
| 712 | t_keys[i] = make_bench_tsharp(i + 1u); | 712 | t_keys[i] = make_bench_tsharp(i + 1u); |
| 713 | table.insert(t_keys[i], 1u + i); | 713 | // The T#s name sampled 2D images (the tagged contract's kind word): a bench entry carries the same word. |
| 714 | table.insert(t_keys[i], 1u + i, leonida::kind_sampled_bit(0)); | ||
| 714 | } | 715 | } |
| 715 | for (std::uint32_t i = 0; i < out.s_count; ++i) { | 716 | for (std::uint32_t i = 0; i < out.s_count; ++i) { |
| 716 | s_keys[i] = make_bench_ssharp(i + 1u); | 717 | s_keys[i] = make_bench_ssharp(i + 1u); |
diff --git a/runtime/test/vk_device_markers_test.cpp b/runtime/test/vk_device_markers_test.cpp new file mode 100644 index 000000000..f6e76fd73 --- /dev/null +++ b/runtime/test/vk_device_markers_test.cpp | |||
| @@ -0,0 +1,142 @@ | |||
| 1 | // The AMD breadcrumbs of the device-fault report (src/vulkan_device_markers.h, LEONIDA_DEVICE_MARKERS=1) on a real | ||
| 2 | // device: dispatches recorded through CheckpointRecorder with the markers on, submitted and waited for, leave their | ||
| 3 | // queue's started and finished markers at the last dispatch's seq, and the report calls none of them hung. Two | ||
| 4 | // submissions, so the second continues the first one's numbering. The shader is an empty hand-written compute | ||
| 5 | // program; nothing is meant to fault or hang. SKIP (77) without a Vulkan device or without VK_AMD_buffer_marker. | ||
| 6 | // LEONIDA_VK_VALIDATION=1 runs it under VK_LAYER_KHRONOS_validation (any validation error fails the test). | ||
| 7 | #include "vk_test_device.h" | ||
| 8 | #include "../src/vulkan_device_fault.h" | ||
| 9 | |||
| 10 | #include <array> | ||
| 11 | #include <cstdint> | ||
| 12 | #include <cstdio> | ||
| 13 | #include <vector> | ||
| 14 | |||
| 15 | #define EXPECT(condition) do { \ | ||
| 16 | if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ | ||
| 17 | } while (0) | ||
| 18 | |||
| 19 | namespace { | ||
| 20 | |||
| 21 | using namespace leonida; | ||
| 22 | |||
| 23 | // OpCapability Shader; OpMemoryModel Logical GLSL450; OpEntryPoint GLCompute %1 "main"; LocalSize 1 1 1; | ||
| 24 | // void main() {} | ||
| 25 | constexpr std::uint32_t empty_compute[] = { | ||
| 26 | 0x07230203u, 0x00010000u, 0u, 5u, 0u, | ||
| 27 | (2u << 16) | 17u, 1u, // OpCapability Shader | ||
| 28 | (3u << 16) | 14u, 0u, 1u, // OpMemoryModel Logical GLSL450 | ||
| 29 | (5u << 16) | 15u, 5u, 1u, 0x6e69616du, 0u, // OpEntryPoint GLCompute %1 "main" | ||
| 30 | (6u << 16) | 16u, 1u, 17u, 1u, 1u, 1u, // OpExecutionMode %1 LocalSize 1 1 1 | ||
| 31 | (2u << 16) | 19u, 2u, // %2 = OpTypeVoid | ||
| 32 | (3u << 16) | 33u, 3u, 2u, // %3 = OpTypeFunction %2 | ||
| 33 | (5u << 16) | 54u, 2u, 1u, 0u, 3u, // %1 = OpFunction %2 None %3 | ||
| 34 | (2u << 16) | 248u, 4u, // %4 = OpLabel | ||
| 35 | (1u << 16) | 253u, // OpReturn | ||
| 36 | (1u << 16) | 56u, // OpFunctionEnd | ||
| 37 | }; | ||
| 38 | |||
| 39 | struct Pipeline { | ||
| 40 | const vktest::Device& d; | ||
| 41 | VkShaderModule module = VK_NULL_HANDLE; | ||
| 42 | VkPipelineLayout layout = VK_NULL_HANDLE; | ||
| 43 | VkPipeline pipeline = VK_NULL_HANDLE; | ||
| 44 | |||
| 45 | explicit Pipeline(const vktest::Device& device) : d(device) { | ||
| 46 | VkShaderModuleCreateInfo code{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; | ||
| 47 | code.codeSize = sizeof(empty_compute); | ||
| 48 | code.pCode = empty_compute; | ||
| 49 | if (d.fn<PFN_vkCreateShaderModule>("vkCreateShaderModule")(d.device, &code, nullptr, &module) != VK_SUCCESS) | ||
| 50 | return; | ||
| 51 | VkPipelineLayoutCreateInfo layout_info{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; | ||
| 52 | if (d.fn<PFN_vkCreatePipelineLayout>("vkCreatePipelineLayout")(d.device, &layout_info, nullptr, &layout) != | ||
| 53 | VK_SUCCESS) | ||
| 54 | return; | ||
| 55 | VkComputePipelineCreateInfo info{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO}; | ||
| 56 | info.stage = {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; | ||
| 57 | info.stage.stage = VK_SHADER_STAGE_COMPUTE_BIT; | ||
| 58 | info.stage.module = module; | ||
| 59 | info.stage.pName = "main"; | ||
| 60 | info.layout = layout; | ||
| 61 | d.fn<PFN_vkCreateComputePipelines>("vkCreateComputePipelines")(d.device, VK_NULL_HANDLE, 1, &info, nullptr, | ||
| 62 | &pipeline); | ||
| 63 | } | ||
| 64 | ~Pipeline() { | ||
| 65 | if (pipeline) d.fn<PFN_vkDestroyPipeline>("vkDestroyPipeline")(d.device, pipeline, nullptr); | ||
| 66 | if (layout) d.fn<PFN_vkDestroyPipelineLayout>("vkDestroyPipelineLayout")(d.device, layout, nullptr); | ||
| 67 | if (module) d.fn<PFN_vkDestroyShaderModule>("vkDestroyShaderModule")(d.device, module, nullptr); | ||
| 68 | } | ||
| 69 | }; | ||
| 70 | |||
| 71 | int run(vktest::Device& d) { | ||
| 72 | VkPhysicalDeviceMemoryProperties memory{}; | ||
| 73 | d.instance_fn<PFN_vkGetPhysicalDeviceMemoryProperties>("vkGetPhysicalDeviceMemoryProperties")(d.physical, &memory); | ||
| 74 | DeviceFaultExtensions enabled; | ||
| 75 | enabled.markers = true; | ||
| 76 | // The runtime's devices always have synchronization2 (vulkan13_features.h), and so does this one: the marker | ||
| 77 | // writes take the vkCmdWriteBufferMarker2AMD path, as in a game run. | ||
| 78 | DeviceFaultDiagnostics diagnostics(d.device_proc, d.device, enabled, &memory, true); | ||
| 79 | EXPECT(diagnostics.markers_on()); | ||
| 80 | diagnostics.add_queue(d.queue); | ||
| 81 | EXPECT(diagnostics.marker_slot(d.queue).started == 0 && diagnostics.marker_slot(d.queue).finished == 0); | ||
| 82 | |||
| 83 | Pipeline pipeline(d); | ||
| 84 | EXPECT(pipeline.pipeline); | ||
| 85 | const auto bind = d.fn<PFN_vkCmdBindPipeline>("vkCmdBindPipeline"); | ||
| 86 | const auto dispatch = d.fn<PFN_vkCmdDispatch>("vkCmdDispatch"); | ||
| 87 | const auto pipeline_id = reinterpret_cast<std::uintptr_t>(&pipeline); | ||
| 88 | diagnostics.pipeline_names[pipeline_id] = {"cs_empty_test"}; | ||
| 89 | const std::array<std::uint32_t, 32> roots{}; | ||
| 90 | |||
| 91 | std::uint64_t last_seq = 0; | ||
| 92 | for (unsigned round = 0; round < 2; ++round) { | ||
| 93 | const unsigned dispatches = round == 0 ? 5 : 3; | ||
| 94 | auto submission = diagnostics.begin_submission(diagnostics.next_execute_call(), d.queue, "direct", 1); | ||
| 95 | EXPECT(submission.markers); | ||
| 96 | const CheckpointRecorder recorder{nullptr, submission, diagnostics.pipeline_names, 0}; | ||
| 97 | const bool ran = d.run([&](VkCommandBuffer cb) { | ||
| 98 | for (unsigned i = 0; i < dispatches; ++i) { | ||
| 99 | recorder.dispatch(cb, i, pipeline.pipeline, pipeline_id, roots, {1 + i, 1, 1}); | ||
| 100 | bind(cb, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline.pipeline); | ||
| 101 | dispatch(cb, 1 + i, 1, 1); | ||
| 102 | recorder.dispatched(cb); | ||
| 103 | } | ||
| 104 | return true; | ||
| 105 | }); | ||
| 106 | EXPECT(ran); | ||
| 107 | EXPECT(submission.dispatches.size() == dispatches); | ||
| 108 | EXPECT(submission.dispatches.front().seq == last_seq + 1); | ||
| 109 | last_seq = submission.dispatches.back().seq; | ||
| 110 | EXPECT(last_seq == (round == 0 ? 5u : 8u)); | ||
| 111 | diagnostics.publish(std::move(submission)); | ||
| 112 | // vkQueueWaitIdle has returned: every marker the GPU wrote is in the coherent buffer. | ||
| 113 | const MarkerSlot slot = diagnostics.marker_slot(d.queue); | ||
| 114 | std::printf("round %u: started=%u finished=%u, last seq %llu\n", round, slot.started, slot.finished, | ||
| 115 | static_cast<unsigned long long>(last_seq)); | ||
| 116 | EXPECT(slot.started == last_seq && slot.finished == last_seq); | ||
| 117 | EXPECT(diagnostics.report_markers(false).empty()); | ||
| 118 | } | ||
| 119 | return 0; | ||
| 120 | } | ||
| 121 | |||
| 122 | } // namespace | ||
| 123 | |||
| 124 | int main() { | ||
| 125 | std::setvbuf(stdout, nullptr, _IONBF, 0); | ||
| 126 | vktest::Device d; | ||
| 127 | d.request_buffer_marker = true; | ||
| 128 | const auto status = d.initialize(); | ||
| 129 | if (status == vktest::DeviceStatus::unavailable) { | ||
| 130 | std::printf("SKIP: no usable Vulkan device\n"); | ||
| 131 | return 77; | ||
| 132 | } | ||
| 133 | if (status != vktest::DeviceStatus::ready) return 1; | ||
| 134 | if (!d.buffer_marker) { | ||
| 135 | std::printf("SKIP: the device has no VK_AMD_buffer_marker\n"); | ||
| 136 | return 77; | ||
| 137 | } | ||
| 138 | const int rc = run(d); | ||
| 139 | const unsigned errors = d.validation_errors(); | ||
| 140 | std::printf("Vulkan validation errors: %u%s\n", errors, d.validation ? "" : " (validation off)"); | ||
| 141 | return rc ? rc : errors ? 1 : 0; | ||
| 142 | } | ||
diff --git a/runtime/test/vk_harness.cpp b/runtime/test/vk_harness.cpp index cd374e8b6..872e30b93 100644 --- a/runtime/test/vk_harness.cpp +++ b/runtime/test/vk_harness.cpp | |||
| @@ -929,7 +929,8 @@ int main(int argc, char** argv) { | |||
| 929 | LOADD(vkCreateSampler); LOADD(vkCreateDescriptorPool); LOADD(vkAllocateDescriptorSets); | 929 | LOADD(vkCreateSampler); LOADD(vkCreateDescriptorPool); LOADD(vkAllocateDescriptorSets); |
| 930 | LOADD(vkUpdateDescriptorSets); | 930 | LOADD(vkUpdateDescriptorSets); |
| 931 | leonida::DescriptorTable desc_table(16); | 931 | leonida::DescriptorTable desc_table(16); |
| 932 | desc_table.insert(tsharp, 1); | 932 | // The translated modules read the entry's kind (descriptor_table.h): this T# is a sampled 2D image. |
| 933 | desc_table.insert(tsharp, 1, leonida::kind_sampled_bit(0)); | ||
| 933 | desc_table.insert(ssharp, 1); | 934 | desc_table.insert(ssharp, 1); |
| 934 | const auto table = desc_table.build_gpu_buffer(true); | 935 | const auto table = desc_table.build_gpu_buffer(true); |
| 935 | VkBuffer tb = VK_NULL_HANDLE; | 936 | VkBuffer tb = VK_NULL_HANDLE; |
diff --git a/runtime/test/vk_host_texture_order_test.cpp b/runtime/test/vk_host_texture_order_test.cpp index 34120f00e..f7aae702f 100644 --- a/runtime/test/vk_host_texture_order_test.cpp +++ b/runtime/test/vk_host_texture_order_test.cpp | |||
| @@ -7,13 +7,21 @@ | |||
| 7 | namespace { | 7 | namespace { |
| 8 | unsigned waits = 0; | 8 | unsigned waits = 0; |
| 9 | VkResult wait_result = VK_SUCCESS; | 9 | VkResult wait_result = VK_SUCCESS; |
| 10 | VkResult VKAPI_CALL idle(VkDevice) { ++waits; return wait_result; } | 10 | std::uint64_t last_timeout = 0; |
| 11 | // The writes wait for the queue timelines (vkWaitSemaphores, bounded), not for the device. | ||
| 12 | VkResult VKAPI_CALL wait_semaphores(VkDevice, const VkSemaphoreWaitInfo* info, std::uint64_t timeout) { | ||
| 13 | ++waits; | ||
| 14 | last_timeout = timeout; | ||
| 15 | return info && info->semaphoreCount ? wait_result : VK_ERROR_UNKNOWN; | ||
| 16 | } | ||
| 17 | VkResult VKAPI_CALL device_idle(VkDevice) { return VK_ERROR_UNKNOWN; } // must not be called any more | ||
| 11 | PFN_vkVoidFunction VKAPI_CALL no_proc(VkDevice, const char*) { return nullptr; } | 18 | PFN_vkVoidFunction VKAPI_CALL no_proc(VkDevice, const char*) { return nullptr; } |
| 12 | } | 19 | } |
| 13 | 20 | ||
| 14 | int main() { | 21 | int main() { |
| 15 | leonida::VulkanContext ctx(no_proc, VK_NULL_HANDLE, false); | 22 | leonida::VulkanContext ctx(no_proc, VK_NULL_HANDLE, false); |
| 16 | ctx.vk.vkDeviceWaitIdle = idle; | 23 | ctx.vk.vkWaitSemaphores = wait_semaphores; |
| 24 | ctx.vk.vkDeviceWaitIdle = device_idle; | ||
| 17 | leonida::ResourceBinding binding{}; | 25 | leonida::ResourceBinding binding{}; |
| 18 | binding.image = reinterpret_cast<VkImage>(1); | 26 | binding.image = reinterpret_cast<VkImage>(1); |
| 19 | binding.mip_levels = 1; | 27 | binding.mip_levels = 1; |
| @@ -32,14 +40,22 @@ int main() { | |||
| 32 | contender.join(); | 40 | contender.join(); |
| 33 | return !raced; | 41 | return !raced; |
| 34 | }; | 42 | }; |
| 35 | ctx.note_image_work_locked(); | 43 | const auto progress = reinterpret_cast<VkSemaphore>(std::uintptr_t{0x10}); |
| 36 | if (ctx.write_host_texture(2, 0, copy) != VK_NOT_READY || copies || waits) return 1; | 44 | const auto submit = [&] { // a queue submission in flight: a retirement ticket, and image work pending |
| 37 | if (ctx.write_host_texture(1, 0, copy) != VK_SUCCESS || copies != 1 || waits != 1) return 1; | 45 | std::lock_guard lock(ctx.submit_mutex()); |
| 38 | if (ctx.write_host_texture(1, 0, copy) != VK_SUCCESS || copies != 2 || waits != 1) return 1; | 46 | ctx.record_submit_locked(progress, 1); |
| 39 | ctx.note_image_work_locked(); | 47 | }; |
| 48 | submit(); | ||
| 49 | if (ctx.write_host_texture(2, 0, copy) != VK_NOT_READY || copies || waits) return 1; // wrong layout: no wait | ||
| 50 | if (ctx.write_host_texture(1, 0, copy) != VK_SUCCESS || copies != 1 || waits != 1) return 2; | ||
| 51 | if (last_timeout == 0 || last_timeout == UINT64_MAX) return 3; // bounded | ||
| 52 | if (ctx.write_host_texture(1, 0, copy) != VK_SUCCESS || copies != 2 || waits != 1) return 4; // wait reused | ||
| 53 | submit(); | ||
| 54 | wait_result = VK_TIMEOUT; // the submitted work is not done in time: skipped as not ready, not a failure | ||
| 55 | if (ctx.write_host_texture(1, 0, copy) != VK_NOT_READY || copies != 2 || waits != 2) return 5; | ||
| 40 | wait_result = VK_ERROR_DEVICE_LOST; | 56 | wait_result = VK_ERROR_DEVICE_LOST; |
| 41 | if (ctx.write_host_texture(1, 0, copy) != VK_ERROR_DEVICE_LOST || copies != 2 || waits != 2) return 1; | 57 | if (ctx.write_host_texture(1, 0, copy) != VK_ERROR_DEVICE_LOST || copies != 2 || waits != 3) return 6; |
| 42 | const auto stats = ctx.host_texture_stats(); | 58 | const auto stats = ctx.host_texture_stats(); |
| 43 | if (stats.copies != 2 || stats.waits != 2) return 1; | 59 | if (stats.copies != 2 || stats.waits != 3) return 7; |
| 44 | std::puts("ordered texture upload: layout, submit exclusion, wait reuse, wait failure passed"); | 60 | std::puts("ordered texture upload: layout, submit exclusion, bounded timeline wait, reuse, timeout, loss passed"); |
| 45 | } | 61 | } |
diff --git a/runtime/test/vk_image_fuzz.cpp b/runtime/test/vk_image_fuzz.cpp index 52b59d6e0..cc645e6d3 100644 --- a/runtime/test/vk_image_fuzz.cpp +++ b/runtime/test/vk_image_fuzz.cpp | |||
| @@ -495,7 +495,7 @@ int main(int argc, char** argv) { | |||
| 495 | std::fprintf(stderr, "FAILED add_image -> 0 (line %d)\n", __LINE__); | 495 | std::fprintf(stderr, "FAILED add_image -> 0 (line %d)\n", __LINE__); |
| 496 | return 1; | 496 | return 1; |
| 497 | } | 497 | } |
| 498 | set->insert_key(make_tsharp_key(spec.tsharp), index); | 498 | set->insert_key(make_tsharp_key(spec.tsharp), index, ImageDimension::dim_2d); |
| 499 | const VkPushConstantRange push{.stageFlags = VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, .size = push_bytes}; | 499 | const VkPushConstantRange push{.stageFlags = VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, .size = push_bytes}; |
| 500 | const VkDescriptorSetLayout set_layout = set->layout(); | 500 | const VkDescriptorSetLayout set_layout = set->layout(); |
| 501 | VkPipelineLayoutCreateInfo pli{.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO, | 501 | VkPipelineLayoutCreateInfo pli{.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO, |
diff --git a/runtime/test/vk_pipeline_check.cpp b/runtime/test/vk_pipeline_check.cpp index 0e39d0f62..3ff89524f 100644 --- a/runtime/test/vk_pipeline_check.cpp +++ b/runtime/test/vk_pipeline_check.cpp | |||
| @@ -7,10 +7,10 @@ | |||
| 7 | // descriptor-free shaders with the standard push-constant range | 7 | // descriptor-free shaders with the standard push-constant range |
| 8 | // - ps/vs/ms/gs: graphics pipeline via vkCreateGraphicsPipelines (Vulkan 1.3 dynamic rendering, no render pass) | 8 | // - ps/vs/ms/gs: graphics pipeline via vkCreateGraphicsPipelines (Vulkan 1.3 dynamic rendering, no render pass) |
| 9 | // paired with minimal partner stubs from <spirv dir>/stubs/ (generated by tools/spirv_stubs.py) | 9 | // paired with minimal partner stubs from <spirv dir>/stubs/ (generated by tools/spirv_stubs.py) |
| 10 | // VK_EXT_mesh_shader (with meshShaderQueries) and VK_KHR_maintenance8 are always enabled when supported so the | 10 | // VK_EXT_mesh_shader (with meshShaderQueries), VK_KHR_maintenance8 and VK_EXT_transform_feedback are always enabled |
| 11 | // saved pipeline cache matches the runtime's device key; other optional device extensions are enabled only when | 11 | // when supported so the saved pipeline cache matches the runtime's device key; other optional device extensions are |
| 12 | // needed by the selected shaders. Shaders whose required features or partner stubs are unavailable are reported as | 12 | // enabled only when needed by the selected shaders. Shaders whose required features or partner stubs are unavailable |
| 13 | // skipped rather than failed. | 13 | // are reported as skipped rather than failed. |
| 14 | // [cache.bin] loaded first if it exists (a stopped run resumes: cached pipelines are instant), saved every | 14 | // [cache.bin] loaded first if it exists (a stopped run resumes: cached pipelines are instant), saved every |
| 15 | // 10 minutes and at the end | 15 | // 10 minutes and at the end |
| 16 | // --jobs N compile on up to N worker threads (default: half the hardware threads) | 16 | // --jobs N compile on up to N worker threads (default: half the hardware threads) |
| @@ -30,6 +30,9 @@ | |||
| 30 | // --cache-feedback count each stage's successful pipelines by VkPipelineCreationFeedback: hits (VALID and | 30 | // --cache-feedback count each stage's successful pipelines by VkPipelineCreationFeedback: hits (VALID and |
| 31 | // APPLICATION_PIPELINE_CACHE_HIT), no hit reported (VALID only) and unavailable (no VALID bit, or a | 31 | // APPLICATION_PIPELINE_CACHE_HIT), no hit reported (VALID only) and unavailable (no VALID bit, or a |
| 32 | // pre-1.3 device without VK_EXT_pipeline_creation_feedback). The three add up to the ok count. | 32 | // pre-1.3 device without VK_EXT_pipeline_creation_feedback). The three add up to the ok count. |
| 33 | // --nv-diagnostics create the device with VK_NV_device_diagnostics_config and the flags the runtime's | ||
| 34 | // LEONIDA_DEVICE_FAULT=1 / LEONIDA_AFTERMATH=1 use (shader debug info, resource tracking, automatic | ||
| 35 | // checkpoints), to measure what that does to compile times and to cache hits | ||
| 33 | // --isolate check in child processes, --isolate-batch modules at a time (default 256), so a module | 36 | // --isolate check in child processes, --isolate-batch modules at a time (default 256), so a module |
| 34 | // that kills the driver is recorded as failed ("MODULE CRASH") and the pass | 37 | // that kills the driver is recorded as failed ("MODULE CRASH") and the pass |
| 35 | // goes on. A crashed batch is bisected to the module. Children run one after the other and share | 38 | // goes on. A crashed batch is bisected to the module. Children run one after the other and share |
| @@ -806,7 +809,7 @@ int main(int argc, char** argv) { | |||
| 806 | unsigned large_parallel = 0; // 0 = by the memory budget | 809 | unsigned large_parallel = 0; // 0 = by the memory budget |
| 807 | double slow = 30.0; | 810 | double slow = 30.0; |
| 808 | std::string stage_filter = "all"; | 811 | std::string stage_filter = "all"; |
| 809 | bool cache_feedback = false, isolate = false, iso_child = false; | 812 | bool cache_feedback = false, isolate = false, iso_child = false, nv_diagnostics = false; |
| 810 | size_t isolate_batch = 256; | 813 | size_t isolate_batch = 256; |
| 811 | for (int i = 2; i < argc; i++) { | 814 | for (int i = 2; i < argc; i++) { |
| 812 | std::string a = argv[i]; | 815 | std::string a = argv[i]; |
| @@ -851,6 +854,7 @@ int main(int argc, char** argv) { | |||
| 851 | else if (a == "--skip-file") valid = !(skip_path = value()).empty(); | 854 | else if (a == "--skip-file") valid = !(skip_path = value()).empty(); |
| 852 | else if (a == "--cache-feedback") cache_feedback = true; | 855 | else if (a == "--cache-feedback") cache_feedback = true; |
| 853 | else if (a == "--isolate") isolate = true; | 856 | else if (a == "--isolate") isolate = true; |
| 857 | else if (a == "--nv-diagnostics") nv_diagnostics = true; | ||
| 854 | else if (a == "--isolate-child") iso_child = true; // internal: the parent's child runs | 858 | else if (a == "--isolate-child") iso_child = true; // internal: the parent's child runs |
| 855 | else if (a == "--isolate-batch") { // parsed like the other numbers (#1735); at least one per batch | 859 | else if (a == "--isolate-batch") { // parsed like the other numbers (#1735); at least one per batch |
| 856 | valid = number(isolate_batch); | 860 | valid = number(isolate_batch); |
| @@ -1122,6 +1126,7 @@ int main(int argc, char** argv) { | |||
| 1122 | 1126 | ||
| 1123 | // Query the core and optional device features used by the checker. | 1127 | // Query the core and optional device features used by the checker. |
| 1124 | VkPhysicalDeviceMeshShaderFeaturesEXT mesh{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MESH_SHADER_FEATURES_EXT}; | 1128 | VkPhysicalDeviceMeshShaderFeaturesEXT mesh{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MESH_SHADER_FEATURES_EXT}; |
| 1129 | VkPhysicalDeviceTransformFeedbackFeaturesEXT tf{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_TRANSFORM_FEEDBACK_FEATURES_EXT}; | ||
| 1125 | VkPhysicalDeviceFragmentShaderBarycentricFeaturesKHR bary{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_SHADER_BARYCENTRIC_FEATURES_KHR}; | 1130 | VkPhysicalDeviceFragmentShaderBarycentricFeaturesKHR bary{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_SHADER_BARYCENTRIC_FEATURES_KHR}; |
| 1126 | VkPhysicalDeviceFragmentShaderInterlockFeaturesEXT lock{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_SHADER_INTERLOCK_FEATURES_EXT}; | 1131 | VkPhysicalDeviceFragmentShaderInterlockFeaturesEXT lock{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_SHADER_INTERLOCK_FEATURES_EXT}; |
| 1127 | #ifdef VK_KHR_MAINTENANCE_8_EXTENSION_NAME | 1132 | #ifdef VK_KHR_MAINTENANCE_8_EXTENSION_NAME |
| @@ -1144,6 +1149,10 @@ int main(int argc, char** argv) { | |||
| 1144 | link(&f12, reinterpret_cast<VkBaseOutStructure*>(&f12), nullptr, true); | 1149 | link(&f12, reinterpret_cast<VkBaseOutStructure*>(&f12), nullptr, true); |
| 1145 | link(&f13, reinterpret_cast<VkBaseOutStructure*>(&f13), nullptr, true); | 1150 | link(&f13, reinterpret_cast<VkBaseOutStructure*>(&f13), nullptr, true); |
| 1146 | const bool ext_mesh = link(&mesh, reinterpret_cast<VkBaseOutStructure*>(&mesh), VK_EXT_MESH_SHADER_EXTENSION_NAME, true); | 1151 | const bool ext_mesh = link(&mesh, reinterpret_cast<VkBaseOutStructure*>(&mesh), VK_EXT_MESH_SHADER_EXTENSION_NAME, true); |
| 1152 | // The runtime's device enables VK_EXT_transform_feedback (transformFeedback, and geometryStreams when the device | ||
| 1153 | // offers it) whenever the extension is present (D3D-302), and a driver makes it part of a pipeline's cache key, so | ||
| 1154 | // the checker enables it too (docs/pipeline_check.md, "The cache and the runtime's device"). | ||
| 1155 | link(&tf, reinterpret_cast<VkBaseOutStructure*>(&tf), VK_EXT_TRANSFORM_FEEDBACK_EXTENSION_NAME, true); | ||
| 1147 | const bool ext_bary = link(&bary, reinterpret_cast<VkBaseOutStructure*>(&bary), VK_KHR_FRAGMENT_SHADER_BARYCENTRIC_EXTENSION_NAME, want_bary); | 1156 | const bool ext_bary = link(&bary, reinterpret_cast<VkBaseOutStructure*>(&bary), VK_KHR_FRAGMENT_SHADER_BARYCENTRIC_EXTENSION_NAME, want_bary); |
| 1148 | const bool ext_lock = link(&lock, reinterpret_cast<VkBaseOutStructure*>(&lock), VK_EXT_FRAGMENT_SHADER_INTERLOCK_EXTENSION_NAME, want_lock); | 1157 | const bool ext_lock = link(&lock, reinterpret_cast<VkBaseOutStructure*>(&lock), VK_EXT_FRAGMENT_SHADER_INTERLOCK_EXTENSION_NAME, want_lock); |
| 1149 | #ifdef VK_KHR_MAINTENANCE_8_EXTENSION_NAME | 1158 | #ifdef VK_KHR_MAINTENANCE_8_EXTENSION_NAME |
| @@ -1158,6 +1167,13 @@ int main(int argc, char** argv) { | |||
| 1158 | #endif | 1167 | #endif |
| 1159 | VkPhysicalDeviceShaderClockFeaturesKHR clock{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_CLOCK_FEATURES_KHR}; | 1168 | VkPhysicalDeviceShaderClockFeaturesKHR clock{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_CLOCK_FEATURES_KHR}; |
| 1160 | const bool ext_clock = link(&clock, reinterpret_cast<VkBaseOutStructure*>(&clock), VK_KHR_SHADER_CLOCK_EXTENSION_NAME, want_clock); | 1169 | const bool ext_clock = link(&clock, reinterpret_cast<VkBaseOutStructure*>(&clock), VK_KHR_SHADER_CLOCK_EXTENSION_NAME, want_clock); |
| 1170 | VkPhysicalDeviceDiagnosticsConfigFeaturesNV diag_features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DIAGNOSTICS_CONFIG_FEATURES_NV}; | ||
| 1171 | const bool ext_diag = link(&diag_features, reinterpret_cast<VkBaseOutStructure*>(&diag_features), | ||
| 1172 | VK_NV_DEVICE_DIAGNOSTICS_CONFIG_EXTENSION_NAME, nv_diagnostics); | ||
| 1173 | if (nv_diagnostics && !ext_diag) { | ||
| 1174 | std::fprintf(stderr, "--nv-diagnostics: the device has no %s\n", VK_NV_DEVICE_DIAGNOSTICS_CONFIG_EXTENSION_NAME); | ||
| 1175 | return 1; | ||
| 1176 | } | ||
| 1161 | const bool ext_exe = link(&exe, reinterpret_cast<VkBaseOutStructure*>(&exe), | 1177 | const bool ext_exe = link(&exe, reinterpret_cast<VkBaseOutStructure*>(&exe), |
| 1162 | VK_KHR_PIPELINE_EXECUTABLE_PROPERTIES_EXTENSION_NAME, !stats_path.empty()); | 1178 | VK_KHR_PIPELINE_EXECUTABLE_PROPERTIES_EXTENSION_NAME, !stats_path.empty()); |
| 1163 | if (!stats_path.empty() && !ext_exe) { | 1179 | if (!stats_path.empty() && !ext_exe) { |
| @@ -1201,6 +1217,15 @@ int main(int argc, char** argv) { | |||
| 1201 | VkDeviceCreateInfo dci{VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO}; | 1217 | VkDeviceCreateInfo dci{VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO}; |
| 1202 | dci.queueCreateInfoCount = 1; dci.pQueueCreateInfos = &qci; dci.pNext = &f2; | 1218 | dci.queueCreateInfoCount = 1; dci.pQueueCreateInfos = &qci; dci.pNext = &f2; |
| 1203 | dci.enabledExtensionCount = uint32_t(enable.size()); dci.ppEnabledExtensionNames = enable.data(); | 1219 | dci.enabledExtensionCount = uint32_t(enable.size()); dci.ppEnabledExtensionNames = enable.data(); |
| 1220 | VkDeviceDiagnosticsConfigCreateInfoNV diag_config{VK_STRUCTURE_TYPE_DEVICE_DIAGNOSTICS_CONFIG_CREATE_INFO_NV}; | ||
| 1221 | if (ext_diag) { | ||
| 1222 | diag_config.flags = VK_DEVICE_DIAGNOSTICS_CONFIG_ENABLE_SHADER_DEBUG_INFO_BIT_NV | | ||
| 1223 | VK_DEVICE_DIAGNOSTICS_CONFIG_ENABLE_RESOURCE_TRACKING_BIT_NV | | ||
| 1224 | VK_DEVICE_DIAGNOSTICS_CONFIG_ENABLE_AUTOMATIC_CHECKPOINTS_BIT_NV; | ||
| 1225 | diag_config.pNext = dci.pNext; | ||
| 1226 | dci.pNext = &diag_config; | ||
| 1227 | std::printf("device: VK_NV_device_diagnostics_config on (shader debug info, resource tracking, checkpoints)\n"); | ||
| 1228 | } | ||
| 1204 | VkDevice dev; | 1229 | VkDevice dev; |
| 1205 | if (VkResult r = vkCreateDevice(pd, &dci, nullptr, &dev)) { std::fprintf(stderr, "vkCreateDevice %d\n", r); return 1; } | 1230 | if (VkResult r = vkCreateDevice(pd, &dci, nullptr, &dev)) { std::fprintf(stderr, "vkCreateDevice %d\n", r); return 1; } |
| 1206 | leonida::SubgroupSizeCaps runtime_subgroups; | 1231 | leonida::SubgroupSizeCaps runtime_subgroups; |
diff --git a/runtime/test/vk_presenter_sparse_capture.h b/runtime/test/vk_presenter_sparse_capture.h new file mode 100644 index 000000000..fc833e4ad --- /dev/null +++ b/runtime/test/vk_presenter_sparse_capture.h | |||
| @@ -0,0 +1,192 @@ | |||
| 1 | // The positive-only cadence oracle in vk_presenter_sync_test.cpp. Included after its driver counters. | ||
| 2 | #pragma once | ||
| 3 | |||
| 4 | namespace sparse_test { | ||
| 5 | namespace fs = std::filesystem; | ||
| 6 | using RGB = std::array<int, 3>; | ||
| 7 | constexpr RGB red{255, 0, 0}, blue{0, 0, 255}, black{0, 0, 0}; | ||
| 8 | |||
| 9 | // Own a newly created owner/SYSTEM-only directory. Never reuse or recursively remove an existing tree. | ||
| 10 | struct Folder { | ||
| 11 | fs::path path; | ||
| 12 | bool create(const char* tag) { | ||
| 13 | auto candidate = fs::temp_directory_path() / (std::string("leonida-sparse-") + tag + "-" + | ||
| 14 | std::to_string(GetCurrentProcessId()) + "-" + std::to_string(GetTickCount64())); | ||
| 15 | PSECURITY_DESCRIPTOR sd = nullptr; | ||
| 16 | if (!ConvertStringSecurityDescriptorToSecurityDescriptorW(L"D:P(A;OICI;FA;;;OW)(A;OICI;FA;;;SY)", | ||
| 17 | SDDL_REVISION_1, &sd, nullptr)) return false; | ||
| 18 | SECURITY_ATTRIBUTES sa{sizeof(sa), sd, FALSE}; | ||
| 19 | const bool fresh = CreateDirectoryW(candidate.c_str(), &sa) != FALSE; | ||
| 20 | LocalFree(sd); | ||
| 21 | if (fresh) path = std::move(candidate); | ||
| 22 | return fresh; | ||
| 23 | } | ||
| 24 | ~Folder() { | ||
| 25 | if (path.empty()) return; | ||
| 26 | std::error_code ec; | ||
| 27 | for (auto name : {"index.txt", "frame_00001.ppm", "frame_00004.ppm"}) fs::remove(path / name, ec); | ||
| 28 | fs::remove(path, ec); // leave unknown contents alone on failure | ||
| 29 | } | ||
| 30 | }; | ||
| 31 | const char* sdr_format(VkFormat f) { | ||
| 32 | switch (f) { | ||
| 33 | case VK_FORMAT_B8G8R8A8_UNORM: return "VK_FORMAT_B8G8R8A8_UNORM"; | ||
| 34 | case VK_FORMAT_B8G8R8A8_SRGB: return "VK_FORMAT_B8G8R8A8_SRGB"; | ||
| 35 | case VK_FORMAT_R8G8B8A8_UNORM: return "VK_FORMAT_R8G8B8A8_UNORM"; | ||
| 36 | case VK_FORMAT_R8G8B8A8_SRGB: return "VK_FORMAT_R8G8B8A8_SRGB"; | ||
| 37 | default: return nullptr; | ||
| 38 | } | ||
| 39 | } | ||
| 40 | bool disk_matches(const fs::path& dir, VkExtent2D extent, VkFormat fmt, RGB fourth) { | ||
| 41 | std::set<fs::path> names; | ||
| 42 | for (const auto& e : fs::directory_iterator(dir)) { | ||
| 43 | if (!fs::is_regular_file(e.symlink_status())) return false; | ||
| 44 | names.insert(e.path().filename()); | ||
| 45 | } | ||
| 46 | if (names != std::set<fs::path>{"index.txt", "frame_00001.ppm", "frame_00004.ppm"} || !sdr_format(fmt)) return false; | ||
| 47 | const auto w=extent.width, h=extent.height; | ||
| 48 | if (!w || !h || w>1024 || h>1024) return false; | ||
| 49 | const std::string header="P6\n"+std::to_string(w)+" "+std::to_string(h)+"\n255\n"; | ||
| 50 | std::ifstream index(dir/"index.txt"); | ||
| 51 | for (const int n : {1,4}) { | ||
| 52 | const RGB color = n==1 ? red : fourth; | ||
| 53 | const fs::path file=dir/(n==1 ? "frame_00001.ppm":"frame_00004.ppm"); | ||
| 54 | if (fs::file_size(file)!=header.size()+3ull*w*h) return false; | ||
| 55 | std::string expected=header; | ||
| 56 | expected.reserve(header.size()+3ull*w*h); | ||
| 57 | for (size_t i=0; i<size_t(w)*h; ++i) for (int c:color) expected.push_back(static_cast<char>(c)); | ||
| 58 | std::ifstream img(file,std::ios::binary); | ||
| 59 | std::string got(expected.size(),'\0'); | ||
| 60 | if (!img.read(got.data(),static_cast<std::streamsize>(got.size())) || got!=expected) return false; | ||
| 61 | const auto row="frame "+std::to_string(n)+" format "+std::to_string(int(fmt))+" ("+sdr_format(fmt)+") extent "+ | ||
| 62 | std::to_string(w)+"x"+std::to_string(h)+" mean rgb "+std::to_string(color[0])+".00 "+ | ||
| 63 | std::to_string(color[1])+".00 "+std::to_string(color[2])+".00"; | ||
| 64 | if (!std::getline(index,got) || got!=row) return false; | ||
| 65 | } | ||
| 66 | return index.peek()==std::char_traits<char>::eof(); | ||
| 67 | } | ||
| 68 | |||
| 69 | int run(vktest::Device& d, HWND window) { | ||
| 70 | using namespace leonida; | ||
| 71 | VulkanContext context(driver::get_device,d.device,true); | ||
| 72 | VulkanQueue queue(context,d.queue,d.family); | ||
| 73 | EXPECT(context.loaded() && queue.ok()); | ||
| 74 | const auto surface_fn=reinterpret_cast<PFN_vkCreateWin32SurfaceKHR>(d.instance_proc(d.instance,"vkCreateWin32SurfaceKHR")); | ||
| 75 | EXPECT(surface_fn); | ||
| 76 | // Two immutable RGBA8 test sources, filled on this queue once. present_blank supplies the third color. | ||
| 77 | for (ResourceId id : {1u,2u}) { | ||
| 78 | ResourceBinding rb{}; | ||
| 79 | rb.width=64;rb.height=64;rb.format=VK_FORMAT_R8G8B8A8_UNORM;rb.depth=rb.mip_levels=rb.array_layers=1; | ||
| 80 | rb.samples=1;rb.color_attachment=true;rb.sampled=true;rb.aspects=VK_IMAGE_ASPECT_COLOR_BIT; | ||
| 81 | rb.image=d.image(rb.format,rb.width,rb.height,1,VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | | ||
| 82 | VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_SAMPLED_BIT); | ||
| 83 | EXPECT(rb.image); | ||
| 84 | context.add_resource(id,rb,VK_IMAGE_LAYOUT_UNDEFINED); | ||
| 85 | CommandList list; | ||
| 86 | EXPECT(list.transition({id,0,d3d12_state::common,d3d12_state::render_target})); | ||
| 87 | EXPECT(list.clear_render_target({id,0,0,1},{id==1?1.f:0.f,0,id==2?1.f:0.f,1})); | ||
| 88 | EXPECT(list.transition({id,0,d3d12_state::render_target,d3d12_state::common}) && list.close()); | ||
| 89 | const CommandList* input=&list; | ||
| 90 | EXPECT(queue.execute({&input,1})==ReplayResult::success); | ||
| 91 | } | ||
| 92 | EXPECT(queue.idle()); | ||
| 93 | EXPECT(!_putenv_s("LEONIDA_CAPTURE_EVERY","3") && !_putenv_s("LEONIDA_CAPTURE_LIMIT","2") && | ||
| 94 | !_putenv_s("LEONIDA_CAPTURE_SOURCE","0")); | ||
| 95 | enum class Phase { sparse, final_pending, continuous, splash, composed }; | ||
| 96 | for (Phase p : {Phase::sparse,Phase::final_pending,Phase::continuous,Phase::splash,Phase::composed}) { | ||
| 97 | Folder folder; | ||
| 98 | EXPECT(folder.create(p==Phase::sparse?"sparse":p==Phase::final_pending?"pending":p==Phase::continuous?"explicit": | ||
| 99 | p==Phase::splash?"splash":"composed")); | ||
| 100 | EXPECT(!_putenv_s("LEONIDA_CAPTURE",folder.path.string().c_str())); | ||
| 101 | VkExtent2D extent{};VkFormat fmt{}; | ||
| 102 | { | ||
| 103 | VkWin32SurfaceCreateInfoKHR info{VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR}; | ||
| 104 | info.hinstance=GetModuleHandleW(nullptr);info.hwnd=window; | ||
| 105 | VkSurfaceKHR surface{};EXPECT(surface_fn(d.instance,&info,nullptr,&surface)==VK_SUCCESS); | ||
| 106 | VulkanPresenter present(context,driver::get_instance,d.instance,d.physical,d.queue,d.family,surface); | ||
| 107 | EXPECT(present.ok()); | ||
| 108 | if (p==Phase::continuous) EXPECT(present.enable_capture()); | ||
| 109 | const unsigned last = p==Phase::final_pending?4:p==Phase::splash?7:8; | ||
| 110 | for (unsigned n=1; n<=last; ++n) { | ||
| 111 | const bool disk=n==1 || n==4; | ||
| 112 | const bool replaced=p==Phase::splash && n>=2 && n<=4; | ||
| 113 | const bool handoff=p==Phase::splash && n==5; | ||
| 114 | const RGB expected=n==1 || replaced ? red : n==4 || handoff ? blue : n%2 ? red : black; | ||
| 115 | driver::capture_copies=0; driver::capture_waw_barriers=0; driver::saw_capture_waw=false; | ||
| 116 | driver::observe_capture=true; | ||
| 117 | if (p==Phase::splash && n==1) { | ||
| 118 | EXPECT(present.present_splash(1,std::make_shared<int>(0))); | ||
| 119 | } else if (replaced || expected==black) EXPECT(present.present_blank(true)==VK_SUCCESS); | ||
| 120 | else if (p==Phase::composed) { | ||
| 121 | const auto before=present.composed_presents(); | ||
| 122 | PresentPlanes planes{}; | ||
| 123 | planes.plane[0].source=expected==red?1:2; | ||
| 124 | EXPECT(present.present_planes(planes,true)==VK_SUCCESS && present.composed_presents()==before+1); | ||
| 125 | } else EXPECT(present.present(expected==red?1:2,true)==VK_SUCCESS); | ||
| 126 | driver::observe_capture=false; | ||
| 127 | EXPECT(present.presented()==n); | ||
| 128 | const unsigned copies=replaced?2u : disk || p==Phase::continuous || handoff ? 1u : 0u; | ||
| 129 | EXPECT(driver::capture_copies==copies && driver::capture_waw_barriers==copies && | ||
| 130 | !driver::saw_capture_waw); // also reject a WAW on a frame with no copy | ||
| 131 | std::vector<std::uint8_t> pixels{77};VkExtent2D e{17,18};VkFormat f=VK_FORMAT_UNDEFINED; | ||
| 132 | EXPECT(present.read_back(pixels,&e,&f)==(copies!=0)); | ||
| 133 | if (copies) { | ||
| 134 | if (n==1) {extent=e;fmt=f;} | ||
| 135 | EXPECT(e.width==extent.width && e.height==extent.height && f==fmt && sdr_format(f)); | ||
| 136 | const bool bgra=f==VK_FORMAT_B8G8R8A8_UNORM || f==VK_FORMAT_B8G8R8A8_SRGB; | ||
| 137 | EXPECT(presenter_capture_matches_rgb(pixels,e.width,e.height,bgra,expected,0)); | ||
| 138 | } else EXPECT(pixels.size()==1 && pixels[0]==77 && e.width==17 && e.height==18 && f==VK_FORMAT_UNDEFINED); | ||
| 139 | } | ||
| 140 | if (p==Phase::final_pending) { | ||
| 141 | EXPECT(fs::exists(folder.path/"frame_00001.ppm") && !fs::exists(folder.path/"frame_00004.ppm")); | ||
| 142 | } | ||
| 143 | } // pending final frame 4 is written here, without another present | ||
| 144 | EXPECT(disk_matches(folder.path,extent,fmt,p==Phase::splash?red:blue)); | ||
| 145 | } | ||
| 146 | // Splash-only storage is not an ongoing readback request. No disk path, no enable_capture(). | ||
| 147 | EXPECT(_putenv_s("LEONIDA_CAPTURE", "") == 0); | ||
| 148 | { | ||
| 149 | VkWin32SurfaceCreateInfoKHR info{VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR}; | ||
| 150 | info.hinstance = GetModuleHandleW(nullptr); | ||
| 151 | info.hwnd = window; | ||
| 152 | VkSurfaceKHR surface{}; | ||
| 153 | EXPECT(surface_fn(d.instance, &info, nullptr, &surface) == VK_SUCCESS); | ||
| 154 | VulkanPresenter present(context, driver::get_instance, d.instance, d.physical, d.queue, d.family, surface); | ||
| 155 | EXPECT(present.ok()); | ||
| 156 | auto owner = std::make_shared<int>(0); | ||
| 157 | std::weak_ptr<int> held = owner; | ||
| 158 | for (unsigned n = 1; n <= 5; ++n) { | ||
| 159 | driver::capture_copies = 0; | ||
| 160 | driver::capture_waw_barriers = 0; | ||
| 161 | driver::saw_capture_waw = false; | ||
| 162 | driver::observe_capture = true; | ||
| 163 | if (n == 1) EXPECT(present.present_splash(1, std::move(owner))); // show the red shell | ||
| 164 | else if (n == 3 || n == 5) EXPECT(present.present(2, true) == VK_SUCCESS); // blue title | ||
| 165 | else EXPECT(present.present_blank(true) == VK_SUCCESS); | ||
| 166 | driver::observe_capture = false; | ||
| 167 | |||
| 168 | // Initial shell: zero copies. Held black: inspect, then overwrite with the red shell. First blue: | ||
| 169 | // inspect once and release. Subsequent black and blue are ordinary frames, with no copies. | ||
| 170 | const unsigned expected_copies = n == 2 ? 2 : n == 3 ? 1 : 0; | ||
| 171 | EXPECT(present.presented() == n && driver::capture_copies == expected_copies && | ||
| 172 | driver::capture_waw_barriers == expected_copies && !driver::saw_capture_waw); | ||
| 173 | EXPECT(held.expired() == (n >= 3)); | ||
| 174 | std::vector<std::uint8_t> pixels{77}; | ||
| 175 | VkExtent2D extent{17, 18}; | ||
| 176 | VkFormat format = VK_FORMAT_UNDEFINED; | ||
| 177 | if (n == 2) { | ||
| 178 | EXPECT(present.read_back(pixels, &extent, &format) && sdr_format(format)); | ||
| 179 | const bool bgra = format == VK_FORMAT_B8G8R8A8_UNORM || format == VK_FORMAT_B8G8R8A8_SRGB; | ||
| 180 | EXPECT(presenter_capture_matches_rgb(pixels, extent.width, extent.height, bgra, red, 0)); | ||
| 181 | } else { | ||
| 182 | EXPECT(!present.read_back(pixels, &extent, &format)); | ||
| 183 | EXPECT(pixels.size() == 1 && pixels[0] == 77 && extent.width == 17 && extent.height == 18 && | ||
| 184 | format == VK_FORMAT_UNDEFINED); | ||
| 185 | } | ||
| 186 | } | ||
| 187 | } | ||
| 188 | EXPECT(queue.idle());context.remove_resource(1);context.remove_resource(2); | ||
| 189 | std::puts("sparse capture: frames 1/4, cap, last-fence drain, explicit readback, disk and splash-only handoffs verified"); | ||
| 190 | return 0; | ||
| 191 | } | ||
| 192 | } // namespace sparse_test | ||
diff --git a/runtime/test/vk_presenter_sync_test.cpp b/runtime/test/vk_presenter_sync_test.cpp index a54bf6662..ee75ad86f 100644 --- a/runtime/test/vk_presenter_sync_test.cpp +++ b/runtime/test/vk_presenter_sync_test.cpp | |||
| @@ -16,6 +16,7 @@ | |||
| 16 | #endif | 16 | #endif |
| 17 | #define VK_USE_PLATFORM_WIN32_KHR | 17 | #define VK_USE_PLATFORM_WIN32_KHR |
| 18 | #include <windows.h> | 18 | #include <windows.h> |
| 19 | #include <sddl.h> | ||
| 19 | 20 | ||
| 20 | #include "vk_presenter_capture_colour.h" | 21 | #include "vk_presenter_capture_colour.h" |
| 21 | #include "vk_test_device.h" | 22 | #include "vk_test_device.h" |
| @@ -28,7 +29,10 @@ | |||
| 28 | #include <cstdint> | 29 | #include <cstdint> |
| 29 | #include <cstdio> | 30 | #include <cstdio> |
| 30 | #include <cstdlib> | 31 | #include <cstdlib> |
| 32 | #include <filesystem> | ||
| 33 | #include <fstream> | ||
| 31 | #include <functional> | 34 | #include <functional> |
| 35 | #include <set> | ||
| 32 | #include <mutex> | 36 | #include <mutex> |
| 33 | #include <string_view> | 37 | #include <string_view> |
| 34 | #include <thread> | 38 | #include <thread> |
| @@ -182,10 +186,14 @@ void install(PFN_vkGetInstanceProcAddr instance_proc, VkInstance instance, VkDev | |||
| 182 | } | 186 | } |
| 183 | } // namespace driver | 187 | } // namespace driver |
| 184 | 188 | ||
| 189 | #include "vk_presenter_sparse_capture.h" | ||
| 190 | |||
| 185 | } // namespace | 191 | } // namespace |
| 186 | 192 | ||
| 187 | int main() { | 193 | int main(int argc, char** argv) { |
| 188 | using namespace leonida; | 194 | using namespace leonida; |
| 195 | const bool sparse = argc==2 && std::string_view(argv[1])=="--sparse-capture"; | ||
| 196 | if (argc!=1 && !sparse) return 2; | ||
| 189 | 197 | ||
| 190 | vktest::Device d; | 198 | vktest::Device d; |
| 191 | if (!d.create(true)) { | 199 | if (!d.create(true)) { |
| @@ -202,7 +210,7 @@ int main() { | |||
| 202 | constexpr std::uint32_t width = 128, height = 96; | 210 | constexpr std::uint32_t width = 128, height = 96; |
| 203 | RECT fr{0, 0, LONG(width), LONG(height)}; | 211 | RECT fr{0, 0, LONG(width), LONG(height)}; |
| 204 | AdjustWindowRect(&fr, WS_OVERLAPPEDWINDOW, FALSE); | 212 | AdjustWindowRect(&fr, WS_OVERLAPPEDWINDOW, FALSE); |
| 205 | HWND window = CreateWindowExW(0, wc.lpszClassName, L"Leonida presenter sync test", WS_OVERLAPPEDWINDOW, 80, 80, | 213 | HWND window = CreateWindowExW(sparse ? WS_EX_NOACTIVATE | WS_EX_TOOLWINDOW : 0, wc.lpszClassName, L"Leonida presenter sync test", WS_OVERLAPPEDWINDOW, 80, 80, |
| 206 | fr.right - fr.left, fr.bottom - fr.top, nullptr, nullptr, wc.hInstance, nullptr); | 214 | fr.right - fr.left, fr.bottom - fr.top, nullptr, nullptr, wc.hInstance, nullptr); |
| 207 | EXPECT(window); | 215 | EXPECT(window); |
| 208 | ShowWindow(window, SW_SHOWNOACTIVATE); | 216 | ShowWindow(window, SW_SHOWNOACTIVATE); |
| @@ -210,6 +218,12 @@ int main() { | |||
| 210 | pump(); | 218 | pump(); |
| 211 | 219 | ||
| 212 | driver::install(d.instance_proc, d.instance, d.device); | 220 | driver::install(d.instance_proc, d.instance, d.device); |
| 221 | if (sparse) { // positive-only: never enter the failure/concurrency regressions below | ||
| 222 | const int result = sparse_test::run(d, window); | ||
| 223 | DestroyWindow(window); | ||
| 224 | UnregisterClassW(wc.lpszClassName, wc.hInstance); | ||
| 225 | return result || d.validation_errors() ? 1 : 0; | ||
| 226 | } | ||
| 213 | { | 227 | { |
| 214 | VulkanContext context(driver::get_device, d.device, true); | 228 | VulkanContext context(driver::get_device, d.device, true); |
| 215 | EXPECT(context.loaded()); | 229 | EXPECT(context.loaded()); |
diff --git a/runtime/test/vk_sampler_test.cpp b/runtime/test/vk_sampler_test.cpp index 98206931b..a35806d8f 100644 --- a/runtime/test/vk_sampler_test.cpp +++ b/runtime/test/vk_sampler_test.cpp | |||
| @@ -265,9 +265,10 @@ int main(int argc, char** argv) { | |||
| 265 | VkBufferDeviceAddressInfo address_info{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; | 265 | VkBufferDeviceAddressInfo address_info{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; |
| 266 | address_info.buffer = heap; | 266 | address_info.buffer = heap; |
| 267 | const VkDeviceAddress heap_base = vkGetBufferDeviceAddress(dev, &address_info); | 267 | const VkDeviceAddress heap_base = vkGetBufferDeviceAddress(dev, &address_info); |
| 268 | // Descriptor hash table: the T# names image 1, the S# sampler 1. Index 0 of each is a magenta fallback. | 268 | // Descriptor hash table: the T# names image 1, the S# sampler 1. Index 0 of each is a magenta fallback. The |
| 269 | // module is tagged (build.py), so the T# entry names the array its index is bound in: a sampled 2D image. | ||
| 269 | leonida::DescriptorTable table(16); | 270 | leonida::DescriptorTable table(16); |
| 270 | table.insert(tsharp.data(), 1); | 271 | table.insert(tsharp.data(), 1, leonida::kind_sampled_bit(0)); |
| 271 | table.insert(leonida::make_ssharp_key(ssharp.data()).data(), 1); | 272 | table.insert(leonida::make_ssharp_key(ssharp.data()).data(), 1); |
| 272 | const auto table_words = table.build_gpu_buffer(true); | 273 | const auto table_words = table.build_gpu_buffer(true); |
| 273 | VkBuffer table_buffer; | 274 | VkBuffer table_buffer; |
diff --git a/runtime/test/vk_sandbox.cpp b/runtime/test/vk_sandbox.cpp index 7ae9e8db6..11718190d 100644 --- a/runtime/test/vk_sandbox.cpp +++ b/runtime/test/vk_sandbox.cpp | |||
| @@ -395,7 +395,8 @@ int main(int argc, char** argv) { | |||
| 395 | }; | 395 | }; |
| 396 | const uint32_t nimg = uint32_t(scene.textures.size()) + 1; // image 0: 1x1 white for untextured draws | 396 | const uint32_t nimg = uint32_t(scene.textures.size()) + 1; // image 0: 1x1 white for untextured draws |
| 397 | leonida::DescriptorTable table(2 * (nimg + 2)); | 397 | leonida::DescriptorTable table(2 * (nimg + 2)); |
| 398 | for (uint32_t i = 0; i < nimg; ++i) table.insert(tsharp(i).data(), i); | 398 | // The module is tagged (build.py), so each T# entry names the array its index is bound in: a sampled 2D image. |
| 399 | for (uint32_t i = 0; i < nimg; ++i) table.insert(tsharp(i).data(), i, leonida::kind_sampled_bit(0)); | ||
| 399 | uint32_t ssharp[8] = {1024, 12582912, 418381824, 0, 0xFFFFFFFFu, 0xFFFFFFFFu, 0xFFFFFFFFu, 0xFFFFFFFFu}; // the PS's literal S# | 400 | uint32_t ssharp[8] = {1024, 12582912, 418381824, 0, 0xFFFFFFFFu, 0xFFFFFFFFu, 0xFFFFFFFFu, 0xFFFFFFFFu}; // the PS's literal S# |
| 400 | table.insert(ssharp, 0); | 401 | table.insert(ssharp, 0); |
| 401 | for (uint32_t d = 0; d < ndraw; ++d) { | 402 | for (uint32_t d = 0; d < ndraw; ++d) { |
diff --git a/runtime/test/vk_semaphore_lifetime_test.cpp b/runtime/test/vk_semaphore_lifetime_test.cpp new file mode 100644 index 000000000..6ee7ffd9b --- /dev/null +++ b/runtime/test/vk_semaphore_lifetime_test.cpp | |||
| @@ -0,0 +1,261 @@ | |||
| 1 | // Semaphore lifetimes across fence and queue teardown (src/vulkan_backend.h, src/vulkan_device_fault.h). No shaders, | ||
| 2 | // no game data. | ||
| 3 | // 1. A fence released right after an unheld Signal: the queue keeps the fence, and so its timeline semaphore, | ||
| 4 | // until the GPU has run the signal (destroying a semaphore a pending submission signals is undefined, | ||
| 5 | // VUID-vkDestroySemaphore-semaphore-05149). The Signal is kept pending on the GPU by a wait on a semaphore the | ||
| 6 | // host signals later. | ||
| 7 | // 2. The queue whose submission uploaded the bindless table is destroyed, then another queue submits: that | ||
| 8 | // submission must not wait on the destroyed queue's progress semaphore. | ||
| 9 | // 3. With the device-fault diagnostics on, the submit ring forgets both semaphores before they are destroyed: its | ||
| 10 | // progress watch (once a second) and a dump after the teardown never read the counter of a destroyed one. | ||
| 11 | // The driver calls are intercepted, so 2 and 3 are checked with or without the validation layer; set | ||
| 12 | // LEONIDA_VK_VALIDATION=1 to also run under VK_LAYER_KHRONOS_validation (any validation error fails the test). | ||
| 13 | #include "vk_test_device.h" | ||
| 14 | #include "../src/vulkan_backend.h" | ||
| 15 | |||
| 16 | #include <algorithm> | ||
| 17 | #include <atomic> | ||
| 18 | #include <chrono> | ||
| 19 | #include <cstdint> | ||
| 20 | #include <cstring> | ||
| 21 | #include <memory> | ||
| 22 | #include <mutex> | ||
| 23 | #include <set> | ||
| 24 | #include <thread> | ||
| 25 | #include <utility> | ||
| 26 | #include <vector> | ||
| 27 | |||
| 28 | #define EXPECT(condition) do { \ | ||
| 29 | if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ | ||
| 30 | } while (0) | ||
| 31 | |||
| 32 | namespace { | ||
| 33 | |||
| 34 | using namespace leonida; | ||
| 35 | |||
| 36 | namespace driver { | ||
| 37 | PFN_vkGetDeviceProcAddr real_get = nullptr; | ||
| 38 | PFN_vkQueueSubmit real_submit = nullptr; | ||
| 39 | PFN_vkCreateSemaphore real_create = nullptr; | ||
| 40 | PFN_vkDestroySemaphore real_destroy = nullptr; | ||
| 41 | PFN_vkGetSemaphoreCounterValue real_counter = nullptr; | ||
| 42 | |||
| 43 | std::mutex mutex; | ||
| 44 | std::set<VkSemaphore> destroyed; // destroyed and not made again | ||
| 45 | std::vector<VkSemaphore> last_signals; // of the last vkQueueSubmit | ||
| 46 | std::vector<VkSemaphore> waits_seen; // every wait semaphore submitted since the last reset | ||
| 47 | std::atomic<unsigned> dead_waits{0}; // submissions that waited on a destroyed semaphore | ||
| 48 | std::atomic<unsigned> dead_reads{0}; // counter reads of a destroyed semaphore | ||
| 49 | std::atomic<unsigned> live_reads{0}; | ||
| 50 | |||
| 51 | VKAPI_ATTR VkResult VKAPI_CALL submit(VkQueue queue, std::uint32_t count, const VkSubmitInfo* submits, VkFence fence) { | ||
| 52 | { | ||
| 53 | std::lock_guard lock(mutex); | ||
| 54 | last_signals.clear(); | ||
| 55 | for (std::uint32_t i = 0; i < count; ++i) { | ||
| 56 | for (std::uint32_t w = 0; w < submits[i].waitSemaphoreCount; ++w) { | ||
| 57 | const VkSemaphore s = submits[i].pWaitSemaphores[w]; | ||
| 58 | waits_seen.push_back(s); | ||
| 59 | if (destroyed.count(s)) dead_waits.fetch_add(1); | ||
| 60 | } | ||
| 61 | for (std::uint32_t s = 0; s < submits[i].signalSemaphoreCount; ++s) | ||
| 62 | last_signals.push_back(submits[i].pSignalSemaphores[s]); | ||
| 63 | } | ||
| 64 | } | ||
| 65 | return real_submit(queue, count, submits, fence); | ||
| 66 | } | ||
| 67 | |||
| 68 | VKAPI_ATTR VkResult VKAPI_CALL create(VkDevice device, const VkSemaphoreCreateInfo* info, | ||
| 69 | const VkAllocationCallbacks* alloc, VkSemaphore* out) { | ||
| 70 | const VkResult result = real_create(device, info, alloc, out); | ||
| 71 | if (result == VK_SUCCESS) { | ||
| 72 | std::lock_guard lock(mutex); | ||
| 73 | destroyed.erase(*out); // a handle value the driver hands out again is alive again | ||
| 74 | } | ||
| 75 | return result; | ||
| 76 | } | ||
| 77 | |||
| 78 | VKAPI_ATTR void VKAPI_CALL destroy(VkDevice device, VkSemaphore semaphore, const VkAllocationCallbacks* alloc) { | ||
| 79 | if (semaphore) { | ||
| 80 | std::lock_guard lock(mutex); | ||
| 81 | destroyed.insert(semaphore); | ||
| 82 | } | ||
| 83 | real_destroy(device, semaphore, alloc); | ||
| 84 | } | ||
| 85 | |||
| 86 | VKAPI_ATTR VkResult VKAPI_CALL counter(VkDevice device, VkSemaphore semaphore, std::uint64_t* value) { | ||
| 87 | { | ||
| 88 | std::lock_guard lock(mutex); | ||
| 89 | if (destroyed.count(semaphore)) { | ||
| 90 | dead_reads.fetch_add(1); | ||
| 91 | *value = 0; | ||
| 92 | return VK_ERROR_UNKNOWN; // never reaches the driver with a dead handle | ||
| 93 | } | ||
| 94 | } | ||
| 95 | live_reads.fetch_add(1); | ||
| 96 | return real_counter(device, semaphore, value); | ||
| 97 | } | ||
| 98 | |||
| 99 | VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL get(VkDevice device, const char* name) { | ||
| 100 | if (!std::strcmp(name, "vkQueueSubmit")) return reinterpret_cast<PFN_vkVoidFunction>(submit); | ||
| 101 | if (!std::strcmp(name, "vkCreateSemaphore")) return reinterpret_cast<PFN_vkVoidFunction>(create); | ||
| 102 | if (!std::strcmp(name, "vkDestroySemaphore")) return reinterpret_cast<PFN_vkVoidFunction>(destroy); | ||
| 103 | if (!std::strcmp(name, "vkGetSemaphoreCounterValue") || !std::strcmp(name, "vkGetSemaphoreCounterValueKHR")) | ||
| 104 | return reinterpret_cast<PFN_vkVoidFunction>(counter); | ||
| 105 | return real_get(device, name); | ||
| 106 | } | ||
| 107 | } // namespace driver | ||
| 108 | |||
| 109 | // A timeline semaphore the test signals from the host, unknown to the queues' holds (so a wait on it is not held on | ||
| 110 | // the CPU: it is submitted, and the GPU waits). Like the runtime's own owners (~VulkanFence, ~VulkanQueue) it tells | ||
| 111 | // the submit ring before it goes. | ||
| 112 | struct HostGate { | ||
| 113 | const vktest::Device& d; | ||
| 114 | DeviceFaultDiagnostics* ring; | ||
| 115 | VkSemaphore semaphore = VK_NULL_HANDLE; | ||
| 116 | HostGate(const vktest::Device& device, DeviceFaultDiagnostics* diagnostics) : d(device), ring(diagnostics) { | ||
| 117 | VkSemaphoreTypeCreateInfo type{VK_STRUCTURE_TYPE_SEMAPHORE_TYPE_CREATE_INFO}; | ||
| 118 | type.semaphoreType = VK_SEMAPHORE_TYPE_TIMELINE; | ||
| 119 | VkSemaphoreCreateInfo info{VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO, &type}; | ||
| 120 | driver::create(d.device, &info, nullptr, &semaphore); | ||
| 121 | } | ||
| 122 | ~HostGate() { | ||
| 123 | if (!semaphore) return; | ||
| 124 | if (ring) ring->forget(semaphore); | ||
| 125 | driver::destroy(d.device, semaphore, nullptr); | ||
| 126 | } | ||
| 127 | bool open(std::uint64_t value) const { | ||
| 128 | VkSemaphoreSignalInfo signal{VK_STRUCTURE_TYPE_SEMAPHORE_SIGNAL_INFO}; | ||
| 129 | signal.semaphore = semaphore; | ||
| 130 | signal.value = value; | ||
| 131 | return d.fn<PFN_vkSignalSemaphore>("vkSignalSemaphore")(d.device, &signal) == VK_SUCCESS; | ||
| 132 | } | ||
| 133 | }; | ||
| 134 | |||
| 135 | int run(vktest::Device& d) { | ||
| 136 | driver::real_get = d.device_proc; | ||
| 137 | driver::real_submit = d.fn<PFN_vkQueueSubmit>("vkQueueSubmit"); | ||
| 138 | driver::real_create = d.fn<PFN_vkCreateSemaphore>("vkCreateSemaphore"); | ||
| 139 | driver::real_destroy = d.fn<PFN_vkDestroySemaphore>("vkDestroySemaphore"); | ||
| 140 | driver::real_counter = d.fn<PFN_vkGetSemaphoreCounterValue>("vkGetSemaphoreCounterValue"); | ||
| 141 | EXPECT(driver::real_submit && driver::real_create && driver::real_destroy && driver::real_counter); | ||
| 142 | |||
| 143 | VulkanContext context(driver::get, d.device, true); | ||
| 144 | EXPECT(context.loaded()); | ||
| 145 | context.configure_device_fault(driver::get, DeviceFaultExtensions{}); // the submit ring and its progress watch | ||
| 146 | EXPECT(context.device_fault()); | ||
| 147 | bool arm_upload = false; | ||
| 148 | context.set_bindless_prepare([&](VkCommandBuffer) { | ||
| 149 | if (std::exchange(arm_upload, false)) context.note_bindless_upload(); // as a replacing bindless flush does | ||
| 150 | return true; | ||
| 151 | }); | ||
| 152 | |||
| 153 | void* map = nullptr; | ||
| 154 | constexpr VkDeviceSize kSize = 4096; | ||
| 155 | const VkBufferUsageFlags usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; | ||
| 156 | VkBuffer a = d.buffer(kSize, usage, &map), b = d.buffer(kSize, usage, &map); | ||
| 157 | EXPECT(a && b); | ||
| 158 | ResourceBinding binding; | ||
| 159 | binding.size = kSize; | ||
| 160 | binding.buffer = a; | ||
| 161 | context.add_resource(1, binding); | ||
| 162 | binding.buffer = b; | ||
| 163 | context.add_resource(2, binding); | ||
| 164 | CommandList copy; | ||
| 165 | EXPECT(copy.copy_buffer({2, 0, 1, 0, kSize})); | ||
| 166 | EXPECT(copy.close()); | ||
| 167 | const CommandList* lists[] = {©}; | ||
| 168 | |||
| 169 | auto stay = std::make_unique<VulkanQueue>(context, d.queue, d.family); | ||
| 170 | EXPECT(stay->ok()); | ||
| 171 | |||
| 172 | // 1. Release a fence right after an unheld Signal that the GPU cannot run yet. | ||
| 173 | { | ||
| 174 | HostGate gate(d, context.device_fault()); | ||
| 175 | EXPECT(gate.semaphore); | ||
| 176 | auto fence = std::make_shared<VulkanFence>(context, 0); | ||
| 177 | const VkSemaphore fence_semaphore = fence->semaphore(); | ||
| 178 | EXPECT(fence_semaphore); | ||
| 179 | std::weak_ptr<VulkanFence> watch = fence; | ||
| 180 | stay->wait(gate.semaphore, 1); // the next submission waits for the host on the GPU | ||
| 181 | EXPECT(stay->signal(fence_semaphore, 1, [&fence] { return std::shared_ptr<void>(fence); })); | ||
| 182 | fence.reset(); // the title's last Release | ||
| 183 | { | ||
| 184 | std::lock_guard lock(driver::mutex); | ||
| 185 | EXPECT(!driver::destroyed.count(fence_semaphore)); | ||
| 186 | } | ||
| 187 | EXPECT(!watch.expired()); // the queue keeps it while the Signal is pending | ||
| 188 | EXPECT(gate.open(1)); | ||
| 189 | // Each execute drains the pins whose submissions are done. | ||
| 190 | bool released = false; | ||
| 191 | for (int i = 0; i < 200 && !released; ++i) { | ||
| 192 | context.wait_retire_ticket(context.submitted_retire_ticket()); | ||
| 193 | EXPECT(stay->execute(lists) == ReplayResult::success); | ||
| 194 | released = watch.expired(); | ||
| 195 | if (!released) std::this_thread::sleep_for(std::chrono::milliseconds(5)); | ||
| 196 | } | ||
| 197 | EXPECT(released); // and lets it go once the GPU has run it | ||
| 198 | std::lock_guard lock(driver::mutex); | ||
| 199 | EXPECT(driver::destroyed.count(fence_semaphore)); | ||
| 200 | std::printf("fence released after an unheld Signal: kept until the signal ran, then destroyed\n"); | ||
| 201 | } | ||
| 202 | |||
| 203 | // 2. The queue that uploaded the bindless table goes; another queue submits next. | ||
| 204 | VkSemaphore uploader_progress = VK_NULL_HANDLE; | ||
| 205 | { | ||
| 206 | auto uploader = std::make_unique<VulkanQueue>(context, d.queue, d.family); | ||
| 207 | EXPECT(uploader->ok()); | ||
| 208 | arm_upload = true; | ||
| 209 | EXPECT(uploader->execute(lists) == ReplayResult::success); | ||
| 210 | EXPECT(!arm_upload); | ||
| 211 | { | ||
| 212 | std::lock_guard lock(driver::mutex); | ||
| 213 | EXPECT(!driver::last_signals.empty()); | ||
| 214 | uploader_progress = driver::last_signals[0]; // a queue's submission signals its progress timeline first | ||
| 215 | } | ||
| 216 | uploader.reset(); | ||
| 217 | } | ||
| 218 | { | ||
| 219 | std::lock_guard lock(driver::mutex); | ||
| 220 | EXPECT(driver::destroyed.count(uploader_progress)); | ||
| 221 | driver::waits_seen.clear(); | ||
| 222 | } | ||
| 223 | EXPECT(stay->execute(lists) == ReplayResult::success); | ||
| 224 | { | ||
| 225 | std::lock_guard lock(driver::mutex); | ||
| 226 | EXPECT(std::find(driver::waits_seen.begin(), driver::waits_seen.end(), uploader_progress) == | ||
| 227 | driver::waits_seen.end()); | ||
| 228 | } | ||
| 229 | EXPECT(driver::dead_waits.load() == 0); | ||
| 230 | std::printf("bindless upload queue destroyed: the next submission on another queue does not wait on it\n"); | ||
| 231 | |||
| 232 | // 3. The ring: the progress watch reads counters once a second; a dump now reads every semaphore it still names. | ||
| 233 | std::this_thread::sleep_for(std::chrono::milliseconds(2200)); | ||
| 234 | const unsigned reads_before = driver::live_reads.load(); | ||
| 235 | context.device_fault()->dump_submits(); | ||
| 236 | EXPECT(driver::live_reads.load() > reads_before); // it did read the live ones | ||
| 237 | EXPECT(driver::dead_reads.load() == 0); | ||
| 238 | std::printf("submit ring: no counter read of a destroyed semaphore (%u live reads)\n", driver::live_reads.load()); | ||
| 239 | |||
| 240 | stay.reset(); | ||
| 241 | context.remove_resource(1); | ||
| 242 | context.remove_resource(2); | ||
| 243 | return 0; | ||
| 244 | } | ||
| 245 | |||
| 246 | } // namespace | ||
| 247 | |||
| 248 | int main() { | ||
| 249 | std::setvbuf(stdout, nullptr, _IONBF, 0); | ||
| 250 | vktest::Device d; | ||
| 251 | const auto status = d.initialize(); | ||
| 252 | if (status == vktest::DeviceStatus::unavailable) { | ||
| 253 | std::printf("SKIP: no usable Vulkan device\n"); | ||
| 254 | return 77; | ||
| 255 | } | ||
| 256 | if (status != vktest::DeviceStatus::ready) return 1; | ||
| 257 | const int rc = run(d); | ||
| 258 | const unsigned errors = d.validation_errors(); | ||
| 259 | std::printf("Vulkan validation errors: %u%s\n", errors, d.validation ? "" : " (validation off)"); | ||
| 260 | return rc ? rc : errors ? 1 : 0; | ||
| 261 | } | ||
diff --git a/runtime/test/vk_store_test.cpp b/runtime/test/vk_store_test.cpp index 0b4c3c6f9..62e1271f2 100644 --- a/runtime/test/vk_store_test.cpp +++ b/runtime/test/vk_store_test.cpp | |||
| @@ -29,6 +29,7 @@ | |||
| 29 | #include "vk_shader_fma.h" | 29 | #include "vk_shader_fma.h" |
| 30 | #include "vk_pc_tail.h" | 30 | #include "vk_pc_tail.h" |
| 31 | #include "spirv_capability.h" | 31 | #include "spirv_capability.h" |
| 32 | #include "../src/descriptor_table.h" | ||
| 32 | #include "../src/gfx10_descriptors.h" | 33 | #include "../src/gfx10_descriptors.h" |
| 33 | 34 | ||
| 34 | #include <cmath> | 35 | #include <cmath> |
| @@ -54,7 +55,10 @@ static uint32_t key_hash(const uint32_t k[8]) { // same FNV-1a as the transl | |||
| 54 | return h; | 55 | return h; |
| 55 | } | 56 | } |
| 56 | 57 | ||
| 57 | static void table_insert(std::vector<uint32_t>& t, const uint32_t key[8], uint32_t index) { | 58 | // `kind` is what the translated modules read next to the index (descriptor_table.h): the arrays this image is |
| 59 | // bound in, sampled and storage. | ||
| 60 | static void table_insert(std::vector<uint32_t>& t, const uint32_t key[8], uint32_t index, | ||
| 61 | uint32_t kind) { | ||
| 58 | uint32_t mask = t[0], h = key_hash(key); | 62 | uint32_t mask = t[0], h = key_hash(key); |
| 59 | for (uint32_t k = 0; k < 8; k++) { | 63 | for (uint32_t k = 0; k < 8; k++) { |
| 60 | uint32_t base = ((h + k) & mask) * 10; | 64 | uint32_t base = ((h + k) & mask) * 10; |
| @@ -63,6 +67,7 @@ static void table_insert(std::vector<uint32_t>& t, const uint32_t key[8], uint32 | |||
| 63 | if (used) continue; | 67 | if (used) continue; |
| 64 | for (int j = 0; j < 8; j++) t[base + 1 + j] = key[j]; | 68 | for (int j = 0; j < 8; j++) t[base + 1 + j] = key[j]; |
| 65 | t[base + 9] = index; | 69 | t[base + 9] = index; |
| 70 | t[base + 10] = kind; | ||
| 66 | return; | 71 | return; |
| 67 | } | 72 | } |
| 68 | } | 73 | } |
| @@ -236,10 +241,10 @@ int main(int argc, char** argv) { | |||
| 236 | for (uint32_t k = 0; k < 3; k++) { | 241 | for (uint32_t k = 0; k < 3; k++) { |
| 237 | uint32_t t[8] = {0x1000 * (k + 1), fmts[k] << 20}; | 242 | uint32_t t[8] = {0x1000 * (k + 1), fmts[k] << 20}; |
| 238 | for (int j = 2; j < 8; j++) t[j] = 0x11 * (k + 1); | 243 | for (int j = 2; j < 8; j++) t[j] = 0x11 * (k + 1); |
| 239 | table_insert(table, t, k + 1); // its index in the 2D arrays; 0 is the fallback, as in the runtime | 244 | table_insert(table, t, k + 1, leonida::kind_sampled_bit(0) | leonida::kind_storage_bit(0)); // its index in the 2D arrays; 0 is the fallback, as in the runtime |
| 240 | if (cube_mode) { // the cube T# (cs_imgstore_cube.asm): word3 also has TYPE = 0xB, index k + 1 of the 2D arrays | 245 | if (cube_mode) { // the cube T# (cs_imgstore_cube.asm): word3 also has TYPE = 0xB, index k + 1 of the 2D arrays |
| 241 | t[3] |= 0xB0000000u; | 246 | t[3] |= 0xB0000000u; |
| 242 | table_insert(table, t, k + 1); | 247 | table_insert(table, t, k + 1, leonida::kind_sampled_bit(0) | leonida::kind_storage_bit(0)); |
| 243 | } | 248 | } |
| 244 | } | 249 | } |
| 245 | // Index 4: a 16x4 rgba8 image with its whole mip chain (16x4, 8x2, 4x1, 2x1, 1x1) for image_get_resinfo. Its key | 250 | // Index 4: a 16x4 rgba8 image with its whole mip chain (16x4, 8x2, 4x1, 2x1, 1x1) for image_get_resinfo. Its key |
| @@ -249,13 +254,13 @@ int main(int argc, char** argv) { | |||
| 249 | wide_desc.address = 0x400000; wide_desc.format = fmts[0]; wide_desc.width = WIDE_W; wide_desc.height = WIDE_H; | 254 | wide_desc.address = 0x400000; wide_desc.format = fmts[0]; wide_desc.width = WIDE_W; wide_desc.height = WIDE_H; |
| 250 | wide_desc.mip_count = wide_desc.resource_mips = WIDE_MIPS; | 255 | wide_desc.mip_count = wide_desc.resource_mips = WIDE_MIPS; |
| 251 | const leonida::gfx10::ImageWords wide_key = leonida::gfx10::encode(wide_desc); | 256 | const leonida::gfx10::ImageWords wide_key = leonida::gfx10::encode(wide_desc); |
| 252 | table_insert(table, wide_key.data(), 4); | 257 | table_insert(table, wide_key.data(), 4, leonida::kind_sampled_bit(0)); // image_get_resinfo reads binding 0 |
| 253 | // The volume of the 3D atomics: index 1 of the 3D arrays, behind a T# of the 2D images' pattern (k = 4). | 258 | // The volume of the 3D atomics: index 1 of the 3D arrays, behind a T# of the 2D images' pattern (k = 4). |
| 254 | const uint32_t VOL = 4; | 259 | const uint32_t VOL = 4; |
| 255 | { | 260 | { |
| 256 | // The volume uses the D3D12 layer's whole-mip UAV tag (FirstWSlice=0, WSize=4). | 261 | // The volume uses the D3D12 layer's whole-mip UAV tag (FirstWSlice=0, WSize=4). |
| 257 | uint32_t t[8] = {0x5000, fmts[1] << 20, 0x55, 0x55, 0x80000055, 0x55, 0x55, 0xd7801800}; | 262 | uint32_t t[8] = {0x5000, fmts[1] << 20, 0x55, 0x55, 0x80000055, 0x55, 0x55, 0xd7801800}; |
| 258 | table_insert(table, t, 1); | 263 | table_insert(table, t, 1, leonida::kind_sampled_bit(2) | leonida::kind_storage_bit(2)); |
| 259 | } | 264 | } |
| 260 | VkBuffer tb; void* tbp; | 265 | VkBuffer tb; void* tbp; |
| 261 | CHECK(make_buffer(table.size() * 4, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, &tb, &tbp)); | 266 | CHECK(make_buffer(table.size() * 4, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, &tb, &tbp)); |
diff --git a/runtime/test/vk_test_device.h b/runtime/test/vk_test_device.h index fd63fca66..eb1be0a2c 100644 --- a/runtime/test/vk_test_device.h +++ b/runtime/test/vk_test_device.h | |||
| @@ -130,6 +130,7 @@ public: | |||
| 130 | std::uint32_t max_draw_indirect_count = 0; | 130 | std::uint32_t max_draw_indirect_count = 0; |
| 131 | bool request_draw_indirect_first_instance = false; // enable the core feature only for positive indirect draws | 131 | bool request_draw_indirect_first_instance = false; // enable the core feature only for positive indirect draws |
| 132 | bool request_debug_utils = false; // set before create(): enable VK_EXT_debug_utils when the loader has it | 132 | bool request_debug_utils = false; // set before create(): enable VK_EXT_debug_utils when the loader has it |
| 133 | bool pipeline_cache_control() const { return v13_.core && v13_.pipeline_creation_cache_control; } | ||
| 133 | bool request_buffer_device_address = false; // set before create(): enable bufferDeviceAddress where supported | 134 | bool request_buffer_device_address = false; // set before create(): enable bufferDeviceAddress where supported |
| 134 | bool buffer_device_address = false; // enabled: buffer() memory and buffers can be addressed (device_address()) | 135 | bool buffer_device_address = false; // enabled: buffer() memory and buffers can be addressed (device_address()) |
| 135 | bool conservative_rasterization = false; // VK_EXT_conservative_rasterization enabled where available | 136 | bool conservative_rasterization = false; // VK_EXT_conservative_rasterization enabled where available |
| @@ -142,6 +143,8 @@ public: | |||
| 142 | bool custom_border_color = false; // VK_EXT_custom_border_color and customBorderColors enabled | 143 | bool custom_border_color = false; // VK_EXT_custom_border_color and customBorderColors enabled |
| 143 | bool custom_border_color_without_format = false; | 144 | bool custom_border_color_without_format = false; |
| 144 | bool shader_output_viewport_index = false; // Vulkan 1.2 shaderOutputViewportIndex enabled | 145 | bool shader_output_viewport_index = false; // Vulkan 1.2 shaderOutputViewportIndex enabled |
| 146 | bool request_buffer_marker = false; // set before initialize(): enable VK_AMD_buffer_marker where available | ||
| 147 | bool buffer_marker = false; // VK_AMD_buffer_marker is enabled | ||
| 145 | bool request_null_descriptor = false; // set before initialize(): enable VK_EXT_robustness2 nullDescriptor | 148 | bool request_null_descriptor = false; // set before initialize(): enable VK_EXT_robustness2 nullDescriptor |
| 146 | bool null_descriptor = false; // VK_EXT_robustness2 and nullDescriptor are enabled | 149 | bool null_descriptor = false; // VK_EXT_robustness2 and nullDescriptor are enabled |
| 147 | // VK_EXT_external_memory_host is enabled when non-zero: its minImportedHostPointerAlignment. | 150 | // VK_EXT_external_memory_host is enabled when non-zero: its minImportedHostPointerAlignment. |
| @@ -189,6 +192,7 @@ public: | |||
| 189 | 192 | ||
| 190 | unsigned validation_errors() const { return validation_error_count(); } | 193 | unsigned validation_errors() const { return validation_error_count(); } |
| 191 | unsigned known_validation_errors() const { return known_validation_error_count(); } | 194 | unsigned known_validation_errors() const { return known_validation_error_count(); } |
| 195 | bool pipeline_cache_control_enabled() const { return v13_.core && v13_.pipeline_creation_cache_control; } | ||
| 192 | 196 | ||
| 193 | // presentation: also enable VK_KHR_surface + VK_KHR_win32_surface and VK_KHR_swapchain (Windows only). | 197 | // presentation: also enable VK_KHR_surface + VK_KHR_win32_surface and VK_KHR_swapchain (Windows only). |
| 194 | bool create(bool presentation = false) { return initialize(presentation) == DeviceStatus::ready; } | 198 | bool create(bool presentation = false) { return initialize(presentation) == DeviceStatus::ready; } |
| @@ -492,6 +496,7 @@ private: | |||
| 492 | enable.multiViewport = features.features.multiViewport; // d3d12_multi_viewport_test, where available | 496 | enable.multiViewport = features.features.multiViewport; // d3d12_multi_viewport_test, where available |
| 493 | enable.geometryShader = features.features.geometryShader; // d3d12_geometry_test, where available | 497 | enable.geometryShader = features.features.geometryShader; // d3d12_geometry_test, where available |
| 494 | enable.dualSrcBlend = features.features.dualSrcBlend; // d3d12_translated_draw_test --dual-source | 498 | enable.dualSrcBlend = features.features.dualSrcBlend; // d3d12_translated_draw_test --dual-source |
| 499 | enable.depthBounds = features.features.depthBounds; // depth-bounds PSOs (d3d12_mesh_test), where available | ||
| 495 | const char* conditional_extension = VK_EXT_CONDITIONAL_RENDERING_EXTENSION_NAME; | 500 | const char* conditional_extension = VK_EXT_CONDITIONAL_RENDERING_EXTENSION_NAME; |
| 496 | 501 | ||
| 497 | // VK_EXT_host_image_copy where the device has it, for the D3D12 layer's CPU texture copies. | 502 | // VK_EXT_host_image_copy where the device has it, for the D3D12 layer's CPU texture copies. |
| @@ -767,6 +772,10 @@ private: | |||
| 767 | if (custom_border_color) device_extensions.push_back(custom_border_color_name); | 772 | if (custom_border_color) device_extensions.push_back(custom_border_color_name); |
| 768 | if (null_descriptor || robust_index_view) device_extensions.push_back(VK_EXT_ROBUSTNESS_2_EXTENSION_NAME); | 773 | if (null_descriptor || robust_index_view) device_extensions.push_back(VK_EXT_ROBUSTNESS_2_EXTENSION_NAME); |
| 769 | if (mesh_shader) device_extensions.push_back(VK_EXT_MESH_SHADER_EXTENSION_NAME); | 774 | if (mesh_shader) device_extensions.push_back(VK_EXT_MESH_SHADER_EXTENSION_NAME); |
| 775 | buffer_marker = request_buffer_marker && std::any_of(extensions.begin(), extensions.end(), [](const auto& e) { | ||
| 776 | return std::strcmp(e.extensionName, VK_AMD_BUFFER_MARKER_EXTENSION_NAME) == 0; | ||
| 777 | }); | ||
| 778 | if (buffer_marker) device_extensions.push_back(VK_AMD_BUFFER_MARKER_EXTENSION_NAME); | ||
| 770 | device_info.enabledExtensionCount = std::uint32_t(device_extensions.size()); | 779 | device_info.enabledExtensionCount = std::uint32_t(device_extensions.size()); |
| 771 | device_info.ppEnabledExtensionNames = device_extensions.data(); | 780 | device_info.ppEnabledExtensionNames = device_extensions.data(); |
| 772 | result = instance_fn<PFN_vkCreateDevice>("vkCreateDevice")(physical, &device_info, nullptr, &device); | 781 | result = instance_fn<PFN_vkCreateDevice>("vkCreateDevice")(physical, &device_info, nullptr, &device); |
diff --git a/runtime/test/vk_texture_test.cpp b/runtime/test/vk_texture_test.cpp index 3dafcaef6..97e93cb04 100644 --- a/runtime/test/vk_texture_test.cpp +++ b/runtime/test/vk_texture_test.cpp | |||
| @@ -327,7 +327,10 @@ int main(int argc, char** argv) { | |||
| 327 | leonida::DescriptorTable desc_table(16); | 327 | leonida::DescriptorTable desc_table(16); |
| 328 | // The heap already holds the original key. Change only the registered key for the miss control. | 328 | // The heap already holds the original key. Change only the registered key for the miss control. |
| 329 | if (fetch_miss) tsharp[7] ^= 1; | 329 | if (fetch_miss) tsharp[7] ^= 1; |
| 330 | desc_table.insert(tsharp, 1); | 330 | // Index 1 is bound in both sampled arrays the shaders read: images[1] (binding 0, the 2D view) and the 2D-array |
| 331 | // images[1] (binding 3, the view of the two cubes). A tagged module reads its instruction's array only when the | ||
| 332 | // entry's kind names it, so the kind carries both: with one bit, a 2D_ARRAY or cube op got the 1x1 fallback. | ||
| 333 | desc_table.insert(tsharp, 1, leonida::kind_sampled_bit(0) | leonida::kind_sampled_bit(1)); | ||
| 331 | desc_table.insert(ssharp, 1); | 334 | desc_table.insert(ssharp, 1); |
| 332 | const auto table = desc_table.build_gpu_buffer(true); | 335 | const auto table = desc_table.build_gpu_buffer(true); |
| 333 | VkBuffer tb; VkDeviceMemory tbm; void* tbp; | 336 | VkBuffer tb; VkDeviceMemory tbm; void* tbp; |
diff --git a/runtime/test/vulkan_device_markers_test.cpp b/runtime/test/vulkan_device_markers_test.cpp new file mode 100644 index 000000000..64693a83d --- /dev/null +++ b/runtime/test/vulkan_device_markers_test.cpp | |||
| @@ -0,0 +1,300 @@ | |||
| 1 | // The AMD breadcrumbs of the device-fault report (src/vulkan_device_markers.h, LEONIDA_DEVICE_MARKERS=1), on the | ||
| 2 | // CPU: seq numbering, the marker writes a recorded dispatch makes, the history ring, and which dispatch the report | ||
| 3 | // calls the likely hang for given marker values. The driver is faked: its marker writes are logged, and a "GPU" | ||
| 4 | // applies a prefix of them to the mapped words, as a queue that stopped at that point would have. No GPU, no game | ||
| 5 | // data. | ||
| 6 | #include "../src/vulkan_device_fault.h" | ||
| 7 | |||
| 8 | #include <cstdint> | ||
| 9 | #include <cstdio> | ||
| 10 | #include <cstring> | ||
| 11 | #include <type_traits> | ||
| 12 | #include <vector> | ||
| 13 | |||
| 14 | #define EXPECT(condition) do { \ | ||
| 15 | if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ | ||
| 16 | } while (0) | ||
| 17 | |||
| 18 | using namespace leonida; | ||
| 19 | |||
| 20 | namespace { | ||
| 21 | |||
| 22 | template<typename Handle> | ||
| 23 | Handle fake_handle(std::uintptr_t value) { | ||
| 24 | if constexpr (std::is_pointer_v<Handle>) return reinterpret_cast<Handle>(value); | ||
| 25 | else return Handle(value); | ||
| 26 | } | ||
| 27 | |||
| 28 | struct Write { | ||
| 29 | VkCommandBuffer command_buffer; | ||
| 30 | std::uint64_t stage; | ||
| 31 | VkDeviceSize offset; | ||
| 32 | std::uint32_t marker; | ||
| 33 | }; | ||
| 34 | std::vector<Write> writes; | ||
| 35 | std::uint32_t words[2 * DeviceMarkers::max_queues]; | ||
| 36 | bool mapped = false, unmapped = false, freed = false; | ||
| 37 | |||
| 38 | VKAPI_ATTR VkResult VKAPI_CALL create_buffer(VkDevice, const VkBufferCreateInfo* info, const VkAllocationCallbacks*, | ||
| 39 | VkBuffer* buffer) { | ||
| 40 | if (info->size < sizeof(words)) return VK_ERROR_UNKNOWN; | ||
| 41 | *buffer = fake_handle<VkBuffer>(0x100); | ||
| 42 | return VK_SUCCESS; | ||
| 43 | } | ||
| 44 | VKAPI_ATTR void VKAPI_CALL requirements(VkDevice, VkBuffer, VkMemoryRequirements* out) { | ||
| 45 | *out = {sizeof(words), 4, 0x6}; | ||
| 46 | } | ||
| 47 | VKAPI_ATTR VkResult VKAPI_CALL allocate(VkDevice, const VkMemoryAllocateInfo* info, const VkAllocationCallbacks*, | ||
| 48 | VkDeviceMemory* memory) { | ||
| 49 | if (info->memoryTypeIndex != 2) return VK_ERROR_UNKNOWN; // host-visible, coherent, not device-local | ||
| 50 | *memory = fake_handle<VkDeviceMemory>(0x200); | ||
| 51 | return VK_SUCCESS; | ||
| 52 | } | ||
| 53 | VKAPI_ATTR VkResult VKAPI_CALL bind(VkDevice, VkBuffer, VkDeviceMemory, VkDeviceSize) { return VK_SUCCESS; } | ||
| 54 | VKAPI_ATTR VkResult VKAPI_CALL map(VkDevice, VkDeviceMemory, VkDeviceSize, VkDeviceSize, VkMemoryMapFlags, void** out) { | ||
| 55 | std::memset(words, 0xcd, sizeof(words)); | ||
| 56 | *out = words; | ||
| 57 | mapped = true; | ||
| 58 | return VK_SUCCESS; | ||
| 59 | } | ||
| 60 | VKAPI_ATTR void VKAPI_CALL unmap(VkDevice, VkDeviceMemory) { unmapped = true; } | ||
| 61 | VKAPI_ATTR void VKAPI_CALL destroy_buffer(VkDevice, VkBuffer, const VkAllocationCallbacks*) {} | ||
| 62 | VKAPI_ATTR void VKAPI_CALL free_memory(VkDevice, VkDeviceMemory, const VkAllocationCallbacks*) { freed = true; } | ||
| 63 | VKAPI_ATTR void VKAPI_CALL write_marker2(VkCommandBuffer command_buffer, VkPipelineStageFlags2 stage, VkBuffer, | ||
| 64 | VkDeviceSize offset, std::uint32_t marker) { | ||
| 65 | writes.push_back({command_buffer, stage, offset, marker}); | ||
| 66 | } | ||
| 67 | VKAPI_ATTR void VKAPI_CALL write_marker(VkCommandBuffer command_buffer, VkPipelineStageFlagBits stage, VkBuffer buffer, | ||
| 68 | VkDeviceSize offset, std::uint32_t marker) { | ||
| 69 | write_marker2(command_buffer, stage, buffer, offset, marker); | ||
| 70 | } | ||
| 71 | |||
| 72 | VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL get_proc(VkDevice, const char* name) { | ||
| 73 | #define LEONIDA_FAKE(entry, fn) if (!std::strcmp(name, entry)) return reinterpret_cast<PFN_vkVoidFunction>(fn) | ||
| 74 | LEONIDA_FAKE("vkCreateBuffer", create_buffer); | ||
| 75 | LEONIDA_FAKE("vkGetBufferMemoryRequirements", requirements); | ||
| 76 | LEONIDA_FAKE("vkAllocateMemory", allocate); | ||
| 77 | LEONIDA_FAKE("vkBindBufferMemory", bind); | ||
| 78 | LEONIDA_FAKE("vkMapMemory", map); | ||
| 79 | LEONIDA_FAKE("vkUnmapMemory", unmap); | ||
| 80 | LEONIDA_FAKE("vkDestroyBuffer", destroy_buffer); | ||
| 81 | LEONIDA_FAKE("vkFreeMemory", free_memory); | ||
| 82 | LEONIDA_FAKE("vkCmdWriteBufferMarkerAMD", write_marker); | ||
| 83 | LEONIDA_FAKE("vkCmdWriteBufferMarker2AMD", write_marker2); | ||
| 84 | #undef LEONIDA_FAKE | ||
| 85 | return nullptr; | ||
| 86 | } | ||
| 87 | |||
| 88 | VkPhysicalDeviceMemoryProperties memory_types() { | ||
| 89 | VkPhysicalDeviceMemoryProperties memory{}; | ||
| 90 | memory.memoryTypeCount = 4; | ||
| 91 | memory.memoryTypes[0].propertyFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT; | ||
| 92 | memory.memoryTypes[1].propertyFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | | ||
| 93 | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT; | ||
| 94 | memory.memoryTypes[2].propertyFlags = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT; | ||
| 95 | memory.memoryTypes[3].propertyFlags = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT | | ||
| 96 | VK_MEMORY_PROPERTY_HOST_CACHED_BIT; | ||
| 97 | return memory; | ||
| 98 | } | ||
| 99 | |||
| 100 | // The "GPU": runs the first `count` logged marker writes, in order. | ||
| 101 | void execute(std::size_t count) { | ||
| 102 | for (std::size_t i = 0; i < count && i < writes.size(); ++i) | ||
| 103 | words[writes[i].offset / 4] = writes[i].marker; | ||
| 104 | } | ||
| 105 | |||
| 106 | struct History { // a plain list in MarkerHistory::for_each order, for judge_markers | ||
| 107 | std::vector<MarkedDispatch> entries; | ||
| 108 | template<typename Visit> | ||
| 109 | void for_each(Visit&& visit) const { | ||
| 110 | for (const auto& d : entries) visit(d); | ||
| 111 | } | ||
| 112 | }; | ||
| 113 | |||
| 114 | int pure_logic() { | ||
| 115 | // Serial order on the 32 bits the GPU writes, across the wrap. | ||
| 116 | EXPECT(marker_after(5, 4) && !marker_after(4, 4) && !marker_after(3, 4)); | ||
| 117 | EXPECT(marker_after(0x100000002ull, 0xfffffffeu)); // seq 2^32 + 2 is after marker 2^32 - 2 | ||
| 118 | EXPECT(!marker_after(0xfffffffeull, 0x00000003u)); // and 2^32 - 2 is before a wrapped 3 | ||
| 119 | |||
| 120 | // The history ring keeps the newest `capacity`, oldest first. | ||
| 121 | MarkerHistory ring; | ||
| 122 | EXPECT(ring.size() == 0); | ||
| 123 | for (std::uint64_t seq = 1; seq <= MarkerHistory::capacity + 5; ++seq) ring.push({seq}); | ||
| 124 | EXPECT(ring.size() == MarkerHistory::capacity); | ||
| 125 | std::uint64_t expect = 6, visited = 0; | ||
| 126 | bool ordered = true; | ||
| 127 | ring.for_each([&](const MarkedDispatch& d) { ordered &= d.seq == expect++; ++visited; }); | ||
| 128 | EXPECT(ordered && visited == MarkerHistory::capacity); | ||
| 129 | |||
| 130 | // Two queues interleaved: compute has 1 3 5 6 8, direct has 2 4 7. | ||
| 131 | const VkQueue compute = fake_handle<VkQueue>(0x10), direct = fake_handle<VkQueue>(0x20); | ||
| 132 | History history; | ||
| 133 | for (std::uint64_t seq : {1, 3, 5, 6, 8}) history.entries.push_back({seq, 1, compute, "compute"}); | ||
| 134 | for (std::uint64_t seq : {2, 4, 7}) history.entries.push_back({seq, 2, direct, "direct"}); | ||
| 135 | std::sort(history.entries.begin(), history.entries.end(), | ||
| 136 | [](const auto& a, const auto& b) { return a.seq < b.seq; }); | ||
| 137 | |||
| 138 | // compute finished 3, started 6: 5 and 6 run, 5 is the likely hang; 8 was submitted and not started. | ||
| 139 | auto r = judge_markers(compute, {6, 3}, history); | ||
| 140 | EXPECT(!r.idle() && r.unfinished == std::vector<std::uint64_t>({5, 6}) && r.likely_hang == 5 && !r.missing); | ||
| 141 | EXPECT(r.next_queued == 0 && r.queue_kind && !std::strcmp(r.queue_kind, "compute")); | ||
| 142 | // One dispatch started and not finished. | ||
| 143 | r = judge_markers(compute, {5, 3}, history); | ||
| 144 | EXPECT(r.unfinished == std::vector<std::uint64_t>({5}) && r.likely_hang == 5); | ||
| 145 | // direct idle after 4: nothing reported as hung, 7 is the next one it had queued. | ||
| 146 | r = judge_markers(direct, {4, 4}, history); | ||
| 147 | EXPECT(r.idle() && r.unfinished.empty() && !r.likely_hang && r.next_queued == 7 && !r.missing); | ||
| 148 | // Everything done. | ||
| 149 | r = judge_markers(direct, {7, 7}, history); | ||
| 150 | EXPECT(r.idle() && !r.likely_hang && !r.next_queued); | ||
| 151 | // Started past the history's newest dispatch of the queue: nothing to name. | ||
| 152 | r = judge_markers(compute, {9, 8}, history); | ||
| 153 | EXPECT(r.missing && !r.likely_hang && r.unfinished.empty()); | ||
| 154 | // A started word behind the finished one (memory a reset scrambled) is read as idle, not as a hang. | ||
| 155 | r = judge_markers(compute, {1, 5}, history); | ||
| 156 | EXPECT(r.idle() && !r.likely_hang && r.next_queued == 6); | ||
| 157 | // No marker yet: every dispatch of the queue is queued, none hung. | ||
| 158 | r = judge_markers(compute, {0, 0}, history); | ||
| 159 | EXPECT(r.idle() && r.next_queued == 1 && !r.likely_hang); | ||
| 160 | // A queue the history does not know. | ||
| 161 | r = judge_markers(fake_handle<VkQueue>(0x30), {0, 0}, history); | ||
| 162 | EXPECT(!r.queue_kind && !r.next_queued); | ||
| 163 | |||
| 164 | // Across the 32-bit wrap: seqs 2^32 - 1, 2^32, 2^32 + 1 on one queue; markers hold their low 32 bits. | ||
| 165 | History wrapped; | ||
| 166 | for (std::uint64_t seq : {0xffffffffull, 0x100000000ull, 0x100000001ull}) | ||
| 167 | wrapped.entries.push_back({seq, 1, compute, "compute"}); | ||
| 168 | r = judge_markers(compute, {0x00000001u, 0xffffffffu}, wrapped); | ||
| 169 | EXPECT(r.unfinished == std::vector<std::uint64_t>({0x100000000ull, 0x100000001ull}) && | ||
| 170 | r.likely_hang == 0x100000000ull); | ||
| 171 | |||
| 172 | // Memory type: host-visible and coherent, system memory first. | ||
| 173 | const auto memory = memory_types(); | ||
| 174 | EXPECT(DeviceMarkers::memory_type(memory, 0xf) == 2); | ||
| 175 | EXPECT(DeviceMarkers::memory_type(memory, 0x3) == 1); // only device-local ones allowed: the BAR one | ||
| 176 | EXPECT(DeviceMarkers::memory_type(memory, 0x1) == UINT32_MAX); | ||
| 177 | return 0; | ||
| 178 | } | ||
| 179 | |||
| 180 | // Recording through CheckpointRecorder with the markers on, then the report's verdict for a stopped "GPU". | ||
| 181 | int recorded(bool synchronization2) { | ||
| 182 | writes.clear(); | ||
| 183 | mapped = unmapped = freed = false; | ||
| 184 | const auto memory = memory_types(); | ||
| 185 | DeviceFaultExtensions enabled; | ||
| 186 | enabled.markers = true; | ||
| 187 | const VkQueue compute = fake_handle<VkQueue>(0x10), direct = fake_handle<VkQueue>(0x20); | ||
| 188 | const VkCommandBuffer cb = fake_handle<VkCommandBuffer>(0x30); | ||
| 189 | { | ||
| 190 | DeviceFaultDiagnostics diagnostics(get_proc, VK_NULL_HANDLE, enabled, &memory, synchronization2); | ||
| 191 | EXPECT(diagnostics.markers_on() && mapped); | ||
| 192 | diagnostics.add_queue(compute); | ||
| 193 | diagnostics.add_queue(direct); | ||
| 194 | diagnostics.add_queue(compute); // once is enough | ||
| 195 | EXPECT(words[0] == 0 && words[3] == 0); // the slots start at no dispatch | ||
| 196 | diagnostics.pipeline_names[4] = {"cs_example_a"}; | ||
| 197 | diagnostics.pipeline_names[5] = {"cs_example_b"}; | ||
| 198 | const std::array<std::uint32_t, 32> roots{}; | ||
| 199 | |||
| 200 | // Submission 1 on the compute queue: seqs 1..3. Submission 2 on the direct queue: 4..5. | ||
| 201 | auto first = diagnostics.begin_submission(diagnostics.next_execute_call(), compute, "compute", 1); | ||
| 202 | EXPECT(first.markers && first.markers.offset == 0); | ||
| 203 | const CheckpointRecorder a{nullptr, first, diagnostics.pipeline_names, 0}; | ||
| 204 | for (unsigned i = 0; i < 3; ++i) { | ||
| 205 | a.dispatch(cb, 10 + i, VK_NULL_HANDLE, i == 1 ? 5 : 4, roots, {1, 1, 1}); | ||
| 206 | a.dispatched(cb); | ||
| 207 | } | ||
| 208 | a.dispatched(cb); // nothing open: no write | ||
| 209 | EXPECT(writes.size() == 6); | ||
| 210 | auto second = diagnostics.begin_submission(diagnostics.next_execute_call(), direct, "direct", 1); | ||
| 211 | EXPECT(second.markers && second.markers.offset == 8); | ||
| 212 | const CheckpointRecorder b{nullptr, second, diagnostics.pipeline_names, 0}; | ||
| 213 | for (unsigned i = 0; i < 2; ++i) { | ||
| 214 | b.dispatch(cb, 20 + i, VK_NULL_HANDLE, 4, roots, {}, true, 1, 0, 0, 0, 1, 12); | ||
| 215 | b.dispatched(cb); | ||
| 216 | } | ||
| 217 | EXPECT(writes.size() == 10); | ||
| 218 | // Each dispatch: started (top of pipe, slot +0) then finished (bottom of pipe, slot +4), with its seq. | ||
| 219 | for (std::size_t i = 0; i < writes.size(); ++i) { | ||
| 220 | const Write& w = writes[i]; | ||
| 221 | const std::uint32_t seq = std::uint32_t(i / 2 + 1); | ||
| 222 | const bool top = i % 2 == 0; | ||
| 223 | const VkDeviceSize slot = seq <= 3 ? 0 : 8; | ||
| 224 | const std::uint64_t top_stage = synchronization2 ? VK_PIPELINE_STAGE_2_TOP_OF_PIPE_BIT | ||
| 225 | : VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT; | ||
| 226 | const std::uint64_t bottom_stage = synchronization2 ? VK_PIPELINE_STAGE_2_BOTTOM_OF_PIPE_BIT | ||
| 227 | : VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT; | ||
| 228 | EXPECT(w.marker == seq && w.command_buffer == cb && w.offset == slot + (top ? 0 : 4) && | ||
| 229 | w.stage == (top ? top_stage : bottom_stage)); | ||
| 230 | } | ||
| 231 | // The report's list numbers them the same way. | ||
| 232 | EXPECT(first.dispatches.size() == 3 && first.dispatches[0].seq == 1 && first.dispatches[2].seq == 3); | ||
| 233 | EXPECT(second.dispatches.size() == 2 && second.dispatches[1].seq == 5); | ||
| 234 | EXPECT(first.marked.size() == 3 && first.marked[1].shader && !std::strcmp(first.marked[1].shader, "cs_example_b")); | ||
| 235 | diagnostics.publish(std::move(first)); | ||
| 236 | diagnostics.publish(std::move(second)); | ||
| 237 | |||
| 238 | // Nothing has run: no queue is reported as hung. | ||
| 239 | EXPECT(diagnostics.report_markers(false).empty()); | ||
| 240 | // The compute queue stopped inside seq 2 (its started write ran, its finished one did not); the direct queue | ||
| 241 | // ran seq 4 completely and stopped inside 5. | ||
| 242 | execute(3); // seq 1 started and finished, seq 2 started | ||
| 243 | words[2] = 4; words[3] = 4; // direct: seq 4 done | ||
| 244 | words[2] = 5; // seq 5 started | ||
| 245 | auto hangs = diagnostics.report_markers(true); | ||
| 246 | EXPECT(hangs == std::vector<std::uint64_t>({2, 5})); | ||
| 247 | diagnostics.report_stall("synthetic marker check", 2, 1); // the list marks seq 2 and 5 as likely hangs | ||
| 248 | // Everything finished: no hang. | ||
| 249 | execute(writes.size()); | ||
| 250 | EXPECT(diagnostics.report_markers(false).empty()); | ||
| 251 | const MarkerSlot compute_slot = diagnostics.marker_slot(compute), direct_slot = diagnostics.marker_slot(direct); | ||
| 252 | EXPECT(compute_slot.started == 3 && compute_slot.finished == 3); | ||
| 253 | EXPECT(direct_slot.started == 5 && direct_slot.finished == 5); | ||
| 254 | } | ||
| 255 | EXPECT(unmapped && freed); | ||
| 256 | return 0; | ||
| 257 | } | ||
| 258 | |||
| 259 | // Without LEONIDA_DEVICE_MARKERS the extension is not asked for, and with it only where the device has it. | ||
| 260 | int extension_request() { | ||
| 261 | const VkExtensionProperties with[] = {{VK_AMD_BUFFER_MARKER_EXTENSION_NAME, 1}}; | ||
| 262 | VkDeviceCreateInfo device{VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO}; | ||
| 263 | const auto no_features = [](VkPhysicalDevice, VkPhysicalDeviceFeatures2*) {}; | ||
| 264 | DeviceFaultFeatures features; | ||
| 265 | std::vector<const char*> extensions; | ||
| 266 | DeviceFaultRequest request; | ||
| 267 | EXPECT(!features.enable(VK_NULL_HANDLE, no_features, with, extensions, device, request).markers); | ||
| 268 | EXPECT(extensions.empty()); | ||
| 269 | request.markers = true; | ||
| 270 | EXPECT(!features.enable(VK_NULL_HANDLE, no_features, {}, extensions, device, request).markers); | ||
| 271 | EXPECT(extensions.empty()); | ||
| 272 | EXPECT(features.enable(VK_NULL_HANDLE, no_features, with, extensions, device, request).markers); | ||
| 273 | EXPECT(extensions.size() == 1 && !std::strcmp(extensions[0], VK_AMD_BUFFER_MARKER_EXTENSION_NAME)); | ||
| 274 | |||
| 275 | // Markers enabled but no memory types given: off, the rest of the report unchanged. | ||
| 276 | DeviceFaultExtensions enabled; | ||
| 277 | enabled.markers = true; | ||
| 278 | DeviceFaultDiagnostics diagnostics(get_proc, VK_NULL_HANDLE, enabled); | ||
| 279 | EXPECT(!diagnostics.markers_on()); | ||
| 280 | auto submission = diagnostics.begin_submission(diagnostics.next_execute_call(), VK_NULL_HANDLE, "compute", 1); | ||
| 281 | EXPECT(!submission.markers); | ||
| 282 | writes.clear(); | ||
| 283 | const CheckpointRecorder recorder{nullptr, submission, diagnostics.pipeline_names, 0}; | ||
| 284 | recorder.dispatch(VK_NULL_HANDLE, 0, VK_NULL_HANDLE, 0, {}, {1, 1, 1}); | ||
| 285 | recorder.dispatched(VK_NULL_HANDLE); | ||
| 286 | EXPECT(writes.empty() && submission.dispatches[0].seq == 1 && submission.marked.empty()); | ||
| 287 | EXPECT(diagnostics.report_markers(true).empty()); | ||
| 288 | return 0; | ||
| 289 | } | ||
| 290 | |||
| 291 | } // namespace | ||
| 292 | |||
| 293 | int main() { | ||
| 294 | if (int failed = pure_logic()) return failed; | ||
| 295 | if (int failed = recorded(true)) return failed; | ||
| 296 | if (int failed = recorded(false)) return failed; | ||
| 297 | if (int failed = extension_request()) return failed; | ||
| 298 | std::puts("vulkan_device_markers: ok"); | ||
| 299 | return 0; | ||
| 300 | } | ||
diff --git a/runtime/test/xbox_bvh_builder_test.cpp b/runtime/test/xbox_bvh_builder_test.cpp index 3deb816b4..8334143fd 100644 --- a/runtime/test/xbox_bvh_builder_test.cpp +++ b/runtime/test/xbox_bvh_builder_test.cpp | |||
| @@ -5,7 +5,9 @@ | |||
| 5 | // `python -I tools/xdxr_bvh.py check-build <out dir>` (ctest: xbox_bvh_builder + xbox_bvh_builder_check), which | 5 | // `python -I tools/xdxr_bvh.py check-build <out dir>` (ctest: xbox_bvh_builder + xbox_bvh_builder_check), which |
| 6 | // checks the records and traces rays against brute force. Also checked: the shim's prebuild sizes are the layer's, | 6 | // checks the records and traces rays against brute force. Also checked: the shim's prebuild sizes are the layer's, |
| 7 | // an element asking for offline statistics is skipped and leaves its destination untouched, a non-empty XDXR stream | 7 | // an element asking for offline statistics is skipped and leaves its destination untouched, a non-empty XDXR stream |
| 8 | // is accepted, rehydration answers E_NOTIMPL, and builders are released. | 8 | // is accepted, rehydration rebuilds from geometry with S_OK (with the title's scratch, with none, and two elements of |
| 9 | // one batch without scratch, which the shim gives regions of their own; their structures go to check-build too) and | ||
| 10 | // refuses a source-only element, and builders are released. | ||
| 9 | // | 11 | // |
| 10 | // xbox_bvh_builder_test <out dir> the shim | 12 | // xbox_bvh_builder_test <out dir> the shim |
| 11 | // xbox_bvh_builder_test --console run with LEONIDA_BVH_BUILDER=console: nothing is registered | 13 | // xbox_bvh_builder_test --console run with LEONIDA_BVH_BUILDER=console: nothing is registered |
| @@ -373,11 +375,96 @@ int main(int argc, char** argv) { | |||
| 373 | list->CopyBufferRegion(compacted_rb.p, 0, compacted.p, 0, post[0]); | 375 | list->CopyBufferRegion(compacted_rb.p, 0, compacted.p, 0, post[0]); |
| 374 | if (!submit()) return fail("the compaction did not complete"); | 376 | if (!submit()) return fail("the compaction did not complete"); |
| 375 | 377 | ||
| 376 | // ---- RehydrateRaytracingAccelerationStructureBatched2X: not implemented yet ---- | 378 | // ---- RehydrateRaytracingAccelerationStructureBatched2X: rebuilds from geometry ---- |
| 379 | Ref<ID3D12Resource> rehydrated_as, rehydrated_rb; | ||
| 380 | if (FAILED(hr = buffer(device.p, D3D12_HEAP_TYPE_DEFAULT, blas_info.ResultDataMaxSizeInBytes, as_state, uav, | ||
| 381 | rehydrated_as.put())) || | ||
| 382 | FAILED(hr = buffer(device.p, D3D12_HEAP_TYPE_READBACK, blas_info.ResultDataMaxSizeInBytes, | ||
| 383 | D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_FLAG_NONE, rehydrated_rb.put()))) | ||
| 384 | return fail("rehydrated buffers", hr); | ||
| 385 | if (FAILED(allocator->Reset()) || FAILED(list->Reset(allocator.p, nullptr))) return fail("Reset for rehydrate"); | ||
| 386 | |||
| 377 | D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC rehydrate_desc{}; | 387 | D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC rehydrate_desc{}; |
| 388 | rehydrate_desc.DestAccelerationStructureData = rehydrated_as->GetGPUVirtualAddress(); | ||
| 389 | rehydrate_desc.Inputs = blas_inputs; | ||
| 390 | rehydrate_desc.ScratchAccelerationStructureData = scratch->GetGPUVirtualAddress(); | ||
| 378 | const UINT64 source = blas->GetGPUVirtualAddress(); | 391 | const UINT64 source = blas->GetGPUVirtualAddress(); |
| 379 | check(rehydrate(builder, list.p, 1, &rehydrate_desc, &source) == E_NOTIMPL, | 392 | |
| 380 | "RehydrateRaytracingAccelerationStructureBatched2X answers E_NOTIMPL (stage 2)"); | 393 | check(rehydrate(builder, nullptr, 1, &rehydrate_desc, &source) == E_INVALIDARG, |
| 394 | "RehydrateRaytracingAccelerationStructureBatched2X rejects null list"); | ||
| 395 | check(rehydrate(builder, list.p, 1, nullptr, &source) == E_INVALIDARG, | ||
| 396 | "RehydrateRaytracingAccelerationStructureBatched2X rejects null descs"); | ||
| 397 | check(rehydrate(builder, list.p, 0, nullptr, nullptr) == S_OK, | ||
| 398 | "RehydrateRaytracingAccelerationStructureBatched2X with count 0 returns S_OK"); | ||
| 399 | |||
| 400 | D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC source_only_desc{}; | ||
| 401 | source_only_desc.DestAccelerationStructureData = rehydrated_as->GetGPUVirtualAddress(); | ||
| 402 | check(rehydrate(builder, list.p, 1, &source_only_desc, &source) == E_NOTIMPL, | ||
| 403 | "RehydrateRaytracingAccelerationStructureBatched2X refuses source-only stream without geometry"); | ||
| 404 | |||
| 405 | D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC empty_desc{}; | ||
| 406 | check(rehydrate(builder, list.p, 1, &empty_desc, nullptr) == S_OK, | ||
| 407 | "RehydrateRaytracingAccelerationStructureBatched2X logs and skips empty structure"); | ||
| 408 | |||
| 409 | check(rehydrate(builder, list.p, 1, &rehydrate_desc, &source) == S_OK, | ||
| 410 | "RehydrateRaytracingAccelerationStructureBatched2X rebuilds BLAS and returns S_OK"); | ||
| 411 | |||
| 412 | // The title passes ScratchAccelerationStructureData = 0: the shim supplies scratch. Each of these builds has a | ||
| 413 | // destination of its own, read back below, so a build the shim skipped fails its check. | ||
| 414 | Ref<ID3D12Resource> zero_scratch_as, zero_scratch_rb; | ||
| 415 | if (FAILED(hr = buffer(device.p, D3D12_HEAP_TYPE_DEFAULT, blas_info.ResultDataMaxSizeInBytes, as_state, uav, | ||
| 416 | zero_scratch_as.put())) || | ||
| 417 | FAILED(hr = buffer(device.p, D3D12_HEAP_TYPE_READBACK, blas_info.ResultDataMaxSizeInBytes, | ||
| 418 | D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_FLAG_NONE, zero_scratch_rb.put()))) | ||
| 419 | return fail("zero-scratch buffers", hr); | ||
| 420 | D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC zero_scratch_desc = rehydrate_desc; | ||
| 421 | zero_scratch_desc.DestAccelerationStructureData = zero_scratch_as->GetGPUVirtualAddress(); | ||
| 422 | zero_scratch_desc.ScratchAccelerationStructureData = 0; | ||
| 423 | check(rehydrate(builder, list.p, 1, &zero_scratch_desc, &source) == S_OK, | ||
| 424 | "RehydrateRaytracingAccelerationStructureBatched2X supplies scratch when ScratchAccelerationStructureData == 0"); | ||
| 425 | |||
| 426 | // Two elements of one batch, both without scratch, and no barrier between them (the title puts none): each needs | ||
| 427 | // a scratch region of its own. The second element has half the triangles, and asks for PERFORM_UPDATE with a | ||
| 428 | // source, as the title's dehydrated stream would be: a rehydrate builds it afresh all the same. | ||
| 429 | const UINT pair_tris[2] = {tris, tris / 2}; | ||
| 430 | D3D12_RAYTRACING_GEOMETRY_DESC pair_geometry[2] = {geometry, geometry}; | ||
| 431 | pair_geometry[1].Triangles.VertexCount = pair_tris[1] * 3; | ||
| 432 | Ref<ID3D12Resource> pair_as[2], pair_rb[2]; | ||
| 433 | D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC pair_desc[2]{}; | ||
| 434 | for (int i = 0; i < 2; ++i) { | ||
| 435 | if (FAILED(hr = buffer(device.p, D3D12_HEAP_TYPE_DEFAULT, blas_info.ResultDataMaxSizeInBytes, as_state, uav, | ||
| 436 | pair_as[i].put())) || | ||
| 437 | FAILED(hr = buffer(device.p, D3D12_HEAP_TYPE_READBACK, blas_info.ResultDataMaxSizeInBytes, | ||
| 438 | D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_FLAG_NONE, pair_rb[i].put()))) | ||
| 439 | return fail("batch-of-two buffers", hr); | ||
| 440 | pair_desc[i].DestAccelerationStructureData = pair_as[i]->GetGPUVirtualAddress(); | ||
| 441 | pair_desc[i].Inputs = blas_inputs; | ||
| 442 | pair_desc[i].Inputs.pGeometryDescs = &pair_geometry[i]; | ||
| 443 | } | ||
| 444 | pair_desc[1].Inputs.Flags |= D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_PERFORM_UPDATE; | ||
| 445 | pair_desc[1].SourceAccelerationStructureData = source; | ||
| 446 | check(rehydrate(builder, list.p, 2, pair_desc, nullptr) == S_OK, | ||
| 447 | "RehydrateRaytracingAccelerationStructureBatched2X builds a batch of two elements without scratch"); | ||
| 448 | |||
| 449 | list->ResourceBarrier(1, &barrier); | ||
| 450 | list->CopyBufferRegion(rehydrated_rb.p, 0, rehydrated_as.p, 0, blas_info.ResultDataMaxSizeInBytes); | ||
| 451 | list->CopyBufferRegion(zero_scratch_rb.p, 0, zero_scratch_as.p, 0, blas_info.ResultDataMaxSizeInBytes); | ||
| 452 | for (int i = 0; i < 2; ++i) | ||
| 453 | list->CopyBufferRegion(pair_rb[i].p, 0, pair_as[i].p, 0, blas_info.ResultDataMaxSizeInBytes); | ||
| 454 | if (!submit()) return fail("the rehydrate build did not complete"); | ||
| 455 | auto header_units = [](ID3D12Resource* rb) { | ||
| 456 | void* p = nullptr; | ||
| 457 | std::uint32_t units = 0; | ||
| 458 | if (SUCCEEDED(rb->Map(0, nullptr, &p))) { | ||
| 459 | std::memcpy(&units, static_cast<char*>(p) + 4, 4); | ||
| 460 | rb->Unmap(0, nullptr); | ||
| 461 | } | ||
| 462 | return units; | ||
| 463 | }; | ||
| 464 | check(header_units(rehydrated_rb.p) > 0, "the rehydrated structure has non-zero totalSizeIn64BNodes header"); | ||
| 465 | check(header_units(zero_scratch_rb.p) > 0, "the structure rehydrated without the title's scratch was built"); | ||
| 466 | check(header_units(pair_rb[0].p) > 0 && header_units(pair_rb[1].p) > 0, | ||
| 467 | "both elements of the batch without scratch were built"); | ||
| 381 | 468 | ||
| 382 | // ---- dump for xdxr_bvh.py check-build ---- | 469 | // ---- dump for xdxr_bvh.py check-build ---- |
| 383 | auto dump = [&](ID3D12Resource* rb, UINT64 size, const std::string& name, const std::string& json) { | 470 | auto dump = [&](ID3D12Resource* rb, UINT64 size, const std::string& name, const std::string& json) { |
| @@ -391,15 +478,18 @@ int main(int argc, char** argv) { | |||
| 391 | rb->Unmap(0, nullptr); | 478 | rb->Unmap(0, nullptr); |
| 392 | return ok; | 479 | return ok; |
| 393 | }; | 480 | }; |
| 394 | std::string triangles = "["; | 481 | auto triangle_list = [&](UINT count) { |
| 395 | for (UINT t = 0; t < tris; ++t) { | 482 | std::string out = "["; |
| 396 | triangles += t ? ",\n [" : "\n ["; | 483 | for (UINT t = 0; t < count; ++t) { |
| 397 | for (int k = 0; k < 3; ++k) | 484 | out += t ? ",\n [" : "\n ["; |
| 398 | triangles += (k ? ", [" : "[") + num(soup[9 * t + 3 * k]) + ", " + num(soup[9 * t + 3 * k + 1]) + ", " + | 485 | for (int k = 0; k < 3; ++k) |
| 399 | num(soup[9 * t + 3 * k + 2]) + "]"; | 486 | out += (k ? ", [" : "[") + num(soup[9 * t + 3 * k]) + ", " + num(soup[9 * t + 3 * k + 1]) + ", " + |
| 400 | triangles += ", 0, " + std::to_string(t) + "]"; | 487 | num(soup[9 * t + 3 * k + 2]) + "]"; |
| 401 | } | 488 | out += ", 0, " + std::to_string(t) + "]"; |
| 402 | triangles += "]"; | 489 | } |
| 490 | return out + "]"; | ||
| 491 | }; | ||
| 492 | const std::string triangles = triangle_list(tris); | ||
| 403 | check(dump(blas_rb.p, blas_info.ResultDataMaxSizeInBytes, "shim_blas", | 493 | check(dump(blas_rb.p, blas_info.ResultDataMaxSizeInBytes, "shim_blas", |
| 404 | "{\"kind\": \"blas\", \"address\": " + std::to_string(blas->GetGPUVirtualAddress()) + | 494 | "{\"kind\": \"blas\", \"address\": " + std::to_string(blas->GetGPUVirtualAddress()) + |
| 405 | ", \"triangles\": " + triangles + "}\n"), | 495 | ", \"triangles\": " + triangles + "}\n"), |
| @@ -419,6 +509,18 @@ int main(int argc, char** argv) { | |||
| 419 | "{\"kind\": \"blas\", \"address\": " + std::to_string(compacted->GetGPUVirtualAddress()) + | 509 | "{\"kind\": \"blas\", \"address\": " + std::to_string(compacted->GetGPUVirtualAddress()) + |
| 420 | ", \"triangles\": " + triangles + "}\n"), | 510 | ", \"triangles\": " + triangles + "}\n"), |
| 421 | "the BLAS compacted through the shim is written for check-build"); | 511 | "the BLAS compacted through the shim is written for check-build"); |
| 512 | check(dump(zero_scratch_rb.p, blas_info.ResultDataMaxSizeInBytes, "shim_blas_rehydrated_zero_scratch", | ||
| 513 | "{\"kind\": \"blas\", \"address\": " + std::to_string(zero_scratch_as->GetGPUVirtualAddress()) + | ||
| 514 | ", \"triangles\": " + triangles + "}\n"), | ||
| 515 | "the BLAS rehydrated with the shim's scratch is written for check-build"); | ||
| 516 | for (int i = 0; i < 2; ++i) { | ||
| 517 | const std::string name = "shim_blas_rehydrated_batch" + std::to_string(i); | ||
| 518 | check(dump(pair_rb[i].p, blas_info.ResultDataMaxSizeInBytes, name, | ||
| 519 | "{\"kind\": \"blas\", \"address\": " + std::to_string(pair_as[i]->GetGPUVirtualAddress()) + | ||
| 520 | ", \"triangles\": " + triangle_list(pair_tris[i]) + "}\n"), | ||
| 521 | i ? "the batch's second element (its own scratch region) is written for check-build" | ||
| 522 | : "the batch's first element (its own scratch region) is written for check-build"); | ||
| 523 | } | ||
| 422 | 524 | ||
| 423 | // ---- the destructor releases the builder ---- | 525 | // ---- the destructor releases the builder ---- |
| 424 | destruct(builder); | 526 | destruct(builder); |
diff --git a/runtime/test/xbox_depth_storage_test.cpp b/runtime/test/xbox_depth_storage_test.cpp index 4ae4a40a3..8164e819b 100644 --- a/runtime/test/xbox_depth_storage_test.cpp +++ b/runtime/test/xbox_depth_storage_test.cpp | |||
| @@ -2,9 +2,12 @@ | |||
| 2 | #include "d3d12_test_shaders.h" | 2 | #include "d3d12_test_shaders.h" |
| 3 | #include "../shims/d3d12_com.h" | 3 | #include "../shims/d3d12_com.h" |
| 4 | #include "../shims/d3d12_xs_device.h" | 4 | #include "../shims/d3d12_xs_device.h" |
| 5 | #include "../src/depth24.h" | ||
| 5 | #include "../src/title_va_alias.h" | 6 | #include "../src/title_va_alias.h" |
| 6 | #include <array> | 7 | #include <array> |
| 7 | #include <cstdio> | 8 | #include <cstdio> |
| 9 | #include <cstring> | ||
| 10 | #include <utility> | ||
| 8 | 11 | ||
| 9 | using namespace d3d12test; | 12 | using namespace d3d12test; |
| 10 | #define VERIFY(expr) do { if (!(expr)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #expr); return 1; } } while (0) | 13 | #define VERIFY(expr) do { if (!(expr)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #expr); return 1; } } while (0) |
| @@ -56,46 +59,304 @@ int check_lease(ID3D12Device* dev, ID3D12Device* xbox) { | |||
| 56 | } | 59 | } |
| 57 | 60 | ||
| 58 | // With the console D16S8 family made as D24S8 (LEONIDA_CONSOLE_D16S8=d24; the default on a GPU with D24S8 | 61 | // With the console D16S8 family made as D24S8 (LEONIDA_CONSOLE_D16S8=d24; the default on a GPU with D24S8 |
| 59 | // attachments, every NVIDIA card), the depth provider has no unordered-access form of a format 118 depth-stencil | 62 | // attachments, every NVIDIA card), format 118 keeps its UAVs through the widened R16_TYPELESS + R8_UINT storage |
| 60 | // texture and refuses it (Resource::enable_depth_stencil_uav). Slots 76 and 133 then make it without unordered | 63 | // planes and Depth24Converter. Check slot 133 (the retail 1280x720 placement), CreateCommittedResource3 with a |
| 61 | // access, as before the provider, so the title gets its texture instead of asserting. The description is the one | 64 | // castable list, R16_UNORM float + R16_UINT uint + R8_UINT stencil UAV clears, and direct readback of the parent |
| 62 | // measured where a real boot stopped: 1280x720, one mip, the all-ones layout through slot 133. | 65 | // D24S8 attachment image. |
| 63 | int check_d16s8_refused_uav(ID3D12Device* xbox) { | 66 | int check_d16s8_d24_uav(ID3D12Device* dev, ID3D12Device* xbox) { |
| 67 | constexpr auto xbox_d16s8 = static_cast<DXGI_FORMAT>(118); | ||
| 68 | constexpr auto xbox_d16_plane = static_cast<DXGI_FORMAT>(119); | ||
| 69 | constexpr auto xbox_s8_plane = static_cast<DXGI_FORMAT>(120); | ||
| 64 | D3D12_RESOURCE_DESC tex{}; | 70 | D3D12_RESOURCE_DESC tex{}; |
| 65 | tex.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; | 71 | tex.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; |
| 66 | tex.Width = 1280; | 72 | tex.Width = 1280; |
| 67 | tex.Height = 720; | 73 | tex.Height = 720; |
| 68 | tex.DepthOrArraySize = tex.MipLevels = 1; | 74 | tex.DepthOrArraySize = tex.MipLevels = 1; |
| 69 | tex.SampleDesc.Count = 1; | 75 | tex.SampleDesc.Count = 1; |
| 70 | tex.Format = static_cast<DXGI_FORMAT>(118); | 76 | tex.Format = xbox_d16s8; |
| 71 | tex.Layout = static_cast<D3D12_TEXTURE_LAYOUT>(0x101); | 77 | tex.Layout = static_cast<D3D12_TEXTURE_LAYOUT>(0x101); |
| 72 | tex.Flags = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; | 78 | tex.Flags = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; |
| 73 | D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_DEFAULT}; | 79 | D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_DEFAULT}; |
| 74 | D3D12_CLEAR_VALUE clear{}; | 80 | D3D12_CLEAR_VALUE clear{}; |
| 75 | clear.Format = tex.Format; | 81 | clear.Format = tex.Format; |
| 76 | clear.DepthStencil.Depth = 1; | 82 | clear.DepthStencil.Depth = 1; |
| 77 | using Create = HRESULT(WINAPI*)(void*, const D3D12_HEAP_PROPERTIES*, UINT, const D3D12_RESOURCE_DESC*, UINT, | ||
| 78 | const D3D12_CLEAR_VALUE*, const IID*, void**); | ||
| 79 | Ref<ID3D12Resource> committed; | ||
| 80 | VERIFY(SUCCEEDED(reinterpret_cast<Create>(slot(xbox, 76))(xbox, &heap, 0, &tex, D3D12_RESOURCE_STATE_DEPTH_WRITE, | ||
| 81 | &clear, &__uuidof(ID3D12Resource), | ||
| 82 | reinterpret_cast<void**>(&committed.p)))); | ||
| 83 | VERIFY(committed.p && committed->GetDesc().Flags == D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL); | ||
| 84 | 83 | ||
| 84 | // Slot 133 placement at 1280x720 with all-ones layout keeps ALLOW_UNORDERED_ACCESS and valid plane UAVs. | ||
| 85 | using Place = HRESULT(WINAPI*)(void*, UINT64, const D3D12_RESOURCE_DESC*, UINT, const D3D12_CLEAR_VALUE*, | 85 | using Place = HRESULT(WINAPI*)(void*, UINT64, const D3D12_RESOURCE_DESC*, UINT, const D3D12_CLEAR_VALUE*, |
| 86 | const IID*, void**); | 86 | const IID*, void**); |
| 87 | constexpr SIZE_T pages = 16u << 20; // past the texture's size on any GPU; VirtualAlloc aligns it to 64 KiB | 87 | constexpr SIZE_T pages = 16u << 20; |
| 88 | void* va = VirtualAlloc(nullptr, pages, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); | 88 | void* va = VirtualAlloc(nullptr, pages, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); |
| 89 | VERIFY(va); | 89 | VERIFY(va); |
| 90 | Ref<ID3D12Resource> placed; | 90 | Ref<ID3D12Resource> placed; |
| 91 | const HRESULT hr = reinterpret_cast<Place>(slot(xbox, 133))(xbox, reinterpret_cast<UINT64>(va), &tex, 0xFFFFFFFFu, | 91 | const HRESULT place_hr = reinterpret_cast<Place>(slot(xbox, 133))(xbox, reinterpret_cast<UINT64>(va), &tex, |
| 92 | &clear, &__uuidof(ID3D12Resource), | 92 | 0xFFFFFFFFu, &clear, &__uuidof(ID3D12Resource), |
| 93 | reinterpret_cast<void**>(&placed.p)); | 93 | reinterpret_cast<void**>(&placed.p)); |
| 94 | const bool made = SUCCEEDED(hr) && placed.p && placed->GetDesc().Flags == D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL; | 94 | const bool placed_ok = SUCCEEDED(place_hr) && placed.p && placed->GetDesc().Flags == tex.Flags && |
| 95 | placed = {}; | 95 | placed->GetDesc().Format == DXGI_FORMAT_D24_UNORM_S8_UINT; |
| 96 | bool placed_views_ok = false; | ||
| 97 | if (placed_ok) { | ||
| 98 | Ref<ID3D12DescriptorHeap> heap_uav; | ||
| 99 | D3D12_DESCRIPTOR_HEAP_DESC hd{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 3}; | ||
| 100 | if (SUCCEEDED(dev->CreateDescriptorHeap(&hd, IID_PPV_ARGS(&heap_uav.p)))) { | ||
| 101 | const SIZE_T step = dev->GetDescriptorHandleIncrementSize(hd.Type); | ||
| 102 | const SIZE_T base = heap_uav->GetCPUDescriptorHandleForHeapStart().ptr; | ||
| 103 | const std::pair<DXGI_FORMAT, UINT> plane_views[3] = { | ||
| 104 | {DXGI_FORMAT_R16_UINT, 0}, {DXGI_FORMAT_R16_UNORM, 0}, {DXGI_FORMAT_R8_UINT, 1}}; | ||
| 105 | placed_views_ok = true; | ||
| 106 | for (UINT i = 0; i < 3; ++i) { | ||
| 107 | D3D12_UNORDERED_ACCESS_VIEW_DESC uv{}; | ||
| 108 | uv.Format = plane_views[i].first; | ||
| 109 | uv.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2D; | ||
| 110 | uv.Texture2D.PlaneSlice = plane_views[i].second; | ||
| 111 | dev->CreateUnorderedAccessView(placed.p, nullptr, &uv, {base + i * step}); | ||
| 112 | leonida::gfx10::ImageWords words{}; | ||
| 113 | std::memcpy(words.data(), reinterpret_cast<const void*>(base + i * step), sizeof(words)); | ||
| 114 | leonida::gfx10::Image image{}; | ||
| 115 | if (!leonida::gfx10::decode(words, image) || !rt::d3d12::uav_image_resource(placed.p, image.address)) | ||
| 116 | placed_views_ok = false; | ||
| 117 | } | ||
| 118 | } | ||
| 119 | } | ||
| 120 | placed.reset(); | ||
| 96 | VirtualFree(va, 0, MEM_RELEASE); | 121 | VirtualFree(va, 0, MEM_RELEASE); |
| 97 | VERIFY(made); | 122 | VERIFY(placed_ok && placed_views_ok); |
| 98 | std::printf("Xbox D16S8 made as D24S8: slots 76 and 133 make the depth-stencil texture without unordered access\n"); | 123 | |
| 124 | // CreateCommittedResource3 with a castable format list also keeps ALLOW_UNORDERED_ACCESS (direct and slot 127), | ||
| 125 | // while plain PC D24_UNORM_S8_UINT refuses R16/R8 castable views and refuses ALLOW_UNORDERED_ACCESS. | ||
| 126 | { | ||
| 127 | Ref<ID3D12Device10> dev10; | ||
| 128 | VERIFY(SUCCEEDED(dev->QueryInterface(IID_PPV_ARGS(&dev10.p)))); | ||
| 129 | D3D12_RESOURCE_DESC1 desc1{tex.Dimension, 0, 32, 32, 1, 1, xbox_d16s8, tex.SampleDesc, | ||
| 130 | D3D12_TEXTURE_LAYOUT_UNKNOWN, tex.Flags, {}}; | ||
| 131 | const DXGI_FORMAT castable[] = {xbox_d16s8, xbox_d16_plane, xbox_s8_plane, | ||
| 132 | DXGI_FORMAT_D24_UNORM_S8_UINT, DXGI_FORMAT_R24_UNORM_X8_TYPELESS, | ||
| 133 | DXGI_FORMAT_X24_TYPELESS_G8_UINT, DXGI_FORMAT_R16_TYPELESS, | ||
| 134 | DXGI_FORMAT_R16_UNORM, DXGI_FORMAT_R16_UINT, DXGI_FORMAT_R8_UINT}; | ||
| 135 | Ref<ID3D12Resource> c3; | ||
| 136 | VERIFY(SUCCEEDED(dev10->CreateCommittedResource3(&heap, D3D12_HEAP_FLAG_NONE, &desc1, | ||
| 137 | D3D12_BARRIER_LAYOUT_COMMON, &clear, nullptr, | ||
| 138 | UINT(std::size(castable)), castable, IID_PPV_ARGS(&c3.p)))); | ||
| 139 | VERIFY(c3.p && c3->GetDesc().Flags == tex.Flags && c3->GetDesc().Format == DXGI_FORMAT_D24_UNORM_S8_UINT); | ||
| 140 | const DXGI_FORMAT bad_view = DXGI_FORMAT_R32_FLOAT; | ||
| 141 | Ref<ID3D12Resource> bad_c3; | ||
| 142 | VERIFY(dev10->CreateCommittedResource3(&heap, D3D12_HEAP_FLAG_NONE, &desc1, D3D12_BARRIER_LAYOUT_COMMON, | ||
| 143 | &clear, nullptr, 1, &bad_view, IID_PPV_ARGS(&bad_c3.p)) == E_INVALIDARG && | ||
| 144 | !bad_c3.p); | ||
| 145 | |||
| 146 | // Xbox slot 127 forwards to CreateCommittedResource3 with the Xbox layout word replaced. | ||
| 147 | using Slot127 = HRESULT(WINAPI*)(void*, const D3D12_HEAP_PROPERTIES*, D3D12_HEAP_FLAGS, | ||
| 148 | const D3D12_RESOURCE_DESC1*, D3D12_BARRIER_LAYOUT, const D3D12_CLEAR_VALUE*, | ||
| 149 | ID3D12ProtectedResourceSession*, UINT, const DXGI_FORMAT*, REFIID, void**); | ||
| 150 | D3D12_RESOURCE_DESC1 xbox_desc1 = desc1; | ||
| 151 | xbox_desc1.Layout = static_cast<D3D12_TEXTURE_LAYOUT>(0x101); | ||
| 152 | Ref<ID3D12Resource> c3x; | ||
| 153 | VERIFY(SUCCEEDED(reinterpret_cast<Slot127>(slot(xbox, 127))( | ||
| 154 | xbox, &heap, D3D12_HEAP_FLAG_NONE, &xbox_desc1, D3D12_BARRIER_LAYOUT_COMMON, &clear, nullptr, | ||
| 155 | UINT(std::size(castable)), castable, IID_PPV_ARGS(&c3x.p)))); | ||
| 156 | VERIFY(c3x.p && c3x->GetDesc().Flags == tex.Flags && c3x->GetDesc().Format == DXGI_FORMAT_D24_UNORM_S8_UINT); | ||
| 157 | |||
| 158 | // Plain PC D24_UNORM_S8_UINT: refuses ALLOW_UNORDERED_ACCESS and refuses R16/R8 castable formats. | ||
| 159 | D3D12_RESOURCE_DESC1 pc_d24 = desc1; | ||
| 160 | pc_d24.Format = DXGI_FORMAT_D24_UNORM_S8_UINT; | ||
| 161 | D3D12_CLEAR_VALUE pc_clear = clear; | ||
| 162 | pc_clear.Format = DXGI_FORMAT_D24_UNORM_S8_UINT; | ||
| 163 | Ref<ID3D12Resource> refused; | ||
| 164 | VERIFY(dev10->CreateCommittedResource3(&heap, D3D12_HEAP_FLAG_NONE, &pc_d24, D3D12_BARRIER_LAYOUT_COMMON, | ||
| 165 | &pc_clear, nullptr, 0, nullptr, IID_PPV_ARGS(&refused.p)) == E_INVALIDARG && | ||
| 166 | !refused.p); | ||
| 167 | pc_d24.Flags = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL; | ||
| 168 | for (const DXGI_FORMAT narrow : {DXGI_FORMAT_R16_TYPELESS, DXGI_FORMAT_R16_UNORM, DXGI_FORMAT_R16_UINT, | ||
| 169 | DXGI_FORMAT_R8_UINT}) { | ||
| 170 | VERIFY(dev10->CreateCommittedResource3(&heap, D3D12_HEAP_FLAG_NONE, &pc_d24, D3D12_BARRIER_LAYOUT_COMMON, | ||
| 171 | &pc_clear, nullptr, 1, &narrow, IID_PPV_ARGS(&refused.p)) == | ||
| 172 | E_INVALIDARG && | ||
| 173 | !refused.p); | ||
| 174 | } | ||
| 175 | |||
| 176 | // CreateCommittedResource2, CreatePlacedResource/2 (in a heap), and CreateReservedResource with format 118. | ||
| 177 | Ref<ID3D12Device8> dev8; | ||
| 178 | VERIFY(SUCCEEDED(dev->QueryInterface(IID_PPV_ARGS(&dev8.p)))); | ||
| 179 | D3D12_RESOURCE_DESC1 d16_no_uav = desc1; | ||
| 180 | d16_no_uav.Flags = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL; | ||
| 181 | Ref<ID3D12Resource> c2; | ||
| 182 | VERIFY(SUCCEEDED(dev8->CreateCommittedResource2(&heap, D3D12_HEAP_FLAG_NONE, &d16_no_uav, | ||
| 183 | D3D12_RESOURCE_STATE_DEPTH_WRITE, &clear, nullptr, | ||
| 184 | IID_PPV_ARGS(&c2.p)))); | ||
| 185 | VERIFY(c2.p && c2->GetDesc().Format == DXGI_FORMAT_D24_UNORM_S8_UINT); | ||
| 186 | VERIFY(dev8->CreateCommittedResource2(&heap, D3D12_HEAP_FLAG_NONE, &desc1, D3D12_RESOURCE_STATE_DEPTH_WRITE, | ||
| 187 | &clear, nullptr, IID_PPV_ARGS(&refused.p)) == E_INVALIDARG && | ||
| 188 | !refused.p); | ||
| 189 | |||
| 190 | D3D12_RESOURCE_DESC placed_desc{}; | ||
| 191 | placed_desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; | ||
| 192 | placed_desc.Width = placed_desc.Height = 32; | ||
| 193 | placed_desc.DepthOrArraySize = placed_desc.MipLevels = 1; | ||
| 194 | placed_desc.Format = xbox_d16s8; | ||
| 195 | placed_desc.SampleDesc.Count = 1; | ||
| 196 | placed_desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL; | ||
| 197 | const auto placed_alloc = dev->GetResourceAllocationInfo(0, 1, &placed_desc); | ||
| 198 | VERIFY(placed_alloc.SizeInBytes > 0 && placed_alloc.SizeInBytes != UINT64_MAX); | ||
| 199 | D3D12_HEAP_DESC heap_desc{placed_alloc.SizeInBytes, heap, placed_alloc.Alignment, D3D12_HEAP_FLAG_NONE}; | ||
| 200 | Ref<ID3D12Heap> placed_heap; | ||
| 201 | VERIFY(SUCCEEDED(dev->CreateHeap(&heap_desc, IID_PPV_ARGS(&placed_heap.p)))); | ||
| 202 | Ref<ID3D12Resource> heap_placed; | ||
| 203 | VERIFY(SUCCEEDED(dev->CreatePlacedResource(placed_heap.p, 0, &placed_desc, D3D12_RESOURCE_STATE_DEPTH_WRITE, | ||
| 204 | &clear, IID_PPV_ARGS(&heap_placed.p)))); | ||
| 205 | VERIFY(heap_placed.p && heap_placed->GetDesc().Format == DXGI_FORMAT_D24_UNORM_S8_UINT); | ||
| 206 | D3D12_RESOURCE_DESC placed_uav = placed_desc; | ||
| 207 | placed_uav.Flags |= D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; | ||
| 208 | VERIFY(dev->CreatePlacedResource(placed_heap.p, 0, &placed_uav, D3D12_RESOURCE_STATE_DEPTH_WRITE, &clear, | ||
| 209 | IID_PPV_ARGS(&refused.p)) == E_INVALIDARG && | ||
| 210 | !refused.p); | ||
| 211 | Ref<ID3D12Resource> heap_placed2; | ||
| 212 | VERIFY(SUCCEEDED(dev10->CreatePlacedResource2(placed_heap.p, 0, &d16_no_uav, D3D12_BARRIER_LAYOUT_COMMON, | ||
| 213 | &clear, 0, nullptr, IID_PPV_ARGS(&heap_placed2.p)))); | ||
| 214 | VERIFY(heap_placed2.p && heap_placed2->GetDesc().Format == DXGI_FORMAT_D24_UNORM_S8_UINT); | ||
| 215 | for (const DXGI_FORMAT narrow : {DXGI_FORMAT_R16_UNORM, DXGI_FORMAT_R8_UINT}) { | ||
| 216 | VERIFY(dev10->CreatePlacedResource2(placed_heap.p, 0, &pc_d24, D3D12_BARRIER_LAYOUT_COMMON, &pc_clear, | ||
| 217 | 1, &narrow, IID_PPV_ARGS(&refused.p)) == E_INVALIDARG && | ||
| 218 | !refused.p); | ||
| 219 | } | ||
| 220 | |||
| 221 | // Reserved resources reject stencil formats (including format 118) because they have no tile shape. | ||
| 222 | D3D12_RESOURCE_DESC reserved_desc = placed_desc; | ||
| 223 | reserved_desc.Layout = D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE; | ||
| 224 | VERIFY(dev->CreateReservedResource(&reserved_desc, D3D12_RESOURCE_STATE_DEPTH_WRITE, &clear, | ||
| 225 | IID_PPV_ARGS(&refused.p)) == E_INVALIDARG && | ||
| 226 | !refused.p); | ||
| 227 | } | ||
| 228 | |||
| 229 | // Direct parent D24S8 attachment readback after R16_UNORM float + R16_UINT uint + R8_UINT stencil UAV clears. | ||
| 230 | constexpr UINT w = 32, layers = 2; | ||
| 231 | tex.Width = tex.Height = w; | ||
| 232 | tex.DepthOrArraySize = layers; | ||
| 233 | using Create = HRESULT(WINAPI*)(void*, const D3D12_HEAP_PROPERTIES*, UINT, const D3D12_RESOURCE_DESC*, UINT, | ||
| 234 | const D3D12_CLEAR_VALUE*, const IID*, void**); | ||
| 235 | Ref<ID3D12Resource> depth; | ||
| 236 | VERIFY(SUCCEEDED(reinterpret_cast<Create>(slot(xbox, 76))(xbox, &heap, 0, &tex, D3D12_RESOURCE_STATE_DEPTH_WRITE, | ||
| 237 | &clear, &__uuidof(ID3D12Resource), | ||
| 238 | reinterpret_cast<void**>(&depth.p)))); | ||
| 239 | const D3D12_RESOURCE_DESC parent_desc = depth->GetDesc(); | ||
| 240 | VERIFY(parent_desc.Flags == tex.Flags && parent_desc.Format == DXGI_FORMAT_D24_UNORM_S8_UINT); | ||
| 241 | |||
| 242 | Ref<ID3D12DescriptorHeap> dsv, uav; | ||
| 243 | D3D12_DESCRIPTOR_HEAP_DESC dsv_hd{D3D12_DESCRIPTOR_HEAP_TYPE_DSV, layers}; | ||
| 244 | D3D12_DESCRIPTOR_HEAP_DESC uav_hd{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 3}; | ||
| 245 | VERIFY(SUCCEEDED(dev->CreateDescriptorHeap(&dsv_hd, IID_PPV_ARGS(&dsv.p)))); | ||
| 246 | VERIFY(SUCCEEDED(dev->CreateDescriptorHeap(&uav_hd, IID_PPV_ARGS(&uav.p)))); | ||
| 247 | const auto hslot = [&](ID3D12DescriptorHeap* h, D3D12_DESCRIPTOR_HEAP_TYPE t, UINT i) { | ||
| 248 | auto handle = h->GetCPUDescriptorHandleForHeapStart(); | ||
| 249 | handle.ptr += i * dev->GetDescriptorHandleIncrementSize(t); | ||
| 250 | return handle; | ||
| 251 | }; | ||
| 252 | const UINT16 seed_d[layers] = {0x2000, 0xc000}; | ||
| 253 | const UINT8 seed_s[layers] = {0x41, 0x42}; | ||
| 254 | for (UINT i = 0; i < layers; ++i) { | ||
| 255 | D3D12_DEPTH_STENCIL_VIEW_DESC dv{}; | ||
| 256 | dv.Format = xbox_d16s8; | ||
| 257 | dv.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2DARRAY; | ||
| 258 | dv.Texture2DArray = {0, i, 1}; | ||
| 259 | dev->CreateDepthStencilView(depth.p, &dv, hslot(dsv.p, dsv_hd.Type, i)); | ||
| 260 | } | ||
| 261 | const std::pair<DXGI_FORMAT, UINT> uv_cfg[3] = { | ||
| 262 | {DXGI_FORMAT_R16_UNORM, 0}, {DXGI_FORMAT_R16_UINT, 0}, {DXGI_FORMAT_R8_UINT, 1}}; | ||
| 263 | for (UINT i = 0; i < 3; ++i) { | ||
| 264 | D3D12_UNORDERED_ACCESS_VIEW_DESC uv{}; | ||
| 265 | uv.Format = uv_cfg[i].first; | ||
| 266 | uv.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2DARRAY; | ||
| 267 | uv.Texture2DArray = {0, 0, 1, uv_cfg[i].second}; | ||
| 268 | dev->CreateUnorderedAccessView(depth.p, nullptr, &uv, hslot(uav.p, uav_hd.Type, i)); | ||
| 269 | } | ||
| 270 | D3D12_PLACED_SUBRESOURCE_FOOTPRINT fp[2 * layers]{}; | ||
| 271 | UINT64 total = 0; | ||
| 272 | dev->GetCopyableFootprints(&parent_desc, 0, 2 * layers, 0, fp, nullptr, nullptr, &total); | ||
| 273 | auto rb_desc = buffer_desc(total); | ||
| 274 | D3D12_HEAP_PROPERTIES host{D3D12_HEAP_TYPE_READBACK}; | ||
| 275 | Ref<ID3D12Resource> readback; | ||
| 276 | VERIFY(SUCCEEDED(dev->CreateCommittedResource(&host, D3D12_HEAP_FLAG_NONE, &rb_desc, | ||
| 277 | D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&readback.p)))); | ||
| 278 | Ref<ID3D12CommandQueue> queue; | ||
| 279 | Ref<ID3D12CommandAllocator> alloc; | ||
| 280 | Ref<ID3D12GraphicsCommandList> list; | ||
| 281 | Ref<ID3D12Fence> fence; | ||
| 282 | D3D12_COMMAND_QUEUE_DESC qd{}; | ||
| 283 | VERIFY(SUCCEEDED(dev->CreateCommandQueue(&qd, IID_PPV_ARGS(&queue.p)))); | ||
| 284 | VERIFY(SUCCEEDED(dev->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&alloc.p)))); | ||
| 285 | VERIFY(SUCCEEDED(dev->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, alloc.p, nullptr, IID_PPV_ARGS(&list.p)))); | ||
| 286 | VERIFY(SUCCEEDED(dev->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p)))); | ||
| 287 | |||
| 288 | for (UINT i = 0; i < layers; ++i) | ||
| 289 | list->ClearDepthStencilView(hslot(dsv.p, dsv_hd.Type, i), | ||
| 290 | D3D12_CLEAR_FLAG_DEPTH | D3D12_CLEAR_FLAG_STENCIL, | ||
| 291 | float(seed_d[i]) / 65535.f, seed_s[i], 0, nullptr); | ||
| 292 | auto to_uav = transition(depth.p, D3D12_RESOURCE_STATE_DEPTH_WRITE, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); | ||
| 293 | list->ResourceBarrier(1, &to_uav); | ||
| 294 | const D3D12_RECT r_unorm{2, 3, 10, 11}, r_uint{14, 5, 22, 13}, r_stencil{4, 4, 12, 12}; | ||
| 295 | const FLOAT fval[4]{0.25f}; | ||
| 296 | const UINT uval[4]{0x9123u}, sval[4]{0xa7u}; | ||
| 297 | list->ClearUnorderedAccessViewFloat({}, hslot(uav.p, uav_hd.Type, 0), depth.p, fval, 1, &r_unorm); | ||
| 298 | D3D12_RESOURCE_BARRIER uav_bar{}; | ||
| 299 | uav_bar.Type = D3D12_RESOURCE_BARRIER_TYPE_UAV; | ||
| 300 | uav_bar.UAV.pResource = depth.p; | ||
| 301 | list->ResourceBarrier(1, &uav_bar); | ||
| 302 | list->ClearUnorderedAccessViewUint({}, hslot(uav.p, uav_hd.Type, 1), depth.p, uval, 1, &r_uint); | ||
| 303 | list->ClearUnorderedAccessViewUint({}, hslot(uav.p, uav_hd.Type, 2), depth.p, sval, 1, &r_stencil); | ||
| 304 | auto to_copy = transition(depth.p, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE); | ||
| 305 | list->ResourceBarrier(1, &to_copy); | ||
| 306 | for (UINT sub = 0; sub < 2 * layers; ++sub) { | ||
| 307 | D3D12_TEXTURE_COPY_LOCATION src{}, dst{}; | ||
| 308 | src.pResource = depth.p; | ||
| 309 | src.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; | ||
| 310 | src.SubresourceIndex = sub; | ||
| 311 | dst.pResource = readback.p; | ||
| 312 | dst.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; | ||
| 313 | dst.PlacedFootprint = fp[sub]; | ||
| 314 | list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); | ||
| 315 | } | ||
| 316 | VERIFY(SUCCEEDED(list->Close())); | ||
| 317 | ID3D12CommandList* batch[]{list.p}; | ||
| 318 | queue->ExecuteCommandLists(1, batch); | ||
| 319 | VERIFY(SUCCEEDED(queue->Signal(fence.p, 1))); | ||
| 320 | const auto end = GetTickCount64() + 5000; | ||
| 321 | while (fence->GetCompletedValue() < 1 && GetTickCount64() < end) Sleep(1); | ||
| 322 | VERIFY(fence->GetCompletedValue() == 1); | ||
| 323 | |||
| 324 | void* mapped{}; | ||
| 325 | VERIFY(SUCCEEDED(readback->Map(0, nullptr, &mapped))); | ||
| 326 | const auto* bytes = static_cast<const std::uint8_t*>(mapped); | ||
| 327 | for (UINT i = 0; i < layers; ++i) { | ||
| 328 | for (int y = 0; y < int(w); ++y) { | ||
| 329 | for (int x = 0; x < int(w); ++x) { | ||
| 330 | UINT16 exp_u16 = seed_d[i]; | ||
| 331 | if (i == 0 && x >= r_unorm.left && x < r_unorm.right && y >= r_unorm.top && y < r_unorm.bottom) | ||
| 332 | exp_u16 = 0x4000u; | ||
| 333 | if (i == 0 && x >= r_uint.left && x < r_uint.right && y >= r_uint.top && y < r_uint.bottom) | ||
| 334 | exp_u16 = 0x9123u; | ||
| 335 | const std::uint32_t exp_d24 = leonida::depth24_quantize(float(exp_u16) / 65535.f); | ||
| 336 | std::uint32_t got_word = 0; | ||
| 337 | std::memcpy(&got_word, bytes + fp[i].Offset + y * fp[i].Footprint.RowPitch + x * 4, 4); | ||
| 338 | const std::uint32_t got_d24 = got_word & 0xffffffu; | ||
| 339 | if (got_d24 != exp_d24) { | ||
| 340 | std::fprintf(stderr, "D24 parent slice %u (%d,%d): expected %06x got %06x\n", | ||
| 341 | i, x, y, exp_d24, got_d24); | ||
| 342 | readback->Unmap(0, nullptr); | ||
| 343 | return 1; | ||
| 344 | } | ||
| 345 | const UINT8 exp_s = (i == 0 && x >= r_stencil.left && x < r_stencil.right && | ||
| 346 | y >= r_stencil.top && y < r_stencil.bottom) ? 0xa7u : seed_s[i]; | ||
| 347 | const UINT8 got_s = bytes[fp[layers + i].Offset + y * fp[layers + i].Footprint.RowPitch + x]; | ||
| 348 | if (got_s != exp_s) { | ||
| 349 | std::fprintf(stderr, "D24 parent stencil slice %u (%d,%d): expected %02x got %02x\n", | ||
| 350 | i, x, y, exp_s, got_s); | ||
| 351 | readback->Unmap(0, nullptr); | ||
| 352 | return 1; | ||
| 353 | } | ||
| 354 | } | ||
| 355 | } | ||
| 356 | } | ||
| 357 | readback->Unmap(0, nullptr); | ||
| 358 | std::printf("Xbox D16S8 made as D24S8: slot 133, CreateCommittedResource3, R16_UNORM/R16_UINT/R8_UINT UAVs " | ||
| 359 | "and D24 parent readback exact\n"); | ||
| 99 | return 0; | 360 | return 0; |
| 100 | } | 361 | } |
| 101 | } | 362 | } |
| @@ -140,11 +401,6 @@ int main() { | |||
| 140 | VERIFY(SUCCEEDED(rt::d3d12_xs::create_device_proxy(dev, __uuidof(ID3D12Device), | 401 | VERIFY(SUCCEEDED(rt::d3d12_xs::create_device_proxy(dev, __uuidof(ID3D12Device), |
| 141 | reinterpret_cast<void**>(&proxy.p), true))); | 402 | reinterpret_cast<void**>(&proxy.p), true))); |
| 142 | rt::d3d12::set_device_outer(dev, proxy.p); | 403 | rt::d3d12::set_device_outer(dev, proxy.p); |
| 143 | if (std::getenv("LEONIDA_TEST_D16S8_REFUSED_UAV")) { | ||
| 144 | VERIFY(check_d16s8_refused_uav(proxy.p) == 0); | ||
| 145 | VERIFY(gpu.validation_errors() == 0); | ||
| 146 | return 0; | ||
| 147 | } | ||
| 148 | VERIFY(check_lease(dev, proxy.p) == 0); | 404 | VERIFY(check_lease(dev, proxy.p) == 0); |
| 149 | const auto allocation = dev->GetResourceAllocationInfo(0, 1, &tex); | 405 | const auto allocation = dev->GetResourceAllocationInfo(0, 1, &tex); |
| 150 | VERIFY(allocation.SizeInBytes >= 768u * 768 * layers * 2 && allocation.SizeInBytes != UINT64_MAX); | 406 | VERIFY(allocation.SizeInBytes >= 768u * 768 * layers * 2 && allocation.SizeInBytes != UINT64_MAX); |
| @@ -286,6 +542,9 @@ int main() { | |||
| 286 | std::printf("Xbox D16S8 depth and stencil: %u depth words and %u stencil bytes exact after UAV round trip\n", width*width*layers,width*width*layers); | 542 | std::printf("Xbox D16S8 depth and stencil: %u depth words and %u stencil bytes exact after UAV round trip\n", width*width*layers,width*width*layers); |
| 287 | } | 543 | } |
| 288 | readback->Unmap(0, nullptr); | 544 | readback->Unmap(0, nullptr); |
| 545 | const char* d16s8_mode = std::getenv("LEONIDA_CONSOLE_D16S8"); | ||
| 546 | if (with_stencil && d16s8_mode && std::strcmp(d16s8_mode, "d24") == 0) | ||
| 547 | VERIFY(check_d16s8_d24_uav(dev, proxy.p) == 0); | ||
| 289 | VERIFY(gpu.validation_errors() == 0); | 548 | VERIFY(gpu.validation_errors() == 0); |
| 290 | std::printf("Depth D16 / storage R16_UINT, six layers and %u exact texels\n", width * width * layers); | 549 | std::printf("Depth D16 / storage R16_UINT, six layers and %u exact texels\n", width * width * layers); |
| 291 | return 0; | 550 | return 0; |
diff --git a/runtime/test/xbox_present_test.cpp b/runtime/test/xbox_present_test.cpp index bc311a87e..5f026a61e 100644 --- a/runtime/test/xbox_present_test.cpp +++ b/runtime/test/xbox_present_test.cpp | |||
| @@ -540,8 +540,9 @@ int main() { | |||
| 540 | } | 540 | } |
| 541 | EXPECT(grab(frame)); | 541 | EXPECT(grab(frame)); |
| 542 | EXPECT(region_is(frame, 0, 0, width, height, {0, 0, 0}, 0)); | 542 | EXPECT(region_is(frame, 0, 0, width, height, {0, 0, 0}, 0)); |
| 543 | // (The blank frame is a frame in flight like any other: with latency 1 the next wait needs it shown first.) | 543 | // (The blank frame is a frame in flight like any other, but at most `latency` frames are: with latency 1 it |
| 544 | EXPECT(xbox.pacer().frames_in_flight() == 2); // the first frame and the blank one | 544 | // replaces the first frame, which still waits for its vblank, and the next wait needs it shown first.) |
| 545 | EXPECT(xbox.pacer().frames_in_flight() == 1); | ||
| 545 | clock.advance_us(period); | 546 | clock.advance_us(period); |
| 546 | std::printf("0 planes (blank): ok\n"); | 547 | std::printf("0 planes (blank): ok\n"); |
| 547 | 548 | ||
diff --git a/runtime/test/xg_xs_test.cpp b/runtime/test/xg_xs_test.cpp index 18356cb41..c6df1bc24 100644 --- a/runtime/test/xg_xs_test.cpp +++ b/runtime/test/xg_xs_test.cpp | |||
| @@ -415,6 +415,62 @@ int main() { | |||
| 415 | for (unsigned pass = 0; pass < 3; ++pass) poll([] { return true; }); | 415 | for (unsigned pass = 0; pass < 3; ++pass) poll([] { return true; }); |
| 416 | check(polled == std::vector<int>{4}, "an expired wall budget advances past priority entries to the next texture"); | 416 | check(polled == std::vector<int>{4}, "an expired wall budget advances past priority entries to the next texture"); |
| 417 | 417 | ||
| 418 | // LEONIDA_TITLE_EVERY_BUDGET_US: the marked textures (mapped or stale) are visited from a cursor of their own | ||
| 419 | // until the budget runs out; the unmarked ones are the round robin's and are skipped here. | ||
| 420 | { | ||
| 421 | Entry m1{true, false, 11}, u1{false, false, 12}, s1{false, true, 13}, m2{true, false, 14}; | ||
| 422 | Entry u2{false, false, 15}, s2{false, true, 16}; | ||
| 423 | std::map<std::uint64_t, Entry*> marked{{100, &m1}, {200, &u1}, {300, &s1}, {400, &m2}, {500, &u2}}; | ||
| 424 | std::uint64_t every = 0; | ||
| 425 | std::vector<int> seen; | ||
| 426 | std::vector<int> urgent_ids; // stands for "mapped and never filled" | ||
| 427 | const auto is_urgent = [&](const Entry& t) { | ||
| 428 | return std::find(urgent_ids.begin(), urgent_ids.end(), t.id) != urgent_ids.end(); | ||
| 429 | }; | ||
| 430 | const auto visit_marked = [&](auto exhausted) { | ||
| 431 | const auto snapshot = leonida::title_texture_snapshot(marked); | ||
| 432 | leonida::visit_marked_title_textures( | ||
| 433 | snapshot, every, | ||
| 434 | [&](Entry& t) { | ||
| 435 | seen.push_back(t.id); | ||
| 436 | urgent_ids.erase(std::remove(urgent_ids.begin(), urgent_ids.end(), t.id), urgent_ids.end()); | ||
| 437 | }, | ||
| 438 | is_urgent, exhausted); | ||
| 439 | }; | ||
| 440 | visit_marked([] { return false; }); | ||
| 441 | check(seen == std::vector<int>{11, 13, 14}, "without a limit every marked texture is visited once, in order"); | ||
| 442 | seen.clear(); | ||
| 443 | for (unsigned pass = 0; pass < 4; ++pass) visit_marked([] { return true; }); | ||
| 444 | check(seen == std::vector<int>{11, 13, 14, 11}, | ||
| 445 | "a budget spent after each visit moves one marked texture a pass and wraps"); | ||
| 446 | seen.clear(); | ||
| 447 | marked.erase(300); | ||
| 448 | marked[350] = &s2; | ||
| 449 | visit_marked([&] { return seen.size() == 2; }); | ||
| 450 | check(seen == std::vector<int>{16, 14}, "the cursor survives an erased entry and reaches a new stale one"); | ||
| 451 | seen.clear(); | ||
| 452 | visit_marked([] { return true; }); | ||
| 453 | check(seen == std::vector<int>{11}, "the pass after resumes past the last visited entry"); | ||
| 454 | // The cursor now points past 100 (m1). Mark m2 (at 400) urgent, as a mapped texture never filled: it is | ||
| 455 | // visited first whatever the budget, and once filled (no longer urgent) it is not visited a second time | ||
| 456 | // in the same pass's rotation. | ||
| 457 | seen.clear(); | ||
| 458 | urgent_ids = {14}; | ||
| 459 | visit_marked([] { return true; }); | ||
| 460 | check(seen == std::vector<int>{14, 16}, "an urgent texture is visited first, then one rotation step"); | ||
| 461 | seen.clear(); | ||
| 462 | urgent_ids = {14}; | ||
| 463 | visit_marked([] { return false; }); | ||
| 464 | check(seen == std::vector<int>{14, 11, 16}, | ||
| 465 | "with no limit an urgent texture is still visited once, not again in the rotation"); | ||
| 466 | seen.clear(); | ||
| 467 | const std::vector<std::pair<std::uint64_t, Entry*>> none; | ||
| 468 | leonida::visit_marked_title_textures( | ||
| 469 | none, every, [&](Entry& t) { seen.push_back(t.id); }, [](const Entry&) { return true; }, | ||
| 470 | [] { return false; }); | ||
| 471 | check(seen.empty(), "an empty registry visits nothing"); | ||
| 472 | } | ||
| 473 | |||
| 418 | // A fill made during a pass submits, and that submission destroys a retired image whose destructor erases its | 474 | // A fill made during a pass submits, and that submission destroys a retired image whose destructor erases its |
| 419 | // registry entry; the registry mutex is recursive for its owner on Windows, so the erase lands inside the pass. | 475 | // registry entry; the registry mutex is recursive for its owner on Windows, so the erase lands inside the pass. |
| 420 | // A walk over a snapshot keeps every entry of the pass alive and in order, which a walk over the registry | 476 | // A walk over a snapshot keeps every entry of the pass alive and in order, which a walk over the registry |
| @@ -436,6 +492,42 @@ int main() { | |||
| 436 | } | 492 | } |
| 437 | 493 | ||
| 438 | { | 494 | { |
| 495 | leonida::TitleTextureRangeIndex index; | ||
| 496 | std::map<std::uint64_t, std::pair<unsigned, unsigned>> ranges; | ||
| 497 | for (unsigned id = 1; id <= 60; ++id) { | ||
| 498 | const auto begin = (id * 17) % 31; | ||
| 499 | ranges[id] = {begin, begin + id}; | ||
| 500 | index.set(id, begin, id); | ||
| 501 | } | ||
| 502 | index.erase(12); | ||
| 503 | ranges.erase(12); | ||
| 504 | index.set(13, 5, 9); | ||
| 505 | ranges[13] = {5, 14}; | ||
| 506 | index.set(2, 0, 0); | ||
| 507 | ranges.erase(2); | ||
| 508 | bool same = true; | ||
| 509 | for (unsigned from = 0; from < 100; ++from) { | ||
| 510 | for (unsigned to = from; to <= 100; ++to) { | ||
| 511 | std::vector<std::uint64_t> got, want; | ||
| 512 | index.overlapping(from, to, [&](auto key) { got.push_back(key); }); | ||
| 513 | std::sort(got.begin(), got.end()); | ||
| 514 | for (const auto& [key, range] : ranges) | ||
| 515 | if (from < to && range.first < to && from < range.second) want.push_back(key); | ||
| 516 | same &= got == want; | ||
| 517 | } | ||
| 518 | } | ||
| 519 | check(same, "indexed invalidation matches all CPU overlaps after alias, replacement and removal"); | ||
| 520 | index.set(99, (UINT64_MAX >> 1) - 2, 16); | ||
| 521 | unsigned hits = 0; | ||
| 522 | index.overlapping(UINT64_MAX >> 1, (UINT64_MAX >> 1) + 1, [&](auto id) { hits += id == 99; }); | ||
| 523 | check(hits == 1, "an interval across bit 63 is indexed without a word-width shift"); | ||
| 524 | const auto slice = leonida::title_texture_snapshot(ranges, 12, 4); | ||
| 525 | check(slice.size() == 4 && slice.front().first == 13 && slice.back().first == 16, | ||
| 526 | "bounded refresh resumes at the next live address"); | ||
| 527 | check(leonida::title_texture_snapshot(ranges, 61, 4).empty(), "end of sweep permits wrap"); | ||
| 528 | } | ||
| 529 | |||
| 530 | { | ||
| 439 | leonida::TitleWriteRanges writes{{20, 30}, {10, 20}, {15, 17}, {60, 75}, {60, 67}, {90, 90}}; | 531 | leonida::TitleWriteRanges writes{{20, 30}, {10, 20}, {15, 17}, {60, 75}, {60, 67}, {90, 90}}; |
| 440 | const auto original = writes; | 532 | const auto original = writes; |
| 441 | leonida::merge_title_writes(writes); | 533 | leonida::merge_title_writes(writes); |
| @@ -699,6 +791,58 @@ int main() { | |||
| 699 | check(create(&d, &computer) == E_NOTIMPL && computer, "unsupported texture keeps a safe fallback object"); | 791 | check(create(&d, &computer) == E_NOTIMPL && computer, "unsupported texture keeps a safe fallback object"); |
| 700 | check(slot<LayoutFn>(computer, 2)(computer, &l) == E_NOTIMPL && l.size == 8192 && | 792 | check(slot<LayoutFn>(computer, 2)(computer, &l) == E_NOTIMPL && l.size == 8192 && |
| 701 | slot<RefFn>(computer, 1)(computer) == 1, "fallback leaves caller outputs untouched and is safe to release"); | 793 | slot<RefFn>(computer, 1)(computer) == 1, "fallback leaves caller outputs untouched and is safe to release"); |
| 794 | |||
| 795 | // A linear 3D texture (layout 0x100) is thin (addrlib HwlComputeSurfaceInfoLinear): rows of 256 bytes, every | ||
| 796 | // depth slice a whole mip chain. The title's texture lock reads mip 0's offset and size from this | ||
| 797 | // computer and, when creation fails, its own uninitialised stack instead: measured with the 32x32x36 R32_UINT | ||
| 798 | // 3D texture it clears 0x48000 bytes at that pointer, which is this layout's size exactly. | ||
| 799 | d = {4, 0, 32, 32, 36, 1, DXGI_FORMAT_R32_UINT, 1, 0, 0x100, 0x300004}; | ||
| 800 | if (!make(create, d, computer, "create linear 3D computer")) return 1; | ||
| 801 | std::memset(&l, 0xa5, sizeof(l)); | ||
| 802 | check(slot<LayoutFn>(computer, 2)(computer, &l) == S_OK && l.size == 0x48000 && l.alignment == 256 && | ||
| 803 | l.mips == 1 && l.dimension == 4 && l.plane[0].slice_bytes == 8192 && | ||
| 804 | l.plane[0].mips[0].offset == 0 && l.plane[0].mips[0].size == 0x48000 && | ||
| 805 | l.plane[0].mips[0].slice_bytes == 8192 && l.plane[0].mips[0].pitch_bytes == 256, | ||
| 806 | "linear 3D 32x32x36 R32 is 36 slices of 32 rows of 256 bytes"); | ||
| 807 | check(slot<SizeFn>(computer, 3)(computer) == 0x48000 && slot<SizeFn>(computer, 4)(computer) == 256, | ||
| 808 | "linear 3D size and alignment agree with slot 2"); | ||
| 809 | check(slot<OffsetFn>(computer, 6)(computer, 0, 0, 3, 2, 5, 0, nullptr) == 5 * 8192 + 2 * 256 + 3 * 4, | ||
| 810 | "linear 3D element offset is slice, row, column"); | ||
| 811 | { | ||
| 812 | // A mip-0 copy through slots 8 and 9: padded source rows and slices land at 256-byte rows, 8 KiB slices. | ||
| 813 | constexpr unsigned row = 32 * 4 + 12, slice = row * 32 + 20; | ||
| 814 | std::vector<uint8_t> source(slice * 36), read_back(source.size(), 0), memory(l.size, 0); | ||
| 815 | for (size_t i = 0; i < source.size(); ++i) source[i] = uint8_t(i * 7 + 3); | ||
| 816 | check(slot<IntoFn>(computer, 8)(computer, memory.data(), 0, 0, source.data(), row, slice) == S_OK && | ||
| 817 | std::memcmp(&memory[35 * 8192 + 31 * 256], &source[35 * slice + 31 * row], 32 * 4) == 0 && | ||
| 818 | slot<FromFn>(computer, 9)(computer, read_back.data(), 0, 0, 0, memory.data(), row, slice) == S_OK && | ||
| 819 | std::memcmp(&read_back[35 * slice + 31 * row], &source[35 * slice + 31 * row], 32 * 4) == 0, | ||
| 820 | "slots 8 and 9 copy a linear 3D mip slice by slice"); | ||
| 821 | check(slot<IntoFn>(computer, 8)(computer, memory.data(), 0, 1, source.data(), row, slice) == E_INVALIDARG, | ||
| 822 | "a 3D texture has no second subresource"); | ||
| 823 | } | ||
| 824 | slot<RefFn>(computer, 1)(computer); | ||
| 825 | |||
| 826 | // A linear 3D texture with more than one mip: its chain layout (slice-major or mip-major) is not measured, so the | ||
| 827 | // description is refused rather than given offsets that may be wrong for mips 1+. | ||
| 828 | d = {4, 0, 32, 16, 8, 3, DXGI_FORMAT_R8_UNORM, 1, 0, 0x100, 0}; | ||
| 829 | check(!build_texture(d, texture), "linear 3D with mips is refused until a title texture measures it"); | ||
| 830 | |||
| 831 | // A render-target or depth flag with an explicit mode takes that mode's layout (measured: 1x1 RGBA32F | ||
| 832 | // descriptions with layout 0x100 and the render-target bit reach the title's CPU upload). | ||
| 833 | d = {3, 0, 1, 1, 1, 1, DXGI_FORMAT_R32G32B32A32_FLOAT, 1, 0, 0x100, 0x300001}; | ||
| 834 | if (!make(create, d, computer, "create linear render-target computer")) return 1; | ||
| 835 | check(slot<LayoutFn>(computer, 2)(computer, &l) == S_OK && l.size == 256 && l.alignment == 256, | ||
| 836 | "explicit linear render target is one 256-byte row"); | ||
| 837 | slot<RefFn>(computer, 1)(computer); | ||
| 838 | // Without a mode, the render target is not this model's (it leaves the mode to XG's Z/R choice): the general layout | ||
| 839 | // model lays it out, as it does the other render targets above. | ||
| 840 | void* general = nullptr; | ||
| 841 | d.layout = 0; | ||
| 842 | Texture own{}; | ||
| 843 | check(!build_texture(d, own), "a render target without a mode is not the explicit-mode model's"); | ||
| 844 | check(create(&d, &general) == S_OK && general, "a render target without a mode uses the general layout model"); | ||
| 845 | if (general) slot<RefFn>(general, 1)(general); | ||
| 702 | std::printf("%d checks, %d failures\n", g_checks, g_failures); | 846 | std::printf("%d checks, %d failures\n", g_checks, g_failures); |
| 703 | return g_failures ? 1 : 0; | 847 | return g_failures ? 1 : 0; |
| 704 | } | 848 | } |
diff --git a/runtime/test/xs_proxy_mock_test.cpp b/runtime/test/xs_proxy_mock_test.cpp index 27af09aec..cb350820e 100644 --- a/runtime/test/xs_proxy_mock_test.cpp +++ b/runtime/test/xs_proxy_mock_test.cpp | |||
| @@ -137,11 +137,62 @@ struct Mock { | |||
| 137 | UINT clear_dsv_num_rects; | 137 | UINT clear_dsv_num_rects; |
| 138 | const D3D12_RECT* clear_dsv_rects; | 138 | const D3D12_RECT* clear_dsv_rects; |
| 139 | D3D_FEATURE_LEVEL max_level; // device: the highest level FEATURE_LEVELS reports (0: the query is refused) | 139 | D3D_FEATURE_LEVEL max_level; // device: the highest level FEATURE_LEVELS reports (0: the query is refused) |
| 140 | // list: set by a call the Vulkan layer's list takes as invalid (a texture barrier with no resource at slot 80, a | ||
| 141 | // clear at slot 48 of a view made with no resource); Close (slot 9) then fails, as that list's does. | ||
| 142 | bool list_error; | ||
| 143 | // list slot 80 (Barrier): what the last call carried, copied (the proxy's converted groups live for the call). | ||
| 144 | UINT barrier_group_count; | ||
| 145 | D3D12_BARRIER_TYPE barrier_group_types[4]; | ||
| 146 | UINT barrier_group_sizes[4]; | ||
| 147 | UINT barrier_global_count; | ||
| 148 | D3D12_GLOBAL_BARRIER barrier_globals[8]; | ||
| 149 | UINT barrier_texture_count; | ||
| 150 | D3D12_TEXTURE_BARRIER barrier_textures[8]; | ||
| 140 | }; | 151 | }; |
| 141 | 152 | ||
| 142 | Mock g_pool[512]; | 153 | Mock g_pool[512]; |
| 143 | unsigned g_pool_used = 0; | 154 | unsigned g_pool_used = 0; |
| 144 | 155 | ||
| 156 | // The real handles the mock device last wrote an RTV with no resource at (device slot 20). A mock list's clear of one | ||
| 157 | // sets list_error, as the Vulkan layer's empty view record does. | ||
| 158 | SIZE_T g_mock_null_rtvs[16]; | ||
| 159 | unsigned g_mock_null_rtv_count = 0; | ||
| 160 | |||
| 161 | void mock_note_rtv(SIZE_T handle, bool no_resource) { | ||
| 162 | for (unsigned i = 0; i < g_mock_null_rtv_count; ++i) | ||
| 163 | if (g_mock_null_rtvs[i] == handle) g_mock_null_rtvs[i--] = g_mock_null_rtvs[--g_mock_null_rtv_count]; | ||
| 164 | if (no_resource && g_mock_null_rtv_count < std::size(g_mock_null_rtvs)) | ||
| 165 | g_mock_null_rtvs[g_mock_null_rtv_count++] = handle; | ||
| 166 | } | ||
| 167 | |||
| 168 | bool mock_is_null_rtv(SIZE_T handle) { | ||
| 169 | for (unsigned i = 0; i < g_mock_null_rtv_count; ++i) | ||
| 170 | if (g_mock_null_rtvs[i] == handle) return true; | ||
| 171 | return false; | ||
| 172 | } | ||
| 173 | |||
| 174 | void mock_barrier(Mock* m, std::uint64_t count, std::uint64_t groups_word) { | ||
| 175 | const auto* groups = reinterpret_cast<const D3D12_BARRIER_GROUP*>(groups_word); | ||
| 176 | m->barrier_group_count = static_cast<UINT>(count); | ||
| 177 | m->barrier_global_count = m->barrier_texture_count = 0; | ||
| 178 | for (UINT g = 0; groups && g < static_cast<UINT>(count); ++g) { | ||
| 179 | const D3D12_BARRIER_GROUP& group = groups[g]; | ||
| 180 | if (g < std::size(m->barrier_group_types)) { | ||
| 181 | m->barrier_group_types[g] = group.Type; | ||
| 182 | m->barrier_group_sizes[g] = group.NumBarriers; | ||
| 183 | } | ||
| 184 | for (UINT i = 0; i < group.NumBarriers; ++i) { | ||
| 185 | if (group.Type == D3D12_BARRIER_TYPE_GLOBAL && m->barrier_global_count < std::size(m->barrier_globals)) { | ||
| 186 | m->barrier_globals[m->barrier_global_count++] = group.pGlobalBarriers[i]; | ||
| 187 | } else if (group.Type == D3D12_BARRIER_TYPE_TEXTURE) { | ||
| 188 | if (!group.pTextureBarriers[i].pResource) m->list_error = true; | ||
| 189 | if (m->barrier_texture_count < std::size(m->barrier_textures)) | ||
| 190 | m->barrier_textures[m->barrier_texture_count++] = group.pTextureBarriers[i]; | ||
| 191 | } | ||
| 192 | } | ||
| 193 | } | ||
| 194 | } | ||
| 195 | |||
| 145 | void** mock_vtable(); | 196 | void** mock_vtable(); |
| 146 | void** mock_list_vtable(); | 197 | void** mock_list_vtable(); |
| 147 | 198 | ||
| @@ -384,6 +435,7 @@ std::uint64_t mock_call(Mock* m, unsigned slot, const std::uint64_t* words) { | |||
| 384 | if (a1) std::memcpy(&m->queue_desc, reinterpret_cast<const void*>(a1), sizeof(m->queue_desc)); | 435 | if (a1) std::memcpy(&m->queue_desc, reinterpret_cast<const void*>(a1), sizeof(m->queue_desc)); |
| 385 | return static_cast<std::uint32_t>(mock_create(m, Kind::queue, a2, a3)); | 436 | return static_cast<std::uint32_t>(mock_create(m, Kind::queue, a2, a3)); |
| 386 | case 9: return static_cast<std::uint32_t>(mock_create(m, Kind::allocator, a2, a3)); // CreateCmdAllocator | 437 | case 9: return static_cast<std::uint32_t>(mock_create(m, Kind::allocator, a2, a3)); // CreateCmdAllocator |
| 438 | case 20: mock_note_rtv(static_cast<SIZE_T>(a3), a1 == 0); break; // CreateRenderTargetView(res, desc, dest) | ||
| 387 | // Slot 12 (CreateCommandList) never reaches this switch: the device vtable's slot is the dedicated | 439 | // Slot 12 (CreateCommandList) never reaches this switch: the device vtable's slot is the dedicated |
| 388 | // mock_create_command_list, which needs the sixth word the generic thunk does not declare on some | 440 | // mock_create_command_list, which needs the sixth word the generic thunk does not declare on some |
| 389 | // builds and which picks the list mock's chain breadth from full_chain_lists. | 441 | // builds and which picks the list mock's chain breadth from full_chain_lists. |
| @@ -524,6 +576,11 @@ std::uint64_t mock_call(Mock* m, unsigned slot, const std::uint64_t* words) { | |||
| 524 | m->om_has_dsv = dsv != nullptr; | 576 | m->om_has_dsv = dsv != nullptr; |
| 525 | m->om_dsv = dsv ? dsv->ptr : 0; | 577 | m->om_dsv = dsv ? dsv->ptr : 0; |
| 526 | } | 578 | } |
| 579 | if (m->kind == Kind::list || m->kind == Kind::command_list) { | ||
| 580 | if (slot == 9) return static_cast<std::uint32_t>(m->list_error ? E_INVALIDARG : S_OK); // Close | ||
| 581 | if (slot == 48 && mock_is_null_rtv(static_cast<SIZE_T>(a1))) m->list_error = true; // ClearRenderTargetView | ||
| 582 | if (slot == 80) mock_barrier(m, a1, a2); // Barrier | ||
| 583 | } | ||
| 527 | return S_OK; | 584 | return S_OK; |
| 528 | } | 585 | } |
| 529 | 586 | ||
| @@ -2419,7 +2476,8 @@ int check_lists() { | |||
| 2419 | so_view.BufferFilledSizeLocation = p2; | 2476 | so_view.BufferFilledSizeLocation = p2; |
| 2420 | EXPECT(hr_of(raw(list, 49, 0, 1, word(&so_view))) == S_OK && real->calls[45] == 1); | 2477 | EXPECT(hr_of(raw(list, 49, 0, 1, word(&so_view))) == S_OK && real->calls[45] == 1); |
| 2421 | // The console tail past the PC chain is refused with E_NOTIMPL only when the mapped PC slot is missing. | 2478 | // The console tail past the PC chain is refused with E_NOTIMPL only when the mapped PC slot is missing. |
| 2422 | EXPECT(hr_of(raw(list, 146, word(list), 0)) == S_OK && real->calls[80] == 1); // enhanced Barrier -> GCL7 80 | 2479 | // Enhanced Barrier -> GCL7 80; an empty call (no groups) goes through as the PC no-op it is. |
| 2480 | EXPECT(hr_of(raw(list, 146, 0, 0)) == S_OK && real->calls[80] == 1); | ||
| 2423 | EXPECT(release(list) == 0 && real->refs == 0); | 2481 | EXPECT(release(list) == 0 && real->refs == 0); |
| 2424 | EXPECT(release(allocator) == 0 && real_allocator->refs == 0); | 2482 | EXPECT(release(allocator) == 0 && real_allocator->refs == 0); |
| 2425 | EXPECT(xs::device_proxy_ref_count(device) == device_refs); | 2483 | EXPECT(xs::device_proxy_ref_count(device) == device_refs); |
| @@ -2952,6 +3010,36 @@ int check_render_target_sizes() { | |||
| 2952 | mips.MipLevels = 3; | 3010 | mips.MipLevels = 3; |
| 2953 | EXPECT(ask(&mips, 1).SizeInBytes == (135 + 40 + 12) * 65536ull); | 3011 | EXPECT(ask(&mips, 1).SizeInBytes == (135 + 40 + 12) * 65536ull); |
| 2954 | 3012 | ||
| 3013 | // A texture the GPU writes through unordered access and the title also clears with the CPU through its lock | ||
| 3014 | // with a layout word naming its mode: 0x100, linear. Its console layout is 36 slices of 32 rows | ||
| 3015 | // of 256 bytes, 0x48000 bytes, where the PC device says 0x30000; the larger size wins, rounded to the | ||
| 3016 | // description's alignment. The title's own layout word decides, though the PC form of the description has lost it. | ||
| 3017 | D3D12_RESOURCE_DESC grid{}; | ||
| 3018 | grid.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE3D; | ||
| 3019 | grid.Width = 32; | ||
| 3020 | grid.Height = 32; | ||
| 3021 | grid.DepthOrArraySize = 36; | ||
| 3022 | grid.MipLevels = 1; | ||
| 3023 | grid.Format = DXGI_FORMAT_R32_UINT; | ||
| 3024 | grid.SampleDesc.Count = 1; | ||
| 3025 | grid.Layout = static_cast<D3D12_TEXTURE_LAYOUT>(0x100); | ||
| 3026 | grid.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; | ||
| 3027 | EXPECT(ask(&grid, 1).SizeInBytes == 0x50000); | ||
| 3028 | // In a list it takes its console size at its own offset. | ||
| 3029 | const D3D12_RESOURCE_DESC grid_and_target[] = {grid, hd}; | ||
| 3030 | EXPECT(ask(grid_and_target, 2).SizeInBytes == 0x50000 + 8847360); | ||
| 3031 | // The rule only grows: a mode XG lays out smaller (4 KiB thick blocks, 32x32x40 x 4 B = 0x28000) keeps the PC | ||
| 3032 | // size, and so does a layout word that leaves the mode to XG, or a mode XG's model lacks. | ||
| 3033 | D3D12_RESOURCE_DESC smaller = grid; | ||
| 3034 | smaller.Layout = static_cast<D3D12_TEXTURE_LAYOUT>(0x105); | ||
| 3035 | EXPECT(ask(&smaller, 1).SizeInBytes == 0x30000); | ||
| 3036 | D3D12_RESOURCE_DESC no_mode = grid; | ||
| 3037 | no_mode.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN; | ||
| 3038 | EXPECT(ask(&no_mode, 1).SizeInBytes == 0x30000); | ||
| 3039 | D3D12_RESOURCE_DESC unknown_mode = grid; | ||
| 3040 | unknown_mode.Layout = static_cast<D3D12_TEXTURE_LAYOUT>(0x11b); // SW_64KB_R_X | ||
| 3041 | EXPECT(ask(&unknown_mode, 1).SizeInBytes == 0x30000); | ||
| 3042 | |||
| 2955 | // The PC form (this in RCX, the buffer in RDX) is not the title's call: it gets the PC device's own size, 127 | 3043 | // The PC form (this in RCX, the buffer in RDX) is not the title's call: it gets the PC device's own size, 127 |
| 2956 | // units of 64 KiB for the mock, so code that compares the proxy with the PC device still agrees. | 3044 | // units of 64 KiB for the mock, so code that compares the proxy with the PC device still agrees. |
| 2957 | D3D12_RESOURCE_ALLOCATION_INFO pc{}; | 3045 | D3D12_RESOURCE_ALLOCATION_INFO pc{}; |
| @@ -4807,10 +4895,18 @@ int check_console_command_list() { | |||
| 4807 | EXPECT(xs::is_command_list_proxy(list7_proxy)); | 4895 | EXPECT(xs::is_command_list_proxy(list7_proxy)); |
| 4808 | Mock* real_list7 = reinterpret_cast<Mock*>(xs::command_list_proxy_real_list(list7_proxy)); | 4896 | Mock* real_list7 = reinterpret_cast<Mock*>(xs::command_list_proxy_real_list(list7_proxy)); |
| 4809 | EXPECT(real_list7 != nullptr); | 4897 | EXPECT(real_list7 != nullptr); |
| 4810 | // Console slot 146 -> PC slot 80 (since 80 < 81 slots) | 4898 | // Console slot 146 -> PC slot 80 (since 80 < 81 slots): a valid group goes through with the title's pointer. |
| 4811 | raw(list7_proxy, 146, 0x9999, 0, 0, 0); | 4899 | { |
| 4812 | EXPECT(real_list7->calls[80] == 1); | 4900 | const D3D12_GLOBAL_BARRIER global{D3D12_BARRIER_SYNC_ALL, D3D12_BARRIER_SYNC_ALL, |
| 4813 | EXPECT(real_list7->args[80][0] == 0x9999); | 4901 | D3D12_BARRIER_ACCESS_UNORDERED_ACCESS, D3D12_BARRIER_ACCESS_UNORDERED_ACCESS}; |
| 4902 | D3D12_BARRIER_GROUP group{}; | ||
| 4903 | group.Type = D3D12_BARRIER_TYPE_GLOBAL; | ||
| 4904 | group.NumBarriers = 1; | ||
| 4905 | group.pGlobalBarriers = &global; | ||
| 4906 | raw(list7_proxy, 146, 1, word(&group), 0, 0); | ||
| 4907 | EXPECT(real_list7->calls[80] == 1); | ||
| 4908 | EXPECT(real_list7->args[80][0] == 1 && real_list7->args[80][1] == word(&group)); | ||
| 4909 | } | ||
| 4814 | EXPECT(release(list7_proxy) == 0 && real_list7->refs == 0); | 4910 | EXPECT(release(list7_proxy) == 0 && real_list7->refs == 0); |
| 4815 | 4911 | ||
| 4816 | // Clean up | 4912 | // Clean up |
| @@ -4830,6 +4926,249 @@ int check_console_command_list() { | |||
| 4830 | return 0; | 4926 | return 0; |
| 4831 | } | 4927 | } |
| 4832 | 4928 | ||
| 4929 | // ---- Console list slots 146 and 52: what the console takes as a no-op or a global barrier ---- | ||
| 4930 | // | ||
| 4931 | // The mock list stands in for the Vulkan layer's: a texture barrier with no resource, or a clear of a view made with | ||
| 4932 | // no resource, puts it in its error state and its Close fails (checked directly on the mock first, so the cases | ||
| 4933 | // below mean something). Through the proxy the barrier becomes a global barrier and the clear is skipped. | ||
| 4934 | int check_console_null_barrier_and_clear() { | ||
| 4935 | g_mock_null_rtv_count = 0; | ||
| 4936 | Mock* mock = nullptr; | ||
| 4937 | void* device = make_device(mock, 9, true, true, /*full_chain_lists=*/true); | ||
| 4938 | EXPECT(device); | ||
| 4939 | const IID allocator_iid = __uuidof(ID3D12CommandAllocator); | ||
| 4940 | const IID gcl_iid = __uuidof(ID3D12GraphicsCommandList); | ||
| 4941 | void* allocator = nullptr; | ||
| 4942 | EXPECT(hr_of(raw(device, 9, D3D12_COMMAND_LIST_TYPE_DIRECT, word(&allocator_iid), word(&allocator))) == S_OK); | ||
| 4943 | void* list = nullptr; | ||
| 4944 | EXPECT(hr_of(raw(device, 12, 0, D3D12_COMMAND_LIST_TYPE_DIRECT, word(allocator), 0, word(&gcl_iid), | ||
| 4945 | word(&list))) == S_OK); | ||
| 4946 | Mock* const real = reinterpret_cast<Mock*>(xs::list_proxy_real_list(list)); | ||
| 4947 | EXPECT(real && real->kind == Kind::list); | ||
| 4948 | Mock* const texture_a = new_mock(Kind::resource); // never dereferenced: only the pointers are compared | ||
| 4949 | Mock* const texture_b = new_mock(Kind::resource); | ||
| 4950 | auto* const resource_a = reinterpret_cast<ID3D12Resource*>(texture_a); | ||
| 4951 | auto* const resource_b = reinterpret_cast<ID3D12Resource*>(texture_b); | ||
| 4952 | |||
| 4953 | // A texture barrier with no resource, as the title records it: render target to pixel-shader read. | ||
| 4954 | D3D12_TEXTURE_BARRIER no_resource{}; | ||
| 4955 | no_resource.SyncBefore = D3D12_BARRIER_SYNC_RENDER_TARGET; | ||
| 4956 | no_resource.SyncAfter = D3D12_BARRIER_SYNC_PIXEL_SHADING; | ||
| 4957 | no_resource.AccessBefore = D3D12_BARRIER_ACCESS_RENDER_TARGET; | ||
| 4958 | no_resource.AccessAfter = D3D12_BARRIER_ACCESS_SHADER_RESOURCE; | ||
| 4959 | no_resource.LayoutBefore = D3D12_BARRIER_LAYOUT_RENDER_TARGET; | ||
| 4960 | no_resource.LayoutAfter = D3D12_BARRIER_LAYOUT_SHADER_RESOURCE; | ||
| 4961 | no_resource.Subresources.IndexOrFirstMipLevel = 0xffffffffu; | ||
| 4962 | D3D12_BARRIER_GROUP texture_group{}; | ||
| 4963 | texture_group.Type = D3D12_BARRIER_TYPE_TEXTURE; | ||
| 4964 | texture_group.NumBarriers = 1; | ||
| 4965 | texture_group.pTextureBarriers = &no_resource; | ||
| 4966 | |||
| 4967 | // The mock models the PC list: the same group sent to it directly fails its Close. | ||
| 4968 | raw(real, 80, 1, word(&texture_group)); | ||
| 4969 | EXPECT(real->list_error && hr_of(raw(real, 9)) == E_INVALIDARG); | ||
| 4970 | real->list_error = false; | ||
| 4971 | real->calls[80] = 0; | ||
| 4972 | |||
| 4973 | // 1. Through the proxy: one global barrier with the same sync and access, in the call's own storage; the | ||
| 4974 | // title's group and barrier are not written; Close succeeds. | ||
| 4975 | EXPECT(hr_of(raw(list, 146, 1, word(&texture_group))) == S_OK); | ||
| 4976 | EXPECT(real->calls[80] == 1 && real->args[80][0] == 1 && real->args[80][1] != word(&texture_group)); | ||
| 4977 | EXPECT(real->barrier_group_count == 1 && real->barrier_group_types[0] == D3D12_BARRIER_TYPE_GLOBAL && | ||
| 4978 | real->barrier_group_sizes[0] == 1 && real->barrier_global_count == 1 && real->barrier_texture_count == 0); | ||
| 4979 | EXPECT(real->barrier_globals[0].SyncBefore == D3D12_BARRIER_SYNC_RENDER_TARGET && | ||
| 4980 | real->barrier_globals[0].SyncAfter == D3D12_BARRIER_SYNC_PIXEL_SHADING && | ||
| 4981 | real->barrier_globals[0].AccessBefore == D3D12_BARRIER_ACCESS_RENDER_TARGET && | ||
| 4982 | real->barrier_globals[0].AccessAfter == D3D12_BARRIER_ACCESS_SHADER_RESOURCE); | ||
| 4983 | EXPECT(texture_group.Type == D3D12_BARRIER_TYPE_TEXTURE && texture_group.pTextureBarriers == &no_resource && | ||
| 4984 | !no_resource.pResource); | ||
| 4985 | EXPECT(!real->list_error && hr_of(raw(list, 9)) == S_OK); | ||
| 4986 | |||
| 4987 | // 2. Valid barriers pass unchanged: a texture group with resources goes through with the title's own pointer. | ||
| 4988 | D3D12_TEXTURE_BARRIER with_resource[2] = {no_resource, no_resource}; | ||
| 4989 | with_resource[0].pResource = resource_a; | ||
| 4990 | with_resource[1].pResource = resource_b; | ||
| 4991 | with_resource[1].Subresources = {2, 1, 0, 1, 0, 1}; | ||
| 4992 | D3D12_BARRIER_GROUP valid_group{}; | ||
| 4993 | valid_group.Type = D3D12_BARRIER_TYPE_TEXTURE; | ||
| 4994 | valid_group.NumBarriers = 2; | ||
| 4995 | valid_group.pTextureBarriers = with_resource; | ||
| 4996 | EXPECT(hr_of(raw(list, 146, 1, word(&valid_group))) == S_OK); | ||
| 4997 | EXPECT(real->calls[80] == 2 && real->args[80][0] == 1 && real->args[80][1] == word(&valid_group)); | ||
| 4998 | EXPECT(real->barrier_texture_count == 2 && real->barrier_global_count == 0 && | ||
| 4999 | real->barrier_textures[0].pResource == resource_a && real->barrier_textures[1].pResource == resource_b && | ||
| 5000 | real->barrier_textures[1].LayoutAfter == D3D12_BARRIER_LAYOUT_SHADER_RESOURCE && | ||
| 5001 | real->barrier_textures[1].Subresources.IndexOrFirstMipLevel == 2); | ||
| 5002 | EXPECT(!real->list_error && hr_of(raw(list, 9)) == S_OK); | ||
| 5003 | |||
| 5004 | // 3. Mixed: a buffer group, then a texture group of [resource, none, none, resource]. The buffer group passes as | ||
| 5005 | // it is and the texture group splits into texture(1), global(2), texture(1), in order. | ||
| 5006 | const D3D12_BUFFER_BARRIER buffer{D3D12_BARRIER_SYNC_COPY, D3D12_BARRIER_SYNC_COMPUTE_SHADING, | ||
| 5007 | D3D12_BARRIER_ACCESS_COPY_DEST, D3D12_BARRIER_ACCESS_UNORDERED_ACCESS, | ||
| 5008 | resource_a, 0, UINT64_MAX}; | ||
| 5009 | D3D12_TEXTURE_BARRIER mixed[4] = {with_resource[0], no_resource, no_resource, with_resource[1]}; | ||
| 5010 | mixed[2].SyncBefore = D3D12_BARRIER_SYNC_COMPUTE_SHADING; | ||
| 5011 | mixed[2].AccessBefore = D3D12_BARRIER_ACCESS_UNORDERED_ACCESS; | ||
| 5012 | D3D12_BARRIER_GROUP mixed_groups[2]{}; | ||
| 5013 | mixed_groups[0].Type = D3D12_BARRIER_TYPE_BUFFER; | ||
| 5014 | mixed_groups[0].NumBarriers = 1; | ||
| 5015 | mixed_groups[0].pBufferBarriers = &buffer; | ||
| 5016 | mixed_groups[1].Type = D3D12_BARRIER_TYPE_TEXTURE; | ||
| 5017 | mixed_groups[1].NumBarriers = 4; | ||
| 5018 | mixed_groups[1].pTextureBarriers = mixed; | ||
| 5019 | EXPECT(hr_of(raw(list, 146, 2, word(mixed_groups))) == S_OK); | ||
| 5020 | EXPECT(real->calls[80] == 3 && real->args[80][0] == 4); | ||
| 5021 | EXPECT(real->barrier_group_types[0] == D3D12_BARRIER_TYPE_BUFFER && real->barrier_group_sizes[0] == 1 && | ||
| 5022 | real->barrier_group_types[1] == D3D12_BARRIER_TYPE_TEXTURE && real->barrier_group_sizes[1] == 1 && | ||
| 5023 | real->barrier_group_types[2] == D3D12_BARRIER_TYPE_GLOBAL && real->barrier_group_sizes[2] == 2 && | ||
| 5024 | real->barrier_group_types[3] == D3D12_BARRIER_TYPE_TEXTURE && real->barrier_group_sizes[3] == 1); | ||
| 5025 | EXPECT(real->barrier_texture_count == 2 && real->barrier_textures[0].pResource == resource_a && | ||
| 5026 | real->barrier_textures[1].pResource == resource_b); | ||
| 5027 | EXPECT(real->barrier_global_count == 2 && | ||
| 5028 | real->barrier_globals[0].SyncBefore == D3D12_BARRIER_SYNC_RENDER_TARGET && | ||
| 5029 | real->barrier_globals[1].SyncBefore == D3D12_BARRIER_SYNC_COMPUTE_SHADING && | ||
| 5030 | real->barrier_globals[1].AccessBefore == D3D12_BARRIER_ACCESS_UNORDERED_ACCESS && | ||
| 5031 | real->barrier_globals[1].AccessAfter == D3D12_BARRIER_ACCESS_SHADER_RESOURCE); | ||
| 5032 | EXPECT(!real->list_error && hr_of(raw(list, 9)) == S_OK); | ||
| 5033 | |||
| 5034 | // 4. Arrays that cannot be read safely are refused whole: nothing reaches the list, which stays valid and keeps | ||
| 5035 | // taking calls. | ||
| 5036 | D3D12_BARRIER_GROUP unknown_type = texture_group; | ||
| 5037 | reinterpret_cast<std::uint32_t&>(unknown_type.Type) = 7; | ||
| 5038 | D3D12_BARRIER_GROUP null_barriers{}; | ||
| 5039 | null_barriers.Type = D3D12_BARRIER_TYPE_TEXTURE; | ||
| 5040 | null_barriers.NumBarriers = 3; | ||
| 5041 | D3D12_BARRIER_GROUP huge_group = valid_group; | ||
| 5042 | huge_group.NumBarriers = 0x10000000u; | ||
| 5043 | EXPECT(hr_of(raw(list, 146, 1, 0)) == S_OK); // null array, nonzero count | ||
| 5044 | EXPECT(hr_of(raw(list, 146, 1, word(&unknown_type))) == S_OK); // a group type the layer does not know | ||
| 5045 | EXPECT(hr_of(raw(list, 146, 1, word(&null_barriers))) == S_OK); // null barrier array, nonzero count | ||
| 5046 | EXPECT(hr_of(raw(list, 146, 1, word(&huge_group))) == S_OK); // barrier count over the limit | ||
| 5047 | EXPECT(hr_of(raw(list, 146, 0x40000000u, word(&valid_group))) == S_OK); // group count over the limit | ||
| 5048 | // A malformed group after a convertible one refuses the call as well: nothing of it is recorded. | ||
| 5049 | D3D12_BARRIER_GROUP half_bad[2] = {texture_group, unknown_type}; | ||
| 5050 | EXPECT(hr_of(raw(list, 146, 2, word(half_bad))) == S_OK); | ||
| 5051 | EXPECT(real->calls[80] == 3 && !real->list_error); | ||
| 5052 | EXPECT(hr_of(raw(list, 146, 1, word(&texture_group))) == S_OK && real->calls[80] == 4); | ||
| 5053 | EXPECT(!real->list_error && hr_of(raw(list, 9)) == S_OK); | ||
| 5054 | |||
| 5055 | // 5. ClearRenderTargetView (console 52 -> PC 48) of a view made with no resource is skipped; a view made with a | ||
| 5056 | // resource is still cleared. No custom heap range here, so the handles reach the device unchanged. | ||
| 5057 | const SIZE_T rtv_none = kMockHeapCpuStart + 0x1000; | ||
| 5058 | const SIZE_T rtv_real = rtv_none + kMockDescriptorInc; | ||
| 5059 | const SIZE_T rtv_copy = rtv_none + 4 * kMockDescriptorInc; | ||
| 5060 | const FLOAT color[4] = {0.0f, 0.0f, 0.0f, 0.0f}; | ||
| 5061 | raw(device, 20, 0, 0, rtv_none); // CreateRenderTargetView(nullptr, nullptr, handle) | ||
| 5062 | raw(device, 20, word(resource_a), 0, rtv_real); | ||
| 5063 | EXPECT(mock->calls[20] == 2 && mock_is_null_rtv(rtv_none) && !mock_is_null_rtv(rtv_real)); | ||
| 5064 | raw(real, 48, rtv_none, word(color), 0, 0); // the mock's model: the direct clear fails the list | ||
| 5065 | EXPECT(real->list_error && hr_of(raw(real, 9)) == E_INVALIDARG); | ||
| 5066 | real->list_error = false; | ||
| 5067 | real->calls[48] = 0; | ||
| 5068 | |||
| 5069 | EXPECT(hr_of(raw(list, 52, rtv_none, word(color), 0, 0)) == S_OK && real->calls[48] == 0); | ||
| 5070 | EXPECT(!real->list_error && hr_of(raw(list, 9)) == S_OK); | ||
| 5071 | const D3D12_RECT rect{0, 0, 4, 4}; | ||
| 5072 | raw(list, 52, rtv_real, word(color), 1, word(&rect)); | ||
| 5073 | EXPECT(real->calls[48] == 1 && real->args[48][0] == rtv_real && real->args[48][1] == word(color) && | ||
| 5074 | real->args[48][2] == 1 && real->args[48][3] == word(&rect)); | ||
| 5075 | EXPECT(!real->list_error && hr_of(raw(list, 9)) == S_OK); | ||
| 5076 | |||
| 5077 | // A view made again at the same handle with a resource is cleared from then on. | ||
| 5078 | raw(device, 20, word(resource_b), 0, rtv_none); | ||
| 5079 | raw(list, 52, rtv_none, word(color), 0, 0); | ||
| 5080 | EXPECT(real->calls[48] == 2 && real->args[48][0] == rtv_none); | ||
| 5081 | raw(device, 20, 0, 0, rtv_none); // and with no resource again: skipped again | ||
| 5082 | raw(list, 52, rtv_none, word(color), 0, 0); | ||
| 5083 | EXPECT(real->calls[48] == 2); | ||
| 5084 | |||
| 5085 | // Descriptor copies move the mark: CopyDescriptorsSimple of the empty view, then of the real one over it. | ||
| 5086 | raw(device, 24, 1, rtv_copy, rtv_none, D3D12_DESCRIPTOR_HEAP_TYPE_RTV); | ||
| 5087 | raw(list, 52, rtv_copy, word(color), 0, 0); | ||
| 5088 | EXPECT(real->calls[48] == 2); | ||
| 5089 | raw(device, 24, 1, rtv_copy, rtv_real, D3D12_DESCRIPTOR_HEAP_TYPE_RTV); | ||
| 5090 | raw(list, 52, rtv_copy, word(color), 0, 0); | ||
| 5091 | EXPECT(real->calls[48] == 3 && real->args[48][0] == rtv_copy); | ||
| 5092 | // A copy of another heap type leaves the RTV marks alone. | ||
| 5093 | raw(device, 24, 1, rtv_copy, rtv_none, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); | ||
| 5094 | raw(list, 52, rtv_copy, word(color), 0, 0); | ||
| 5095 | EXPECT(real->calls[48] == 4); | ||
| 5096 | // CopyDescriptors with ranges: one destination range of two from two source ranges of one (empty, then real). | ||
| 5097 | const D3D12_CPU_DESCRIPTOR_HANDLE dest_starts[1] = {{rtv_copy}}; | ||
| 5098 | const UINT dest_sizes[1] = {2}; | ||
| 5099 | const D3D12_CPU_DESCRIPTOR_HANDLE src_starts[2] = {{rtv_none}, {rtv_real}}; | ||
| 5100 | const UINT src_sizes[2] = {1, 1}; | ||
| 5101 | raw10(device, 23, {1, word(dest_starts), word(dest_sizes), 2, word(src_starts), word(src_sizes), | ||
| 5102 | D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 0, 0, 0}); | ||
| 5103 | EXPECT(mock->calls[23] == 1); | ||
| 5104 | raw(list, 52, rtv_copy, word(color), 0, 0); | ||
| 5105 | EXPECT(real->calls[48] == 4); | ||
| 5106 | raw(list, 52, rtv_copy + kMockDescriptorInc, word(color), 0, 0); | ||
| 5107 | EXPECT(real->calls[48] == 5 && real->args[48][0] == rtv_copy + kMockDescriptorInc); | ||
| 5108 | EXPECT(!real->list_error && hr_of(raw(list, 9)) == S_OK); | ||
| 5109 | |||
| 5110 | // Releasing an RTV heap drops the marks in its real range, so a heap made later at the same address starts | ||
| 5111 | // unmarked; a mark outside that range stays. | ||
| 5112 | g_heap_hook.next_ptr = nullptr; // a plain PC heap even if a descriptor-heap hook is registered: real handles | ||
| 5113 | D3D12_DESCRIPTOR_HEAP_DESC rtv_heap_desc{}; | ||
| 5114 | rtv_heap_desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_RTV; | ||
| 5115 | rtv_heap_desc.NumDescriptors = 4; | ||
| 5116 | const IID heap_iid = __uuidof(ID3D12DescriptorHeap); | ||
| 5117 | void* rtv_heap = nullptr; | ||
| 5118 | EXPECT(SUCCEEDED(hr_of(raw(device, 14, word(&rtv_heap_desc), word(&heap_iid), word(&rtv_heap))))); | ||
| 5119 | EXPECT(rtv_heap && xs::is_heap_proxy(rtv_heap) && raw(rtv_heap, 9) == kMockHeapCpuStart); | ||
| 5120 | const SIZE_T in_heap = kMockHeapCpuStart + 2 * kMockDescriptorInc; | ||
| 5121 | raw(device, 20, 0, 0, in_heap); | ||
| 5122 | const unsigned clears = real->calls[48]; | ||
| 5123 | raw(list, 52, in_heap, word(color), 0, 0); | ||
| 5124 | EXPECT(real->calls[48] == clears); // marked while the heap lives: skipped | ||
| 5125 | EXPECT(raw(rtv_heap, 2) == 0); | ||
| 5126 | raw(list, 52, in_heap, word(color), 0, 0); | ||
| 5127 | EXPECT(real->calls[48] == clears + 1 && real->args[48][0] == in_heap); // the mark went with the heap | ||
| 5128 | real->list_error = false; // the mock list still takes its own view there as invalid | ||
| 5129 | raw(list, 52, rtv_none, word(color), 0, 0); | ||
| 5130 | EXPECT(real->calls[48] == clears + 1); // outside the released heap: still skipped | ||
| 5131 | // A second RTV heap at the same address: the view made there with a resource is cleared, and a view made with | ||
| 5132 | // no resource is marked again for as long as that heap lives. | ||
| 5133 | void* rtv_heap2 = nullptr; | ||
| 5134 | EXPECT(SUCCEEDED(hr_of(raw(device, 14, word(&rtv_heap_desc), word(&heap_iid), word(&rtv_heap2))))); | ||
| 5135 | raw(device, 20, word(resource_a), 0, in_heap); | ||
| 5136 | raw(list, 52, in_heap, word(color), 0, 0); | ||
| 5137 | EXPECT(real->calls[48] == clears + 2 && !real->list_error); | ||
| 5138 | raw(device, 20, 0, 0, in_heap); | ||
| 5139 | raw(list, 52, in_heap, word(color), 0, 0); | ||
| 5140 | EXPECT(real->calls[48] == clears + 2); | ||
| 5141 | EXPECT(raw(rtv_heap2, 2) == 0); | ||
| 5142 | EXPECT(!real->list_error && hr_of(raw(list, 9)) == S_OK); | ||
| 5143 | |||
| 5144 | // The marks are the device's own: another device's clear at a handle marked on the first is forwarded (its mock | ||
| 5145 | // list then takes the view as invalid, which is what that device was told). | ||
| 5146 | Mock* other_mock = nullptr; | ||
| 5147 | void* other = make_device(other_mock, 9, true, true, true); | ||
| 5148 | EXPECT(other); | ||
| 5149 | void* other_allocator = nullptr; | ||
| 5150 | EXPECT(hr_of(raw(other, 9, D3D12_COMMAND_LIST_TYPE_DIRECT, word(&allocator_iid), word(&other_allocator))) == S_OK); | ||
| 5151 | void* other_list = nullptr; | ||
| 5152 | EXPECT(hr_of(raw(other, 12, 0, D3D12_COMMAND_LIST_TYPE_DIRECT, word(other_allocator), 0, word(&gcl_iid), | ||
| 5153 | word(&other_list))) == S_OK); | ||
| 5154 | Mock* const other_real = reinterpret_cast<Mock*>(xs::list_proxy_real_list(other_list)); | ||
| 5155 | raw(other_list, 52, rtv_none, word(color), 0, 0); | ||
| 5156 | EXPECT(other_real->calls[48] == 1 && other_real->args[48][0] == rtv_none); | ||
| 5157 | |||
| 5158 | EXPECT(release(other_list) == 0 && other_real->refs == 0); | ||
| 5159 | EXPECT(release(other_allocator) == 0); | ||
| 5160 | EXPECT(release(other) == 0 && other_mock->refs == 0); | ||
| 5161 | EXPECT(release(list) == 0 && real->refs == 0); | ||
| 5162 | EXPECT(release(allocator) == 0); | ||
| 5163 | EXPECT(release(device) == 0 && mock->refs == 0); | ||
| 5164 | g_mock_null_rtv_count = 0; | ||
| 5165 | std::printf("%s: list slot 146 turns texture barriers with no resource into global barriers (valid groups pass " | ||
| 5166 | "unchanged, unreadable ones are refused whole) and slot 52 skips the clear of an RTV made with no " | ||
| 5167 | "resource; the list stays valid\n", | ||
| 5168 | g_label); | ||
| 5169 | return 0; | ||
| 5170 | } | ||
| 5171 | |||
| 4833 | // ---- 11. Presentation handler wiring (device slots 78–81 + queue PresentX/SuspendX/ResumeX) ---- | 5172 | // ---- 11. Presentation handler wiring (device slots 78–81 + queue PresentX/SuspendX/ResumeX) ---- |
| 4834 | 5173 | ||
| 4835 | struct MockPresenter { | 5174 | struct MockPresenter { |
| @@ -4980,6 +5319,7 @@ int main(int argc, char** argv) { | |||
| 4980 | check_slot74() || | 5319 | check_slot74() || |
| 4981 | check_xbox_queue_slots() || | 5320 | check_xbox_queue_slots() || |
| 4982 | check_list_cpu_handles() || | 5321 | check_list_cpu_handles() || |
| 5322 | check_console_null_barrier_and_clear() || | ||
| 4983 | check_presentation_wiring() || check_queue_copy_page_mappings()) | 5323 | check_presentation_wiring() || check_queue_copy_page_mappings()) |
| 4984 | return 1; | 5324 | return 1; |
| 4985 | if (check_placed_resource_x() || check_depth_provider_refusal()) return 1; | 5325 | if (check_placed_resource_x() || check_depth_provider_refusal()) return 1; |