#include "model.h" #include "history.h" #include "render.h" #include "tui.h" #include "sampler.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace { volatile sig_atomic_t running = 1; void stop(int) { running = 0; } struct Terminal { termios original{}; bool active = false; explicit Terminal(bool enabled) { if (!enabled || tcgetattr(STDIN_FILENO, &original)) return; termios raw = original; raw.c_lflag &= ~(ICANON | ECHO); raw.c_cc[VMIN] = 0; raw.c_cc[VTIME] = 0; active = tcsetattr(STDIN_FILENO, TCSANOW, &raw) == 0; if (active) std::cout<<"\033[?1049h\033[?25l"; } ~Terminal() { if (active) {std::cout<<"\033[0m\033[?25h\033[?1049l"< &devices, const mtop::Selection &selection, const std::string &error) { auto now = std::chrono::duration_cast( std::chrono::system_clock::now().time_since_epoch()).count(); std::cout << "{\"schema\":1,\"timestamp_unix_ms\":" << now << ",\"selected_registry_id\":" << (selection.registry ? quote(id(*selection.registry)) : "null") << ",\"error\":" << (error.empty() ? "null" : quote(error)) << ",\"devices\":["; bool first = true; for (const auto &d : devices) { if (!first) std::cout << ','; first = false; std::cout << "{\"registry_id\":" << quote(id(d.registry)) << ",\"error\":" << (d.error.empty() ? "null" : quote(d.error)); if (d.error.empty()) { std::cout << ",\"driver_build\":" << d.build << ",\"stage\":" << d.stage << ",\"vram_total_bytes\":" << (d.total ? std::to_string(d.total) : "null") << ",\"vram_cpu_visible_bytes\":" << (d.visible ? std::to_string(d.visible) : "null"); } accountingJson(d); softwareJson(d); clocksJson(d); using namespace amdgpu::metrics; const auto reason = telemetryReason(d); std::cout << ",\"telemetry_status\":" << quote(telemetryStatus(d)) << ",\"telemetry_error\":" << (reason.empty() ? "null" : quote(reason)) << ",\"telemetry_profile\":" << quote(telemetryProfile(d)); if (d.telemetrySupported) std::cout << ",\"telemetry_driver_status\":" << d.metrics.status << ",\"firmware_interface\":" << d.metrics.driverInterface << ",\"verified_firmware_interfaces\":[" << amdgpu::metrics::kDriverInterface << ']' << ",\"sample_generation\":" << d.metrics.generation << ",\"sample_sequence\":" << d.metrics.sequence << ",\"sample_uptime_ns\":" << d.metrics.collectedAtNs << ",\"firmware_metrics_counter\":" << d.metrics.firmwareCounter; std::cout << ",\"gfx_activity_percent\":" << metric(d, GfxActivityPercent, 1, "", true) << ",\"gfx_activity_source\":\"SMU AverageGfxActivity (raw firmware field; incoherent on this host — the live GPU CORE LOAD row uses the driver dispatch-in-flight delta)\"" << ",\"gfx_activity_scope\":\"firmware-reported activity; not CU occupancy or productive workload utilization\"" << ",\"gfx_activity_accuracy\":" << quote(d.metrics.driverInterface==amdgpu::metrics::kCompatibleInterface && (d.metrics.flags&amdgpu::kSMUMetricsLinuxCompatible) ? "idle_100_percent_observed; workload_utilization_unverified" : "not_independently_calibrated") << ",\"umc_activity_percent\":" << metric(d, UmcActivityPercent, 1, "", true) << ",\"umc_activity_source\":\"" << (mtop::validMmhub(d, clock_gettime_nsec_np(CLOCK_UPTIME_RAW)) ? "MMHUB PERFSTATUS UMC busy (hardware PERFCTR delta, selector 68)" : "SMU UmcActivityPercent (firmware offset 126); low-sensitivity on this host (~0-1% even under real memory traffic; no MMHUB UMC-busy counter on gfx1201)") << "\"" << ",\"media_activity_percent\":" << metric(d, MediaActivityPercent, 1, "", true) << ",\"vram_used_bytes\":null,\"gtt_used_bytes\":null" << ",\"gfx_clock_mhz\":" << metric(d, GfxClockMHz, 1, "", true) << ",\"memory_clock_mhz\":" << metric(d, MemoryClockMHz, 1, "", true) << ",\"soc_clock_mhz\":" << metric(d, SocClockMHz, 1, "", true) << ",\"fabric_clock_mhz\":" << metric(d, FabricClockMHz, 1, "", true) << ",\"socket_power_watts\":" << metric(d, SocketPowerMilliwatts, 1000, "", true) << ",\"board_power_watts\":" << metric(d, BoardPowerMilliwatts, 1000, "", true) << ",\"edge_temperature_celsius\":" << metric(d, EdgeTemperatureMillicelsius, 1000, "", true) << ",\"hotspot_temperature_celsius\":" << metric(d, HotspotTemperatureMillicelsius, 1000, "", true) << ",\"memory_temperature_celsius\":" << metric(d, MemoryTemperatureMillicelsius, 1000, "", true) << ",\"fan_rpm\":" << metric(d, FanRPM, 1, "", true) << '}'; } std::cout << "]}\n"; } using Histories=std::map; std::optional hardwareValue(const mtop::Device &d,amdgpu::metrics::Field field,uint64_t now) { if (!mtop::fresh(d,now) || !(d.metrics.validFields&(uint64_t(1)< umcValue(const mtop::Device &d, uint64_t now, std::string &source, uint64_t previousUmcQ8 = 0, uint64_t previousUmcAtNs = 0) { if (const auto smu = hardwareValue(d, amdgpu::metrics::UmcActivityPercent, now)) { if (*smu <= 100.0) { source = "SMU UmcActivityPercent (firmware table offset 126; UMC busy 0-100%)"; return *smu; } } if (const auto mmhub = mtop::mmhubUmcPercent(d, previousUmcQ8, previousUmcAtNs)) { source = "MMHUB PERFSTATUS UMC busy (hardware PERFCTR delta, selector 68; 0-100%)"; return *mmhub; } return {}; } std::optional temperatureValue(const mtop::Device &d,uint64_t now) { // Hotspot first, then edge, then memory; 1000 mC per 1 C. for (const auto field:std::array{amdgpu::metrics::HotspotTemperatureMillicelsius, amdgpu::metrics::EdgeTemperatureMillicelsius,amdgpu::metrics::MemoryTemperatureMillicelsius}) { if (const auto value=hardwareValue(d,field,now)) return *value/1000.0; } return {}; } // True delta-based utilization from driver activity telemetry: software // pendingNs (union of dispatch-in-flight intervals) is a cumulative busy // counter maintained by the single-writer lifecycle queue; dividing its delta // by the monotonic elapsed time is a fraction of the window the engines were // in flight, clamped to 100%. This is the fallback source; a reachable // hardware busy counter would take precedence (none is exposed by the // current observer surface: the SMU table carries only the uncalibrated // AverageGfxActivity average, documented as "idle can report 100%"). std::optional rateCounters(const mtop::Device &d) { if (!mtop::hasSoftware(d) || (d.software.flags&amdgpu::software_stats::Saturated)) return {}; mtop::RateCounters out{d.software.generation,d.software.sampledAtNs,d.software.publishedPackets,0}; for (unsigned i=0;i engineBusyPercent(const mtop::Device &d, unsigned engine, const mtop::History &history) { if (!mtop::hasSoftware(d) || (d.software.flags&amdgpu::software_stats::Saturated) || engine>=amdgpu::software_stats::EngineCount) return {}; const auto &previous=history.previousBusy; if (!previous || previous->generation!=d.software.generation || previous->timeNs>=d.software.sampledAtNs || d.software.engines[engine].pendingNsenginePendingNs[engine]) return {}; const uint64_t delta=d.software.engines[engine].pendingNs-previous->enginePendingNs[engine]; const uint64_t elapsed=d.software.sampledAtNs-previous->timeNs; if (elapsed>2'000'000'000ull) return {}; // stale gap: no rate across it return mtop::busyRatio(delta,0,elapsed); } [[maybe_unused]] std::string utilizationSource(const mtop::Device &d) { if (!mtop::hasSoftware(d)) return "unavailable"; if (d.software.flags&amdgpu::software_stats::Saturated) return "saturated"; return "driver dispatch-in-flight telemetry (software_stats pendingNs delta / wall window)"; } // True delta-based utilization, computed by the monitor from the driver's // cumulative in-flight telemetry: pendingNs is the union of dispatch-in- // flight intervals, maintained by the single-writer lifecycle queue; its delta // over the previous sample divided by the monotonic wall interval is the // fraction of that window the engines were in flight, clamped to 100%. // The first sample after a baseline has no window and reports unavailable. // A hardware busy counter would be preferred, but the observer surface only // exposes the SMU AverageGfxActivity average, which is documented as // uncalibrated ("idle can report 100%") — see utilizationSource(). std::optional busyPercent(const mtop::Device &d, const mtop::History &history) { const auto counters=rateCounters(d); if (!counters) return {}; const auto &previous=history.previousBusy; const bool reset=!previous || previous->generation!=counters->generation || previous->timeNs>counters->timeNs || previous->pendingNs>counters->pendingNs || counters->timeNs-previous->timeNs>2'000'000'000ull; if (reset || !previous) return {}; return mtop::busyRatio(counters->pendingNs,previous->pendingNs,counters->timeNs-previous->timeNs); } std::optional allocatedGiB(const mtop::Device &d) { using namespace amdgpu::vram_accounting; if (!mtop::hasAccounting(d)) return {}; return (double(d.accounting.values[VisibleUsed])+double(d.accounting.values[DeviceUsed]))/1073741824.0; } std::optional capacityGiB(const mtop::Device &d) { using namespace amdgpu::vram_accounting; if (!mtop::hasAccounting(d)) return {}; return (double(d.accounting.values[VisibleCapacity])+double(d.accounting.values[DeviceCapacity]))/1073741824.0; } std::string decimal(std::optional value,unsigned places=1) { if (!value) return "--"; std::ostringstream out;out<> &values, std::optional current,double ceiling) { const auto minimum=mtop::stats(values); std::ostringstream out; out<at(0),0)<<" avg "<at(2),0)<<" max "<at(1),0); return out.str(); } std::optional clockValue(const mtop::Device &d,unsigned index,uint64_t now,unsigned kind=0) { if (index>=4 || (kind ? !mtop::validClocks(d) || d.stage!=15 : !mtop::freshClocks(d,now))) return {}; const auto &s=d.clocks; if (!((kind ? s.limitsValid : s.currentValid)&(1u< &devices, const mtop::Selection &selection, const std::string &error, bool interactive, bool listOnly, const Histories *histories=nullptr,mtop::RefreshMode mode={}, unsigned columns=100,unsigned rows=40,uint64_t now=0, mtop::Graphics graphics=mtop::Graphics::Text,mtop::Frame *frame=nullptr,bool demo=false, const mtop::tui::Ui *ui=nullptr,mtop::tui::Palette palette=mtop::tui::Palette{}) { if (!now) now=clock_gettime_nsec_np(CLOCK_UPTIME_RAW); columns=std::clamp(columns,24u,200u);rows=std::max(8u,rows); std::vector lines; struct PixelChart {unsigned row,height;std::vector png;}; std::vector images; auto tint=[&](const std::string&text,const char*code){return interactive ? std::string(code)+text+"\033[0m" : text;}; auto line=[&](std::string value) {lines.push_back(std::move(value));}; const auto sort=ui ? ui->sort : mtop::tui::Sort{}; const bool engines=ui ? ui->enginesVisible : true; using namespace mtop::tui; if (!error.empty()) line(palette.label("Enumeration: "+error)); if (devices.empty()) line(palette.label("Waiting for a GPU bound to MacAMDGPU...")); for (const auto &d:devices) { line(palette.value(std::string(selection.registry==d.registry ? "> " : " ")+id(d.registry))+ palette.label(d.error.empty() ? " gfx"+std::to_string(d.gfx[0])+"."+std::to_string(d.gfx[1])+"."+std::to_string(d.gfx[2])+ " build "+std::to_string(d.build)+" "+(d.stage==15 ? "initialized" : "stage "+std::to_string(d.stage)) : " "+d.error)); } if (!listOnly) { const auto *d=selection.find(devices); if (!d && selection.registry) line("Selected GPU disconnected: "+id(*selection.registry)); if (d && d->error.empty()) { using namespace amdgpu::vram_accounting; using namespace amdgpu::metrics; const mtop::History empty; const auto it=histories ? histories->find(d->registry) : Histories::const_iterator{}; const auto &history=histories && it!=histories->end() ? it->second : empty; const auto utilizationBuckets=history.buckets(120,now,&mtop::ActivityPoint::busyPercent); const auto vramBuckets=history.buckets(60,now,&mtop::ActivityPoint::allocatedGiB); const auto tempBuckets=history.buckets(60,now,&mtop::ActivityPoint::temperatureC); const auto nad=[&](const std::string&text){return std::string(palette.kNad)+text+"\033[0m";}; const auto smuBuckets=history.buckets(60,now,&mtop::ActivityPoint::gfxPercent); const auto umcBuckets=history.buckets(60,now,&mtop::ActivityPoint::umcPercent); // UMC chart source: pick the label from the most recent point that // actually has a value, so the panel always matches the data. std::string umcSourceLabel; for (auto it = history.points.rbegin(); it != history.points.rend(); ++it) { if (it->umcPercent && !it->umcSource.empty()) { umcSourceLabel = it->umcSource; break; } } if (umcSourceLabel.empty()) umcSourceLabel = mtop::fresh(*d, now) && (d->metrics.validFields & (uint64_t(1) << UmcActivityPercent)) && d->metrics.values[UmcActivityPercent] <= 100u ? "SMU UmcActivityPercent (firmware table offset 126; UMC busy 0-100%)" : "MMHUB PERFSTATUS UMC busy (hardware PERFCTR delta, selector 68; 0-100%)"; const auto copyBuckets=history.buckets(60,now,&mtop::ActivityPoint::transferMiBPerSecond); // Y-axis labels for a chart of `rows` text rows: each quarter // (100/75/50/25/0) labels the row nearest its position, so the // five labels never overflow the row budget. 5+ rows show all // five; 4 rows show only 100%/0% (the middle quarters would sit // a row apart with 50% dropped, which reads as a broken axis); // a single row shows 0% (the baseline). Matches the original // 20-row chart's nearest-quarter convention. const auto ylabels=[&](size_t rows)->std::vector>{ std::vector> out(rows); if (!rows) return out; const double denom=double(rows-1); const std::array quarters{100u,75u,50u,25u,0u}; // 4-row charts: only 100% and 0% (middle quarters would be // misplaced). 1-row: only 0% (the baseline). 5+ rows: all five. const unsigned skip = (rows==4) ? 3u : 0u; // skip 75/50/25 for (unsigned i=0;i<5;++i) { if (skip && i>0 && i<4) continue; const unsigned q=quarters[i]; const double target=(100.0-double(q))*denom/100.0; const size_t r=std::min(rows-1,size_t(std::lround(target))); out[r]=q; // last quarter wins a tie; with 1 row only 0% } return out; }; // Adaptive chart budget: the charts must fit the terminal, not // vice versa. `rows` covers everything the dashboard renders // (measured from the actual render at 40x100): // device-list header (3 rows single GPU, 4+ multi) + GPU CORE // LOAD chart block + SMU MEMORY ACTIVITY chart block + VRAM / // POWER block (8 rows) + GRBM block (17 rows, 16 hidden) + // processes block (8 rows) + footer (1 row) + blank separators // (4 rows, 3 hidden). Charts get what is left, split between // the two, clamped to a floor of 4 text rows (one braille cell // row: still a chart) and a ceiling of 20 (five braille cell // rows: the full 5-row axis). const unsigned blankSep = engines ? 4u : 3u; const unsigned grbmRows = engines ? 17u : 16u; const unsigned headerRows = devices.size() > 1u ? 4u : 3u; const unsigned vramRows = 8u; const unsigned procRows = 8u; const unsigned otherRows = headerRows + vramRows + grbmRows + procRows + 1u + blankSep; const unsigned chartBudget = rows > otherRows ? rows - otherRows : 0u; unsigned chartRows = chartBudget / 2u; // Floor: 4 text rows = one braille cell row, the smallest thing // that still reads as a chart. The floor may consume terminal // rows on very short terminals; the interactive frame resize // below absorbs the overflow so the footer is never clipped. if (chartRows > 20u) chartRows = 20u; if (chartRows < 4u) chartRows = 4u; // One labeled Braille activity chart (same treatment as GPU CORE // LOAD): adaptive-height Y-axis, Braille matrix, X-axis caption, // and a min/max/avg footer computed from the plotted window. // `title` is the top border text; `source` is a dim caption // citing the field. Y-axis labels degrade gracefully on short // charts: all five quarters at 5+ rows, 100/0% at 4 rows. const auto activityChart=[&](std::vector> buckets, const std::string &title,const std::string &source){ const std::optional current=buckets.empty()?std::optional{}:buckets.back(); line(tint(top(columns,palette.section(title)+(current?palette.value("["+decimal(*current,0)+"%]"):nad("[ n/a ]"))),palette.kBorder)); const size_t chCells=columns>10?columns-10:10; const size_t n=std::min(buckets.size(),chCells*2); std::vector> plot; for(size_t i=0;iat(0),1)+"% max "):nad("n/a max "))+ (s?palette.value(decimal(s->at(1),1)+"% avg "):nad("n/a avg "))+ (s?palette.value(decimal(s->at(2),1)+"%") : nad("n/a")))); line(cell(columns,palette.label(" ")+nad(source))); line(""); }; const auto vramCeiling=capacityGiB(*d).value_or(1.0); const auto utilNow=history.points.empty() ? std::optional{} : history.points.back().busyPercent; const auto pwr=hardwareValue(*d,SocketPowerMilliwatts,now); const auto pwrCap=hardwareValue(*d,BoardPowerMilliwatts,now); const auto edgeT=hardwareValue(*d,EdgeTemperatureMillicelsius,now); const auto hotT=hardwareValue(*d,HotspotTemperatureMillicelsius,now); const auto fan=hardwareValue(*d,FanRPM,now); const auto sclk=hardwareValue(*d,GfxClockMHz,now); const auto mclk=hardwareValue(*d,MemoryClockMHz,now); const double pwrW=pwr ? *pwr/1000.0 : 0.0; const double pwrWCap=pwrCap ? *pwrCap/1000.0 : 0.0; const auto edgeTc=edgeT ? *edgeT/1000.0 : 0.0; const auto hotTc=hotT ? *hotT/1000.0 : 0.0; const auto fanRpm=fan ? *fan : 0.0; const auto sclkMhz=sclk ? *sclk : 0.0; const auto mclkMhz=mclk ? *mclk : 0.0; const auto visibleCap=hasAccounting(*d) ? double(d->accounting.values[VisibleCapacity])/(1ull<<30) : 0.0; const auto deviceCap=hasAccounting(*d) ? double(d->accounting.values[DeviceCapacity])/(1ull<<30) : 0.0; const auto visibleUsed=hasAccounting(*d) ? double(d->accounting.values[VisibleUsed])/(1ull<<30) : 0.0; const auto deviceUsed=hasAccounting(*d) ? double(d->accounting.values[DeviceUsed])/(1ull<<30) : 0.0; const double vramTotal=visibleCap+deviceCap; const double vramUsed=visibleUsed+deviceUsed; const double vramPct=vramTotal>0 ? vramUsed/vramTotal : 0.0; const double gttPct=visibleCap>0 ? visibleUsed/visibleCap : 0.0; const unsigned pixelRows=interactive && graphics!=mtop::Graphics::Text ? 5 : 0; if (pixelRows) { images.push_back({unsigned(lines.size()+1),1,mtop::chartPNG(utilizationBuckets,480,18,100)}); images.push_back({unsigned(lines.size()+2),1,mtop::chartPNG(vramBuckets,480,18,vramCeiling,{230,181,74})}); images.push_back({unsigned(lines.size()+3),1,mtop::chartPNG(tempBuckets,480,18,100,{240,120,90})}); images.push_back({unsigned(lines.size()+4),1,mtop::chartPNG(smuBuckets,480,18,100,{120,160,200})}); images.push_back({unsigned(lines.size()+5),1,mtop::chartPNG(copyBuckets,480,18,0.0,{140,200,140})}); for(unsigned i=0;i<5;++i)line(""); } // ===== Section 1: Header ===== std::string header=palette.value("AMDGPU gfx"+std::to_string(d->gfx[0])+'.'+std::to_string(d->gfx[1])+'.'+std::to_string(d->gfx[2])); if (d->spec.valid) header+=palette.label(" "+std::to_string(d->spec.words[12])+" CUs / "+std::to_string(d->spec.words[4])+" SEs"); header+=palette.label(std::string(" build ")+std::to_string(d->build)+" "+(d->stage==15 ? "initialized" : "stage "+std::to_string(d->stage))); header+=palette.label(std::string(" sensors ")+telemetryStatus(*d)); if (demo) header+=palette.label(" DEMO (synthetic)"); line(tint(top(columns,header),palette.kBorder)); line(""); // ===== Section 2: GPU CORE LOAD (Braille) ===== line(tint(top(columns,palette.section("GPU CORE LOAD ")+(utilNow ? palette.value("["+decimal(*utilNow,0)+"%]") : nad("[ n/a ]"))),palette.kBorder)); const size_t cells=columns>10 ? columns-10 : 10; const size_t xCount=std::min(utilizationBuckets.size(), cells*2); std::vector> plot; for(size_t i=0;i0 ? palette.value("["+decimal(vramUsed,1)+" / "+decimal(vramTotal,1)+" GB -- "+decimal(vramPct*100.0,1)+"%]") : nad("[ n/a ]"))),palette.kBorder)); const unsigned barW=std::min(columns-24u, 40u); line(cell(columns," "+gradientBar(vramUsed, barW,palette)+" "+palette.label("VRAM: ")+palette.value(decimal(vramUsed,1)+" GB / "+decimal(vramPct*100.0,0)+"%"))); line(cell(columns," "+gradientBar(visibleUsed, barW,palette)+" "+palette.label("GTT: ")+palette.value(decimal(visibleUsed,1)+" GB / "+decimal(gttPct*100.0,0)+"%"))); line(""); line(cell(columns,palette.section("POWER & SENSOR STATE"))); const unsigned pwrBarW=std::min(columns-32u, 18u); const std::string deg = "\xc2\xb0"; auto tempStr = edgeT ? (palette.value(decimal(edgeTc,0)+deg+"C (Junc: ")) + (hotT?palette.value(decimal(hotTc,0)):nad("n/a")) + palette.value(deg+"C))") : nad("n/a"); line(cell(columns,palette.label(" Pwr: ")+(pwr ? palette.value(decimal(pwrW,0)+ "W / "+decimal(pwrWCap,0)+"W [")+gradientBar(pwrW,pwrBarW,palette)+ palette.value("]") : nad("n/a"))+palette.label(" Temp: ")+tempStr)); const unsigned fanBarW=std::min(columns-32u, 18u); line(cell(columns,palette.label(" Fan: ")+(fan ? palette.value(decimal(fanRpm,0)+" RPM [")+gradientBar(fanRpm/200.0,fanBarW,palette)+palette.value("]") : nad("n/a"))+ palette.label(" Clock: SCLK ")+(sclk?palette.value(decimal(sclkMhz,0)):nad("n/a"))+palette.label("MHz MCLK ")+(mclk?palette.value(decimal(mclkMhz,0)):nad("n/a"))+palette.label("MHz"))); line(""); // ===== Section 3: GRBM / GRBM2 ===== const auto sdma0=mtop::hasSoftware(*d) ? engineBusyPercent(*d,amdgpu::software_stats::SDMA0,history) : std::optional{}; const auto gfxEng=mtop::hasSoftware(*d) ? engineBusyPercent(*d,amdgpu::software_stats::GFX,history) : std::optional{}; const auto aqlEng=mtop::hasSoftware(*d) ? engineBusyPercent(*d,amdgpu::software_stats::AQL,history) : std::optional{}; auto engineBar=[&](std::optional v){ return v ? gradientBar(*v/100.0,16,palette)+" "+palette.value(decimal(*v,0)+"%") : nad("n/a (no in-flight sample window yet)"); }; line(tint(mid(columns,palette.section("PERFORMANCE COUNTERS (GRBM / GRBM2)")),palette.kBorder)); if (engines) { line(cell(columns,palette.section(" [GRBM Status]")+" "+palette.label("source: driver dispatch-in-flight per engine (selector 61)"))); line(cell(columns,palette.label(" Graphics Pipe (GFX) : ")+(utilNow ? gradientBar(*utilNow/100.0,16,palette)+" "+palette.value(decimal(*utilNow,0)+"%") : nad("n/a (no in-flight sample window yet)")))); line(cell(columns,palette.label(" Compute Engine 0 : ")+engineBar(gfxEng))); line(cell(columns,palette.label(" Compute Engine 1 : ")+(aqlEng ? engineBar(aqlEng) : nad("n/a (AQL compute queue in-flight)")))); line(cell(columns,palette.label(" SDMA Engine (DMA) : ")+engineBar(sdma0)+" "+palette.label("(SDMA0; SDMA1 not observed)"))); line(cell(columns,palette.label(" VCN (Video Decode) : ")+nad("n/a (driver exposes no VCN counter; would need MMIO PERFSTATUS or SMU media field)"))); line(cell(columns,palette.label(" JPEG Engine : ")+nad("n/a (driver exposes no JPEG counter)"))); line(""); line(cell(columns,palette.section(" [GRBM2 Status]")+" "+palette.label("source: none (MMHUB/GFXHUB PERFSTATUS + L2 counters not exposed by driver)"))); line(cell(columns,palette.label(" Command Processor (CPF) : ")+nad("n/a (MMHUB_PERFSTATUS not exposed)"))); line(cell(columns,palette.label(" Texture Cache (TCC) : ")+nad("n/a (MMHUB_L2 hit/miss counters not exposed)"))); line(cell(columns,palette.label(" Depth Block (DB) : ")+nad("n/a (GRBM select + MMIO read not exposed)"))); line(cell(columns,palette.label(" Color Block (CB) : ")+nad("n/a (GRBM select + MMIO read not exposed)"))); line(cell(columns,palette.label(" Shader Pipe (SPI) : ")+nad("n/a (per-SPI activity not exposed)"))); line(cell(columns,palette.label(" Primitive Assembly (PA) : ")+nad("n/a (per-PA activity not exposed)"))); } else { line(cell(columns,palette.label(" (hidden; press r to toggle)"))); } line(""); // ===== Section 4: GPU PROCESSES ===== line(tint(mid(columns,palette.section("GPU PROCESSES (fdinfo)")+palette.label(" [sort: ")+std::string(sort.label())+"]"),palette.kBorder)); line(cell(columns,palette.label(" PID USER PROCESS NAME CPU% GPU% GFX/COMP MEDIA VRAM USAGE VRAM BAR"))); line(cell(columns,palette.label(" "+std::string(columns>24?columns-4:20,'-')))); line(cell(columns,palette.label(" n/a n/a ")+nad("per-process GPU accounting not exposed by macOS driver"))); line(cell(columns,palette.label(" Driver exposes total VRAM pools + dispatch-in-flight + SMU sensors only."))); line(cell(columns,palette.label(" Per-PID GPU%, engine breakdown, VRAM require a driver-side per-client counter."))); line(cell(columns,palette.label(" See mtop-report.md for the exact missing query."))); line(""); // ===== Footer ===== const std::string footer="[q] Quit [h] Interval: "+std::to_string(mode.milliseconds())+"ms"+ " [p] Sort PID [m] Sort VRAM [g] Sort GPU [r] Toggle GRBM"; if (interactive) { lines.resize(std::min(lines.size(),rows-1)); while(lines.size()previous.clear(); std::string output=(frame?*frame:temporary).update(lines,columns,rows); if(graphics==mtop::Graphics::Kitty) for(unsigned i=0;i<3;++i)output+="\033_Ga=d,d=I,i="+std::to_string(5001+i)+",q=2\033\\"; for(size_t i=0;i> values(320); for(size_t i=0;i130)values[i]=30+25*std::sin(double(i)/15)+12*std::cos(double(i)/6); const auto png=mtop::chartPNG(values,960,180,100); std::ofstream file(previewPNG,std::ios::binary);file.write(reinterpret_cast(png.data()),png.size()); return file ? 0 : 1; } const bool interactive = !jsonMode && !listOnly && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO); Terminal terminal(interactive); if (interactive && !terminal.active) { std::cerr << "Unable to configure terminal\n"; return 1; } std::signal(SIGINT, stop); std::signal(SIGTERM, stop); const auto env=[](const char*name){const char*v=std::getenv(name);return std::string(v?v:"");}; auto program=env("TERM_PROGRAM"); unsigned major=0,minor=0; if(program=="iTerm.app" && std::sscanf(env("TERM_PROGRAM_VERSION").c_str(),"%u.%u",&major,&minor)==2 && (major>3 || (major==3 && minor>=7)))program="kitty"; const auto graphics=mtop::graphicsFor(graphicsOption,program,env("TERM"),!env("TMUX").empty() || !env("STY").empty()); mtop::Frame frame; mtop::tui::Ui uiState; std::unique_ptr sampler; if(interactive && !demo)sampler=std::make_unique(mode.milliseconds()); uint64_t sequence=0; int result = 0; while (running) { const auto refreshStart=std::chrono::steady_clock::now(); std::string error; std::vector devices; bool newSample=true; if(sampler) { auto sample=sampler->latest();devices=std::move(sample.devices);error=std::move(sample.error); newSample=sample.sequence!=sequence;sequence=sample.sequence; } else if(!demo) devices=mtop::discover(error); if(demo) { mtop::Device d;d.registry=0x100000001;d.build=195;d.stage=15;d.gfx[0]=12;d.gfx[2]=1; const auto t=clock_gettime_nsec_np(CLOCK_UPTIME_RAW); d.telemetrySupported=true;d.metrics.version=amdgpu::kSMUMetricsSnapshotVersion;d.metrics.size=sizeof(d.metrics); d.metrics.flags=amdgpu::kSMUMetricsValid;d.metrics.driverInterface=amdgpu::metrics::kDriverInterface; d.metrics.collectedAtNs=t;d.metrics.validFields=(1ull<first;}); if (!present) i->second.previous.reset(); if (!present) i->second.previousBusy.reset(); if (!present && !i->second.points.empty() && sampledAt-i->second.points.back().timeNs>mtop::History::windowNs) i=histories.erase(i); else ++i; } result = error.empty() ? 0 : 1; if (const auto *device = selected.find(devices); device && !device->error.empty()) result = 1; if (selected.registry && !selected.find(devices)) result = 1; if (jsonMode) json(devices, selected, error); else { winsize dimensions{}; if (ioctl(STDOUT_FILENO,TIOCGWINSZ,&dimensions)) dimensions={}; dashboard(devices,selected,error,interactive,listOnly,&histories,mode, dimensions.ws_col ? dimensions.ws_col : 100,dimensions.ws_row ? dimensions.ws_row : 40,sampledAt,graphics,&frame,demo,&uiState,mtop::tui::makePalette(dark)); } std::cout.flush(); if (listOnly || (!interactive && !watch)) break; fd_set descriptors; FD_ZERO(&descriptors); if (interactive) FD_SET(STDIN_FILENO, &descriptors); const auto remaining=std::max(0,mode.milliseconds()*1000- std::chrono::duration_cast(std::chrono::steady_clock::now()-refreshStart).count()); timeval timeout{0, static_cast(remaining)}; const int ready = select(interactive ? STDIN_FILENO + 1 : 0, &descriptors, nullptr, nullptr, &timeout); if (ready > 0 && interactive) { const int key=terminal.readKey(); if (key > 0) { if (key == 'q') break; if (key == 'h') {mode.toggle();if(sampler)sampler->period(mode.milliseconds());} // 'p' is PID sort per the spec footer; GPU navigation is the // Up/Down arrows (key 'A'/'B'). if (key == 'A') selected.step(devices, false); if (key == 'B') selected.step(devices, true); uiState.onKey(char(key)); } } else if (ready < 0 && errno != EINTR) { std::cerr << "Input wait failed\n"; return 1; } } return result; }