radiance 1.4.0

- Qwen3.8-Flash-Next on one card: the heat engine moves 64 experts a step (was 8), its copies and
  the prefill's expert staging run on the card's DMA engines instead of as copy kernels, and at
  decode the next layer's likeliest experts are copied onto the card ahead of its GEMMs. Against
  1.3.0 at --tp 1: prefill +17-20% from 8K tokens up, throughput under load +16-20%
- deploy/compose/flashnext-tp1.yaml: Qwen3.8-Flash-Next on one card and 64 GB of host RAM
  (4096-token prefill steps, 4 sequences, a 301K-token cache)
- #61: --busy-prefill-chunk (default auto): a long prefill leaves the rest of the step to the
  requests decoding beside it and to new arrivals, instead of taking all of it (baKon)
- LiquidAI's LFM2 and LFM2-VL, and d1's /v1/systemone (after zivius's PR #50)
- a startup report: every option with its value and where it came from, the hardware, and what
  on it costs speed with the fix; /diagnostics serves it (behind the API key; without one, only
  to the same machine)
- #69: a GPU memory fault names the buffer and kernel argument behind it and ends the server at
  once (exit status 70), instead of hanging or writing a core of tens of gigabytes
- #64: a card without Resizable BAR is refused at startup, naming what to turn on, instead of
  crashing at the first launch
- the image is built with ROCm 10.1 (the host's amdgpu driver must support it), with ROCm's
  libLLVM rebuilt so the same source compiles to the same kernels every time; a source build
  takes ROCm 10.1 or 7.2
- #71: the image ships curl, jq and a CA bundle, so --model <HF repo id> works in the container,
  and hfget.sh runs under its busybox (baKon)
- --profile-ops shows how long each op's lane sat idle before it; cardclock.py skips an
  integrated GPU instead of stopping
This commit is contained in:
Deadcode committed 2026-10-12 11:46:14 +02:00
1 parent d5b65cddc6
commit dc339b4cd2
153 files changed
+12956 -1067

No files matched your search

+446
View File
@@ -0,0 +1,446 @@
/* checks.cpp -- what in the configuration or on the machine costs speed or correctness, and what to
* do about it.
*
* EACH CHECK IS A FUNCTION OF THE FACTS AND NOTHING ELSE: no file is read here and no device is
* asked, so every one of them is tested by handing it a machine described in a struct. A check
* says what it saw with the numbers, why that matters, and the change that addresses it -- a
* warning without a fix is a worry handed to the reader.
*
* WARN is a cost or a risk the operator should act on; NOTE is a setting that is a trade-off or
* worth knowing when reading a benchmark. A finding that depends on load (a parked link) is only
* raised when the card was busy when the facts were read: at startup the cards are idle and a
* PCIe link at rest parks at its lowest speed, which is the power management doing its job.
*/
#include "diag/diag.h"
#include "rad_internal.h"
#include <algorithm>
#include <cstdlib>
#include <map>
#include <set>
namespace rad {
namespace diag {
namespace {
constexpr int64_t kGiB = (int64_t)1 << 30;
constexpr int64_t kMiB = (int64_t)1 << 20;
/* A card this busy when its link was read is under load, so a link below its maximum is not the
* idle parking every PCIe link does. */
constexpr int kBusyPercent = 30;
void add(std::vector<Finding>* out, Finding::Level lv, const char* id, std::string what,
std::string why, std::string fix) {
Finding f;
f.level = lv;
f.id = id;
f.what = std::move(what);
f.why = std::move(why);
f.fix = std::move(fix);
out->push_back(std::move(f));
}
std::vector<const CardFacts*> served(const Facts& f) {
std::vector<const CardFacts*> out;
for (const CardFacts& c : f.cards)
if (c.rank >= 0) out.push_back(&c);
std::sort(out.begin(), out.end(),
[](const CardFacts* a, const CardFacts* b) { return a->rank < b->rank; });
return out;
}
/* WHETHER THE SERVING CARDS' DMA IS TRANSLATED, from their own IOMMU groups where the kernel
* says, and from the machine's mode where it does not. */
bool translated(const Facts& f) {
bool any = false, dma = false;
for (const CardFacts* c : served(f)) {
if (c->iommu_type.empty()) continue;
any = true;
if (c->iommu_type != "identity") dma = true;
}
return any ? dma : f.host.iommu == "translated";
}
/* A GPU the engine could serve on: an amdgpu device with VRAM of its own worth the name. An
* integrated GPU's carve-out of a few hundred MiB is not one; an APU set up with tens of GiB is. */
bool servable_gpu(const CardFacts& c) {
return c.vendor == "0x1002" && c.driver == "amdgpu" && c.vram_total >= ((int64_t)4 << 30);
}
std::string card_name(const CardFacts& c) {
return c.rank >= 0 ? fmt("card %s (rank %d)", c.bdf.c_str(), c.rank) : "card " + c.bdf;
}
std::string hop_link(const PciHop& h, bool cur) {
const std::string& s = cur ? h.cur_speed : h.max_speed;
const int w = cur ? h.cur_width : h.max_width;
std::string sp = s;
const size_t p = sp.find(" PCIe");
if (p != std::string::npos) sp.erase(p);
return w > 0 ? fmt("%s x%d", sp.c_str(), w) : sp;
}
/* ---- the link ------------------------------------------------------------------------------ */
/* A HOP BELOW ITS OWN MAXIMUM WHILE THE CARD IS BUSY: the SMU's link power management stuck a
* level down, or a link that retrained narrower. The card's own endpoint can read full speed
* while the root port above it runs at half (a card with a switch on it), so every hop is read. */
void check_link_under_load(const Facts& f, std::vector<Finding>* out) {
for (const CardFacts* c : served(f)) {
if (c->busy_percent < kBusyPercent) continue;
for (const PciHop& h : c->chain) {
const double cur = link_gts(h.cur_speed), mx = link_gts(h.max_speed);
const bool slow = cur > 0 && mx > 0 && cur < mx;
const bool narrow = h.cur_width > 0 && h.max_width > 0 && h.cur_width < h.max_width;
if (!slow && !narrow) continue;
add(out, Finding::Warn, "link-below-max",
fmt("%s: the PCIe link at %s runs %s of its %s while the card is %d%% busy",
card_name(*c).c_str(), h.bdf.c_str(), hop_link(h, true).c_str(),
hop_link(h, false).c_str(), c->busy_percent),
"every copy between host memory and the card -- experts streamed from the host "
"pool, the all-reduce through host memory, the embedding read in place -- and "
"every kernel launch's packet fetch cross this link, so the card serves at the "
"slower link's rate and a tensor-parallel step waits for it",
"a link stuck one level down after long uptime has been cleared by a reboot; "
"check that it recovers under load (GET /diagnostics during a long prefill), and "
"reseat or move the card if it trains narrow");
break;
}
if (c->dpm_pcie_cur >= 0 && c->dpm_pcie_cur + 1 < (int)c->dpm_pcie.size())
add(out, Finding::Warn, "link-dpm-below-top",
fmt("%s: the card's PCIe power level is %s, not its top level %s, while it is "
"%d%% busy", card_name(*c).c_str(), c->dpm_pcie[(size_t)c->dpm_pcie_cur].c_str(),
c->dpm_pcie.back().c_str(), c->busy_percent),
"the SMU picks the link's speed from this table; a level below the top under load "
"is half the host bandwidth or less",
"a reboot has cleared a level stuck after long uptime; pp_dpm_pcie can pin a level "
"(echo 2 | sudo tee /sys/class/drm/CARD/device/pp_dpm_pcie with "
"power_dpm_force_performance_level manual), with the server stopped");
}
}
/* A LINK THAT CANNOT REACH THE CARD'S SPEED, whatever the load: a hop whose own maximum is below
* the card's -- a slot one generation older, a riser, a lane split. Not a fault, and often the
* board's design; worth knowing when two machines measure differently. */
void check_link_capped(const Facts& f, std::vector<Finding>* out) {
for (const CardFacts* c : served(f)) {
if (c->chain.size() < 2) continue;
const PciHop& ep = c->chain.back();
const double card = link_gts(ep.max_speed);
for (size_t i = 0; i + 1 < c->chain.size(); ++i) {
const PciHop& h = c->chain[i];
const double mx = link_gts(h.max_speed);
const bool slower = mx > 0 && card > 0 && mx < card;
const bool narrower = h.max_width > 0 && ep.max_width > 0 && h.max_width < ep.max_width;
if (!slower && !narrower) continue;
add(out, Finding::Note, "link-capped",
fmt("%s: the card's link is %s at most, and %s above it is %s at most",
card_name(*c).c_str(), hop_link(ep, false).c_str(), h.bdf.c_str(),
hop_link(h, false).c_str()),
"the host side of the link bounds what the card can move to and from host memory: "
"streamed experts, the host pool and the all-reduce when it goes through host memory",
"a slot with the card's full width and speed (the board manual says which slots "
"share lanes), or no riser; nothing to do if the board has no faster slot");
break;
}
}
}
/* ---- the cards against each other ----------------------------------------------------------- */
/* A TENSOR-PARALLEL STEP ENDS WHEN ITS SLOWEST RANK DOES, so cards set up differently serve at
* the slower one's pace, and a difference in a setting nobody remembers making is the usual
* reason one card is the slow one. */
void check_cards_differ(const Facts& f, std::vector<Finding>* out) {
const auto cs = served(f);
if (cs.size() < 2) return;
std::vector<std::string> diffs;
auto field = [&](const char* what, auto get, auto show) {
std::map<std::string, std::vector<std::string>> by;
for (const CardFacts* c : cs) by[show(get(*c))].push_back(c->bdf);
if (by.size() < 2) return;
std::string d = std::string(what) + ":";
for (const auto& [v, bdfs] : by) {
d += " " + v + " on";
for (const std::string& b : bdfs) d += " " + b;
d += ";";
}
d.pop_back();
diffs.push_back(d);
};
auto str = [](const std::string& s) { return s.empty() ? std::string("unknown") : s; };
field("root port link", [](const CardFacts& c) {
return c.chain.empty() ? std::string() : hop_link(c.chain.front(), false); }, str);
field("power cap", [](const CardFacts& c) { return c.power_cap_uw; },
[](int64_t uw) { return uw < 0 ? std::string("unknown") : fmt("%lld W", (long long)(uw / 1000000)); });
field("voltage offset", [](const CardFacts& c) { return c.vddgfx_offset; }, str);
field("top PCIe power level", [](const CardFacts& c) {
return c.dpm_pcie.empty() ? std::string() : c.dpm_pcie.back(); }, str);
field("runtime power management", [](const CardFacts& c) { return c.runtime_control; }, str);
field("target", [](const CardFacts& c) { return c.gfx; }, str);
if (diffs.empty()) return;
std::string what = "the cards serving this model are not set up alike -- ";
for (size_t i = 0; i < diffs.size(); ++i) what += (i ? "; " : "") + diffs[i];
add(out, Finding::Warn, "cards-differ", what,
"a tensor-parallel step waits for its slowest rank in every all-reduce, so the whole "
"server runs at the pace of the card with the lower limit or the slower link",
"make the settings match (the power cap and voltage offset are per card under "
"/sys/class/drm/cardN/device; set them with the server stopped)");
}
/* A CAP LOWERED BELOW THE CARD'S OWN DEFAULT. The default, not the maximum, is the yardstick: a
* stock card ships below the most its board allows (300 W of 330 W on an R9700), and a finding on
* every stock card is one nobody reads. A cap someone lowered -- or one a reset left at a value a
* tool set before it -- is the one that changes what the card does under load. */
void check_power_cap(const Facts& f, std::vector<Finding>* out) {
for (const CardFacts* c : served(f)) {
if (c->power_cap_uw <= 0 || c->power_cap_default_uw <= 0) continue;
if (c->power_cap_uw >= c->power_cap_default_uw) continue;
add(out, Finding::Note, "power-cap-below-default",
fmt("%s: the power cap is %lld W, below the card's default of %lld W",
card_name(*c).c_str(), (long long)(c->power_cap_uw / 1000000),
(long long)(c->power_cap_default_uw / 1000000)),
"under a sustained load the power cap is what sets the clock on these cards "
"(scripts/cardclock.py shows which limit binds)",
fmt("echo %lld | sudo tee /sys/class/drm/%s/device/hwmon/hwmon*/power1_cap restores "
"the default, with the server stopped; nothing to do if the cap was lowered on "
"purpose", (long long)c->power_cap_default_uw,
c->drm.empty() ? "cardN" : c->drm.c_str()));
}
}
void check_small_bar(const Facts& f, std::vector<Finding>* out) {
for (const CardFacts* c : served(f)) {
if (c->vram_visible <= 0 || c->vram_total <= 0) continue;
if (c->vram_visible * 10 >= c->vram_total * 9) continue;
add(out, Finding::Warn, "small-bar",
fmt("%s: the host and the other cards see %s of its %s of VRAM", card_name(*c).c_str(),
humanb(c->vram_visible).c_str(), humanb(c->vram_total).c_str()),
"without Resizable BAR a peer can address only a window of the card's memory, which "
"limits peer-to-peer collectives and copies into VRAM from the host",
"enable Resizable BAR (\"Re-Size BAR Support\" and \"Above 4G Decoding\") in the "
"firmware setup");
}
}
/* AN OVERDRIVE SETTING AND RUNTIME SUSPEND. The driver holds the offset and uploads it again
* whenever the card resumes from runtime suspend; on RDNA4 that upload has been seen to fail in
* the kernel log ("Failed to upload customized OD settings") at every resume. Whether the
* firmware still holds the offset afterwards is not readable here, and a card that lost it runs a
* lower clock at the same power cap. Keeping the card out of runtime suspend keeps the question
* from arising. */
void check_od_runtime_pm(const Facts& f, std::vector<Finding>* out) {
for (const CardFacts* c : served(f)) {
if (c->vddgfx_offset.empty() || c->vddgfx_offset == "0 mV") continue;
if (c->runtime_control != "auto") continue;
add(out, Finding::Note, "od-runtime-suspend",
fmt("%s: a voltage offset of %s is set and the card runtime-suspends when idle "
"(power/control auto)", card_name(*c).c_str(), c->vddgfx_offset.c_str()),
"the driver re-uploads overdrive settings on every resume and can fail to (\"Failed "
"to upload customized OD settings\" in the kernel log); a card that resumed without "
"its offset clocks lower at the same power cap, and in a tensor-parallel world sets "
"the pace for every card",
fmt("echo on | sudo tee /sys/bus/pci/devices/%s/power/control keeps it resumed; check "
"`journalctl -k | grep -i overdrive` for failed uploads", c->bdf.c_str()));
}
}
/* ---- the host ------------------------------------------------------------------------------- */
void check_cwsr(const Facts& f, std::vector<Finding>* out) {
if (f.host.cwsr_enable != 0) return;
add(out, Finding::Warn, "cwsr-off", "amdgpu cwsr_enable is 0",
"the driver cannot preempt a running queue: any queue eviction (host memory the card maps, "
"moved under memory pressure) waits for a queue a serve never lets drain, and ends in a "
"GPU hang and reset",
"amdgpu.cwsr_enable=1 as a module option, then rebuild the initramfs and reboot");
}
void check_huge_pages(const Facts& f, const RunFacts& r, std::vector<Finding>* out) {
if (f.host.thp_enabled != "never") return;
if (r.host_pool_mib <= 0 && r.pinned_bytes < kGiB) return;
const bool tr = translated(f);
add(out, tr ? Finding::Warn : Finding::Note, "thp-never",
"transparent huge pages are off (/sys/kernel/mm/transparent_hugepage/enabled is never), so "
"every pinned range is 4 KiB pages",
tr ? "with an IOMMU translating the cards' reads each page is a translation of its "
"own; a host pool streamed at 4 KiB pages measured 10-21% slower prefill"
: "with the IOMMU in passthrough the page size has not measured slower; it "
"matters as soon as the IOMMU translates",
"echo madvise | sudo tee /sys/kernel/mm/transparent_hugepage/enabled (or "
"transparent_hugepage=madvise on the kernel command line)");
}
void check_iommu(const Facts& f, const RunFacts& r, std::vector<Finding>* out) {
if (!translated(f)) return;
if (r.host_weight_bytes <= 0 && r.host_pool_mib <= 0 && r.tp < 2) return;
std::string groups;
for (const CardFacts* c : served(f))
if (!c->iommu_type.empty()) groups += (groups.empty() ? "" : ", ") + c->bdf + " " + c->iommu_type;
add(out, Finding::Note, "iommu-translated",
"the IOMMU translates the cards' DMA (" + (groups.empty() ? f.host.iommu_why : groups) + ")",
"every read a card makes of host memory -- the host pool, the embedding in RAM, the "
"all-reduce through host memory -- goes through an IOMMU translation; with huge pages that "
"is cheap, at 4 KiB pages it measured 10-21% prefill",
std::string("iommu=pt on the kernel command line (amd_iommu=pt / intel_iommu=pt), if "
"nothing on the machine needs DMA isolation; otherwise keep transparent huge "
"pages at madvise or always") +
(r.tp > 1 ? "; with more than one card, check that peer access survives the change "
"(--p2p on refuses to start without it): iommu=pt removed it on an Intel "
"VT-d host (GUIDE §7.2)"
: ""));
}
void check_memory(const Facts& f, const RunFacts& r, std::vector<Finding>* out) {
const HostFacts& h = f.host;
if (h.mem_available >= 0 && h.mem_total > 0 &&
(h.mem_available < 2 * kGiB || h.mem_available * 20 < h.mem_total))
add(out, Finding::Warn, "memory-low",
fmt("%s of %s of RAM is available after startup", humanb(h.mem_available).c_str(),
humanb(h.mem_total).c_str()),
"the page cache is what a container read in place and the n-gram rows read from disk "
"come through; with it starved every step waits on the drive, and the kernel starts "
"reclaiming and swapping",
"lower --host-pool-mib or --prefix-cache-host-mib, or stop what else holds memory");
if (h.swap_total > 0 && h.swap_free >= 0 && h.swap_total - h.swap_free > 256 * kMiB)
add(out, Finding::Note, "swap-in-use",
fmt("%s of swap is in use", humanb(h.swap_total - h.swap_free).c_str()),
"a host thread that faults on a swapped page stalls the step it is part of",
"free memory, or turn swap off on a machine that only serves");
if (h.cgroup_mem_limit > 0 && h.mem_total > 0 && h.cgroup_mem_limit < h.mem_total &&
r.pinned_bytes > 0 && r.pinned_bytes * 10 > h.cgroup_mem_limit * 8)
add(out, Finding::Warn, "cgroup-limit",
fmt("the container's memory limit is %s and the process pins %s",
humanb(h.cgroup_mem_limit).c_str(), humanb(r.pinned_bytes).c_str()),
"pinned memory counts against the limit and cannot be reclaimed; what is left is all "
"the page cache and the process's own allocations get before the OOM killer",
"raise the container's memory limit or lower the pools");
}
void check_memlock(const Facts& f, const RunFacts& r, std::vector<Finding>* out) {
if (f.host.memlock_soft == -2 || f.host.memlock_soft < 0) return;
if (r.locked_bytes > 0 || r.ngram_placement != "disk") return;
add(out, Finding::Note, "memlock-limited",
fmt("RLIMIT_MEMLOCK is %s and the n-gram table is read from the container on disk",
humanb(f.host.memlock_soft).c_str()),
"a locked copy of the table in RAM is one of the faster tiers, and the memlock limit is "
"one of the things that keeps --ngram-placement auto off it",
"Docker: ulimits memlock -1 (--ulimit memlock=-1); systemd: LimitMEMLOCK=infinity");
}
void check_cpu(const Facts& f, std::vector<Finding>* out) {
const HostFacts& h = f.host;
if (h.cpu_governor.empty() || h.cpu_governor == "performance") return;
if (h.cpu_governor == "powersave" && h.cpu_epp == "performance") return;
if (h.cpu_governor == "schedutil") return;
add(out, Finding::Note, "cpu-governor",
fmt("the CPU governor is %s%s", h.cpu_governor.c_str(),
h.cpu_epp.empty() ? "" : (" with energy preference " + h.cpu_epp).c_str()),
"the host side of a step -- scheduling, sampling, the n-gram gather, launch bookkeeping -- "
"is single-threaded per rank, and a core that ramps slowly shows as host gap between steps",
"cpupower frequency-set -g performance, or echo performance | sudo tee "
"/sys/devices/system/cpu/cpu*/cpufreq/energy_performance_preference");
}
/* ---- the engine ----------------------------------------------------------------------------- */
void check_engine(const Facts& f, const RunFacts& r, std::vector<Finding>* out) {
std::string gpus;
for (const CardFacts& c : f.cards)
if (servable_gpu(c))
gpus += (gpus.empty() ? "" : ", ") + c.bdf + (c.gfx.empty() ? "" : " " + c.gfx);
if (r.host_backend && !gpus.empty())
add(out, Finding::Warn, "host-backend",
"the engine serves on the CPU although this machine has an AMD GPU (" + gpus + ")",
r.device_build ? "the device runtime found no card it could use, so every op runs on the host"
: "this build has no device runtime (built without HIP), so every op runs "
"on the host",
r.device_build
? "the device lines at the top of the log say why: /dev/kfd and /dev/dri must be "
"passed to a container with the render and video groups, ROCm must support the "
"card, and HIP_VISIBLE_DEVICES / ROCR_VISIBLE_DEVICES must not hide it"
: "build with ROCm (RAD_WITH_HIP=ON, hipcc on the PATH), or run the image");
for (const std::string& why : r.ignored)
add(out, Finding::Note, "device-ignored", "a device was left out: " + why,
"a rank placed on a slower or different card would set the pace of every step",
"ROCR_VISIBLE_DEVICES names the cards to use explicitly");
if (r.tp > 1 && r.p2p == 0 && !r.p2p_forced_off)
add(out, Finding::Note, "p2p-off",
"the cards cannot reach each other's memory directly" +
(r.p2p_blocked.empty() ? std::string() : " (" + r.p2p_blocked + ")"),
"the collectives exchange through pinned host memory, which crosses each card's link "
"twice",
"peer access needs Resizable BAR and the cards under one root complex; whether the "
"IOMMU's mode allows it depends on the platform -- iommu=pt removed it on an Intel "
"VT-d host (GUIDE §7.2) -- so check `--p2p on`, which refuses to start without it, "
"before and after changing the mode");
if (r.tp > 1 && r.tp_wire_lossy)
add(out, Finding::Note, "tp-wire-lossy",
fmt("--tp-wire wht6: all-reduce messages from %lld KiB up carry a quantised payload",
(long long)r.tp_wire_min_kb),
"faster prefill, but the model does not compute the exact function; two runs on "
"different world sizes are not comparable token for token",
"--tp-wire exact when exactness matters more than prefill speed");
/* Only when the operator turned it off: where the engine did (the KL mode, an embedding
* model) there is no cache to have, and the configuration line says why. */
if (!r.prefix_cache && r.prefix_cache_off_why.empty())
add(out, Finding::Note, "prefix-cache-off", "prefix caching is off (--no-prefix-cache)",
"every request prefills its whole prompt, including the conversation it shares with "
"the turn before",
"drop --no-prefix-cache");
if (r.host_weight_bytes > 0)
add(out, Finding::Note, "experts-from-host",
fmt("%s of weights a rank live in the pinned host pool and cross PCIe when they are "
"used", humanb(r.host_weight_bytes).c_str()),
"a prefill step streams every routed layer's pooled experts onto the card, so its speed "
"is bounded by the link; decode reads the ones it routes to",
"more VRAM for the experts: a shorter --max-model-len or fewer --max-num-seqs, "
"--embedding-placement ram, --kv-cache-dtype fp8, or more cards (--tp)");
if (r.file_weight_bytes > 0)
add(out, Finding::Warn, "weights-from-disk",
fmt("%s of weights a rank are read from the container on disk as they are needed",
humanb(r.file_weight_bytes).c_str()),
"a step that needs them is paced by the drive",
"a larger --host-pool-mib (if RAM allows) or more VRAM for the weights");
if (r.reference_kernels)
add(out, Finding::Warn, "reference-kernels",
"--debug-accept-reference-kernels: ops may run on the reference implementation",
"the reference library is an oracle, orders of magnitude slower than a device kernel",
"install a kernel library for this card and drop the flag");
if (r.profile_ops)
add(out, Finding::Warn, "profile-ops",
"--profile-ops times every op, which restores synchronisations",
"the run is slower and its numbers are not comparable against an unprofiled one",
"drop --profile-ops for anything measured");
}
} /* namespace */
std::vector<Finding> check(const Facts& f, const RunFacts& r) {
std::vector<Finding> out;
check_engine(f, r, &out);
check_link_under_load(f, &out);
check_cards_differ(f, &out);
check_link_capped(f, &out);
check_small_bar(f, &out);
check_power_cap(f, &out);
check_od_runtime_pm(f, &out);
check_cwsr(f, &out);
check_memory(f, r, &out);
check_huge_pages(f, r, &out);
check_iommu(f, r, &out);
check_memlock(f, r, &out);
check_cpu(f, &out);
/* Warnings first, each group in the order above: what to act on before what to know. */
std::stable_sort(out.begin(), out.end(),
[](const Finding& a, const Finding& b) { return a.level > b.level; });
return out;
}
double link_gts(const std::string& speed) {
return speed.empty() ? 0.0 : std::strtod(speed.c_str(), nullptr);
}
} /* namespace diag */
} /* namespace rad */
+216
View File
@@ -0,0 +1,216 @@
/* diag.h -- the startup report: what was configured, what it runs on, and what looks wrong.
*
* WHY ONE REPORT AND NOT THE LINES ALREADY IN THE LOG. Every decision startup makes is said
* somewhere on the way up, in the order it was made, between a hundred other lines. A log a user
* pastes into an issue is read by someone who has to find the line about the embedding, the one
* about the VRAM split and the one about the card's link, and cannot find the line that was never
* printed because the value was a default. The report puts all of it in one block at the end of
* startup: every option the command line takes with the value in force and where it came from,
* the machine as the kernel describes it, and a list of the things on it that cost speed or
* correctness with what to do about each.
*
* THREE PARTS, each built from data rather than from a list kept beside the code:
*
* CONFIGURATION every row of the option table (core/config.cpp), so an option added there
* appears here without anyone remembering to; a value startup resolved carries
* the reason it was resolved that way (Decision).
* HARDWARE read from /proc and /sys under a ROOT, so a test can hand the collector a
* directory tree of its own and a container built FROM scratch -- no shell, no
* lspci, no rocm-smi -- reads the same files the host does.
* FINDINGS each a small function over the two above (checks.cpp), unit-testable without
* a card.
*
* Unknown is a value. A field that could not be read is reported as unknown rather than left out:
* a report that silently drops a line reads as a machine that does not have the thing.
*/
#pragma once
#include <cstdint>
#include <string>
#include <vector>
namespace rad {
struct Config;
namespace diag {
/* ------------------------------------------------------------------ decisions */
/* ONE VALUE STARTUP RESOLVED, and why. `key` is the option it resolves (`--placement`) when there
* is one, so the configuration table can show it on that option's row, or a topic of its own
* (`vram split`) for what no single option states. Recording the same key again replaces the
* earlier answer: a later stage that revises a choice (the n-gram copy that could not be made)
* is the answer in force. */
struct Decision {
std::string key;
std::string value;
std::string why;
};
void decide(std::vector<Decision>* list, const std::string& key, const std::string& value,
const std::string& why);
/* ------------------------------------------------------------------ the configuration table */
/* One option as the report shows it: the value in force, where it came from (`default`, `command
* line`, an environment variable, or `auto` for a value startup derived), and the reason when
* startup derived it. */
struct ConfigRow {
std::string flag;
std::string value;
std::string source;
std::string why;
};
/* Every option in the command line's table (core/config.cpp), in its order, with the value `c`
* holds and its source from Config::given. Secrets are not values: --api-key is "set" or "not
* set". */
std::vector<ConfigRow> config_rows(const Config& c);
/* The options the table holds, for a test that every one reaches the report. */
std::vector<std::string> config_option_names();
/* ------------------------------------------------------------------ hardware */
/* One PCIe link on the way from the root port to a card. Speeds are the kernel's strings
* ("32.0 GT/s PCIe"), widths lanes; -1 / "" where the file is absent, as it is on a bridge
* internal to a card's own switch on some boards. */
struct PciHop {
std::string bdf;
std::string cur_speed, max_speed;
int cur_width = -1, max_width = -1;
};
struct CardFacts {
std::string bdf; /* 0000:03:00.0 */
std::string vendor, pci_device; /* 0x1002, 0x7551 */
std::string driver; /* the bound kernel driver, "" for none */
std::string drm; /* card1, "" when the driver made no DRM node */
std::string gfx; /* gfx1201, from the KFD topology; "" when unknown */
int simd = -1; /* SIMDs the KFD topology reports */
int numa_node = -1;
int64_t vram_total = -1, vram_visible = -1; /* the BAR the host and the peers see */
int busy_percent = -1;
std::string runtime_status; /* active | suspended, "" when unknown */
std::string runtime_control; /* auto | on */
std::string iommu_type; /* the card's IOMMU group: identity, DMA, DMA-FQ */
std::vector<PciHop> chain; /* root port first, the card's own link last */
std::vector<std::string> dpm_pcie; /* the SMU's link levels, as listed */
int dpm_pcie_cur = -1; /* the level marked current, -1 unknown */
std::string sclk, mclk; /* "500-2350 MHz", the lowest and highest DPM level */
int64_t power_cap_uw = -1, power_cap_default_uw = -1, power_cap_max_uw = -1;
std::string vddgfx_offset; /* "-75 mV" from pp_od_clk_voltage, "" when unknown */
bool integrated = false; /* the KFD topology's node has no local memory of its own */
/* What the engine knows and the kernel does not: filled by the engine for its own cards. */
std::string name; /* the runtime's product name */
int rank = -1; /* the tensor-parallel rank it serves, -1 none */
int device = -1; /* the backend's device index, -1 none */
std::string dma; /* what carries its copy lists (dev_dma_lane), "" unknown */
};
struct HostFacts {
std::string cpu_model;
int cores = -1, threads = -1;
int64_t mem_total = -1, mem_available = -1, swap_total = -1, swap_free = -1;
std::string kernel, distro;
std::string container; /* "docker", "podman", "" for none seen */
int64_t cgroup_mem_limit = -1; /* bytes; -2 is "max", -1 unknown */
int64_t memlock_soft = -1; /* bytes; -2 is unlimited, -1 unknown */
std::string thp_enabled, thp_defrag, thp_shmem; /* the selected word of each */
std::string iommu; /* passthrough | translated | off | unknown */
std::string iommu_why; /* what that was read from */
std::string cmdline; /* the boot parameters that bear on a card, space separated */
int64_t ttm_pages_limit = -1; /* pages; TTM's limit on the system memory it allocates */
int64_t page_size = 4096;
int cwsr_enable = -1;
std::string io_uring; /* available | refused (why) | unknown */
std::string cpu_governor, cpu_epp, cpu_driver;
std::string runtime; /* the device runtime's version, "" for none */
};
struct Facts {
HostFacts host;
std::vector<CardFacts> cards; /* every display-class PCI device, in address order */
};
/* Reads /proc and /sys under `root` ("" is the live system). Never fails: what cannot be read is
* left unknown.
*
* `managed`, when given, names the cards (by PCI address) whose power-management files are read
* -- the DPM tables, the overdrive block, the busy percentage and the hwmon power limits; every
* other card is described from its PCI and memory files alone. The driver answers those files
* from the card's SMU under its power-management lock, and wakes a card that was runtime-
* suspended to do it, so a server reading the machine again while it serves reads them for the
* cards it serves on and no others. Null reads them for every card. */
Facts collect(const std::string& root, const std::vector<std::string>* managed = nullptr);
/* What only a system call answers, filled for the live process: the memlock limit and whether
* io_uring is allowed here (a container's seccomp profile refuses it). */
void probe_process(HostFacts* h);
/* The names of the variables in `env` (an environ-shaped, null-terminated array) that start with
* `prefix`, sorted. Names only: a value can be a path, a host name or a token, and the report is
* written to be pasted into an issue. */
std::vector<std::string> env_names(char* const* env, const char* prefix);
/* ------------------------------------------------------------------ what the engine did */
struct RunFacts {
std::string version; /* the engine's, for the report's first line */
bool device_build = true; /* built with a device runtime (HIP) */
int tp = 1;
bool host_backend = false;
bool failed = false; /* startup stopped; the report is what it got to */
int p2p = -1; /* 1 peer to peer, 0 through host memory, -1 n/a */
bool p2p_forced_off = false; /* --p2p off */
std::string p2p_blocked; /* the pairs the driver refused */
std::vector<std::string> ignored; /* devices left out, each with the reason */
bool tp_wire_lossy = false;
int64_t tp_wire_min_kb = 0;
bool prefix_cache = true;
/* Why the engine turned prefix caching off itself (the KL mode, an embedding model); "" when
* it is on or the operator turned it off. */
std::string prefix_cache_off_why;
int64_t prefix_host_mib = 0, prefix_disk_mib = 0;
int64_t host_pool_mib = 0; /* a rank, as configured */
int64_t pinned_bytes = -1; /* every pinned host allocation the process made */
int64_t host_weight_bytes = 0; /* weights a rank reads from the pinned host pool */
int64_t file_weight_bytes = 0; /* and from the container on disk */
int64_t locked_bytes = 0; /* memory locked for a host gather (an n-gram copy) */
std::string ngram_placement; /* where an n-gram table went, "" for a model without one */
bool reference_kernels = false;
bool profile_ops = false;
bool deterministic = false;
/* The RADIANCE_* variables set in the environment, by name (env_names). The option table
* covers what the command line takes; these change behaviour beside it -- the log level, a
* pinned tuning, an instrument left on -- and a report of every setting in force names them. */
std::vector<std::string> environment;
};
/* ------------------------------------------------------------------ findings */
struct Finding {
enum Level { Note = 0, Warn = 1 };
Level level = Note;
std::string id; /* stable, for a test or a grep: "link-below-max" */
std::string what; /* what was seen, with the numbers */
std::string why; /* what it costs */
std::string fix; /* what to do: a flag, a setting, a command */
};
std::vector<Finding> check(const Facts& f, const RunFacts& r);
/* ------------------------------------------------------------------ the report */
std::string render(const std::vector<ConfigRow>& config, const std::vector<Decision>& derived,
const Facts& f, const RunFacts& r, const std::vector<Finding>& findings);
/* The same, as a JSON object in text: {"configuration", "derived", "hardware", "findings"}. */
std::string to_json(const std::vector<ConfigRow>& config, const std::vector<Decision>& derived,
const Facts& f, const RunFacts& r, const std::vector<Finding>& findings);
/* Merges the decisions into the option rows: a decision whose key is an option's flag supplies
* that row's value and reason (and `auto` as its source when the option was not given). The
* decisions no row took are returned in `derived`, in the order they were made. */
void merge(std::vector<ConfigRow>* rows, const std::vector<Decision>& decisions,
std::vector<Decision>* derived);
/* "32.0 GT/s PCIe" -> 32.0; 0 when it does not parse. */
double link_gts(const std::string& speed);
} /* namespace diag */
} /* namespace rad */
+296
View File
@@ -0,0 +1,296 @@
/* report.cpp -- the startup report, as text for the log and as JSON for /diagnostics.
*
* ONE LAYOUT FOR A READER WHO DID NOT RUN THE SERVER: every option on its own line with the value
* in force and where it came from, the reason under any value startup derived, the machine in a
* few dense lines and a block a card, and the findings last with what to do about each. The text
* and the JSON are rendered from the same structs, so neither can say something the other does
* not.
*/
#include "diag/diag.h"
#include "rad_internal.h"
#include <nlohmann/json.hpp>
#include <algorithm>
namespace rad {
namespace diag {
void decide(std::vector<Decision>* list, const std::string& key, const std::string& value,
const std::string& why) {
for (Decision& d : *list)
if (d.key == key) { d.value = value; d.why = why; return; }
list->push_back({ key, value, why });
}
void merge(std::vector<ConfigRow>* rows, const std::vector<Decision>& decisions,
std::vector<Decision>* derived) {
derived->clear();
for (const Decision& d : decisions) {
auto it = std::find_if(rows->begin(), rows->end(),
[&](const ConfigRow& r) { return r.flag == d.key; });
if (it == rows->end()) { derived->push_back(d); continue; }
it->value = d.value;
it->why = d.why;
if (it->source == "default") it->source = "auto";
}
}
namespace {
std::string or_unknown(const std::string& s) { return s.empty() ? "unknown" : s; }
std::string bytes_or_unknown(int64_t b) { return b < 0 ? "unknown" : humanb(b); }
/* Continuation lines of a multi-line value, indented under the column they belong to. */
void indented(std::string* out, const std::string& text, int indent) {
size_t at = 0;
while (at <= text.size()) {
size_t nl = text.find('\n', at);
if (nl == std::string::npos) nl = text.size();
const std::string l = text.substr(at, nl - at);
if (!l.empty()) *out += std::string((size_t)indent, ' ') + l + "\n";
at = nl + 1;
}
}
std::string short_bdf(const std::string& b) {
return b.rfind("0000:", 0) == 0 ? b.substr(5) : b;
}
std::string link(const std::string& speed, int width) {
std::string s = speed;
const size_t p = s.find(" PCIe");
if (p != std::string::npos) s.erase(p);
if (s.empty()) s = "?";
return width > 0 ? fmt("%s x%d", s.c_str(), width) : s;
}
std::string watts(int64_t uw) { return uw < 0 ? std::string("unknown") : fmt("%lld W", (long long)(uw / 1000000)); }
std::string host_lines(const HostFacts& h, const RunFacts& r) {
std::string o;
o += fmt(" host %s | %s cores, %s threads | RAM %s, %s available | swap %s\n",
or_unknown(h.cpu_model).c_str(),
h.cores > 0 ? std::to_string(h.cores).c_str() : "?",
h.threads > 0 ? std::to_string(h.threads).c_str() : "?",
bytes_or_unknown(h.mem_total).c_str(), bytes_or_unknown(h.mem_available).c_str(),
h.swap_total == 0 ? "none"
: h.swap_total < 0 ? "unknown"
: fmt("%s, %s used", humanb(h.swap_total).c_str(),
humanb(h.swap_total - std::max<int64_t>(h.swap_free, 0)).c_str()).c_str());
o += fmt(" system kernel %s | %s | %s | cgroup memory %s | memlock %s\n",
or_unknown(h.kernel).c_str(), or_unknown(h.distro).c_str(),
h.container.empty() ? "no container seen" : ("in a " + h.container + " container").c_str(),
h.cgroup_mem_limit == -2 ? "unlimited" : bytes_or_unknown(h.cgroup_mem_limit).c_str(),
h.memlock_soft == -2 ? "unlimited" : bytes_or_unknown(h.memlock_soft).c_str());
o += fmt(" memory huge pages %s (defrag %s, shmem %s) | ttm.pages_limit %s "
"| pinned by this process %s\n",
or_unknown(h.thp_enabled).c_str(), or_unknown(h.thp_defrag).c_str(),
or_unknown(h.thp_shmem).c_str(),
h.ttm_pages_limit > 0 ? humanb(h.ttm_pages_limit * h.page_size).c_str() : "unknown",
bytes_or_unknown(r.pinned_bytes).c_str());
o += fmt(" iommu %s (%s)\n", or_unknown(h.iommu).c_str(), or_unknown(h.iommu_why).c_str());
o += fmt(" amdgpu cwsr_enable %s | boot parameters: %s\n",
h.cwsr_enable < 0 ? "unknown" : std::to_string(h.cwsr_enable).c_str(),
h.cmdline.empty() ? "none that bear on a card" : h.cmdline.c_str());
o += fmt(" cpu governor %s%s%s | io_uring %s\n", or_unknown(h.cpu_governor).c_str(),
h.cpu_epp.empty() ? "" : (", energy preference " + h.cpu_epp).c_str(),
h.cpu_driver.empty() ? "" : (" (" + h.cpu_driver + ")").c_str(),
or_unknown(h.io_uring).c_str());
o += fmt(" runtime %s | backend %s\n",
h.runtime.empty() ? "no device runtime" : h.runtime.c_str(),
r.host_backend ? "host (CPU)" : "device");
return o;
}
std::string card_lines(const CardFacts& c) {
std::string o;
std::string who = c.rank >= 0 ? fmt("rank %d (device %d)", c.rank, c.device)
: c.device >= 0 ? fmt("device %d, not serving", c.device) : "not serving";
o += fmt(" card %s %s %s%s%s %s VRAM",
c.bdf.c_str(), who.c_str(), c.gfx.empty() ? (c.vendor + ":" + c.pci_device).c_str() : c.gfx.c_str(),
c.name.empty() ? "" : " ", c.name.empty() ? "" : ("\"" + c.name + "\"").c_str(),
bytes_or_unknown(c.vram_total).c_str());
if (c.vram_visible > 0 && c.vram_visible != c.vram_total)
o += fmt(" (BAR %s)", humanb(c.vram_visible).c_str());
o += fmt(" NUMA %d driver %s%s%s\n", c.numa_node, or_unknown(c.driver).c_str(),
c.drm.empty() ? "" : " ", c.drm.c_str());
std::string chain;
for (const PciHop& h : c.chain)
chain += fmt("%s%s %s (max %s)", chain.empty() ? "" : " -> ", short_bdf(h.bdf).c_str(),
link(h.cur_speed, h.cur_width).c_str(), link(h.max_speed, h.max_width).c_str());
o += fmt(" link %s [read at %s%% busy%s]\n", chain.empty() ? "unknown" : chain.c_str(),
c.busy_percent < 0 ? "?" : std::to_string(c.busy_percent).c_str(),
c.busy_percent >= 0 && c.busy_percent < 30 ? ": a link at rest parks below its maximum" : "");
if (!c.dpm_pcie.empty()) {
std::string t;
for (size_t i = 0; i < c.dpm_pcie.size(); ++i)
t += fmt("%s%s%s", i ? " | " : "", (int)i == c.dpm_pcie_cur ? "*" : "", c.dpm_pcie[i].c_str());
o += " pcie " + t + "\n";
}
if (!c.dma.empty()) o += " dma " + c.dma + "\n";
o += fmt(" power cap %s (default %s, max %s) | voltage offset %s | sclk %s | mclk %s | "
"runtime pm %s (control %s) | iommu group %s\n",
watts(c.power_cap_uw).c_str(), watts(c.power_cap_default_uw).c_str(),
watts(c.power_cap_max_uw).c_str(), or_unknown(c.vddgfx_offset).c_str(),
or_unknown(c.sclk).c_str(), or_unknown(c.mclk).c_str(),
or_unknown(c.runtime_status).c_str(), or_unknown(c.runtime_control).c_str(),
c.iommu_type.empty() ? "none" : c.iommu_type.c_str());
return o;
}
} /* namespace */
std::string render(const std::vector<ConfigRow>& config, const std::vector<Decision>& derived,
const Facts& f, const RunFacts& r, const std::vector<Finding>& findings) {
std::string o;
o += "STARTUP REPORT" + (r.version.empty() ? std::string() : " -- radiance " + r.version) +
(r.failed ? " -- STARTUP STOPPED; this is what it had resolved when it did\n" : "\n");
o += "CONFIGURATION -- every option, the value in force, and where it came from\n";
size_t w = 0;
for (const ConfigRow& c : config) w = std::max(w, c.flag.size());
w = std::min<size_t>(w + 2, 34);
for (const ConfigRow& c : config) {
const std::string v = c.value.empty() ? "\"\"" : c.value;
const std::string first = v.substr(0, v.find('\n'));
std::string l = fmt(" %-*s %s", (int)w, c.flag.c_str(), first.c_str());
const size_t col = 2 + w + 1 + 44;
l += l.size() < col ? std::string(col - l.size(), ' ') : std::string(" ");
o += l + "[" + c.source + "]\n";
if (first.size() != v.size()) indented(&o, v.substr(first.size() + 1), (int)(3 + w));
if (!c.why.empty()) indented(&o, c.why, (int)(5 + w));
}
o += "ENVIRONMENT -- the RADIANCE_* variables set, by name; their values are not shown\n";
if (r.environment.empty()) o += " none\n";
for (const std::string& n : r.environment) o += " " + n + "\n";
if (!derived.empty()) {
o += "DERIVED -- what startup worked out that no single option states\n";
for (const Decision& d : derived) {
o += fmt(" %-*s %s\n", (int)w, d.key.c_str(), d.value.c_str());
if (!d.why.empty()) indented(&o, d.why, (int)(5 + w));
}
}
o += "HARDWARE\n";
o += host_lines(f.host, r);
for (const CardFacts& c : f.cards) o += card_lines(c);
if (f.cards.empty()) o += " no display-class PCI device is visible\n";
int nw = 0, nn = 0;
for (const Finding& x : findings) (x.level == Finding::Warn ? nw : nn)++;
o += fmt("FINDINGS -- %d warning%s, %d note%s\n", nw, nw == 1 ? "" : "s", nn, nn == 1 ? "" : "s");
if (findings.empty()) o += " nothing found that costs speed or correctness\n";
for (const Finding& x : findings) {
o += fmt(" %s %s: %s\n", x.level == Finding::Warn ? "WARN" : "note", x.id.c_str(),
x.what.c_str());
o += " why: " + x.why + "\n";
o += " fix: " + x.fix + "\n";
}
return o;
}
std::string to_json(const std::vector<ConfigRow>& config, const std::vector<Decision>& derived,
const Facts& f, const RunFacts& r, const std::vector<Finding>& findings) {
using J = nlohmann::ordered_json;
J o;
o["startup_failed"] = r.failed;
J cfg = J::array();
for (const ConfigRow& c : config) {
J e;
e["option"] = c.flag;
e["value"] = c.value;
e["source"] = c.source;
if (!c.why.empty()) e["why"] = c.why;
cfg.push_back(std::move(e));
}
o["configuration"] = std::move(cfg);
o["environment"] = r.environment;
J der = J::array();
for (const Decision& d : derived) der.push_back({ { "topic", d.key }, { "value", d.value }, { "why", d.why } });
o["derived"] = std::move(der);
const HostFacts& h = f.host;
J host;
host["cpu"] = h.cpu_model;
host["cores"] = h.cores;
host["threads"] = h.threads;
host["mem_total"] = h.mem_total;
host["mem_available"] = h.mem_available;
host["swap_total"] = h.swap_total;
host["swap_free"] = h.swap_free;
host["kernel"] = h.kernel;
host["distro"] = h.distro;
host["container"] = h.container;
host["cgroup_mem_limit"] = h.cgroup_mem_limit;
host["memlock"] = h.memlock_soft;
host["thp"] = { { "enabled", h.thp_enabled }, { "defrag", h.thp_defrag },
{ "shmem_enabled", h.thp_shmem } };
host["iommu"] = { { "mode", h.iommu }, { "why", h.iommu_why } };
host["boot_parameters"] = h.cmdline;
host["ttm_pages_limit"] = h.ttm_pages_limit;
host["page_size"] = h.page_size;
host["cwsr_enable"] = h.cwsr_enable;
host["io_uring"] = h.io_uring;
host["cpu_governor"] = h.cpu_governor;
host["cpu_epp"] = h.cpu_epp;
host["cpu_driver"] = h.cpu_driver;
host["runtime"] = h.runtime;
J cards = J::array();
for (const CardFacts& c : f.cards) {
J e;
e["bdf"] = c.bdf;
e["rank"] = c.rank;
e["device"] = c.device;
e["name"] = c.name;
e["vendor"] = c.vendor;
e["pci_device"] = c.pci_device;
e["gfx"] = c.gfx;
e["simd"] = c.simd;
e["driver"] = c.driver;
e["drm"] = c.drm;
e["numa_node"] = c.numa_node;
e["vram_total"] = c.vram_total;
e["vram_visible"] = c.vram_visible;
e["busy_percent"] = c.busy_percent;
e["runtime_status"] = c.runtime_status;
e["runtime_control"] = c.runtime_control;
e["iommu_group_type"] = c.iommu_type;
e["dma"] = c.dma;
J chain = J::array();
for (const PciHop& hp : c.chain)
chain.push_back({ { "bdf", hp.bdf }, { "speed", hp.cur_speed }, { "width", hp.cur_width },
{ "max_speed", hp.max_speed }, { "max_width", hp.max_width } });
e["link_chain"] = std::move(chain);
e["pcie_dpm"] = c.dpm_pcie;
e["pcie_dpm_current"] = c.dpm_pcie_cur;
e["sclk"] = c.sclk;
e["mclk"] = c.mclk;
e["power_cap_uw"] = c.power_cap_uw;
e["power_cap_default_uw"] = c.power_cap_default_uw;
e["power_cap_max_uw"] = c.power_cap_max_uw;
e["vddgfx_offset"] = c.vddgfx_offset;
cards.push_back(std::move(e));
}
J run;
run["version"] = r.version;
run["device_build"] = r.device_build;
run["tp"] = r.tp;
run["host_backend"] = r.host_backend;
run["p2p"] = r.p2p;
run["p2p_blocked"] = r.p2p_blocked;
run["ignored_devices"] = r.ignored;
run["pinned_bytes"] = r.pinned_bytes;
run["host_weight_bytes"] = r.host_weight_bytes;
run["file_weight_bytes"] = r.file_weight_bytes;
o["hardware"] = { { "host", std::move(host) }, { "cards", std::move(cards) }, { "run", std::move(run) } };
J fs = J::array();
for (const Finding& x : findings)
fs.push_back({ { "level", x.level == Finding::Warn ? "warn" : "note" }, { "id", x.id },
{ "what", x.what }, { "why", x.why }, { "fix", x.fix } });
o["findings"] = std::move(fs);
/* REPLACE, NOT THROW, on bytes that are not UTF-8. Values here come from the operator and the
* filesystem -- a --model path, a boot parameter, a product name -- and none of them is
* promised to be UTF-8; the strict default would make the whole answer an exception. */
return o.dump(-1, ' ', false, J::error_handler_t::replace);
}
} /* namespace diag */
} /* namespace rad */
+473
View File
@@ -0,0 +1,473 @@
/* sysinfo.cpp -- the machine, as /proc and /sys describe it.
*
* EVERY READ IS A FILE UNDER A ROOT. No tool is run and no library beyond the C++ runtime is
* asked: the production image is built FROM scratch and has no shell, no lspci and no rocm-smi,
* and a test hands the collector a directory tree of its own to stand for a machine with two cards
* behind a switch, a parked link, or an IOMMU that translates. What a file does not say is left
* unknown, never guessed.
*/
#include "diag/diag.h"
#include "rad_internal.h"
#include <cerrno>
#include <cctype>
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <filesystem>
#include <fstream>
#include <map>
#include <set>
#include <sstream>
#include <sys/resource.h>
#include <sys/syscall.h>
#include <unistd.h>
namespace rad {
namespace diag {
namespace fs = std::filesystem;
namespace {
std::string slurp(const std::string& path) {
std::ifstream f(path);
if (!f) return std::string();
std::stringstream ss;
ss << f.rdbuf();
return ss.str();
}
std::string trim(std::string s) {
while (!s.empty() && (s.back() == '\n' || s.back() == ' ' || s.back() == '\t' || s.back() == '\r'))
s.pop_back();
size_t i = 0;
while (i < s.size() && (s[i] == ' ' || s[i] == '\t')) ++i;
return s.substr(i);
}
/* The first line of a sysfs attribute, trimmed; "" when it cannot be read. */
std::string line(const std::string& path) {
const std::string s = slurp(path);
const size_t nl = s.find('\n');
return trim(nl == std::string::npos ? s : s.substr(0, nl));
}
int64_t num(const std::string& path, int64_t dflt = -1) {
const std::string s = line(path);
if (s.empty()) return dflt;
char* end = nullptr;
const long long v = std::strtoll(s.c_str(), &end, 0);
return end && end != s.c_str() ? (int64_t)v : dflt;
}
/* The bracketed word of a sysfs choice list: "always [madvise] never" -> "madvise". */
std::string selected(const std::string& path) {
const std::string s = line(path);
const size_t a = s.find('['), b = s.find(']');
if (a == std::string::npos || b == std::string::npos || b < a) return s;
return s.substr(a + 1, b - a - 1);
}
bool exists(const std::string& p) {
std::error_code ec;
return fs::exists(p, ec);
}
std::vector<std::string> list(const std::string& dir) {
std::vector<std::string> out;
std::error_code ec;
for (fs::directory_iterator it(dir, ec), end; !ec && it != end; it.increment(ec))
out.push_back(it->path().filename().string());
std::sort(out.begin(), out.end());
return out;
}
bool is_bdf(const std::string& s) {
unsigned d, b, dv, f;
char tail;
return s.size() == 12 && std::sscanf(s.c_str(), "%4x:%2x:%2x.%1x%c", &d, &b, &dv, &f, &tail) == 4;
}
/* "0x7551" from a sysfs id file, which the kernel writes with its prefix. */
std::string hexid(const std::string& path) { return line(path); }
/* The lowest and highest level of a pp_dpm_* table, "500-2350 MHz"; the levels are listed in
* order, one a line, as "N: 2350Mhz *". */
std::string dpm_range(const std::string& path) {
std::istringstream in(slurp(path));
std::string l;
long lo = -1, hi = -1;
while (std::getline(in, l)) {
const size_t c = l.find(':');
const char* p = l.c_str() + (c == std::string::npos ? 0 : c + 1);
long v = std::strtol(p, nullptr, 10);
if (v <= 0) continue;
if (lo < 0 || v < lo) lo = v;
if (v > hi) hi = v;
}
if (lo < 0) return std::string();
return fmt("%ld-%ld MHz", lo, hi);
}
/* `pm`: whether the power-management files are read as well (collect's `managed`). */
void read_card(const std::string& root, const std::string& bdf, bool pm, CardFacts* c) {
const std::string dev = root + "/sys/bus/pci/devices/" + bdf;
c->bdf = bdf;
c->vendor = hexid(dev + "/vendor");
c->pci_device = hexid(dev + "/device");
{
std::error_code ec;
const fs::path drv = fs::read_symlink(dev + "/driver", ec);
if (!ec) c->driver = drv.filename().string();
}
c->numa_node = (int)num(dev + "/numa_node", -1);
c->runtime_status = line(dev + "/power/runtime_status");
c->runtime_control = line(dev + "/power/control");
c->iommu_type = line(dev + "/iommu_group/type");
for (const std::string& d : list(dev + "/drm"))
if (d.rfind("card", 0) == 0 && d.size() > 4 && std::isdigit((unsigned char)d[4])) c->drm = d;
/* THE WHOLE PATH TO THE ROOT PORT, not the card's own link alone. A card with a switch on it
* reports its own endpoint link at full speed whatever the slot does upstream: a root port
* parked one speed down shows only at the root port (and in the card's DPM table). */
std::error_code ec;
const fs::path real = fs::canonical(dev, ec);
if (!ec) {
for (const fs::path& part : real) {
const std::string p = part.string();
if (!is_bdf(p)) continue;
const std::string hd = root + "/sys/bus/pci/devices/" + p;
PciHop h;
h.bdf = p;
h.cur_speed = line(hd + "/current_link_speed");
h.max_speed = line(hd + "/max_link_speed");
h.cur_width = (int)num(hd + "/current_link_width", -1);
h.max_width = (int)num(hd + "/max_link_width", -1);
c->chain.push_back(h);
}
}
if (c->chain.empty()) {
PciHop h;
h.bdf = bdf;
h.cur_speed = line(dev + "/current_link_speed");
h.max_speed = line(dev + "/max_link_speed");
h.cur_width = (int)num(dev + "/current_link_width", -1);
h.max_width = (int)num(dev + "/max_link_width", -1);
c->chain.push_back(h);
}
c->vram_total = num(dev + "/mem_info_vram_total", -1);
c->vram_visible = num(dev + "/mem_info_vis_vram_total", -1);
if (!pm) return;
c->busy_percent = (int)num(dev + "/gpu_busy_percent", -1);
{
std::istringstream in(slurp(dev + "/pp_dpm_pcie"));
std::string l;
while (std::getline(in, l)) {
l = trim(l);
if (l.empty()) continue;
if (l.find('*') != std::string::npos) c->dpm_pcie_cur = (int)c->dpm_pcie.size();
l.erase(std::remove(l.begin(), l.end(), '*'), l.end());
c->dpm_pcie.push_back(trim(l));
}
}
c->sclk = dpm_range(dev + "/pp_dpm_sclk");
c->mclk = dpm_range(dev + "/pp_dpm_mclk");
for (const std::string& h : list(dev + "/hwmon")) {
const std::string hp = dev + "/hwmon/" + h;
if (!exists(hp + "/power1_cap")) continue;
c->power_cap_uw = num(hp + "/power1_cap", -1);
c->power_cap_default_uw = num(hp + "/power1_cap_default", -1);
c->power_cap_max_uw = num(hp + "/power1_cap_max", -1);
break;
}
{
/* "OD_VDDGFX_OFFSET:\n-75mV": the offset the driver holds for the card, which is the one
* it uploads; whether the firmware took it is not in this file. */
const std::string od = slurp(dev + "/pp_od_clk_voltage");
const size_t at = od.find("OD_VDDGFX_OFFSET:");
if (at != std::string::npos) {
const char* p = od.c_str() + at + std::strlen("OD_VDDGFX_OFFSET:");
char* end = nullptr;
const long v = std::strtol(p, &end, 10);
if (end && end != p) c->vddgfx_offset = fmt("%ld mV", v);
}
}
}
/* The KFD topology knows what the PCI files do not: each GPU node's target and SIMD count, keyed
* by its PCI location -- `location_id` is (bus << 8) | (device << 3) | function. */
void read_kfd(const std::string& root, std::vector<CardFacts>* cards) {
const std::string nodes = root + "/sys/class/kfd/kfd/topology/nodes";
for (const std::string& n : list(nodes)) {
/* A LINE AT A TIME, and only the four keys this needs parsed: the file holds values no
* signed 64-bit integer takes (unique_id is a full 64-bit hash), and a stream extraction
* that meets one fails and stops reading every key after it. */
std::istringstream in(slurp(nodes + "/" + n + "/properties"));
std::string l;
long long loc = -1, dom = 0, gfx = 0, simd = -1;
while (std::getline(in, l)) {
const size_t sp = l.find_first_of(" \t");
if (sp == std::string::npos) continue;
const std::string k = l.substr(0, sp);
long long* into = k == "location_id" ? &loc
: k == "domain" ? &dom
: k == "gfx_target_version" ? &gfx
: k == "simd_count" ? &simd
: nullptr;
if (!into) continue;
const char* p = l.c_str() + sp + 1;
char* end = nullptr;
errno = 0;
const long long v = std::strtoll(p, &end, 10);
if (end != p && errno == 0) *into = v;
}
if (gfx <= 0 || loc < 0) continue;
const std::string bdf = fmt("%04llx:%02llx:%02llx.%llx", dom, (loc >> 8) & 0xff,
(loc >> 3) & 0x1f, loc & 7);
for (CardFacts& c : *cards) {
if (c.bdf != bdf) continue;
c.gfx = fmt("gfx%lld%llx%llx", gfx / 10000, (gfx / 100) % 100, gfx % 100);
c.simd = (int)simd;
}
}
}
/* Of two memory limits in HostFacts' encoding (bytes, -2 unlimited, -1 unknown), the one that
* binds: the smaller number, else unlimited over unknown. */
int64_t tighter(int64_t a, int64_t b) {
if (a >= 0 && b >= 0) return std::min(a, b);
if (a >= 0 || b >= 0) return std::max(a, b);
return a == -2 || b == -2 ? -2 : -1;
}
/* THE TIGHTEST MEMORY LIMIT FROM A CGROUP UP TO THE MOUNT'S ROOT. A limit binds every cgroup
* below it, so the process's own group can say "max" while the systemd slice or the container's
* group above it holds the limit that counts. `rel` is the path /proc/self/cgroup names, under
* `mount`; every level on the way up is read, the mount's root included -- inside a container's
* cgroup namespace that root is the container's own group. */
int64_t cgroup_limit(const std::string& mount, std::string rel, const char* file) {
int64_t lim = -1;
while (!rel.empty() && rel.back() == '/') rel.pop_back();
for (;;) {
const std::string v = line(mount + rel + "/" + file);
if (v == "max") {
lim = tighter(lim, -2);
} else if (!v.empty()) {
char* end = nullptr;
errno = 0;
const long long n = std::strtoll(v.c_str(), &end, 10);
/* Version 1 writes "no limit" as the largest page-aligned number below 2^63. */
if (end != v.c_str() && errno == 0 && n >= 0)
lim = tighter(lim, n >= ((long long)1 << 62) ? -2 : (int64_t)n);
}
if (rel.empty()) break;
const size_t up = rel.rfind('/');
rel.erase(up == std::string::npos ? 0 : up);
}
return lim;
}
void read_host(const std::string& root, HostFacts* h) {
{
std::istringstream in(slurp(root + "/proc/cpuinfo"));
std::string l;
std::set<std::pair<std::string, std::string>> cores;
std::string phys;
int threads = 0;
while (std::getline(in, l)) {
const size_t c = l.find(':');
if (c == std::string::npos) continue;
const std::string k = trim(l.substr(0, c)), v = trim(l.substr(c + 1));
if (k == "processor") ++threads;
else if (k == "model name" && h->cpu_model.empty()) h->cpu_model = v;
else if (k == "physical id") phys = v;
else if (k == "core id") cores.insert({ phys, v });
}
if (threads > 0) h->threads = threads;
if (!cores.empty()) h->cores = (int)cores.size();
}
{
std::istringstream in(slurp(root + "/proc/meminfo"));
std::string k;
long long v;
std::string unit;
while (in >> k >> v) {
std::getline(in, unit);
const int64_t b = (int64_t)v * 1024;
if (k == "MemTotal:") h->mem_total = b;
else if (k == "MemAvailable:") h->mem_available = b;
else if (k == "SwapTotal:") h->swap_total = b;
else if (k == "SwapFree:") h->swap_free = b;
}
}
h->kernel = line(root + "/proc/sys/kernel/osrelease");
{
std::istringstream in(slurp(root + "/etc/os-release"));
std::string l;
while (std::getline(in, l))
if (l.rfind("PRETTY_NAME=", 0) == 0) {
h->distro = l.substr(12);
if (h->distro.size() >= 2 && h->distro.front() == '"') h->distro = h->distro.substr(1, h->distro.size() - 2);
}
}
if (exists(root + "/.dockerenv")) h->container = "docker";
else if (exists(root + "/run/.containerenv")) h->container = "podman";
else {
const std::string cg = slurp(root + "/proc/1/cgroup");
if (cg.find("docker") != std::string::npos) h->container = "docker";
else if (cg.find("kubepods") != std::string::npos) h->container = "kubernetes";
else if (cg.find("containerd") != std::string::npos) h->container = "containerd";
}
{
/* THE PROCESS'S OWN CGROUP, which inside a container is "/" under its namespace, and
* every one above it: cgroup_limit says why. Version 2 is the "0::" line; version 1's
* memory controller is the ":memory:" one, where "unlimited" is a number near 2^63. */
std::istringstream in(slurp(root + "/proc/self/cgroup"));
std::string l;
int64_t lim = -1;
while (std::getline(in, l)) {
int64_t v = -1;
if (l.rfind("0::", 0) == 0)
v = cgroup_limit(root + "/sys/fs/cgroup", l.substr(3), "memory.max");
else if (l.find(":memory:") != std::string::npos)
v = cgroup_limit(root + "/sys/fs/cgroup/memory", l.substr(l.find(":memory:") + 8),
"memory.limit_in_bytes");
lim = tighter(lim, v);
}
h->cgroup_mem_limit = lim;
}
const std::string thp = root + "/sys/kernel/mm/transparent_hugepage";
h->thp_enabled = selected(thp + "/enabled");
h->thp_defrag = selected(thp + "/defrag");
h->thp_shmem = selected(thp + "/shmem_enabled");
{
std::istringstream in(line(root + "/proc/cmdline"));
std::string t;
static const char* const kKeep[] = { "iommu", "amd_iommu", "intel_iommu", "amdgpu.", "ttm.",
"transparent_hugepage", "hugepages", "pcie_aspm",
"pci=", "default_hugepagesz" };
while (in >> t)
for (const char* k : kKeep)
if (t.rfind(k, 0) == 0) { h->cmdline += (h->cmdline.empty() ? "" : " ") + t; break; }
}
{
/* PASSTHROUGH OR TRANSLATED, from what decides it for the cards: their IOMMU groups' type
* (identity is passthrough) is the kernel's own answer; the boot parameters and the
* presence of an IOMMU are what is left when a card has no group. */
const bool any_iommu = !list(root + "/sys/class/iommu").empty();
const bool groups = !list(root + "/sys/kernel/iommu_groups").empty();
const std::string cl = " " + h->cmdline + " ";
if (!any_iommu && !groups) {
h->iommu = "off";
h->iommu_why = "no IOMMU is registered (/sys/class/iommu is empty)";
} else if (cl.find(" iommu=pt ") != std::string::npos ||
cl.find(" amd_iommu=pt ") != std::string::npos ||
cl.find(" intel_iommu=pt ") != std::string::npos) {
h->iommu = "passthrough";
h->iommu_why = "iommu=pt on the kernel command line";
} else if (cl.find("iommu=off") != std::string::npos) {
h->iommu = "off";
h->iommu_why = "the kernel command line turns it off";
} else {
h->iommu = "unknown";
h->iommu_why = "an IOMMU is present; its mode is read from the cards' groups below";
}
}
{
int64_t lim = num(root + "/sys/module/ttm/parameters/pages_limit", -1);
/* 0 IS THE DRIVER'S DEFAULT, which is half of RAM. */
if (lim == 0 && h->mem_total > 0) lim = h->mem_total / 2 / h->page_size;
h->ttm_pages_limit = lim;
}
h->cwsr_enable = (int)num(root + "/sys/module/amdgpu/parameters/cwsr_enable", -1);
{
const int64_t d = num(root + "/proc/sys/kernel/io_uring_disabled", -1);
h->io_uring = d == 0 ? "available" : d == 1 ? "restricted to a group (io_uring_disabled 1)"
: d == 2 ? "refused (io_uring_disabled 2)" : "unknown";
}
const std::string cpu = root + "/sys/devices/system/cpu/cpu0/cpufreq";
h->cpu_governor = line(cpu + "/scaling_governor");
h->cpu_epp = line(cpu + "/energy_performance_preference");
h->cpu_driver = line(cpu + "/scaling_driver");
}
} /* namespace */
Facts collect(const std::string& root, const std::vector<std::string>* managed) {
Facts f;
if (root.empty()) {
const long ps = sysconf(_SC_PAGE_SIZE);
if (ps > 0) f.host.page_size = ps;
}
read_host(root, &f.host);
/* EVERY DISPLAY-CLASS DEVICE, the engine's or not: an integrated GPU beside the cards, or a
* card the engine was told not to use, is part of the answer to "what is in this machine". */
for (const std::string& d : list(root + "/sys/bus/pci/devices")) {
const std::string cls = line(root + "/sys/bus/pci/devices/" + d + "/class");
if (cls.rfind("0x03", 0) != 0) continue;
const bool pm =
!managed || std::find(managed->begin(), managed->end(), d) != managed->end();
CardFacts c;
read_card(root, d, pm, &c);
f.cards.push_back(std::move(c));
}
read_kfd(root, &f.cards);
/* THE IOMMU'S MODE AS THE CARDS SEE IT, which beats the command line where both exist: each
* card's group says identity (passthrough) or DMA / DMA-FQ (translated), and a machine can
* hold both -- an integrated GPU left identity-mapped beside a translated discrete card. */
if (f.host.iommu == "unknown") {
std::map<std::string, std::string> by;
for (const CardFacts& c : f.cards)
if (!c.iommu_type.empty()) by[c.iommu_type] += (by[c.iommu_type].empty() ? "" : ", ") + c.bdf;
if (by.size() == 1) {
const bool id = by.begin()->first == "identity";
f.host.iommu = id ? "passthrough" : "translated";
f.host.iommu_why = "the display devices' IOMMU groups are of type " + by.begin()->first;
} else if (by.size() > 1) {
f.host.iommu = "mixed";
f.host.iommu_why.clear();
for (const auto& [t, bdfs] : by)
f.host.iommu_why += (f.host.iommu_why.empty() ? "" : "; ") + t + " for " + bdfs;
}
}
return f;
}
void probe_process(HostFacts* h) {
struct rlimit rl{};
if (getrlimit(RLIMIT_MEMLOCK, &rl) == 0)
h->memlock_soft = rl.rlim_cur == RLIM_INFINITY ? -2 : (int64_t)rl.rlim_cur;
#ifdef SYS_io_uring_setup
/* ASKED, NOT INFERRED: a seccomp profile (Docker's default) refuses the call whatever the
* sysctl says, and the answer is the error the call returns. One entry, closed at once. */
struct { uint32_t sq_entries, cq_entries, flags, sq_thread_cpu, sq_thread_idle, features,
wq_fd, resv[3]; uint64_t sq_off[5]; uint64_t cq_off[5]; } p{};
static_assert(sizeof(p) == 120, "io_uring_params is 120 bytes");
const long fd = syscall(SYS_io_uring_setup, 1, &p);
if (fd >= 0) {
close((int)fd);
h->io_uring = "available";
} else {
h->io_uring = fmt("refused (%s)", std::strerror(errno));
}
#endif
}
std::vector<std::string> env_names(char* const* env, const char* prefix) {
std::vector<std::string> out;
const size_t n = std::strlen(prefix);
for (char* const* e = env; e && *e; ++e) {
if (std::strncmp(*e, prefix, n) != 0) continue;
const char* eq = std::strchr(*e, '=');
out.emplace_back(*e, eq ? (size_t)(eq - *e) : std::strlen(*e));
}
std::sort(out.begin(), out.end());
return out;
}
} /* namespace diag */
} /* namespace rad */