diff --git a/docs/designs/simx_simulator_architecture.md b/docs/designs/simx_simulator_architecture.md index 89ee110b32..0fc68fd365 100644 --- a/docs/designs/simx_simulator_architecture.md +++ b/docs/designs/simx_simulator_architecture.md @@ -149,6 +149,30 @@ writeback. Memory: LSU → coalescer → L1 `Cache` → L2/L3 `cache_cluster` `Memory`. Standalone, `main.cpp` loads an image into `RAM`, programs the KMU via DCR writes, and ticks `SimPlatform` until `!any_running()`. +### 4.1 Diagnostics: PC profile and launch checkpoints + +Two opt-in diagnostics observe a run without changing simulated behaviour: + +- **Per-launch PC profile** ([`pc_prof.h`](../../sim/simx/pc_prof.h), + `SIMX_PCPROF=`). Each core counts per PC the committed instructions, the + threads they ran for and the cycles its warp spent since its previous commit + (warp residence; a warp's first commit in a launch counts one cycle). Each + core owns its table and alone writes it, from its own execution domain; at + the end of each launch the processor merges the tables in host context, with + no lock, and appends them with each PC's instruction word, as the core + fetched it, to `/pcprof..txt`. It only reads commit events. +- **Launch checkpoints** ([`launch_ckpt.h`](../../sim/simx/launch_ckpt.h)). With + `SIMX_CKPT=` (and `SIMX_CKPT_FROM` / `SIMX_CKPT_TO`) the simx runtime + saves, at the start of each launch in range, the DCR writes the device took + since reset (`/dcr.log`) and every allocated device page (content + deduplicated across launches in `/pages.dat`, indexed by + `/L.idx`), after a system-scope cache flush so memory holds what + the command processor's DMA left in the last-level cache. `simx -C + -L ` replays that launch on any SimX build: it allocates exactly + those pages, replays the DCR writes in order and runs. A checkpoint carries + no cache contents, so the replayed launch starts with empty caches. Launch + indices are the PC profile's. + --- ## 5. SST integration diff --git a/sim/common/mem.cpp b/sim/common/mem.cpp index 2e0b6ac74d..0d16cb8a44 100644 --- a/sim/common/mem.cpp +++ b/sim/common/mem.cpp @@ -458,6 +458,17 @@ void RAM::clear() { last_chunk_ = nullptr; } +void RAM::for_each_page(const std::function& fn) const { + for (const auto& entry : chunks_) { + for (int i = 0; i < CHUNK_SIZE; ++i) { + const uint8_t* page = entry.second[i]; + if (page) { + fn(((entry.first << CHUNK_BITS) | uint64_t(i)) << page_bits_, page); + } + } + } +} + uint64_t RAM::size() const { uint64_t allocated_pages = 0; for (const auto& entry : chunks_) { diff --git a/sim/common/mem.h b/sim/common/mem.h index 5687613d84..31f64c9ddd 100644 --- a/sim/common/mem.h +++ b/sim/common/mem.h @@ -13,6 +13,8 @@ #pragma once +#include + #include #include #include @@ -315,6 +317,14 @@ class RAM : public MemDevice { check_acl_ = enable; } + // Bytes per page. + uint64_t page_size() const { return uint64_t(1) << page_bits_; } + + // Visit every allocated (written) page: its byte address and + // contents (page_size() bytes). A page never written is not visited and + // reads as the sentinel page. (SimX launch checkpoints.) + void for_each_page(const std::function& fn) const; + private: // `allocate=false` returns a pointer into `zero_page_` for unmapped diff --git a/sim/simx/core.cpp b/sim/simx/core.cpp index b224f1a6f9..b5f5d3b860 100644 --- a/sim/simx/core.cpp +++ b/sim/simx/core.cpp @@ -44,6 +44,7 @@ #include "processor_impl.h" #include "kmu.h" #include "debug.h" +#include "pc_prof.h" #ifdef VX_CFG_EXT_TCU_ENABLE #include "tcu_unit.h" #endif @@ -489,9 +490,15 @@ class Core::Impl { #endif gather_holds_.resize(VX_CFG_ISSUE_WIDTH, std::vector((uint32_t)FUType::Count)); + if (PcProf::enabled()) { + pc_prof_ = std::make_unique(VX_CFG_NUM_WARPS); + } + this->reset(); } + PcProfTable* pc_prof() const { return pc_prof_.get(); } + void reset() { for (auto& arb : ibuffer_arbs_) { arb.reset(); @@ -520,6 +527,8 @@ class Core::Impl { std::fill(ibuf_inflight_.begin(), ibuf_inflight_.end(), 0); std::fill(ibuf_full_r_.begin(), ibuf_full_r_.end(), false); + ibuf_any_full_ = false; + queue_flags_idle_ = false; std::fill(ibuf_queued_.begin(), ibuf_queued_.end(), 0); std::fill(ibuf_queue_full_r_.begin(), ibuf_queue_full_r_.end(), false); @@ -531,6 +540,13 @@ class Core::Impl { } void tick() { + #if !defined(VX_CFG_EXT_C_ENABLE) + if (this->quiescent()) { + this->idle_tick(); + return; + } + queue_flags_idle_ = false; + #endif this->commit(); this->return_dispatch_credits(); this->issue(); @@ -558,6 +574,60 @@ class Core::Impl { DPN(2, std::flush); } + // Nothing resident, in flight, arriving or left to clock in: no warp, CTA, + // fragment wave or spawn to start, no instruction between schedule and + // commit, no instruction fetch or LSU request outstanding, no warp-control, + // branch or barrier message waiting, no dispatch credit to return and no + // instruction-buffer full flag set. A tick then changes nothing but the + // counters idle_tick() advances, as the full one would. (A core with the + // compressed-instruction decompressor, which can hold a refetch of its own, + // always takes the full tick.) + bool quiescent() const { + if (pending_total_ != 0 || pending_ifetches_ != 0 || ibuf_any_full_ + || !scheduler_->settled() || this->running()) { + return false; + } + if (simobject_->branch_ctl_in.size() != 0 || simobject_->warp_ctl_in.size() != 0 + || simobject_->bar_unlock_in.size() != 0 || simobject_->sched_unlock_in.size() != 0 + || simobject_->sched_csr_wr_in.size() != 0) { + return false; + } + for (uint32_t fu = 0; fu < (uint32_t)FUType::Count; ++fu) { + if (dispatchers_.at(fu)->ReleaseOut.size() != 0) { + return false; + } + } + for (uint32_t w = 0; w < VX_CFG_NUM_WARPS; ++w) { + if (ibuf_inflight_[w] != 0) { + return false; + } + } + return true; + } + + // The full tick of a quiescent core, as far as it shows: schedule() counts + // the (inactive) warps and an idle cycle, and update_queue_full() re-derives + // the dispatch-queue flags from the unchanged credits. Every other stage + // finds its inputs empty, and busy() is false, so the cycle is not charged. + void idle_tick() { + perf_stats_.ifetch_latency += pending_ifetches_; + perf_stats_.active_warps += scheduler_->active_warps().count(); + perf_stats_.stalled_warps += scheduler_->stalled_warps().count(); + ++perf_stats_.sched_idle; + // The credits do not change while the core is quiescent, so after one + // update the flags hold still. + if (!queue_flags_idle_) { + this->update_queue_full(); + queue_flags_idle_ = true; + } + } + + bool busy() const { + return scheduler_->active_warps().any() + || pending_total_ != 0 + || scheduler_->cta_dispatcher()->running(); + } + // ----- Pipeline stages (private) ----- // Abort when a warp's staged instruction has not issued for STALL_TIMEOUT @@ -630,8 +700,10 @@ class Core::Impl { if (!any_cand) { ++perf_stats_.sched_idle; } + ibuf_any_full_ = false; for (uint32_t w = 0; w < VX_CFG_NUM_WARPS; ++w) { ibuf_full_r_.at(w) = (ibuf_inflight_.at(w) == VX_CFG_IBUF_SIZE); + ibuf_any_full_ |= ibuf_full_r_.at(w); ibuf_queue_full_r_.at(w) = (ibuf_queued_.at(w) >= VX_CFG_IBUF_SIZE); } @@ -1263,6 +1335,10 @@ class Core::Impl { if (trace->eop && trace->instr_ptr->fcsr_writes()) { scoreboard_->release_fcsr(trace); } + if (pc_prof_) { + PcProf::commit(pc_prof_.get(), trace->wid, trace->PC, trace->code, (uint32_t)trace->tmask.count(), + trace->eop, SimPlatform::instance().cycles()); + } if (trace->eop) { @@ -1339,7 +1415,10 @@ class Core::Impl { if (local_mem_->ReqIn.at(b).size() != 0) { return false; } - if (dcache_adapters_.at(b) && !dcache_adapters_.at(b)->ReqIn.empty()) { + // A single-channel adapter is a pass-through: its input forwards to the + // data cache and holds nothing of its own. + if (dcache_adapters_.at(b) && (DCACHE_CHANNELS > 1) + && !dcache_adapters_.at(b)->ReqIn.empty()) { return false; } } @@ -1552,12 +1631,16 @@ class Core::Impl { std::vector ibuf_inflight_; std::vector ibuf_full_r_; + bool ibuf_any_full_ = false; // any ibuf_full_r_ set (schedule()) + bool queue_flags_idle_ = false; // update_queue_full() since the last full tick std::vector ibuf_queued_; // [wid] instructions past the icache, not yet staged std::vector ibuf_queue_full_r_; // [wid] full flag from ibuf_queued_, registered std::vector last_issue_; // [wid] cycle of the warp's last issue std::vector staged_since_; // [wid] cycle the last issued candidate was staged std::vector head_staged_; // [wid] the buffer head has left for staging + std::unique_ptr pc_prof_; // SIMX_PCPROF only + PoolAllocator trace_pool_; #ifdef VX_CFG_EXT_C_ENABLE @@ -1647,6 +1730,10 @@ const Core::PerfStats& Core::perf_stats() const { return impl_->perf_stats(); } +PcProfTable* Core::pc_prof() const { + return impl_->pc_prof(); +} + int Core::get_exitcode() const { return impl_->get_exitcode(); } diff --git a/sim/simx/core.h b/sim/simx/core.h index 73d1cec312..fa59cf5eab 100644 --- a/sim/simx/core.h +++ b/sim/simx/core.h @@ -30,6 +30,7 @@ class TcuUnit; class SfuUnit; class LocalMem; class MemCoalescer; +struct PcProfTable; class Core : public SimObject { public: @@ -179,6 +180,9 @@ class Core : public SimObject { const PerfStats& perf_stats() const; PerfStats& perf_stats(); + // SIMX_PCPROF: this core's PC profile (nullptr when profiling is off) + PcProfTable* pc_prof() const; + int get_exitcode() const; protected: diff --git a/sim/simx/cta_dispatcher.h b/sim/simx/cta_dispatcher.h index 8acc9a2e56..3e056c9eb7 100644 --- a/sim/simx/cta_dispatcher.h +++ b/sim/simx/cta_dispatcher.h @@ -75,6 +75,12 @@ class CtaDispatcher : public SimObject { return has_cta_ || (bus_in.size() != 0); } + // Not running, and no warp retirement or CTA completion left to register: + // step() would leave every piece of state as it is. + bool settled() const { + return !this->running() && retiring_.empty() && !cta_done_ && !payload_wait_; + } + protected: void on_reset(); diff --git a/sim/simx/decode.cpp b/sim/simx/decode.cpp index 927ee37310..066005c29e 100644 --- a/sim/simx/decode.cpp +++ b/sim/simx/decode.cpp @@ -1424,6 +1424,12 @@ Instr::Ptr Decoder::decode(uint32_t code, uint64_t uuid, bool fs_off) { } break; #endif default: + // A unit this build leaves out (TEX funct3 1/5, RASTER 4, OM 3, RTU 6/7; + // misa ext bits 6, 7, 8, 11) decodes nothing: software that emits its + // instruction ignored VX_CAPS_ISA_FLAGS. + std::cerr << "error: custom-1 instruction 0x" << std::hex << code << std::dec + << " (funct3=" << funct3 << ") is not decoded: its unit is not in this build" + << std::endl; std::abort(); } // FF<->SIMT interface-law structural assertion: every FF diff --git a/sim/simx/launch_ckpt.h b/sim/simx/launch_ckpt.h new file mode 100644 index 0000000000..41bbd7fd5c --- /dev/null +++ b/sim/simx/launch_ckpt.h @@ -0,0 +1,184 @@ +// Copyright © 2019-2026 +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#pragma once + +// SimX launch checkpoints: replay one kernel launch of a long application run +// on a different SimX build -- typically a launch captured by the fast +// functional kernel, replayed on the timed one -- without re-running what came +// before it (a game trace's state load, say). +// +// A launch is fully described by the device memory at its start and the DCR +// writes the device has taken since reset (the command processor delivers +// every launch parameter -- KMU grid, startup address, texture and raster +// stages, MMU root -- as DCR writes before it pulses start). So: +// +// save (the simx runtime, SIMX_CKPT=, SIMX_CKPT_FROM=): at the start +// of every launch with index >= n (the index SIMX_PCPROF numbers launches +// by), append the device pages that changed to /pages.dat (content +// deduplicated across launches) and write /L.idx: the DCR-log +// prefix length and every allocated page's (address, offset). The DCR log +// is /dcr.log, appended as the device takes the writes. +// +// load (the simx binary, -C -L ): allocate exactly those pages, +// replay the DCR prefix in order, run the launch. +// +// What a checkpoint does not carry is cache contents: the replayed launch +// starts with every cache empty (the original met the last-level cache the +// launches before it left), so its memory stalls are an upper bound. + +#include +#include +#include +#include +#include +#include +#include +#include "mem.h" + +namespace vortex { + +class LaunchCkpt { +public: + struct Rec { uint32_t addr, value; }; + + // ── save side ─────────────────────────────────────────────────────────── + static LaunchCkpt* saver() { + static LaunchCkpt* s = [] () -> LaunchCkpt* { + const char* d = std::getenv("SIMX_CKPT"); + if (!d || !*d) return nullptr; + auto* c = new LaunchCkpt(); + c->dir_ = d; + const char* f = std::getenv("SIMX_CKPT_FROM"); + c->from_ = f ? std::strtoull(f, nullptr, 0) : 0; + const char* t = std::getenv("SIMX_CKPT_TO"); + c->to_ = t ? std::strtoull(t, nullptr, 0) : ~uint64_t(0); + c->dcr_ = std::fopen((c->dir_ + "/dcr.log").c_str(), "wb"); + c->pages_ = std::fopen((c->dir_ + "/pages.dat").c_str(), "wb"); + if (!c->dcr_ || !c->pages_) { + std::fprintf(stderr, "simx-ckpt: cannot write %s\n", d); + std::abort(); + } + return c; + }(); + return s; + } + + void on_dcr_write(uint32_t addr, uint32_t value) { + Rec r{addr, value}; + std::fwrite(&r, sizeof r, 1, dcr_); + ++num_dcr_; + } + + // Whether the next launch is one to save: the caller then makes device memory + // whole first (a system-scope cache flush: the command processor's DMA lands + // in the last-level cache, and a line not yet written back has no page). + bool next_saved() const { return launch_ >= from_ && launch_ <= to_; } + + // At a launch's start (before the processor runs it), with memory whole. + void on_launch(const RAM& ram) { + const uint64_t idx = launch_++; + if (idx < from_ || idx > to_) return; + std::fflush(dcr_); + const uint64_t psize = ram.page_size(); + std::vector> idxv; + ram.for_each_page([&](uint64_t addr, const uint8_t* data) { + const Key k = hash(data, psize); + auto it = store_.find(k); + uint64_t off; + if (it != store_.end()) { + off = it->second; + } else { + off = pages_off_; + std::fwrite(data, 1, psize, pages_); + pages_off_ += psize; + store_.emplace(k, off); + } + idxv.emplace_back(addr, off); + }); + std::fflush(pages_); + const std::string p = dir_ + "/L" + std::to_string(idx) + ".idx"; + FILE* f = std::fopen(p.c_str(), "wb"); + if (!f) { std::fprintf(stderr, "simx-ckpt: cannot write %s\n", p.c_str()); std::abort(); } + const uint64_t hdr[3] = {psize, num_dcr_, (uint64_t)idxv.size()}; + std::fwrite(hdr, sizeof hdr, 1, f); + std::fwrite(idxv.data(), sizeof(idxv[0]), idxv.size(), f); + std::fclose(f); + std::fprintf(stderr, "simx-ckpt: launch %llu: %zu pages, store %.1f MB, dcr %llu\n", + (unsigned long long)idx, idxv.size(), pages_off_ / 1048576.0, + (unsigned long long)num_dcr_); + } + + // ── load side ─────────────────────────────────────────────────────────── + // Fill `ram` with launch `idx`'s pages and return its DCR-write prefix. + static bool load(const std::string& dir, uint64_t idx, RAM& ram, std::vector* dcrs) { + const std::string p = dir + "/L" + std::to_string(idx) + ".idx"; + FILE* f = std::fopen(p.c_str(), "rb"); + if (!f) return false; + uint64_t hdr[3]; + if (std::fread(hdr, sizeof hdr, 1, f) != 1) { std::fclose(f); return false; } + std::vector> idxv(hdr[2]); + if (hdr[2] && std::fread(idxv.data(), sizeof(idxv[0]), hdr[2], f) != hdr[2]) { + std::fclose(f); + return false; + } + std::fclose(f); + if (hdr[0] != ram.page_size()) return false; + FILE* pg = std::fopen((dir + "/pages.dat").c_str(), "rb"); + if (!pg) return false; + std::vector buf(hdr[0]); + for (auto& e : idxv) { + if (fseeko(pg, (off_t)e.second, SEEK_SET) != 0 || std::fread(buf.data(), 1, hdr[0], pg) != hdr[0]) { + std::fclose(pg); + return false; + } + ram.write(buf.data(), e.first, hdr[0]); + } + std::fclose(pg); + FILE* d = std::fopen((dir + "/dcr.log").c_str(), "rb"); + if (!d) return false; + dcrs->resize(hdr[1]); + const size_t n = hdr[1] ? std::fread(dcrs->data(), sizeof(Rec), hdr[1], d) : 0; + std::fclose(d); + return n == hdr[1]; + } + +private: + struct Key { + uint64_t a, b; + bool operator==(const Key& o) const { return a == o.a && b == o.b; } + }; + struct KeyHash { + size_t operator()(const Key& k) const { return size_t(k.a ^ (k.b * 0x9e3779b97f4a7c15ull)); } + }; + // Two independent 64-bit word hashes of a page (collisions negligible). + static Key hash(const uint8_t* p, uint64_t n) { + uint64_t a = 0xcbf29ce484222325ull, b = 0x84222325cbf29ce4ull; + for (uint64_t i = 0; i < n; i += 8) { + uint64_t w; + std::memcpy(&w, p + i, 8); + a = (a ^ w) * 0x100000001b3ull; + b = (b + w) * 0xff51afd7ed558ccdull; + b ^= b >> 29; + } + return Key{a, b}; + } + + std::string dir_; + uint64_t from_ = 0, to_ = ~uint64_t(0), launch_ = 0, num_dcr_ = 0, pages_off_ = 0; + FILE* dcr_ = nullptr; + FILE* pages_ = nullptr; + std::unordered_map store_; +}; + +} // namespace vortex diff --git a/sim/simx/main.cpp b/sim/simx/main.cpp index 2432b19841..0d1ed264fa 100644 --- a/sim/simx/main.cpp +++ b/sim/simx/main.cpp @@ -33,11 +33,13 @@ #include "dtm/debug_module.h" #include "dtm/jtag_dtm.h" #include "dtm/remote_bitbang.h" +#include "launch_ckpt.h" using namespace vortex; static void show_usage() { std::cout << "Usage: [-s: stats] [-d: debug-mode] [-p : RBB port] [-V: verbose debug logging] [-h: help] " << std::endl; + std::cout << " -C -L : replay launch of a SimX launch checkpoint (launch_ckpt.h)" << std::endl; } bool showStats = false; @@ -45,10 +47,12 @@ bool debug_mode = false; bool debug_verbose = false; // Verbose debug module logging uint16_t rbb_port = 9823; // Default OpenOCD remote bitbang port const char* program = nullptr; +const char* ckpt_dir = nullptr; // -C: launch checkpoint directory +long long ckpt_launch = -1; // -L: the launch to replay static void parse_args(int argc, char **argv) { int c; - while ((c = getopt(argc, argv, "shdp:V")) != -1) { + while ((c = getopt(argc, argv, "shdp:VC:L:")) != -1) { switch (c) { case 's': showStats = true; @@ -62,6 +66,12 @@ static void parse_args(int argc, char **argv) { case 'V': debug_verbose = true; break; + case 'C': + ckpt_dir = optarg; + break; + case 'L': + ckpt_launch = atoll(optarg); + break; case 'h': show_usage(); exit(0); @@ -72,6 +82,13 @@ static void parse_args(int argc, char **argv) { } } + if (ckpt_dir) { + if (ckpt_launch < 0) { + show_usage(); + exit(-1); + } + return; + } if (optind < argc) { program = argv[optind]; if (!debug_mode) { @@ -88,6 +105,28 @@ int main(int argc, char **argv) { parse_args(argc, argv); + if (ckpt_dir) { + // Replay one launch of a checkpoint: its pages, its DCR writes, its run. + RAM ram(0, VX_VM_PAGE_SIZE); + ram.enable_acl(false); + Processor processor; + processor.attach_ram(&ram); + std::vector dcrs; + if (!LaunchCkpt::load(ckpt_dir, (uint64_t)ckpt_launch, ram, &dcrs)) { + std::cerr << "Error: cannot load launch " << ckpt_launch << " of " << ckpt_dir << std::endl; + return -1; + } + for (auto& r : dcrs) { + processor.dcr_write(r.addr, r.value); + } + const uint64_t c0 = SimPlatform::instance().cycles(); + exitcode = processor.run(); + const uint64_t c1 = SimPlatform::instance().cycles(); + std::cout << "CKPT: launch=" << ckpt_launch << ", dcrs=" << dcrs.size() + << ", cycles=" << (c1 - c0) << ", exitcode=" << exitcode << std::endl; + return exitcode; + } + { // create memory module RAM ram(0, VX_VM_PAGE_SIZE); diff --git a/sim/simx/mem/cache.cpp b/sim/simx/mem/cache.cpp index 3f029992e4..e54e8cf0d1 100644 --- a/sim/simx/mem/cache.cpp +++ b/sim/simx/mem/cache.cpp @@ -2751,7 +2751,10 @@ class CachePortArb : public SimObject { } // The cache's line initialization holds the core ports for these cycles. - void set_init_cycles(uint32_t cycles) { init_cycles_ = cycles; } + void set_init_cycles(uint32_t cycles) { + init_cycles_ = cycles; + this->tick_wake(); + } protected: // Sleeps once the ports, the tree and the offers have been empty for two @@ -2773,7 +2776,6 @@ class CachePortArb : public SimObject { offer.held = false; } held_ = false; - idle_ticks_ = 0; std::fill(realign_.begin(), realign_.end(), realign_t()); } @@ -2798,17 +2800,6 @@ class CachePortArb : public SimObject { --init_cycles_; return; } - // Sleep once the ports, the tree and the offers have been empty for two - // ticks: the second idle tick settles the realign registers, so a skipped - // tick cannot change them. A request sent toward any port wakes it. - if (this->quiescent()) { - if (++idle_ticks_ >= 2) { - idle_ticks_ = 0; - asleep_ = true; - } - } else { - idle_ticks_ = 0; - } uint32_t nb = ReqOut.size(); uint32_t nl = levels_.size(); held_ = false; @@ -2855,6 +2846,17 @@ class CachePortArb : public SimObject { } } uint32_t n = ReqIn.size(); + if (this->ports_idle()) { + // Nothing at any port: the port stage below would do nothing, and with + // the tree, the offers and the IO outputs empty too no later tick does + // anything until a request is sent toward a port or a stage, which + // re-arms the tick. Asleep, it holds no token and no IO request, which + // the cache's own tick relies on (Cache::Impl::tick). + if (this->tree_idle() && this->io_idle()) { + asleep_ = true; + } + return; + } const bool hold = this->any_token(); this->update_realign(); // merged ports riding each leader's bank access, by offset in its group @@ -3033,6 +3035,44 @@ class CachePortArb : public SimObject { bool offers_enabled() const { return levels_.empty() && delay_ == 0; } + // No request at a port, delivered or on its way. + bool ports_idle() const { + for (auto& in : ReqIn) { + if (in.size() != 0) { + return false; + } + } + return true; + } + + // No non-cacheable request waiting for the cache to take it. + bool io_idle() const { + for (auto& out : IoOut) { + if (out.size() != 0) { + return false; + } + } + return true; + } + + // No request in the tree's buffers, delivered or on its way, and no offer + // standing at a bank. + bool tree_idle() const { + for (auto& level : tree_stage_) { + for (auto& stage : level) { + if (stage.size() != 0) { + return false; + } + } + } + for (auto& offer : offers_) { + if (offer.valid) { + return false; + } + } + return true; + } + // Under line merging, the merged ports' own tags, which ride the leader's // bank access and its response. std::shared_ptr> merged_tags(uint32_t i, uint64_t mask) const { @@ -3163,21 +3203,6 @@ class CachePortArb : public SimObject { return (merge_group_ == 2) && !merge_line_; } - // Nothing at the ports, in the tree or offered to a bank. - bool quiescent() const { - for (auto& in : ReqIn) { - if (in.size() != 0) { - return false; - } - } - for (auto& offer : offers_) { - if (offer.valid || offer.held) { - return false; - } - } - return this->drained(); - } - // A plain read: no write, flush, IO, local or atomic attribute. bool is_plain_read(uint32_t i) const { if (ReqIn.at(i).empty()) { @@ -3221,7 +3246,6 @@ class CachePortArb : public SimObject { std::vector wants_; std::vector start_; std::vector owes_head_; - uint32_t idle_ticks_ = 0; bool asleep_ = false; SimObjectBase* token_waiter_ = nullptr; struct offer_t { @@ -4003,6 +4027,7 @@ Cache::PerfStats Cache::perf_stats() const { void Cache::flush_begin(uint32_t fence_op) { impl_->flush_begin(fence_op); + this->tick_wake(); } bool Cache::flush_done() const { @@ -4011,4 +4036,5 @@ bool Cache::flush_done() const { void Cache::invalidate() { impl_->invalidate(); + this->tick_wake(); } diff --git a/sim/simx/pc_prof.h b/sim/simx/pc_prof.h new file mode 100644 index 0000000000..7a32f05b9c --- /dev/null +++ b/sim/simx/pc_prof.h @@ -0,0 +1,130 @@ +// Copyright © 2019-2026 +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#pragma once + +// Per-launch PC profile (diagnostics only; off unless SIMX_PCPROF= is set). +// +// For every committed instruction a core counts, per PC: the instruction +// (once, at its last pass), the threads it ran for (every pass), and the cycles +// its warp spent since the warp's previous commit ("warp residence": issue +// waits, operand and memory latency of the instruction that ends them). A +// warp's first commit in a launch counts one cycle, so time before a warp is +// spawned is not counted. Each core owns its table and alone writes it, from +// its own execution domain. At the end of each launch the processor, in host +// context, merges the cores' tables and appends them, with the instruction +// word at each PC (as the core fetched it), to /pcprof..txt: +// L +// (hex pc/word, decimal counts) +// The word lets an offline tool find which kernel image (ELF) the launch ran, +// as every compute kernel is linked at the same start address. +// +// Profiling changes no simulated behaviour: it only reads commit events. + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace vortex { + +struct PcProfTable { + struct Ent { + uint64_t instrs = 0; + uint64_t threads = 0; + uint64_t cycles = 0; + uint32_t word = 0; // the instruction word as fetched + }; + std::unordered_map pcs; + std::vector last; // per-warp cycle of the previous commit (0 = none) + + explicit PcProfTable(uint32_t num_warps) : last(num_warps, 0) {} +}; + +class PcProf { +public: + using Table = PcProfTable; + using Ent = PcProfTable::Ent; + + static bool enabled() { + static const bool on = std::getenv("SIMX_PCPROF") != nullptr; + return on; + } + + // `code` is the fetched instruction word (the trace's own copy: device memory + // can lag the caches the core fetched it through, and the next kernel's + // upload may overwrite it before the launch ends). + static void commit(Table* t, uint32_t wid, uint64_t pc, uint32_t code, uint32_t nthreads, + bool eop, uint64_t now) { + Ent& e = t->pcs[pc]; + e.word = code; + e.threads += nthreads; + if (!eop) + return; + uint64_t& last = t->last[wid]; + e.cycles += last ? (now > last ? now - last : 0) : 1; + last = now; + e.instrs += 1; + } + + // Called by the processor at the end of a launch, in host context, with the + // cores' tables in core order; it merges and empties them. + static void dump(const std::vector& tables, uint64_t launch_cycles) { + std::unordered_map all; + for (auto* t : tables) { + for (auto& kv : t->pcs) { + Ent& e = all[kv.first]; + e.instrs += kv.second.instrs; + e.threads += kv.second.threads; + e.cycles += kv.second.cycles; + e.word = kv.second.word; + } + t->pcs.clear(); + for (auto& l : t->last) l = 0; + } + const uint64_t idx = launch_index()++; + if (all.empty()) + return; + FILE* f = file(); + if (!f) + return; + std::fprintf(f, "L %llu %llu %zu %lld\n", (unsigned long long)idx, + (unsigned long long)launch_cycles, all.size(), (long long)std::time(nullptr)); + for (auto& kv : all) { + const uint32_t w = kv.second.word; + std::fprintf(f, "%llx %08x %llu %llu %llu\n", (unsigned long long)kv.first, w, + (unsigned long long)kv.second.instrs, + (unsigned long long)kv.second.threads, + (unsigned long long)kv.second.cycles); + } + std::fflush(f); + } + +private: + static uint64_t& launch_index() { static uint64_t n = 0; return n; } + static FILE* file() { + static FILE* f = [] { + const char* d = std::getenv("SIMX_PCPROF"); + std::string p = std::string(d && *d ? d : ".") + "/pcprof." + + std::to_string((long)getpid()) + ".txt"; + return std::fopen(p.c_str(), "a"); + }(); + return f; + } +}; + +} // namespace vortex diff --git a/sim/simx/processor.cpp b/sim/simx/processor.cpp index 2bbf240dd4..638c44b09a 100644 --- a/sim/simx/processor.cpp +++ b/sim/simx/processor.cpp @@ -13,6 +13,7 @@ #include "processor.h" #include "processor_impl.h" +#include "pc_prof.h" #include "core.h" #include "scheduler.h" #ifdef VX_CFG_EXT_RASTER_ENABLE @@ -340,6 +341,7 @@ void ProcessorImpl::flush_caches(uint32_t fence_op) { int ProcessorImpl::run() { this->launch_reset(); kmu_->start(); + const uint64_t prof_c0 = SimPlatform::instance().cycles(); int exitcode = 0; // Evaluated after every cycle (see SimPlatform::run_until). busy: a core @@ -394,6 +396,16 @@ int ProcessorImpl::run() { SimPlatform::instance().run_until([&]() { return stop(false); }); } + if (PcProf::enabled()) { + std::vector prof_tables; + for (auto& cluster : clusters_) { + for (uint32_t c = 0; c < NUM_SOCKETS * VX_CFG_SOCKET_SIZE; ++c) { + prof_tables.push_back(cluster->get_core(c)->pc_prof()); + } + } + PcProf::dump(prof_tables, SimPlatform::instance().cycles() - prof_c0); + } + return exitcode; } diff --git a/sim/simx/scheduler.h b/sim/simx/scheduler.h index 4019f6ffd9..23187c8276 100644 --- a/sim/simx/scheduler.h +++ b/sim/simx/scheduler.h @@ -195,6 +195,16 @@ class Scheduler : public SimObject { const auto& active_warps() const { return active_warps_; } const auto& stalled_warps() const { return stalled_warps_; } + // No warp, CTA, fragment wave or spawn to start and no stall change left to + // clock in: schedule_begin()/schedule_end() would leave the state as it is + // (see Core's idle tick). + bool settled() const { + return active_warps_.none() && cta_fire_cnt_ == 0 && !wspawn_.valid + && !wspawn_next_.valid && !single_warp_r_ + && stalled_warps_ == stalled_warps_next_ && cta_active_view_ == active_warps_ + && cta_dispatcher_->settled(); + } + protected: void on_reset(); diff --git a/sw/runtime/simx/vortex.cpp b/sw/runtime/simx/vortex.cpp index 35e231f387..99a053518b 100644 --- a/sw/runtime/simx/vortex.cpp +++ b/sw/runtime/simx/vortex.cpp @@ -31,6 +31,7 @@ #include #include #include +#include #include #include @@ -195,6 +196,7 @@ class vx_device { if (future_.valid()) { future_.wait(); } + if (auto* ck = LaunchCkpt::saver()) ck->on_dcr_write(addr, value); // SIMX_CKPT processor_.dcr_write(addr, value); }; h.vortex_dcr_read = [this](uint32_t addr, uint32_t tag) -> uint32_t { @@ -205,6 +207,17 @@ class vx_device { return v; }; h.vortex_start = [this]() { + if (auto* ck = LaunchCkpt::saver()) { // SIMX_CKPT + if (ck->next_saved()) { + // write every cache level back to RAM (a system-scope flush), so the + // saved pages hold what the launch will read + if (future_.valid()) future_.wait(); + uint32_t v = 0; + processor_.dcr_write(VX_DCR_BASE_CACHE_FLUSH, VX_FENCE_ACQ | VX_FENCE_REL | VX_FENCE_SYS); + processor_.dcr_read(VX_DCR_BASE_CACHE_FLUSH, 0, &v); + } + ck->on_launch(ram_); + } future_ = std::async(std::launch::async, [&] { processor_.run(); }); }; h.vortex_busy = [this]() -> bool {