diff options
| author | Jan Trencansky <jan.trencansky@protonmail.com> | 2026-11-25 18:36:19 -0500 |
|---|---|---|
| committer | Jan Trencansky <jan.trencansky@protonmail.com> | 2026-11-25 18:36:19 -0500 |
| commit | 3a2820b3bff812ff3cff6a4d4087912edb0541bb (patch) | |
| tree | ab2522760b3930781a3531f7ded56ba449041e77 /runtime/src | |
| parent | 75f6890bb98214d5112c7eb1126f67f9e2948a0a (diff) | |
| parent | c1e1ef0b81234ac46ca25a810ab81219408ea6ba (diff) | |
Merge main c1e1ef0b8 into RT-POST-LOAD-GPU-MEMORY (#2098)
Two conflicts:
- d3d12_com.cpp, note_direct_heap_indexing: main's console_descriptor_table_va(cbv_srv_uav_base_) for the tracked
table, with this branch's per-site once() flag instead of note_once on every draw.
- d3d12_vulkan_device.cpp, PipelineState::build_compute: this branch's body (build_compute_pipeline, journal, compile
helper). main's dev_status::Build around the compute create moves into build_compute_pipeline, next to the
pipeline_profile::DriverCall, so the status line still names the compute pipeline in the driver.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Diffstat (limited to 'runtime/src')
| -rw-r--r-- | runtime/src/base_reservation.h | 5 | ||||
| -rw-r--r-- | runtime/src/dev_overlay.h | 282 | ||||
| -rw-r--r-- | runtime/src/dev_status.h | 51 | ||||
| -rw-r--r-- | runtime/src/frame_pacer.h | 40 | ||||
| -rw-r--r-- | runtime/src/main.cpp | 12 | ||||
| -rw-r--r-- | runtime/src/memory_figures.h | 147 | ||||
| -rw-r--r-- | runtime/src/pe_loader.cpp | 35 | ||||
| -rw-r--r-- | runtime/src/root_signature.cpp | 11 | ||||
| -rw-r--r-- | runtime/src/root_signature.h | 8 | ||||
| -rw-r--r-- | runtime/src/submit_phases.h | 44 | ||||
| -rw-r--r-- | runtime/src/vulkan_backend.h | 13 | ||||
| -rw-r--r-- | runtime/src/vulkan_memory_budget.h | 46 | ||||
| -rw-r--r-- | runtime/src/vulkan_replay.h | 68 |
13 files changed, 715 insertions, 47 deletions
diff --git a/runtime/src/base_reservation.h b/runtime/src/base_reservation.h index b76c28c70..5ccfe1aaa 100644 --- a/runtime/src/base_reservation.h +++ b/runtime/src/base_reservation.h | |||
| @@ -63,7 +63,10 @@ inline void* commit_reserved(std::uint64_t base, std::uint64_t size) { | |||
| 63 | } | 63 | } |
| 64 | 64 | ||
| 65 | // The preferred range of `image` when it has no relocations and that range is not free in this process; nullopt | 65 | // The preferred range of `image` when it has no relocations and that range is not free in this process; nullopt |
| 66 | // when the image can be mapped as it is (or is not a readable PE32+, which the loader reports itself). | 66 | // when the image can be mapped as it is (or is not a readable PE32+, which the loader reports itself). Without a |
| 67 | // relocation directory the loader refuses to move an image that has IMAGE_FILE_RELOCS_STRIPPED, and moves one with | ||
| 68 | // the flag clear with nothing fixed up: that is right only for an image with no absolute addresses in it, so its | ||
| 69 | // range is kept free either way. An image with a relocation table is moved and fixed up whatever the flag says. | ||
| 67 | inline std::optional<Range> needed(const std::filesystem::path& image) { | 70 | inline std::optional<Range> needed(const std::filesystem::path& image) { |
| 68 | std::ifstream file(image, std::ios::binary); | 71 | std::ifstream file(image, std::ios::binary); |
| 69 | IMAGE_DOS_HEADER dos{}; | 72 | IMAGE_DOS_HEADER dos{}; |
diff --git a/runtime/src/dev_overlay.h b/runtime/src/dev_overlay.h new file mode 100644 index 000000000..1eecfc366 --- /dev/null +++ b/runtime/src/dev_overlay.h | |||
| @@ -0,0 +1,282 @@ | |||
| 1 | #pragma once | ||
| 2 | // LEONIDA_DEV_OVERLAY=1 (off by default, Windows): a small click-through window over the top left corner of the title's | ||
| 3 | // window that says how the boot is doing: frames and submissions a second, where a submission's CPU time goes and which | ||
| 4 | // phase runs now, pipeline builds, indirect draws, CPU, memory. It is its own window with its own thread and GDI text, | ||
| 5 | // so it keeps counting while the title shows no frames for seconds (pipeline builds, a stalled submission), it is in no | ||
| 6 | // captured frame, and it changes nothing the GPU does. It only reads counters: submit_phases.h, indirect_draw_stats.h, | ||
| 7 | // dev_status.h, and memory_figures.h for the private memory and the device's GPU memory, which LEONIDA_TITLE_HUD | ||
| 8 | // (shims/title_hud.h) shows with the same text. The HUD is the other view: frame times, memory and compile time in the | ||
| 9 | // window's title bar. | ||
| 10 | #include "dev_status.h" | ||
| 11 | #include "indirect_draw_stats.h" | ||
| 12 | #include "memory_figures.h" | ||
| 13 | #include "submit_phases.h" | ||
| 14 | |||
| 15 | #ifdef _WIN32 | ||
| 16 | #ifndef NOMINMAX | ||
| 17 | #define NOMINMAX | ||
| 18 | #endif | ||
| 19 | #include <windows.h> | ||
| 20 | #include <psapi.h> | ||
| 21 | #ifdef _MSC_VER | ||
| 22 | #pragma comment(lib, "user32.lib") | ||
| 23 | #pragma comment(lib, "gdi32.lib") | ||
| 24 | #pragma comment(lib, "psapi.lib") | ||
| 25 | #endif | ||
| 26 | #endif | ||
| 27 | |||
| 28 | #include <algorithm> | ||
| 29 | #include <cstdint> | ||
| 30 | #include <cstdio> | ||
| 31 | #include <cstdlib> | ||
| 32 | #include <string> | ||
| 33 | #include <thread> | ||
| 34 | #include <vector> | ||
| 35 | |||
| 36 | namespace leonida::dev_overlay { | ||
| 37 | |||
| 38 | // The counters between two looks. A total that went down was reset by its own log line: what it holds is the new part. | ||
| 39 | inline std::uint64_t grown(std::uint64_t now, std::uint64_t& before) { | ||
| 40 | const std::uint64_t by = now >= before ? now - before : now; | ||
| 41 | before = now; | ||
| 42 | return by; | ||
| 43 | } | ||
| 44 | |||
| 45 | struct Sample { | ||
| 46 | double seconds = 0; | ||
| 47 | double frames = 0, submissions = 0; // a second | ||
| 48 | double phase_ms[submit_phases::kCount]{}; // a submission | ||
| 49 | int phase = -1; // running now | ||
| 50 | double phase_for = 0; // seconds it has been | ||
| 51 | unsigned building = 0; | ||
| 52 | std::uint64_t built = 0; | ||
| 53 | std::string build; // the last one started | ||
| 54 | unsigned long long drawn = 0, skipped = 0; // indirect draws so far | ||
| 55 | double cores = 0, free_gb = 0; | ||
| 56 | memory_figures::ProcessMemory ram; // private memory and working set | ||
| 57 | VramBudget vram; // the device's VK_EXT_memory_budget; "n/a" without it | ||
| 58 | }; | ||
| 59 | |||
| 60 | // The text of one sample: pure, for the test. | ||
| 61 | inline std::vector<std::string> lines(const Sample& s, double age) { | ||
| 62 | char text[160]; | ||
| 63 | std::vector<std::string> out; | ||
| 64 | std::snprintf(text, sizeof text, "Leonida dev %.0f s %.1f fps %.1f submissions/s", age, s.frames, s.submissions); | ||
| 65 | out.emplace_back(text); | ||
| 66 | double total = 0; | ||
| 67 | for (const double ms : s.phase_ms) total += ms; | ||
| 68 | std::snprintf(text, sizeof text, "CPU/submission %.1f ms: descriptors %.1f, textures %.1f, copies %.1f, replay %.1f", total, | ||
| 69 | s.phase_ms[submit_phases::heaps], s.phase_ms[submit_phases::textures], | ||
| 70 | s.phase_ms[submit_phases::shadows] + s.phase_ms[submit_phases::geometry], | ||
| 71 | s.phase_ms[submit_phases::replay]); | ||
| 72 | out.emplace_back(text); | ||
| 73 | static const char* const now[submit_phases::kCount] = {"waiting for the GPU", "fixing descriptors", "copying title memory", | ||
| 74 | "copying geometry", "refreshing textures", "recording and submitting"}; | ||
| 75 | if (s.phase >= 0 && s.phase < int(submit_phases::kCount)) | ||
| 76 | std::snprintf(text, sizeof text, "now: %s%s", now[s.phase], | ||
| 77 | s.phase_for >= 1 ? (" for " + std::to_string(int(s.phase_for)) + " s").c_str() : ""); | ||
| 78 | else | ||
| 79 | std::snprintf(text, sizeof text, "now: the title's own code"); | ||
| 80 | out.emplace_back(text); | ||
| 81 | if (s.building) | ||
| 82 | std::snprintf(text, sizeof text, "pipelines: %llu built, %u building (%.50s)", | ||
| 83 | static_cast<unsigned long long>(s.built), s.building, s.build.c_str()); | ||
| 84 | else | ||
| 85 | std::snprintf(text, sizeof text, "pipelines: %llu built", static_cast<unsigned long long>(s.built)); | ||
| 86 | out.emplace_back(text); | ||
| 87 | std::snprintf(text, sizeof text, "indirect draws: %llu drawn, %llu skipped", s.drawn, s.skipped); | ||
| 88 | out.emplace_back(text); | ||
| 89 | std::snprintf(text, sizeof text, "%.1f cores, %.1f GB RAM free", s.cores, s.free_gb); | ||
| 90 | out.emplace_back(text); | ||
| 91 | out.emplace_back(memory_figures::ram_text(s.ram) + " " + memory_figures::vram_text(s.vram)); | ||
| 92 | return out; | ||
| 93 | } | ||
| 94 | |||
| 95 | inline bool enabled() { | ||
| 96 | static const bool on = [] { | ||
| 97 | #ifdef _WIN32 | ||
| 98 | char value[3]{}; | ||
| 99 | std::size_t length = 0; | ||
| 100 | return getenv_s(&length, value, sizeof value, "LEONIDA_DEV_OVERLAY") == 0 && length == 2 && value[0] == '1'; | ||
| 101 | #else | ||
| 102 | const char* value = std::getenv("LEONIDA_DEV_OVERLAY"); | ||
| 103 | return value && value[0] == '1' && !value[1]; | ||
| 104 | #endif | ||
| 105 | }(); | ||
| 106 | return on; | ||
| 107 | } | ||
| 108 | |||
| 109 | #ifdef _WIN32 | ||
| 110 | class Overlay { | ||
| 111 | public: | ||
| 112 | void run() { | ||
| 113 | WNDCLASSW type{}; | ||
| 114 | type.lpfnWndProc = &Overlay::procedure; | ||
| 115 | type.hInstance = GetModuleHandleW(nullptr); | ||
| 116 | type.lpszClassName = L"LeonidaDevOverlay"; | ||
| 117 | if (!RegisterClassW(&type)) return; | ||
| 118 | window_ = CreateWindowExW(WS_EX_LAYERED | WS_EX_TRANSPARENT | WS_EX_NOACTIVATE | WS_EX_TOPMOST | WS_EX_TOOLWINDOW, | ||
| 119 | type.lpszClassName, L"", WS_POPUP, 0, 0, 10, 10, nullptr, nullptr, type.hInstance, this); | ||
| 120 | if (!window_) return; | ||
| 121 | SetWindowLongPtrW(window_, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(this)); | ||
| 122 | SetLayeredWindowAttributes(window_, 0, 205, LWA_ALPHA); | ||
| 123 | font_ = CreateFontW(-14, 0, 0, 0, FW_NORMAL, FALSE, FALSE, FALSE, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, | ||
| 124 | CLIP_DEFAULT_PRECIS, CLEARTYPE_QUALITY, FIXED_PITCH | FF_MODERN, L"Consolas"); | ||
| 125 | look(); | ||
| 126 | SetTimer(window_, 1, 500, nullptr); | ||
| 127 | MSG message; | ||
| 128 | while (GetMessageW(&message, nullptr, 0, 0) > 0) DispatchMessageW(&message); | ||
| 129 | } | ||
| 130 | |||
| 131 | private: | ||
| 132 | static LRESULT CALLBACK procedure(HWND window, UINT message, WPARAM w, LPARAM l) { | ||
| 133 | auto* self = reinterpret_cast<Overlay*>(GetWindowLongPtrW(window, GWLP_USERDATA)); | ||
| 134 | if (self && message == WM_TIMER) { | ||
| 135 | self->look(); | ||
| 136 | return 0; | ||
| 137 | } | ||
| 138 | if (self && message == WM_PAINT) { | ||
| 139 | self->paint(); | ||
| 140 | return 0; | ||
| 141 | } | ||
| 142 | if (message == WM_NCHITTEST) return HTTRANSPARENT; | ||
| 143 | return DefWindowProcW(window, message, w, l); | ||
| 144 | } | ||
| 145 | |||
| 146 | // The process's largest visible top-level window is the title's. | ||
| 147 | struct Search { | ||
| 148 | HWND own, found; | ||
| 149 | std::int64_t area; | ||
| 150 | }; | ||
| 151 | static BOOL CALLBACK consider(HWND window, LPARAM parameter) { | ||
| 152 | auto& search = *reinterpret_cast<Search*>(parameter); | ||
| 153 | DWORD process = 0; | ||
| 154 | GetWindowThreadProcessId(window, &process); | ||
| 155 | RECT r{}; | ||
| 156 | if (process != GetCurrentProcessId() || window == search.own || !IsWindowVisible(window) || IsIconic(window) || | ||
| 157 | !GetClientRect(window, &r)) | ||
| 158 | return TRUE; | ||
| 159 | const std::int64_t area = std::int64_t(r.right) * r.bottom; | ||
| 160 | if (area > search.area) search = {search.own, window, area}; | ||
| 161 | return TRUE; | ||
| 162 | } | ||
| 163 | |||
| 164 | void look() { | ||
| 165 | namespace sp = submit_phases; | ||
| 166 | sp::Totals& totals = sp::totals(); | ||
| 167 | const std::int64_t now = sp::now_ns(); | ||
| 168 | Sample s; | ||
| 169 | s.seconds = before_ ? double(now - before_) * 1e-9 : 0; | ||
| 170 | const std::uint64_t frames = grown(totals.present_serial.load(std::memory_order_relaxed), frames_); | ||
| 171 | const std::uint64_t submissions = grown(totals.all_submissions.load(std::memory_order_relaxed), submissions_); | ||
| 172 | std::uint64_t ns[sp::kCount]; | ||
| 173 | for (unsigned p = 0; p < sp::kCount; ++p) ns[p] = grown(totals.ns[p].load(std::memory_order_relaxed), ns_[p]); | ||
| 174 | // A stall longer than a look leaves nothing to divide by: the figures then cover the last two seconds. | ||
| 175 | window_frames_ += frames; | ||
| 176 | window_submissions_ += submissions; | ||
| 177 | window_seconds_ += s.seconds; | ||
| 178 | for (unsigned p = 0; p < sp::kCount; ++p) window_ns_[p] += ns[p]; | ||
| 179 | if (window_seconds_ >= 2 || !before_) { | ||
| 180 | shown_ = {}; | ||
| 181 | if (window_seconds_ > 0) { | ||
| 182 | shown_.frames = double(window_frames_) / window_seconds_; | ||
| 183 | shown_.submissions = double(window_submissions_) / window_seconds_; | ||
| 184 | } | ||
| 185 | for (unsigned p = 0; p < sp::kCount; ++p) { | ||
| 186 | if (window_submissions_) shown_.phase_ms[p] = double(window_ns_[p]) * 1e-6 / double(window_submissions_); | ||
| 187 | window_ns_[p] = 0; | ||
| 188 | } | ||
| 189 | window_frames_ = window_submissions_ = 0; | ||
| 190 | window_seconds_ = 0; | ||
| 191 | } | ||
| 192 | s.frames = shown_.frames; | ||
| 193 | s.submissions = shown_.submissions; | ||
| 194 | std::copy(std::begin(shown_.phase_ms), std::end(shown_.phase_ms), std::begin(s.phase_ms)); | ||
| 195 | before_ = now; | ||
| 196 | |||
| 197 | const sp::Running running = sp::running(); | ||
| 198 | s.phase = running.phase; | ||
| 199 | if (s.phase >= 0) s.phase_for = std::max(0.0, double(now - running.since) * 1e-9); | ||
| 200 | dev_status::Builds& builds = dev_status::builds(); | ||
| 201 | s.building = builds.active.load(std::memory_order_relaxed); | ||
| 202 | s.built = builds.done.load(std::memory_order_relaxed); | ||
| 203 | s.build = builds.last(); | ||
| 204 | const auto& draws = indirect_stats::counts().values; | ||
| 205 | s.drawn = draws[std::size_t(indirect_stats::Event::emitted)].load(std::memory_order_relaxed); | ||
| 206 | s.skipped = draws[std::size_t(indirect_stats::Event::record_skip)].load(std::memory_order_relaxed) + | ||
| 207 | draws[std::size_t(indirect_stats::Event::replay_skip)].load(std::memory_order_relaxed); | ||
| 208 | FILETIME created{}, exited{}, kernel{}, user{}; | ||
| 209 | if (GetProcessTimes(GetCurrentProcess(), &created, &exited, &kernel, &user)) { | ||
| 210 | const auto ticks = [](const FILETIME& f) { return (std::uint64_t(f.dwHighDateTime) << 32) | f.dwLowDateTime; }; | ||
| 211 | const std::uint64_t used = grown(ticks(kernel) + ticks(user), cpu_); | ||
| 212 | if (s.seconds > 0) s.cores = double(used) * 1e-7 / s.seconds; | ||
| 213 | } | ||
| 214 | s.ram = memory_figures::process_memory(); | ||
| 215 | s.vram = memory_figures::latest_vram(); // reads the device at most once per 500 ms | ||
| 216 | MEMORYSTATUSEX status{sizeof status}; | ||
| 217 | if (GlobalMemoryStatusEx(&status)) s.free_gb = double(status.ullAvailPhys) / double(1u << 30); | ||
| 218 | lines_ = lines(s, sp::process_age()); | ||
| 219 | place(); | ||
| 220 | } | ||
| 221 | |||
| 222 | void place() { | ||
| 223 | Search search{window_, nullptr, 0}; | ||
| 224 | EnumWindows(&Overlay::consider, reinterpret_cast<LPARAM>(&search)); | ||
| 225 | // Shown only over the title while it is the window in front, so the topmost text is never over anything else. | ||
| 226 | if (!search.found || GetForegroundWindow() != search.found) { | ||
| 227 | ShowWindow(window_, SW_HIDE); | ||
| 228 | return; | ||
| 229 | } | ||
| 230 | POINT corner{8, 8}; | ||
| 231 | ClientToScreen(search.found, &corner); | ||
| 232 | std::size_t longest = 0; | ||
| 233 | for (const auto& line : lines_) longest = std::max(longest, line.size()); | ||
| 234 | SetWindowPos(window_, HWND_TOPMOST, corner.x, corner.y, int(longest) * 8 + 12, int(lines_.size()) * 17 + 8, | ||
| 235 | SWP_NOACTIVATE | SWP_SHOWWINDOW); | ||
| 236 | InvalidateRect(window_, nullptr, FALSE); | ||
| 237 | } | ||
| 238 | |||
| 239 | void paint() { | ||
| 240 | PAINTSTRUCT ps; | ||
| 241 | HDC dc = BeginPaint(window_, &ps); | ||
| 242 | RECT area; | ||
| 243 | GetClientRect(window_, &area); | ||
| 244 | HDC memory = CreateCompatibleDC(dc); | ||
| 245 | HBITMAP bitmap = CreateCompatibleBitmap(dc, area.right, area.bottom); | ||
| 246 | HGDIOBJ old_bitmap = SelectObject(memory, bitmap), old_font = SelectObject(memory, font_); | ||
| 247 | FillRect(memory, &area, static_cast<HBRUSH>(GetStockObject(BLACK_BRUSH))); | ||
| 248 | SetBkMode(memory, TRANSPARENT); | ||
| 249 | int y = 4; | ||
| 250 | for (std::size_t i = 0; i < lines_.size(); ++i, y += 17) { | ||
| 251 | SetTextColor(memory, i == 0 ? RGB(120, 255, 140) : RGB(235, 235, 235)); | ||
| 252 | TextOutA(memory, 6, y, lines_[i].data(), int(lines_[i].size())); | ||
| 253 | } | ||
| 254 | BitBlt(dc, 0, 0, area.right, area.bottom, memory, 0, 0, SRCCOPY); | ||
| 255 | SelectObject(memory, old_bitmap); | ||
| 256 | SelectObject(memory, old_font); | ||
| 257 | DeleteObject(bitmap); | ||
| 258 | DeleteDC(memory); | ||
| 259 | EndPaint(window_, &ps); | ||
| 260 | } | ||
| 261 | |||
| 262 | HWND window_ = nullptr; | ||
| 263 | HFONT font_ = nullptr; | ||
| 264 | std::vector<std::string> lines_; | ||
| 265 | std::int64_t before_ = 0; | ||
| 266 | std::uint64_t frames_ = 0, submissions_ = 0, cpu_ = 0, ns_[submit_phases::kCount]{}; | ||
| 267 | std::uint64_t window_frames_ = 0, window_submissions_ = 0, window_ns_[submit_phases::kCount]{}; | ||
| 268 | double window_seconds_ = 0; | ||
| 269 | Sample shown_; | ||
| 270 | }; | ||
| 271 | #endif | ||
| 272 | |||
| 273 | // Once per process; nothing without LEONIDA_DEV_OVERLAY=1. | ||
| 274 | inline void start() { | ||
| 275 | #ifdef _WIN32 | ||
| 276 | if (!enabled()) return; | ||
| 277 | std::fprintf(stderr, "[rt] dev overlay on (LEONIDA_DEV_OVERLAY=1)\n"); | ||
| 278 | std::thread([] { static Overlay overlay; overlay.run(); }).detach(); | ||
| 279 | #endif | ||
| 280 | } | ||
| 281 | |||
| 282 | } // namespace leonida::dev_overlay | ||
diff --git a/runtime/src/dev_status.h b/runtime/src/dev_status.h new file mode 100644 index 000000000..3efc9bf4f --- /dev/null +++ b/runtime/src/dev_status.h | |||
| @@ -0,0 +1,51 @@ | |||
| 1 | #pragma once | ||
| 2 | // What the runtime is building now, for the dev overlay (dev_overlay.h). Always on: two relaxed atomics a build, and a | ||
| 3 | // short copy under a lock for the name. | ||
| 4 | #include <algorithm> | ||
| 5 | #include <atomic> | ||
| 6 | #include <cstdint> | ||
| 7 | #include <cstring> | ||
| 8 | #include <mutex> | ||
| 9 | #include <string> | ||
| 10 | |||
| 11 | namespace leonida::dev_status { | ||
| 12 | |||
| 13 | struct Builds { | ||
| 14 | std::atomic<unsigned> active{0}; | ||
| 15 | std::atomic<std::uint64_t> done{0}; | ||
| 16 | |||
| 17 | std::string last() { | ||
| 18 | std::lock_guard lock(mutex_); | ||
| 19 | return name_; | ||
| 20 | } | ||
| 21 | void name(const char* text) { | ||
| 22 | std::lock_guard lock(mutex_); | ||
| 23 | const std::size_t n = std::min(std::strlen(text), sizeof name_ - 1); | ||
| 24 | std::memcpy(name_, text, n); | ||
| 25 | name_[n] = 0; | ||
| 26 | } | ||
| 27 | |||
| 28 | private: | ||
| 29 | std::mutex mutex_; | ||
| 30 | char name_[96]{}; | ||
| 31 | }; | ||
| 32 | inline Builds& builds() { | ||
| 33 | static Builds instance; | ||
| 34 | return instance; | ||
| 35 | } | ||
| 36 | |||
| 37 | // One pipeline build, from construction to destruction. | ||
| 38 | struct Build { | ||
| 39 | explicit Build(const char* name) { | ||
| 40 | builds().name(name); | ||
| 41 | builds().active.fetch_add(1, std::memory_order_relaxed); | ||
| 42 | } | ||
| 43 | ~Build() { | ||
| 44 | builds().active.fetch_sub(1, std::memory_order_relaxed); | ||
| 45 | builds().done.fetch_add(1, std::memory_order_relaxed); | ||
| 46 | } | ||
| 47 | Build(const Build&) = delete; | ||
| 48 | Build& operator=(const Build&) = delete; | ||
| 49 | }; | ||
| 50 | |||
| 51 | } // namespace leonida::dev_status | ||
diff --git a/runtime/src/frame_pacer.h b/runtime/src/frame_pacer.h index 2c9f1fd7e..5588d73ea 100644 --- a/runtime/src/frame_pacer.h +++ b/runtime/src/frame_pacer.h | |||
| @@ -19,6 +19,10 @@ | |||
| 19 | // * A frame is "in flight" from PresentX until the vblank that shows it. Frames show one per vblank, in order. | 19 | // * A frame is "in flight" from PresentX until the vblank that shows it. Frames show one per vblank, in order. |
| 20 | // WaitFrameEventX does not return while `latency` frames are in flight. A frame presented while the origin event | 20 | // WaitFrameEventX does not return while `latency` frames are in flight. A frame presented while the origin event |
| 21 | // is not armed is not paced (PresentX does not hold it for a vblank): it shows at once and is never in flight. | 21 | // is not armed is not paced (PresentX does not hold it for a vblank): it shows at once and is never in flight. |
| 22 | // * At most `latency` frames are in flight. A present into a full queue (several presents with no wait between | ||
| 23 | // them) replaces the newest queued frame and takes its vblank, like a mailbox: the replaced frame is never shown, | ||
| 24 | // and the older ones keep their vblanks. So the queue, and the next wait, never reach further than `latency` | ||
| 25 | // vblanks ahead, however many presents came in between. | ||
| 22 | // * A wait that comes late (after the next origin already passed) returns at once with the newest passed origin; | 26 | // * A wait that comes late (after the next origin already passed) returns at once with the newest passed origin; |
| 23 | // the missed origins are skipped, not queued. | 27 | // the missed origins are skipped, not queued. |
| 24 | // * Tokens are 1, 2, 3, ... (0 is the null token), one per successful wait, never reused, across suspend/resume. | 28 | // * Tokens are 1, 2, 3, ... (0 is the null token), one per successful wait, never reused, across suspend/resume. |
| @@ -266,8 +270,9 @@ public: | |||
| 266 | 270 | ||
| 267 | // GetFrameStatisticsX(token, type_mask, &count, array). `count` is the room in `out` on entry and the number of | 271 | // GetFrameStatisticsX(token, type_mask, &count, array). `count` is the room in `out` on entry and the number of |
| 268 | // entries written on return. S_OK when every producible requested type was written (event, present, display), | 272 | // entries written on return. S_OK when every producible requested type was written (event, present, display), |
| 269 | // S_FALSE with count 0 or fewer when they are not (there yet, or the token is unknown or has aged out of the | 273 | // S_FALSE with count 0 or fewer when they are not (there yet, the frame was replaced in a full queue and never |
| 270 | // last 64). With a null `out`, count only receives how many entries are available. | 274 | // shown, or the token is unknown or has aged out of the last 64). With a null `out`, count only receives how many |
| 275 | // entries are available. | ||
| 271 | std::int32_t get_frame_statistics(std::uint64_t token, std::uint32_t type_mask, std::uint32_t* count, | 276 | std::int32_t get_frame_statistics(std::uint64_t token, std::uint32_t type_mask, std::uint32_t* count, |
| 272 | FrameStatistic* out) { | 277 | FrameStatistic* out) { |
| 273 | if (!count) return pacer_hr::invalid_arg; | 278 | if (!count) return pacer_hr::invalid_arg; |
| @@ -359,12 +364,10 @@ public: | |||
| 359 | if (r.token == token) { r.presented = r.displayed = true; r.present_us = r.display_us = now; } | 364 | if (r.token == token) { r.presented = r.displayed = true; r.present_us = r.display_us = now; } |
| 360 | return; | 365 | return; |
| 361 | } | 366 | } |
| 362 | // The vblank after now, and not before the one after the previous queued frame. | 367 | const bool queued_before = !pending_.empty(); |
| 363 | const std::uint64_t since = now > epoch_us_ ? now - epoch_us_ : 0; | 368 | std::uint64_t flip = queue_flip_locked(now); |
| 364 | std::uint64_t flip = epoch_us_ + (since / period_us_ + 1) * period_us_; | ||
| 365 | if (!pending_.empty()) flip = std::max(flip, pending_.back().flip_us + period_us_); | ||
| 366 | float percent = 0.0f; | 369 | float percent = 0.0f; |
| 367 | if (sync == PresentSync::immediate && pending_.empty()) { | 370 | if (sync == PresentSync::immediate && !queued_before) { |
| 368 | flip = now; | 371 | flip = now; |
| 369 | std::uint64_t late_us = 0; | 372 | std::uint64_t late_us = 0; |
| 370 | for (const Record& r : records_) | 373 | for (const Record& r : records_) |
| @@ -386,9 +389,7 @@ public: | |||
| 386 | record_present_timing_locked(now, 0); | 389 | record_present_timing_locked(now, 0); |
| 387 | if (!interval_set_ || !any_armed_locked() || uncapped_) return; | 390 | if (!interval_set_ || !any_armed_locked() || uncapped_) return; |
| 388 | retire_locked(now); | 391 | retire_locked(now); |
| 389 | const std::uint64_t since = now > epoch_us_ ? now - epoch_us_ : 0; | 392 | const std::uint64_t flip = queue_flip_locked(now); |
| 390 | std::uint64_t flip = epoch_us_ + (since / period_us_ + 1) * period_us_; | ||
| 391 | if (!pending_.empty()) flip = std::max(flip, pending_.back().flip_us + period_us_); | ||
| 392 | pending_.push_back(Pending{0, flip, 0.0f}); | 393 | pending_.push_back(Pending{0, flip, 0.0f}); |
| 393 | cv_.notify_all(); | 394 | cv_.notify_all(); |
| 394 | } | 395 | } |
| @@ -484,6 +485,25 @@ private: | |||
| 484 | bool presented = false, displayed = false; | 485 | bool presented = false, displayed = false; |
| 485 | }; | 486 | }; |
| 486 | 487 | ||
| 488 | // The vblank a frame presented now is queued for: the vblank after now, and not before the one after the previous | ||
| 489 | // queued frame. At most `latency_` frames are in flight, so with the queue full the newest queued frame is | ||
| 490 | // replaced (dropped: never shown) and the new one takes its vblank; the older ones keep theirs. A queue longer | ||
| 491 | // than the latency (after SetFrameIntervalX lowered it) is cut back the same way, from the newest end. | ||
| 492 | std::uint64_t queue_flip_locked(std::uint64_t now) { | ||
| 493 | if (pending_.size() >= latency_) { // latency_ is at least 1, so the queue is not empty | ||
| 494 | std::uint64_t flip = 0; | ||
| 495 | while (pending_.size() >= latency_) { | ||
| 496 | flip = pending_.back().flip_us; | ||
| 497 | pending_.pop_back(); | ||
| 498 | } | ||
| 499 | return flip; | ||
| 500 | } | ||
| 501 | const std::uint64_t since = now > epoch_us_ ? now - epoch_us_ : 0; | ||
| 502 | std::uint64_t flip = epoch_us_ + (since / period_us_ + 1) * period_us_; | ||
| 503 | if (!pending_.empty()) flip = std::max(flip, pending_.back().flip_us + period_us_); | ||
| 504 | return flip; | ||
| 505 | } | ||
| 506 | |||
| 487 | void record_present_timing_locked(std::uint64_t now, std::uint64_t token) { | 507 | void record_present_timing_locked(std::uint64_t now, std::uint64_t token) { |
| 488 | ++presents_recorded_; | 508 | ++presents_recorded_; |
| 489 | if (has_last_present_ && now >= last_present_us_) { | 509 | if (has_last_present_ && now >= last_present_us_) { |
diff --git a/runtime/src/main.cpp b/runtime/src/main.cpp index 76b180475..4d483ed59 100644 --- a/runtime/src/main.cpp +++ b/runtime/src/main.cpp | |||
| @@ -156,6 +156,7 @@ void start_title_peek(std::uint8_t* base) { | |||
| 156 | #include "mods.h" | 156 | #include "mods.h" |
| 157 | #include "pe_loader.h" | 157 | #include "pe_loader.h" |
| 158 | #include "thread_stacks.h" | 158 | #include "thread_stacks.h" |
| 159 | #include "dev_overlay.h" | ||
| 159 | #include "thread_sampler.h" | 160 | #include "thread_sampler.h" |
| 160 | #include "title_page_watch.h" | 161 | #include "title_page_watch.h" |
| 161 | #include "title_geometry_watch.h" | 162 | #include "title_geometry_watch.h" |
| @@ -612,7 +613,9 @@ int wmain(int argc, wchar_t** argv) { | |||
| 612 | std::fprintf(stderr, "error: %s has no entry point\n", main_module.name.c_str()); | 613 | std::fprintf(stderr, "error: %s has no entry point\n", main_module.name.c_str()); |
| 613 | return 1; | 614 | return 1; |
| 614 | } | 615 | } |
| 615 | const std::wstring paths = L"console paths: GAME: -> " + game_dir.native() + L", writes -> " + overlay_dir.native(); | 616 | const std::filesystem::path scratch_dir = rt::fs::scratch_dir(); |
| 617 | const std::wstring paths = L"console paths: GAME: -> " + game_dir.native() + L", writes -> " + | ||
| 618 | overlay_dir.native() + L", T: -> " + scratch_dir.native(); | ||
| 616 | const HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE); | 619 | const HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE); |
| 617 | DWORD mode; | 620 | DWORD mode; |
| 618 | bool printed = false; | 621 | bool printed = false; |
| @@ -625,13 +628,16 @@ int wmain(int argc, wchar_t** argv) { | |||
| 625 | if (!printed) { | 628 | if (!printed) { |
| 626 | const auto game = game_dir.u8string(); | 629 | const auto game = game_dir.u8string(); |
| 627 | const auto overlay = overlay_dir.u8string(); | 630 | const auto overlay = overlay_dir.u8string(); |
| 628 | std::printf("console paths: GAME: -> %s, writes -> %s\n", | 631 | const auto scratch = scratch_dir.u8string(); |
| 629 | reinterpret_cast<const char*>(game.c_str()), reinterpret_cast<const char*>(overlay.c_str())); | 632 | std::printf("console paths: GAME: -> %s, writes -> %s, T: -> %s\n", |
| 633 | reinterpret_cast<const char*>(game.c_str()), reinterpret_cast<const char*>(overlay.c_str()), | ||
| 634 | reinterpret_cast<const char*>(scratch.c_str())); | ||
| 630 | } | 635 | } |
| 631 | std::printf("running %s\n", main_module.name.c_str()); | 636 | std::printf("running %s\n", main_module.name.c_str()); |
| 632 | std::fflush(stdout); | 637 | std::fflush(stdout); |
| 633 | keep_title_watchdog_kicked(main_module.base); | 638 | keep_title_watchdog_kicked(main_module.base); |
| 634 | start_title_peek(main_module.base); | 639 | start_title_peek(main_module.base); |
| 640 | leonida::dev_overlay::start(); // LEONIDA_DEV_OVERLAY=1 | ||
| 635 | leonida::thread_sampler::start(main_module.base, main_module.size); // LEONIDA_SAMPLE_MS (diagnostic) | 641 | leonida::thread_sampler::start(main_module.base, main_module.size); // LEONIDA_SAMPLE_MS (diagnostic) |
| 636 | #ifdef LEONIDA_VULKAN_DEVICE | 642 | #ifdef LEONIDA_VULKAN_DEVICE |
| 637 | SetConsoleCtrlHandler(&stop_compiles_on_console_exit, TRUE); | 643 | SetConsoleCtrlHandler(&stop_compiles_on_console_exit, TRUE); |
diff --git a/runtime/src/memory_figures.h b/runtime/src/memory_figures.h new file mode 100644 index 000000000..8bf611553 --- /dev/null +++ b/runtime/src/memory_figures.h | |||
| @@ -0,0 +1,147 @@ | |||
| 1 | #pragma once | ||
| 2 | // The memory figures that the title HUD (shims/title_hud.h, LEONIDA_TITLE_HUD) and the dev overlay (dev_overlay.h, | ||
| 3 | // LEONIDA_DEV_OVERLAY) both show, and the text for each. Both views use this header, so they show the same figures | ||
| 4 | // and the same "n/a" where there is no figure, never a false 0: | ||
| 5 | // GPU memory: in use and the budget over the device-local heaps, and in use in the other heaps, from the device's | ||
| 6 | // VK_EXT_memory_budget (vulkan_memory_budget.h reads it). The device publishes a reader here (publish_vram_reader) | ||
| 7 | // because the overlay runs outside the device, and latest_vram() calls it at most once per refresh_ms. | ||
| 8 | // Private memory: the process's commit charge. Wine fills only PagefileUsage, which on Windows 8 and later is the | ||
| 9 | // same figure as PrivateUsage. | ||
| 10 | // No Vulkan here, and Win32 only under _WIN32, so the overlay's test builds on every host. | ||
| 11 | #ifdef _WIN32 | ||
| 12 | #ifndef NOMINMAX | ||
| 13 | #define NOMINMAX | ||
| 14 | #endif | ||
| 15 | #include <windows.h> | ||
| 16 | #include <psapi.h> | ||
| 17 | #ifdef _MSC_VER | ||
| 18 | #pragma comment(lib, "psapi.lib") | ||
| 19 | #endif | ||
| 20 | #endif | ||
| 21 | |||
| 22 | #include <algorithm> | ||
| 23 | #include <chrono> | ||
| 24 | #include <cstdint> | ||
| 25 | #include <cstdio> | ||
| 26 | #include <mutex> | ||
| 27 | #include <string> | ||
| 28 | |||
| 29 | namespace leonida { | ||
| 30 | |||
| 31 | struct VramBudget { | ||
| 32 | // False when there is nothing to show: no VK_EXT_memory_budget on the device, no device, or a device that | ||
| 33 | // reports no budget for any DEVICE_LOCAL heap. The views show "n/a" then, not a 0. | ||
| 34 | bool available = false; | ||
| 35 | std::uint64_t local_usage = 0; // heapUsage summed over the DEVICE_LOCAL heaps | ||
| 36 | std::uint64_t local_budget = 0; // heapBudget summed over the DEVICE_LOCAL heaps | ||
| 37 | std::uint64_t shared_usage = 0; // heapUsage summed over the other heaps: system memory the GPU uses | ||
| 38 | }; | ||
| 39 | |||
| 40 | namespace memory_figures { | ||
| 41 | |||
| 42 | inline double gb(std::uint64_t bytes) { return double(bytes) / double(1ull << 30); } | ||
| 43 | |||
| 44 | // "VRAM 3.5/16.0 GB +0.5 shared", or "VRAM n/a". | ||
| 45 | inline std::string vram_text(const VramBudget& vram) { | ||
| 46 | if (!vram.available) return "VRAM n/a"; | ||
| 47 | char text[96]; | ||
| 48 | std::snprintf(text, sizeof text, "VRAM %.1f/%.1f GB +%.1f shared", gb(vram.local_usage), gb(vram.local_budget), | ||
| 49 | gb(vram.shared_usage)); | ||
| 50 | return text; | ||
| 51 | } | ||
| 52 | |||
| 53 | struct ProcessMemory { | ||
| 54 | bool read = false; // GetProcessMemoryInfo answered | ||
| 55 | std::uint64_t private_usage = 0, pagefile_usage = 0, working_set = 0; | ||
| 56 | }; | ||
| 57 | |||
| 58 | // The commit charge. PrivateUsage and PagefileUsage are the same figure on Windows 8 and later. Wine's | ||
| 59 | // GetProcessMemoryInfo writes only the PROCESS_MEMORY_COUNTERS part, so PrivateUsage reads 0 there. | ||
| 60 | inline std::uint64_t private_bytes(const ProcessMemory& memory) { | ||
| 61 | return (std::max)(memory.private_usage, memory.pagefile_usage); // parenthesised: windows.h may define max | ||
| 62 | } | ||
| 63 | |||
| 64 | // "RAM 2.5 GB (ws 1.0)". "RAM n/a (ws 1.0)" when the private bytes read 0, "RAM n/a" when nothing could be read. | ||
| 65 | inline std::string ram_text(const ProcessMemory& memory) { | ||
| 66 | char text[96]; | ||
| 67 | if (!memory.read) | ||
| 68 | std::snprintf(text, sizeof text, "RAM n/a"); | ||
| 69 | else if (const std::uint64_t bytes = private_bytes(memory); !bytes) | ||
| 70 | std::snprintf(text, sizeof text, "RAM n/a (ws %.1f)", gb(memory.working_set)); | ||
| 71 | else | ||
| 72 | std::snprintf(text, sizeof text, "RAM %.1f GB (ws %.1f)", gb(bytes), gb(memory.working_set)); | ||
| 73 | return text; | ||
| 74 | } | ||
| 75 | |||
| 76 | #ifdef _WIN32 | ||
| 77 | // This process's figures now. | ||
| 78 | inline ProcessMemory process_memory() { | ||
| 79 | PROCESS_MEMORY_COUNTERS_EX counters{}; | ||
| 80 | counters.cb = sizeof counters; | ||
| 81 | ProcessMemory out; | ||
| 82 | if (!GetProcessMemoryInfo(GetCurrentProcess(), reinterpret_cast<PROCESS_MEMORY_COUNTERS*>(&counters), | ||
| 83 | sizeof counters)) | ||
| 84 | return out; | ||
| 85 | out.read = true; | ||
| 86 | out.private_usage = counters.PrivateUsage; | ||
| 87 | out.pagefile_usage = counters.PagefileUsage; | ||
| 88 | out.working_set = counters.WorkingSetSize; | ||
| 89 | return out; | ||
| 90 | } | ||
| 91 | #endif | ||
| 92 | |||
| 93 | // The device's figure, published for views outside the device. A device with VK_EXT_memory_budget publishes a reader | ||
| 94 | // when it is created and withdraws it first thing when it goes. The views call latest_vram(), which calls the reader at | ||
| 95 | // most once per refresh_ms and returns the last figure in between. The lock is held during a read, so withdrawing | ||
| 96 | // waits for a read that is in progress, and a reader is never called after its device is gone. | ||
| 97 | using VramReader = VramBudget (*)(const void* context); | ||
| 98 | inline constexpr std::chrono::milliseconds refresh_ms{500}; | ||
| 99 | |||
| 100 | class VramPublisher { | ||
| 101 | public: | ||
| 102 | void publish(VramReader reader, const void* context) { | ||
| 103 | std::lock_guard lock(mutex_); | ||
| 104 | reader_ = reader; | ||
| 105 | context_ = context; | ||
| 106 | last_ = {}; | ||
| 107 | read_ = false; | ||
| 108 | } | ||
| 109 | // Only the device that published the current reader withdraws it. Another device may have published since. | ||
| 110 | void withdraw(const void* context) { | ||
| 111 | std::lock_guard lock(mutex_); | ||
| 112 | if (context_ != context) return; | ||
| 113 | reader_ = nullptr; | ||
| 114 | context_ = nullptr; | ||
| 115 | last_ = {}; | ||
| 116 | read_ = false; | ||
| 117 | } | ||
| 118 | VramBudget latest(std::chrono::steady_clock::time_point now = std::chrono::steady_clock::now()) { | ||
| 119 | std::lock_guard lock(mutex_); | ||
| 120 | if (!reader_) return {}; | ||
| 121 | if (!read_ || now - at_ >= refresh_ms) { | ||
| 122 | last_ = reader_(context_); | ||
| 123 | at_ = now; | ||
| 124 | read_ = true; | ||
| 125 | } | ||
| 126 | return last_; | ||
| 127 | } | ||
| 128 | |||
| 129 | private: | ||
| 130 | std::mutex mutex_; | ||
| 131 | VramReader reader_ = nullptr; | ||
| 132 | const void* context_ = nullptr; | ||
| 133 | VramBudget last_; | ||
| 134 | std::chrono::steady_clock::time_point at_{}; | ||
| 135 | bool read_ = false; | ||
| 136 | }; | ||
| 137 | |||
| 138 | inline VramPublisher& vram_publisher() { | ||
| 139 | static VramPublisher instance; | ||
| 140 | return instance; | ||
| 141 | } | ||
| 142 | inline void publish_vram_reader(VramReader reader, const void* context) { vram_publisher().publish(reader, context); } | ||
| 143 | inline void withdraw_vram_reader(const void* context) { vram_publisher().withdraw(context); } | ||
| 144 | inline VramBudget latest_vram() { return vram_publisher().latest(); } | ||
| 145 | |||
| 146 | } // namespace memory_figures | ||
| 147 | } // namespace leonida | ||
diff --git a/runtime/src/pe_loader.cpp b/runtime/src/pe_loader.cpp index 3558cffb5..fc73f37f5 100644 --- a/runtime/src/pe_loader.cpp +++ b/runtime/src/pe_loader.cpp | |||
| @@ -1721,10 +1721,7 @@ Module& Loader::map_image(const std::filesystem::path& path, const std::string& | |||
| 1721 | if (!m->base) | 1721 | if (!m->base) |
| 1722 | m->base = static_cast<uint8_t*>(VirtualAlloc(reinterpret_cast<void*>(oh.ImageBase), oh.SizeOfImage, | 1722 | m->base = static_cast<uint8_t*>(VirtualAlloc(reinterpret_cast<void*>(oh.ImageBase), oh.SizeOfImage, |
| 1723 | MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); | 1723 | MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); |
| 1724 | if (!m->base) { | 1724 | if (!m->base) { // whether the image may move is decided at the relocation step below |
| 1725 | const auto relocs = directory(nt, IMAGE_DIRECTORY_ENTRY_BASERELOC); | ||
| 1726 | if (!relocs.Size) | ||
| 1727 | throw std::runtime_error(m->name + ": preferred base is taken and the image has no relocations"); | ||
| 1728 | m->base = static_cast<uint8_t*>(VirtualAlloc(nullptr, oh.SizeOfImage, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); | 1725 | m->base = static_cast<uint8_t*>(VirtualAlloc(nullptr, oh.SizeOfImage, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); |
| 1729 | if (!m->base) throw std::runtime_error(m->name + ": VirtualAlloc failed"); | 1726 | if (!m->base) throw std::runtime_error(m->name + ": VirtualAlloc failed"); |
| 1730 | } | 1727 | } |
| @@ -1749,10 +1746,19 @@ Module& Loader::map_image(const std::filesystem::path& path, const std::string& | |||
| 1749 | } | 1746 | } |
| 1750 | 1747 | ||
| 1751 | int64_t delta = reinterpret_cast<int64_t>(m->base) - static_cast<int64_t>(oh.ImageBase); | 1748 | int64_t delta = reinterpret_cast<int64_t>(m->base) - static_cast<int64_t>(oh.ImageBase); |
| 1752 | if (delta) { | 1749 | // A moved image with a relocation table is fixed up, whatever IMAGE_FILE_RELOCS_STRIPPED says. Without a table, |
| 1753 | m->relocated = true; | 1750 | // the flag refuses the move; with the flag clear the image is moved and nothing is fixed up, so it is trusted to |
| 1754 | const auto dir = directory(nt, IMAGE_DIRECTORY_ENTRY_BASERELOC); | 1751 | // hold no absolute addresses. The Windows 11 loader does all three (runtime/README.md); that move is logged so |
| 1755 | if (!dir.Size) throw std::runtime_error(m->name + ": the image has no relocations and isn't at its base"); | 1752 | // it shows in traces. base_reservation::needed still keeps the main image's range free when it has no |
| 1753 | // relocation directory, so a main image is moved this way only where the range could not be had. | ||
| 1754 | const auto dir = directory(nt, IMAGE_DIRECTORY_ENTRY_BASERELOC); | ||
| 1755 | if (delta) m->relocated = true; | ||
| 1756 | if (delta && !dir.Size && (nt->FileHeader.Characteristics & IMAGE_FILE_RELOCS_STRIPPED)) | ||
| 1757 | throw std::runtime_error(m->name + ": preferred base is taken and the image's relocations are stripped"); | ||
| 1758 | if (delta && !dir.Size) | ||
| 1759 | std::fprintf(stderr, "[rt] loader: %s: preferred base %#llx is taken, moved to %p with no relocations\n", | ||
| 1760 | m->name.c_str(), static_cast<unsigned long long>(oh.ImageBase), static_cast<void*>(m->base)); | ||
| 1761 | if (delta && dir.Size) { | ||
| 1756 | require_range(m->name, dir.VirtualAddress, dir.Size, m->size, "the relocation table"); | 1762 | require_range(m->name, dir.VirtualAddress, dir.Size, m->size, "the relocation table"); |
| 1757 | auto* block = at<IMAGE_BASE_RELOCATION>(m->base, dir.VirtualAddress); | 1763 | auto* block = at<IMAGE_BASE_RELOCATION>(m->base, dir.VirtualAddress); |
| 1758 | auto* end = reinterpret_cast<uint8_t*>(block) + dir.Size; | 1764 | auto* end = reinterpret_cast<uint8_t*>(block) + dir.Size; |
| @@ -2123,7 +2129,10 @@ void Loader::bind_imports(Module& m) { | |||
| 2123 | const uint64_t headers_end = nt->OptionalHeader.SizeOfHeaders; | 2129 | const uint64_t headers_end = nt->OptionalHeader.SizeOfHeaders; |
| 2124 | 2130 | ||
| 2125 | // Thunk tables have no length field: they end at a zero entry, so each step is checked against the image. | 2131 | // Thunk tables have no length field: they end at a zero entry, so each step is checked against the image. |
| 2126 | auto bind_thunks = [&](const std::string& dll, uint64_t lookup_rva, uint64_t iat_rva) { | 2132 | // `delayed`: a delay import that binds to an unimplemented thunk is traced. Windows' delay-load helper would raise |
| 2133 | // 0xC06D007E (module) or 0xC06D007F (procedure) at its first call, which a title can catch for a fallback; the | ||
| 2134 | // thunk returns 0 instead, so the trace names each such import before any image code runs. | ||
| 2135 | auto bind_thunks = [&](const std::string& dll, uint64_t lookup_rva, uint64_t iat_rva, bool delayed) { | ||
| 2127 | for (;; lookup_rva += sizeof(IMAGE_THUNK_DATA64), iat_rva += sizeof(IMAGE_THUNK_DATA64)) { | 2136 | for (;; lookup_rva += sizeof(IMAGE_THUNK_DATA64), iat_rva += sizeof(IMAGE_THUNK_DATA64)) { |
| 2128 | require_range(m.name, lookup_rva, sizeof(IMAGE_THUNK_DATA64), m.size, "an import lookup table"); | 2137 | require_range(m.name, lookup_rva, sizeof(IMAGE_THUNK_DATA64), m.size, "an import lookup table"); |
| 2129 | require_range(m.name, iat_rva, sizeof(IMAGE_THUNK_DATA64), m.size, "an import address table"); | 2138 | require_range(m.name, iat_rva, sizeof(IMAGE_THUNK_DATA64), m.size, "an import address table"); |
| @@ -2141,6 +2150,10 @@ void Loader::bind_imports(Module& m) { | |||
| 2141 | throw std::runtime_error(m.name + ": an import address table lands in the headers"); | 2150 | throw std::runtime_error(m.name + ": an import address table lands in the headers"); |
| 2142 | at<IMAGE_THUNK_DATA64>(m.base, static_cast<uint32_t>(iat_rva))->u1.Function = | 2151 | at<IMAGE_THUNK_DATA64>(m.base, static_cast<uint32_t>(iat_rva))->u1.Function = |
| 2143 | reinterpret_cast<uint64_t>(resolve(m, dll, name, ord, by_ord)); | 2152 | reinterpret_cast<uint64_t>(resolve(m, dll, name, ord, by_ord)); |
| 2153 | if (delayed && startup_trace::enabled() && m.imports.back().binding == Binding::Unimplemented) | ||
| 2154 | startup_trace::event("delay_import_unimplemented", | ||
| 2155 | "\"module\":" + startup_trace::quote(m.name) + ",\"import\":" + | ||
| 2156 | startup_trace::quote(dll + "!" + m.imports.back().name)); | ||
| 2144 | } | 2157 | } |
| 2145 | }; | 2158 | }; |
| 2146 | 2159 | ||
| @@ -2153,7 +2166,7 @@ void Loader::bind_imports(Module& m) { | |||
| 2153 | if (!d->Name) break; | 2166 | if (!d->Name) break; |
| 2154 | std::string dll = read_string(m.name, m.base, m.size, d->Name, "an imported DLL name"); | 2167 | std::string dll = read_string(m.name, m.base, m.size, d->Name, "an imported DLL name"); |
| 2155 | uint32_t lookup = d->OriginalFirstThunk ? d->OriginalFirstThunk : d->FirstThunk; | 2168 | uint32_t lookup = d->OriginalFirstThunk ? d->OriginalFirstThunk : d->FirstThunk; |
| 2156 | bind_thunks(dll, lookup, d->FirstThunk); | 2169 | bind_thunks(dll, lookup, d->FirstThunk, false); |
| 2157 | } | 2170 | } |
| 2158 | } | 2171 | } |
| 2159 | // Delay imports are bound eagerly: simpler, and the full import surface shows up in --dry-run. | 2172 | // Delay imports are bound eagerly: simpler, and the full import surface shows up in --dry-run. |
| @@ -2176,7 +2189,7 @@ void Loader::bind_imports(Module& m) { | |||
| 2176 | // thunk addresses as name RVAs. | 2189 | // thunk addresses as name RVAs. |
| 2177 | if (!d->ImportNameTableRVA) | 2190 | if (!d->ImportNameTableRVA) |
| 2178 | throw std::runtime_error(m.name + ": a delay-import descriptor has no name table"); | 2191 | throw std::runtime_error(m.name + ": a delay-import descriptor has no name table"); |
| 2179 | bind_thunks(dll, d->ImportNameTableRVA, d->ImportAddressTableRVA); | 2192 | bind_thunks(dll, d->ImportNameTableRVA, d->ImportAddressTableRVA, true); |
| 2180 | } | 2193 | } |
| 2181 | } | 2194 | } |
| 2182 | } | 2195 | } |
diff --git a/runtime/src/root_signature.cpp b/runtime/src/root_signature.cpp index 10dd1e02c..41d3f6c5a 100644 --- a/runtime/src/root_signature.cpp +++ b/runtime/src/root_signature.cpp | |||
| @@ -17,10 +17,8 @@ PackResult pack(const RootSignature& sig) { | |||
| 17 | out.error = "unknown root parameter type"; | 17 | out.error = "unknown root parameter type"; |
| 18 | return out; | 18 | return out; |
| 19 | } | 19 | } |
| 20 | if (p.type == ParamType::Constants && p.num_values == 0) { | 20 | // A constant parameter of 0 values is valid (the host serializer warns, CreateRootSignature answers S_OK): |
| 21 | out.error = "root constant parameter needs at least 1 dword"; | 21 | // it takes no dwords, so it gets no provenance entry and the parameters after it pack as if it were absent. |
| 22 | return out; | ||
| 23 | } | ||
| 24 | const uint32_t dwords = p.type == ParamType::Table ? 2 | 22 | const uint32_t dwords = p.type == ParamType::Table ? 2 |
| 25 | : p.type == ParamType::Descriptor ? 2 | 23 | : p.type == ParamType::Descriptor ? 2 |
| 26 | : p.num_values; | 24 | : p.num_values; |
| @@ -71,15 +69,12 @@ StagePackResult pack_stage(const RootSignature& sig, Stage stage) { | |||
| 71 | out.error = "unknown root parameter type"; | 69 | out.error = "unknown root parameter type"; |
| 72 | return out; | 70 | return out; |
| 73 | } | 71 | } |
| 74 | if (p.type == ParamType::Constants && p.num_values == 0) { | ||
| 75 | out.error = "root constant parameter needs at least 1 dword"; | ||
| 76 | return out; | ||
| 77 | } | ||
| 78 | cost += param_cost(p.type, p.num_values); | 72 | cost += param_cost(p.type, p.num_values); |
| 79 | if (cost > kMaxD3d12Cost) { | 73 | if (cost > kMaxD3d12Cost) { |
| 80 | out.error = "root signature exceeds the 64-dword D3D12 cost limit"; | 74 | out.error = "root signature exceeds the 64-dword D3D12 cost limit"; |
| 81 | return out; | 75 | return out; |
| 82 | } | 76 | } |
| 77 | // 0 for a constant parameter of 0 values, which then shares its first SGPR with the next parameter. | ||
| 83 | const uint64_t dwords = stage_dwords(p.type, p.num_values); | 78 | const uint64_t dwords = stage_dwords(p.type, p.num_values); |
| 84 | if (!spilling && next + dwords <= kMaxUserSgprs) { | 79 | if (!spilling && next + dwords <= kMaxUserSgprs) { |
| 85 | first.push_back(static_cast<uint32_t>(next)); | 80 | first.push_back(static_cast<uint32_t>(next)); |
diff --git a/runtime/src/root_signature.h b/runtime/src/root_signature.h index e7976fc73..559f4c54d 100644 --- a/runtime/src/root_signature.h +++ b/runtime/src/root_signature.h | |||
| @@ -114,7 +114,8 @@ constexpr uint32_t kMaxD3d12Cost = 64; | |||
| 114 | // Packs root parameters in order. Static samplers consume no dwords. | 114 | // Packs root parameters in order. Static samplers consume no dwords. |
| 115 | // Fails (ok == false) when the signature needs more than 32 user SGPRs | 115 | // Fails (ok == false) when the signature needs more than 32 user SGPRs |
| 116 | // (spill layout unknown: refuse, do not guess) or exceeds the 64-dword | 116 | // (spill layout unknown: refuse, do not guess) or exceeds the 64-dword |
| 117 | // D3D12 cost limit, or holds more than 64 root parameters. | 117 | // D3D12 cost limit, or holds more than 64 root parameters. A constant |
| 118 | // parameter of 0 values takes no dwords, as on the host. | ||
| 118 | [[nodiscard]] PackResult pack(const RootSignature& sig); | 119 | [[nodiscard]] PackResult pack(const RootSignature& sig); |
| 119 | 120 | ||
| 120 | // The console layout of root arguments in a stage's user SGPRs (docs/d3d12_vulkan.md section 3.5, D3D-448). | 121 | // The console layout of root arguments in a stage's user SGPRs (docs/d3d12_vulkan.md section 3.5, D3D-448). |
| @@ -183,8 +184,9 @@ struct StagePackResult { | |||
| 183 | }; | 184 | }; |
| 184 | 185 | ||
| 185 | // Lays the parameters out for `stage` in the console layout. Fails like pack() on more than 64 parameters, an | 186 | // Lays the parameters out for `stage` in the console layout. Fails like pack() on more than 64 parameters, an |
| 186 | // unknown parameter type, a constant parameter of 0 values, or the 64-dword cost limit. Compute spills any trailing | 187 | // unknown parameter type or the 64-dword cost limit. Compute spills any trailing parameters from the first one |
| 187 | // parameters from the first one that does not fit whole into spill_dword; non-compute stages refuse any spill. | 188 | // that does not fit whole into spill_dword; non-compute stages refuse any spill. A constant parameter of 0 values |
| 189 | // takes no SGPRs and no spill dwords. | ||
| 188 | [[nodiscard]] StagePackResult pack_stage(const RootSignature& sig, Stage stage); | 190 | [[nodiscard]] StagePackResult pack_stage(const RootSignature& sig, Stage stage); |
| 189 | 191 | ||
| 190 | // D3D12 cost of one parameter against the 64-dword limit. | 192 | // D3D12 cost of one parameter against the 64-dword limit. |
diff --git a/runtime/src/submit_phases.h b/runtime/src/submit_phases.h index 8c697979a..dfaf8ce95 100644 --- a/runtime/src/submit_phases.h +++ b/runtime/src/submit_phases.h | |||
| @@ -42,6 +42,10 @@ struct Totals { | |||
| 42 | std::atomic<std::int64_t> last_log{0}; | 42 | std::atomic<std::int64_t> last_log{0}; |
| 43 | std::atomic<std::uint64_t> presents{0}; // frames the presenter showed (VulkanPresenter), since the last line | 43 | std::atomic<std::uint64_t> presents{0}; // frames the presenter showed (VulkanPresenter), since the last line |
| 44 | std::atomic<std::uint64_t> present_serial{0}; // the same, never reset (LEONIDA_REFRESH_PER_FRAME) | 44 | std::atomic<std::uint64_t> present_serial{0}; // the same, never reset (LEONIDA_REFRESH_PER_FRAME) |
| 45 | // Threads whose innermost Scope is this phase now, and when the first of them entered it (steady_clock). Counted | ||
| 46 | // per phase, since queues submit from several threads: one value would go stale when their scopes overlap. | ||
| 47 | std::atomic<unsigned> active[kCount]{}; | ||
| 48 | std::atomic<std::int64_t> active_since[kCount]{}; | ||
| 45 | std::atomic<std::uint32_t> thread{0}; // the thread of the last submission (the thread sampler reports it apart) | 49 | std::atomic<std::uint32_t> thread{0}; // the thread of the last submission (the thread sampler reports it apart) |
| 46 | }; | 50 | }; |
| 47 | inline Totals& totals() { | 51 | inline Totals& totals() { |
| @@ -88,12 +92,48 @@ inline void add(Phase p, std::uint64_t ns) { | |||
| 88 | struct Scope { | 92 | struct Scope { |
| 89 | Phase phase; | 93 | Phase phase; |
| 90 | std::int64_t start = now_ns(); | 94 | std::int64_t start = now_ns(); |
| 91 | explicit Scope(Phase p) : phase(p) {} | 95 | int outer; // the phase of this thread's Scope around this one, -1 for none |
| 92 | ~Scope() { add(phase, std::uint64_t(now_ns() - start)); } | 96 | explicit Scope(Phase p) : phase(p), outer(innermost()) { |
| 97 | if (outer >= 0) leave(outer); | ||
| 98 | enter(int(p), start); | ||
| 99 | innermost() = int(p); | ||
| 100 | } | ||
| 101 | ~Scope() { | ||
| 102 | const std::int64_t end = now_ns(); | ||
| 103 | add(phase, std::uint64_t(end - start)); | ||
| 104 | leave(int(phase)); | ||
| 105 | if (outer >= 0) enter(outer, end); | ||
| 106 | innermost() = outer; | ||
| 107 | } | ||
| 108 | static int& innermost() { | ||
| 109 | thread_local int phase_of_this_thread = -1; | ||
| 110 | return phase_of_this_thread; | ||
| 111 | } | ||
| 112 | static void enter(int p, std::int64_t at) { | ||
| 113 | Totals& t = totals(); | ||
| 114 | if (t.active[p].fetch_add(1, std::memory_order_relaxed) == 0) t.active_since[p].store(at, std::memory_order_relaxed); | ||
| 115 | } | ||
| 116 | static void leave(int p) { totals().active[p].fetch_sub(1, std::memory_order_relaxed); } | ||
| 93 | Scope(const Scope&) = delete; | 117 | Scope(const Scope&) = delete; |
| 94 | Scope& operator=(const Scope&) = delete; | 118 | Scope& operator=(const Scope&) = delete; |
| 95 | }; | 119 | }; |
| 96 | 120 | ||
| 121 | // The phase that some thread has been in longest, -1 when none is in one. | ||
| 122 | struct Running { | ||
| 123 | int phase = -1; | ||
| 124 | std::int64_t since = 0; | ||
| 125 | }; | ||
| 126 | inline Running running() { | ||
| 127 | Totals& t = totals(); | ||
| 128 | Running r; | ||
| 129 | for (unsigned p = 0; p < kCount; ++p) { | ||
| 130 | if (!t.active[p].load(std::memory_order_relaxed)) continue; | ||
| 131 | const std::int64_t since = t.active_since[p].load(std::memory_order_relaxed); | ||
| 132 | if (r.phase < 0 || since < r.since) r = {int(p), since}; | ||
| 133 | } | ||
| 134 | return r; | ||
| 135 | } | ||
| 136 | |||
| 97 | // After each submission: counts it, and prints the line when the period has passed. One thread wins the line. | 137 | // After each submission: counts it, and prints the line when the period has passed. One thread wins the line. |
| 98 | inline void submitted() { | 138 | inline void submitted() { |
| 99 | Totals& t = totals(); | 139 | Totals& t = totals(); |
diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h index dd5a44ef7..4a4d9d485 100644 --- a/runtime/src/vulkan_backend.h +++ b/runtime/src/vulkan_backend.h | |||
| @@ -131,7 +131,8 @@ struct VulkanDeviceFunctions { | |||
| 131 | X(vkCreatePipelineCache) X(vkDestroyPipelineCache) X(vkGetPipelineCacheData) X(vkMergePipelineCaches) \ | 131 | X(vkCreatePipelineCache) X(vkDestroyPipelineCache) X(vkGetPipelineCacheData) X(vkMergePipelineCaches) \ |
| 132 | X(vkCreateEvent) X(vkDestroyEvent) X(vkResetEvent) X(vkCmdSetEvent) X(vkCmdWaitEvents) X(vkCmdDrawMeshTasksEXT) X(vkCmdDrawMeshTasksIndirectEXT) X(vkCmdDrawMeshTasksIndirectCountEXT) \ | 132 | X(vkCreateEvent) X(vkDestroyEvent) X(vkResetEvent) X(vkCmdSetEvent) X(vkCmdWaitEvents) X(vkCmdDrawMeshTasksEXT) X(vkCmdDrawMeshTasksIndirectEXT) X(vkCmdDrawMeshTasksIndirectCountEXT) \ |
| 133 | X(vkCreateRenderPass2) X(vkDestroyRenderPass) X(vkCreateFramebuffer) X(vkDestroyFramebuffer) \ | 133 | X(vkCreateRenderPass2) X(vkDestroyRenderPass) X(vkCreateFramebuffer) X(vkDestroyFramebuffer) \ |
| 134 | X(vkCmdBeginRenderPass) X(vkCmdEndRenderPass) | 134 | X(vkCmdBeginRenderPass) X(vkCmdEndRenderPass) \ |
| 135 | X(vkCmdBeginQueryIndexedEXT) X(vkCmdEndQueryIndexedEXT) | ||
| 135 | #define LEONIDA_VK_MEMBER(name) PFN_##name name = nullptr; | 136 | #define LEONIDA_VK_MEMBER(name) PFN_##name name = nullptr; |
| 136 | LEONIDA_VK_DEVICE_FUNCTIONS(LEONIDA_VK_MEMBER) | 137 | LEONIDA_VK_DEVICE_FUNCTIONS(LEONIDA_VK_MEMBER) |
| 137 | #undef LEONIDA_VK_MEMBER | 138 | #undef LEONIDA_VK_MEMBER |
| @@ -166,6 +167,9 @@ struct VulkanDeviceFunctions { | |||
| 166 | return vkCmdBeginRendering && vkCmdEndRendering && vkCmdBindVertexBuffers2 && vkCmdSetPrimitiveTopology && | 167 | return vkCmdBeginRendering && vkCmdEndRendering && vkCmdBindVertexBuffers2 && vkCmdSetPrimitiveTopology && |
| 167 | vkCmdSetPrimitiveRestartEnable; | 168 | vkCmdSetPrimitiveRestartEnable; |
| 168 | } | 169 | } |
| 170 | // VK_EXT_transform_feedback is enabled on the device: the indexed-query entry points are loaded, so an | ||
| 171 | // SO_STATISTICS heap can be a real transform-feedback pool (D3D-302). | ||
| 172 | bool transform_feedback = false; | ||
| 169 | }; | 173 | }; |
| 170 | 174 | ||
| 171 | // Both kinds of compute resolve use the same storage buffer, descriptor set and pipeline layout. | 175 | // Both kinds of compute resolve use the same storage buffer, descriptor set and pipeline layout. |
| @@ -1123,6 +1127,8 @@ public: | |||
| 1123 | GraphicsIndirectCapabilities indirect = {}) | 1127 | GraphicsIndirectCapabilities indirect = {}) |
| 1124 | : device_(device), tracker_(separate_depth_stencil_layouts), ray_tracing_(ray_tracing) { | 1128 | : device_(device), tracker_(separate_depth_stencil_layouts), ray_tracing_(ray_tracing) { |
| 1125 | loaded_ = vk.load(get, device); | 1129 | loaded_ = vk.load(get, device); |
| 1130 | // VK_EXT_transform_feedback: enabled on the device when its indexed-query entry points resolved (D3D-302). | ||
| 1131 | vk.transform_feedback = vk.vkCmdBeginQueryIndexedEXT && vk.vkCmdEndQueryIndexedEXT; | ||
| 1126 | if (loaded_ && gpu_labels_.initialize(device, get)) { | 1132 | if (loaded_ && gpu_labels_.initialize(device, get)) { |
| 1127 | replay_.gpu_label = [this](VkCommandBuffer cb, const label::Write& write) { gpu_labels_.record(cb, write); }; | 1133 | replay_.gpu_label = [this](VkCommandBuffer cb, const label::Write& write) { gpu_labels_.record(cb, write); }; |
| 1128 | } | 1134 | } |
| @@ -1158,6 +1164,11 @@ public: | |||
| 1158 | replay_.reset_query_pool = vk.vkCmdResetQueryPool; | 1164 | replay_.reset_query_pool = vk.vkCmdResetQueryPool; |
| 1159 | replay_.begin_query = vk.vkCmdBeginQuery; | 1165 | replay_.begin_query = vk.vkCmdBeginQuery; |
| 1160 | replay_.end_query = vk.vkCmdEndQuery; | 1166 | replay_.end_query = vk.vkCmdEndQuery; |
| 1167 | // VK_EXT_transform_feedback (D3D-302), loaded when the device enabled it: indexed SO_STATISTICS queries. | ||
| 1168 | if (vk.transform_feedback) { | ||
| 1169 | replay_.begin_query_indexed = vk.vkCmdBeginQueryIndexedEXT; | ||
| 1170 | replay_.end_query_indexed = vk.vkCmdEndQueryIndexedEXT; | ||
| 1171 | } | ||
| 1161 | replay_.write_timestamp = vk.vkCmdWriteTimestamp; | 1172 | replay_.write_timestamp = vk.vkCmdWriteTimestamp; |
| 1162 | replay_.copy_query_pool_results = vk.vkCmdCopyQueryPoolResults; | 1173 | replay_.copy_query_pool_results = vk.vkCmdCopyQueryPoolResults; |
| 1163 | replay_.bind_pipeline = vk.vkCmdBindPipeline; | 1174 | replay_.bind_pipeline = vk.vkCmdBindPipeline; |
diff --git a/runtime/src/vulkan_memory_budget.h b/runtime/src/vulkan_memory_budget.h new file mode 100644 index 000000000..e9bc549b1 --- /dev/null +++ b/runtime/src/vulkan_memory_budget.h | |||
| @@ -0,0 +1,46 @@ | |||
| 1 | #pragma once | ||
| 2 | |||
| 3 | // VK_EXT_memory_budget: how much GPU memory this process uses and may use, read from the Vulkan device itself. The | ||
| 4 | // device publishes it (memory_figures.h) for the title HUD (shims/title_hud.h, LEONIDA_TITLE_HUD) and the dev overlay | ||
| 5 | // (dev_overlay.h, LEONIDA_DEV_OVERLAY); DXGI's QueryVideoMemoryInfo, which the HUD read before, is 0 under Wine. The | ||
| 6 | // sums depend only on the two Vulkan structures, so a test can feed them made-up heaps. | ||
| 7 | |||
| 8 | #ifndef VK_NO_PROTOTYPES | ||
| 9 | #define VK_NO_PROTOTYPES | ||
| 10 | #endif | ||
| 11 | #include <vulkan/vulkan.h> | ||
| 12 | |||
| 13 | #include <cstdint> | ||
| 14 | |||
| 15 | #include "memory_figures.h" // VramBudget | ||
| 16 | |||
| 17 | namespace leonida { | ||
| 18 | |||
| 19 | inline VramBudget sum_vram_budget(const VkPhysicalDeviceMemoryProperties& memory, | ||
| 20 | const VkPhysicalDeviceMemoryBudgetPropertiesEXT& budget) { | ||
| 21 | VramBudget out; | ||
| 22 | for (std::uint32_t i = 0; i < memory.memoryHeapCount && i < VK_MAX_MEMORY_HEAPS; ++i) { | ||
| 23 | if (memory.memoryHeaps[i].flags & VK_MEMORY_HEAP_DEVICE_LOCAL_BIT) { | ||
| 24 | out.local_usage += budget.heapUsage[i]; | ||
| 25 | out.local_budget += budget.heapBudget[i]; | ||
| 26 | } else { | ||
| 27 | out.shared_usage += budget.heapUsage[i]; | ||
| 28 | } | ||
| 29 | } | ||
| 30 | out.available = out.local_budget != 0; | ||
| 31 | return out; | ||
| 32 | } | ||
| 33 | |||
| 34 | // Reads the budget now. `physical` must have VK_EXT_memory_budget (enabled on the logical device, as the runtime's | ||
| 35 | // device does). One vkGetPhysicalDeviceMemoryProperties2 call, which needs no external synchronization, so another | ||
| 36 | // thread (the HUD's or the overlay's) may call it while the device is in use. | ||
| 37 | inline VramBudget query_vram_budget(PFN_vkGetPhysicalDeviceMemoryProperties2 get_memory_properties2, | ||
| 38 | VkPhysicalDevice physical) { | ||
| 39 | if (!get_memory_properties2 || physical == VK_NULL_HANDLE) return {}; | ||
| 40 | VkPhysicalDeviceMemoryBudgetPropertiesEXT budget{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MEMORY_BUDGET_PROPERTIES_EXT}; | ||
| 41 | VkPhysicalDeviceMemoryProperties2 properties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MEMORY_PROPERTIES_2, &budget}; | ||
| 42 | get_memory_properties2(physical, &properties); | ||
| 43 | return sum_vram_budget(properties.memoryProperties, budget); | ||
| 44 | } | ||
| 45 | |||
| 46 | } // namespace leonida | ||
diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h index fc8d27d3c..706bb2f72 100644 --- a/runtime/src/vulkan_replay.h +++ b/runtime/src/vulkan_replay.h | |||
| @@ -846,14 +846,19 @@ struct OcclusionResult { | |||
| 846 | // A D3D12 query heap on Vulkan. The host tracks which queries hold a result. A resolve of a query that | 846 | // A D3D12 query heap on Vulkan. The host tracks which queries hold a result. A resolve of a query that |
| 847 | // was never ended writes zeros instead of waiting on it. | 847 | // was never ended writes zeros instead of waiting on it. |
| 848 | struct QueryPool { | 848 | struct QueryPool { |
| 849 | // Null for a stream-output statistics heap: the layer has no stream output (PSOs with StreamOutput entries are | 849 | // Null for a stream-output statistics heap on a device without VK_EXT_transform_feedback (D3D-302): every |
| 850 | // refused), so every SO_STATISTICS_STREAMn query counts 0 written and 0 needed, and a resolve fills zeros. | 850 | // SO_STATISTICS_STREAMn query then counts 0 written and 0 needed, and a resolve fills zeros. With the feature |
| 851 | // it is a VK_QUERY_TYPE_TRANSFORM_FEEDBACK_STREAM_EXT pool, begun/ended indexed on the stream. | ||
| 851 | VkQueryPool pool = VK_NULL_HANDLE; | 852 | VkQueryPool pool = VK_NULL_HANDLE; |
| 852 | std::uint32_t heap_type = 0; // d3d12_query_heap | 853 | std::uint32_t heap_type = 0; // d3d12_query_heap |
| 853 | std::uint32_t count = 0; | 854 | std::uint32_t count = 0; |
| 854 | bool precise = false; // occlusionQueryPrecise: D3D12_QUERY_TYPE_OCCLUSION counts exact samples | 855 | bool precise = false; // occlusionQueryPrecise: D3D12_QUERY_TYPE_OCCLUSION counts exact samples |
| 855 | std::vector<bool> ended; | 856 | std::vector<bool> ended; |
| 856 | std::unordered_map<std::uint32_t, OcclusionResult> occlusion; | 857 | std::unordered_map<std::uint32_t, OcclusionResult> occlusion; |
| 858 | // Transform-feedback streams the pool can query (D3D-302): 0 when it has no pool, otherwise the device's | ||
| 859 | // maxTransformFeedbackStreams clamped to D3D12's four. SO_STATISTICS_STREAMn with n at or above this runs nothing | ||
| 860 | // and resolves zero. | ||
| 861 | std::uint32_t streams = 0; | ||
| 857 | }; | 862 | }; |
| 858 | 863 | ||
| 859 | // A compute pipeline as replay needs it. code_base is the console VA of the shader's FSSM blob (push-constant | 864 | // A compute pipeline as replay needs it. code_base is the console VA of the shader's FSSM blob (push-constant |
| @@ -1179,6 +1184,10 @@ struct ReplayFunctions { | |||
| 1179 | PFN_vkCmdResetQueryPool reset_query_pool = nullptr; // queries, with fill_buffer for unavailable results | 1184 | PFN_vkCmdResetQueryPool reset_query_pool = nullptr; // queries, with fill_buffer for unavailable results |
| 1180 | PFN_vkCmdBeginQuery begin_query = nullptr; | 1185 | PFN_vkCmdBeginQuery begin_query = nullptr; |
| 1181 | PFN_vkCmdEndQuery end_query = nullptr; | 1186 | PFN_vkCmdEndQuery end_query = nullptr; |
| 1187 | // VK_EXT_transform_feedback (D3D-302): SO_STATISTICS queries begin/end indexed on a stream. Null when the device | ||
| 1188 | // lacks the feature. | ||
| 1189 | PFN_vkCmdBeginQueryIndexedEXT begin_query_indexed = nullptr; | ||
| 1190 | PFN_vkCmdEndQueryIndexedEXT end_query_indexed = nullptr; | ||
| 1182 | PFN_vkCmdWriteTimestamp write_timestamp = nullptr; | 1191 | PFN_vkCmdWriteTimestamp write_timestamp = nullptr; |
| 1183 | PFN_vkCmdCopyQueryPoolResults copy_query_pool_results = nullptr; | 1192 | PFN_vkCmdCopyQueryPoolResults copy_query_pool_results = nullptr; |
| 1184 | // Set only where a copy of timestamp results is not ordered after the timestamps written before it (MoltenVK on | 1193 | // Set only where a copy of timestamp results is not ordered after the timestamps written before it (MoltenVK on |
| @@ -3403,6 +3412,8 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun | |||
| 3403 | out.unpredicated_copies = 0; | 3412 | out.unpredicated_copies = 0; |
| 3404 | const bool queries = vk.reset_query_pool && vk.begin_query && vk.end_query && vk.write_timestamp && | 3413 | const bool queries = vk.reset_query_pool && vk.begin_query && vk.end_query && vk.write_timestamp && |
| 3405 | vk.copy_query_pool_results && vk.fill_buffer && vk.query_pool; | 3414 | vk.copy_query_pool_results && vk.fill_buffer && vk.query_pool; |
| 3415 | // An SO_STATISTICS query on a real transform-feedback heap additionally needs the indexed begin/end (D3D-302). | ||
| 3416 | const bool so_queries = vk.begin_query_indexed && vk.end_query_indexed; | ||
| 3406 | // Vulkan allows one active query per type. Overlapping ordinary and binary occlusion share one physical | 3417 | // Vulkan allows one active query per type. Overlapping ordinary and binary occlusion share one physical |
| 3407 | // segment pool, and overlapping statistics split into the statistics pool (D3D-252); a physical query of a | 3418 | // segment pool, and overlapping statistics split into the statistics pool (D3D-252); a physical query of a |
| 3408 | // type is still open at most once at any point, because each event closes the one open slot and opens a new | 3419 | // type is still open at most once at any point, because each event closes the one open slot and opens a new |
| @@ -3410,6 +3421,10 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun | |||
| 3410 | VkDeviceAddress indirect_list_budget = 0; | 3421 | VkDeviceAddress indirect_list_budget = 0; |
| 3411 | std::size_t ordinary_active = 0, binary_active = 0, statistics_active_count = 0; | 3422 | std::size_t ordinary_active = 0, binary_active = 0, statistics_active_count = 0; |
| 3412 | bool overlaps = false, statistics_overlaps = false, statistics_active = false; | 3423 | bool overlaps = false, statistics_overlaps = false, statistics_active = false; |
| 3424 | // Streams with an active SO_STATISTICS query in this list, one bit each (D3D-302). Two active transform-feedback | ||
| 3425 | // queries on one stream break VUID-vkCmdBeginQueryIndexedEXT-queryPool-04753 anywhere in the command buffer, | ||
| 3426 | // whatever their pools, so prepare refuses a second Begin on an active stream. | ||
| 3427 | std::uint32_t so_active = 0; | ||
| 3413 | out.wrote_readback = false; | 3428 | out.wrote_readback = false; |
| 3414 | out.readback_src_stages = 0; | 3429 | out.readback_src_stages = 0; |
| 3415 | 3430 | ||
| @@ -3958,7 +3973,23 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun | |||
| 3958 | overlaps |= begin && (ordinary_active || binary_active); | 3973 | overlaps |= begin && (ordinary_active || binary_active); |
| 3959 | if (begin) ++binary_active; else --binary_active; | 3974 | if (begin) ++binary_active; else --binary_active; |
| 3960 | } else if (is_so_statistics(range.type)) { | 3975 | } else if (is_so_statistics(range.type)) { |
| 3961 | // No Vulkan query runs for it (QueryPool::pool is null), so it overlaps nothing. | 3976 | // A real transform-feedback heap queries on a stream (D3D-302). Stream n runs only when the |
| 3977 | // heap's pool covers it; then the indexed commands are required. Without a pool (the feature is | ||
| 3978 | // off or has no transformFeedbackQueries) or past maxTransformFeedbackStreams it runs nothing | ||
| 3979 | // and resolves zero. Two overlapping queries on one stream cannot both be active in one command | ||
| 3980 | // buffer, even in two heaps (VUID-vkCmdBeginQueryIndexedEXT-queryPool-04753), so a second Begin | ||
| 3981 | // is refused. | ||
| 3982 | const std::uint32_t stream = range.type - d3d12_query::so_statistics_stream0; | ||
| 3983 | if (heap->pool && stream < heap->streams) { | ||
| 3984 | if (!so_queries) return unsupported_at(__LINE__); | ||
| 3985 | const std::uint32_t bit = 1u << stream; // stream < heap->streams <= 4 | ||
| 3986 | if (begin) { | ||
| 3987 | if (so_active & bit) return ReplayResult::invalid_query; | ||
| 3988 | so_active |= bit; | ||
| 3989 | } else { | ||
| 3990 | so_active &= ~bit; | ||
| 3991 | } | ||
| 3992 | } | ||
| 3962 | } else { | 3993 | } else { |
| 3963 | statistics_overlaps |= begin && statistics_active_count; | 3994 | statistics_overlaps |= begin && statistics_active_count; |
| 3964 | if (begin) ++statistics_active_count; else --statistics_active_count; | 3995 | if (begin) ++statistics_active_count; else --statistics_active_count; |
| @@ -4332,12 +4363,16 @@ public: | |||
| 4332 | query.statistics_end != detail::PreparedQuery::no_segment; | 4363 | query.statistics_end != detail::PreparedQuery::no_segment; |
| 4333 | const std::uint32_t size = query_result_size(resolve.type); | 4364 | const std::uint32_t size = query_result_size(resolve.type); |
| 4334 | const auto offset = list.commands[query.command].binding.buffer_offset + resolve.offset; | 4365 | const auto offset = list.commands[query.command].binding.buffer_offset + resolve.offset; |
| 4366 | // A stream past the pool's maxTransformFeedbackStreams ran nothing (D3D-302): its resolve is zeros. | ||
| 4367 | const std::uint32_t so_stream = | ||
| 4368 | is_so_statistics(resolve.type) ? resolve.type - d3d12_query::so_statistics_stream0 : 0; | ||
| 4369 | const bool so_runs = !is_so_statistics(resolve.type) || so_stream < query.heap->streams; | ||
| 4335 | for (std::uint32_t i = 0; i < resolve.count; ++i) { | 4370 | for (std::uint32_t i = 0; i < resolve.count; ++i) { |
| 4336 | const auto index = resolve.first + i; | 4371 | const auto index = resolve.first + i; |
| 4337 | const auto value = lookup(*query.heap, index); | 4372 | const auto value = lookup(*query.heap, index); |
| 4338 | if (binary && value.ended && !uncounted) return unsupported_at(__LINE__); | 4373 | if (binary && value.ended && !uncounted) return unsupported_at(__LINE__); |
| 4339 | needs_binary |= binary && value.ended; | 4374 | needs_binary |= binary && value.ended; |
| 4340 | detail::QueryResolveRun run{value.ended ? query.heap->pool : VK_NULL_HANDLE, | 4375 | detail::QueryResolveRun run{value.ended && so_runs ? query.heap->pool : VK_NULL_HANDLE, |
| 4341 | index, 1, offset + VkDeviceSize(i) * size}; | 4376 | index, 1, offset + VkDeviceSize(i) * size}; |
| 4342 | if (value.occlusion.segments) { | 4377 | if (value.occlusion.segments) { |
| 4343 | if (resolve.type != d3d12_query::occlusion && !binary && !statistics) | 4378 | if (resolve.type != d3d12_query::occlusion && !binary && !statistics) |
| @@ -4461,17 +4496,34 @@ inline void emit_query(const PreparedList& list, const detail::PreparedQuery& qu | |||
| 4461 | begin_statistics(); | 4496 | begin_statistics(); |
| 4462 | return; | 4497 | return; |
| 4463 | } | 4498 | } |
| 4464 | // A heap without a Vulkan pool (stream-output statistics: the layer has no stream output) runs nothing for | 4499 | // A heap without a Vulkan pool (stream-output statistics on a device without VK_EXT_transform_feedback) runs |
| 4465 | // BeginQuery and EndQuery; its resolves were planned as zero fills. | 4500 | // nothing for BeginQuery and EndQuery; its resolves were planned as zero fills. |
| 4466 | if (!heap.pool && !std::holds_alternative<ResolveQueries>(command)) return; | 4501 | if (!heap.pool && !std::holds_alternative<ResolveQueries>(command)) return; |
| 4502 | // An SO_STATISTICS_STREAMn query begins/ends indexed on that stream (D3D-302): the query type's stream index is | ||
| 4503 | // the `index` argument of vkCmdBeginQueryIndexedEXT / vkCmdEndQueryIndexedEXT. A stream past the pool's | ||
| 4504 | // maxTransformFeedbackStreams runs nothing, like a heap without a pool: its resolves were planned as zero fills. | ||
| 4505 | const auto so_stream = [](std::uint32_t type) -> std::uint32_t { | ||
| 4506 | return is_so_statistics(type) ? type - d3d12_query::so_statistics_stream0 : 0; | ||
| 4507 | }; | ||
| 4508 | const auto so_runs = [&](std::uint32_t type) { | ||
| 4509 | return !is_so_statistics(type) || so_stream(type) < heap.streams; | ||
| 4510 | }; | ||
| 4467 | if (const auto* begin = std::get_if<BeginQuery>(&command)) { | 4511 | if (const auto* begin = std::get_if<BeginQuery>(&command)) { |
| 4512 | if (!so_runs(begin->type)) return; | ||
| 4468 | vk.reset_query_pool(cb, heap.pool, begin->index, 1); | 4513 | vk.reset_query_pool(cb, heap.pool, begin->index, 1); |
| 4469 | const bool precise = begin->type == d3d12_query::occlusion && heap.precise; | 4514 | if (is_so_statistics(begin->type)) { |
| 4470 | vk.begin_query(cb, heap.pool, begin->index, precise ? VK_QUERY_CONTROL_PRECISE_BIT : 0); | 4515 | vk.begin_query_indexed(cb, heap.pool, begin->index, so_stream(begin->type), 0); |
| 4516 | } else { | ||
| 4517 | const bool precise = begin->type == d3d12_query::occlusion && heap.precise; | ||
| 4518 | vk.begin_query(cb, heap.pool, begin->index, precise ? VK_QUERY_CONTROL_PRECISE_BIT : 0); | ||
| 4519 | } | ||
| 4471 | } else if (const auto* end = std::get_if<EndQuery>(&command)) { | 4520 | } else if (const auto* end = std::get_if<EndQuery>(&command)) { |
| 4521 | if (!so_runs(end->type)) return; | ||
| 4472 | if (end->type == d3d12_query::timestamp) { | 4522 | if (end->type == d3d12_query::timestamp) { |
| 4473 | vk.reset_query_pool(cb, heap.pool, end->index, 1); | 4523 | vk.reset_query_pool(cb, heap.pool, end->index, 1); |
| 4474 | vk.write_timestamp(cb, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, heap.pool, end->index); | 4524 | vk.write_timestamp(cb, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, heap.pool, end->index); |
| 4525 | } else if (is_so_statistics(end->type)) { | ||
| 4526 | vk.end_query_indexed(cb, heap.pool, end->index, so_stream(end->type)); | ||
| 4475 | } else { | 4527 | } else { |
| 4476 | vk.end_query(cb, heap.pool, end->index); | 4528 | vk.end_query(cb, heap.pool, end->index); |
| 4477 | } | 4529 | } |