Lightweight server monitoring with historical data, docker stats, and alerts.
fix(agent): only add AMD GTT memory on unified memory devices (#2715)
alexcastgonz74c60849afb3
diff --git a/agent/gpu_amd_linux.go b/agent/gpu_amd_linux.goindex bd751c889..bc5b3ae43 100644--- a/agent/gpu_amd_linux.go+++ b/agent/gpu_amd_linux.go@@ -6,6 +6,8 @@ import ("bufio""errors""fmt"+ "io"+ "io/fs""log/slog""os""path/filepath"@@ -102,6 +104,80 @@ func isAmdGpu(cardPath string) bool {return vendor == "0x1002"}+// unifiedMemoryMaxVram is the dedicated VRAM size below which a device without a+// gpu_metrics table is taken for an APU (typical carve-out sizes are 512 MiB to 1 GiB).+const unifiedMemoryMaxVram = 2 << 30++// amdMemoryKind is the cached result of classifying an AMD device's memory.+type amdMemoryKind uint8++const (+ amdMemoryUnknown amdMemoryKind = iota // not classified yet; gpu_metrics is read again on the next poll+ amdMemoryDiscrete // gpu_metrics format revision 1+ amdMemoryUnified // gpu_metrics format revision 2 or 3+ amdMemoryBySize // no usable gpu_metrics table; decide by dedicated VRAM size+)++// amdMemoryKindCache holds the memory kind per device path, since it never changes for a device.+var amdMemoryKindCache = struct {+ sync.Mutex+ kinds map[string]amdMemoryKind+}{kinds: make(map[string]amdMemoryKind)}++// amdGpuIsUnifiedMemory reports whether the device shares memory with the CPU (an APU).+// The gpu_metrics header is read only until it yields a stable answer, which is then cached.+func amdGpuIsUnifiedMemory(devicePath string, vramTotal float64) bool {+ amdMemoryKindCache.Lock()+ kind := amdMemoryKindCache.kinds[devicePath]+ amdMemoryKindCache.Unlock()++ if kind == amdMemoryUnknown {+ kind = detectAmdMemoryKind(devicePath)+ if kind != amdMemoryUnknown {+ amdMemoryKindCache.Lock()+ amdMemoryKindCache.kinds[devicePath] = kind+ amdMemoryKindCache.Unlock()+ }+ }++ switch kind {+ case amdMemoryDiscrete:+ return false+ case amdMemoryUnified:+ return true+ default:+ // No gpu_metrics table (older ASICs) or a transient read failure: fall back to the+ // size of the dedicated VRAM. A failed VRAM read (0) is not taken for an APU.+ return vramTotal > 0 && vramTotal < unifiedMemoryMaxVram+ }+}++// detectAmdMemoryKind classifies a device from its gpu_metrics table.+//+// amdgpu exposes the gpu_metrics table in sysfs, whose first four bytes are a+// metrics_table_header (u16 structure_size, u8 format_revision, u8 content_revision).+// Format revision 1 is used by discrete cards (gpu_metrics_v1_x), 2 and 3 by APUs+// (gpu_metrics_v2_x / v3_x). Returns amdMemoryUnknown only for failures that may be+// transient, so the table is read again on the next poll.+func detectAmdMemoryKind(devicePath string) amdMemoryKind {+ header := make([]byte, 4)+ n, err := readSysfsHead(filepath.Join(devicePath, "gpu_metrics"), header)+ switch {+ case err == nil && n == len(header):+ switch header[2] {+ case 1:+ return amdMemoryDiscrete+ case 2, 3:+ return amdMemoryUnified+ }+ return amdMemoryBySize+ case err == nil, errors.Is(err, fs.ErrNotExist), errors.Is(err, syscall.EOPNOTSUPP):+ // short table, no table, or not supported by this ASIC: none of these change at runtime+ return amdMemoryBySize+ }+ return amdMemoryUnknown+}+// updateAmdGpuData reads GPU metrics from sysfs and updates the GPU data map.// Returns true if at least some data was successfully read.func (gm *GPUManager) updateAmdGpuData(cardPath string) bool {@@ -112,11 +188,15 @@ func (gm *GPUManager) updateAmdGpuData(cardPath string) bool {usage, usageErr := readSysfsFloat(filepath.Join(devicePath, "gpu_busy_percent"))memUsed, memUsedErr := readSysfsFloat(filepath.Join(devicePath, "mem_info_vram_used"))memTotal, _ := readSysfsFloat(filepath.Join(devicePath, "mem_info_vram_total"))- // if gtt is present, add it to the memory used and total (https://github.com/henrygd/beszel/issues/1569#issuecomment-3837640484)- if gttUsed, err := readSysfsFloat(filepath.Join(devicePath, "mem_info_gtt_used")); err == nil && gttUsed > 0 {- if gttTotal, err := readSysfsFloat(filepath.Join(devicePath, "mem_info_gtt_total")); err == nil {- memUsed += gttUsed- memTotal += gttTotal+ // On a unified memory device (APU) the GPU mostly uses system memory through GTT, so add it to the+ // memory used and total (https://github.com/henrygd/beszel/issues/1569#issuecomment-3837640484).+ // On a discrete card GTT is just mappable system RAM, not VRAM, and must not inflate the numbers.+ if amdGpuIsUnifiedMemory(devicePath, memTotal) {+ if gttUsed, err := readSysfsFloat(filepath.Join(devicePath, "mem_info_gtt_used")); err == nil && gttUsed > 0 {+ if gttTotal, err := readSysfsFloat(filepath.Join(devicePath, "mem_info_gtt_total")); err == nil {+ memUsed += gttUsed+ memTotal += gttTotal+ }}}@@ -175,6 +255,34 @@ func readSysfsFloat(path string) (float64, error) {return strconv.ParseFloat(val, 64)}+// readSysfsHead reads up to len(buf) bytes from the start of a binary sysfs file,+// honoring the same backoff as readSysfsFloat. A file shorter than buf is not an error.+func readSysfsHead(path string, buf []byte) (int, error) {+ now := time.Now()+ if !amdSysfsBackoff.allow(path, now) {+ return 0, errSysfsBackoff+ }+ n, err := readFileHead(path, buf)+ amdSysfsBackoff.record(path, err, time.Since(now), now)+ if err != nil {+ slog.Debug("Failed to read sysfs file", "path", path, "error", err)+ }+ return n, err+}++func readFileHead(path string, buf []byte) (int, error) {+ f, err := os.Open(path)+ if err != nil {+ return 0, err+ }+ defer f.Close()+ n, err := io.ReadFull(f, buf)+ if errors.Is(err, io.EOF) || errors.Is(err, io.ErrUnexpectedEOF) {+ err = nil+ }+ return n, err+}+const (// sysfsSlowReadThreshold is how long a read may take to fail before the file is backed off.// Healthy amdgpu reads take well under a millisecond.diff --git a/agent/gpu_amd_linux_test.go b/agent/gpu_amd_linux_test.goindex 9b43dcf20..b27e8736e 100644--- a/agent/gpu_amd_linux_test.go+++ b/agent/gpu_amd_linux_test.go@@ -6,6 +6,7 @@ import ("os""path/filepath""runtime"+ "strconv""syscall""testing""time"@@ -257,23 +258,77 @@ func TestAmdgpuNameCacheRoundTrip(t *testing.T) {}func TestUpdateAmdGpuDataWithFakeSysfs(t *testing.T) {+ const gib = 1 << 30+ // gpu_metrics starts with metrics_table_header: u16 structure_size, u8 format_revision, u8 content_revision+ metrics := func(formatRevision byte) []byte { return []byte{0x68, 0x00, formatRevision, 0x00} }+tests := []struct {name string- writeGTT bool+ gpuMetrics []byte // nil: no gpu_metrics file+ vramUsed int64+ vramTotal int64+ gttUsed int64 // 0: no gtt files+ gttTotal int64wantMemoryUsed float64wantMemoryTotal float64}{{- name: "sums vram and gtt when gtt is present",- writeGTT: true,- wantMemoryUsed: utils.BytesToMegabytes(1073741824 + 536870912),- wantMemoryTotal: utils.BytesToMegabytes(2147483648 + 4294967296),+ // Strix Halo style APU (issue 1569): 1 GiB carve-out, huge GTT+ name: "apu sums vram and gtt",+ gpuMetrics: metrics(2),+ vramUsed: gib / 4,+ vramTotal: gib,+ gttUsed: gib / 2,+ gttTotal: 96 * gib,+ wantMemoryUsed: utils.BytesToMegabytes(gib/4 + gib/2),+ wantMemoryTotal: utils.BytesToMegabytes(gib + 96*gib),+ },+ {+ name: "gpu_metrics v3 is an apu too",+ gpuMetrics: metrics(3),+ vramUsed: gib / 4,+ vramTotal: gib,+ gttUsed: gib / 2,+ gttTotal: 4 * gib,+ wantMemoryUsed: utils.BytesToMegabytes(gib/4 + gib/2),+ wantMemoryTotal: utils.BytesToMegabytes(gib + 4*gib),+ },+ {+ // RX 5700 XT style card (issue 2682): GTT is system RAM, not VRAM+ name: "discrete card ignores gtt",+ gpuMetrics: metrics(1),+ vramUsed: gib / 2,+ vramTotal: 8 * gib,+ gttUsed: 21 << 20,+ gttTotal: 15*gib + 700<<20,+ wantMemoryUsed: utils.BytesToMegabytes(gib / 2),+ wantMemoryTotal: utils.BytesToMegabytes(8 * gib),+ },+ {+ name: "no gpu_metrics and large vram is a discrete card",+ vramUsed: gib,+ vramTotal: 8 * gib,+ gttUsed: gib / 2,+ gttTotal: 16 * gib,+ wantMemoryUsed: utils.BytesToMegabytes(gib),+ wantMemoryTotal: utils.BytesToMegabytes(8 * gib),+ },+ {+ name: "no gpu_metrics and small vram is an apu",+ vramUsed: gib / 4,+ vramTotal: gib,+ gttUsed: gib / 2,+ gttTotal: 4 * gib,+ wantMemoryUsed: utils.BytesToMegabytes(gib/4 + gib/2),+ wantMemoryTotal: utils.BytesToMegabytes(gib + 4*gib),},{name: "falls back to vram when gtt is missing",- writeGTT: false,- wantMemoryUsed: utils.BytesToMegabytes(1073741824),- wantMemoryTotal: utils.BytesToMegabytes(2147483648),+ gpuMetrics: metrics(2),+ vramUsed: gib,+ vramTotal: 2 * gib,+ wantMemoryUsed: utils.BytesToMegabytes(gib),+ wantMemoryTotal: utils.BytesToMegabytes(2 * gib),},}@@ -292,11 +347,14 @@ func TestUpdateAmdGpuDataWithFakeSysfs(t *testing.T) {write("device", "0x1506")write("revision", "0xc1")write("gpu_busy_percent", "25")- write("mem_info_vram_used", "1073741824")- write("mem_info_vram_total", "2147483648")- if tt.writeGTT {- write("mem_info_gtt_used", "536870912")- write("mem_info_gtt_total", "4294967296")+ write("mem_info_vram_used", strconv.FormatInt(tt.vramUsed, 10))+ write("mem_info_vram_total", strconv.FormatInt(tt.vramTotal, 10))+ if tt.gttUsed > 0 {+ write("mem_info_gtt_used", strconv.FormatInt(tt.gttUsed, 10))+ write("mem_info_gtt_total", strconv.FormatInt(tt.gttTotal, 10))+ }+ if tt.gpuMetrics != nil {+ require.NoError(t, os.WriteFile(filepath.Join(devicePath, "gpu_metrics"), tt.gpuMetrics, 0o644))}require.NoError(t, os.WriteFile(filepath.Join(hwmonPath, "temp1_input"), []byte("45000"), 0o644))require.NoError(t, os.WriteFile(filepath.Join(hwmonPath, "power1_input"), []byte("20000000"), 0o644))@@ -321,6 +379,58 @@ func TestUpdateAmdGpuDataWithFakeSysfs(t *testing.T) {}}+func TestAmdGpuIsUnifiedMemoryCaching(t *testing.T) {+ const gib = 1 << 30+ metrics := func(formatRevision byte) []byte { return []byte{0x68, 0x00, formatRevision, 0x00} }++ t.Run("gpu_metrics result is cached", func(t *testing.T) {+ devicePath := t.TempDir()+ metricsPath := filepath.Join(devicePath, "gpu_metrics")+ require.NoError(t, os.WriteFile(metricsPath, metrics(2), 0o644))++ assert.True(t, amdGpuIsUnifiedMemory(devicePath, 8*gib))+ // the table is not read again, so a changed (or removed) file has no effect+ require.NoError(t, os.WriteFile(metricsPath, metrics(1), 0o644))+ assert.True(t, amdGpuIsUnifiedMemory(devicePath, 8*gib))+ require.NoError(t, os.Remove(metricsPath))+ assert.True(t, amdGpuIsUnifiedMemory(devicePath, 8*gib))+ })++ t.Run("missing gpu_metrics caches size fallback", func(t *testing.T) {+ devicePath := t.TempDir()+ assert.True(t, amdGpuIsUnifiedMemory(devicePath, gib))+ assert.False(t, amdGpuIsUnifiedMemory(devicePath, 8*gib), "size is re-evaluated each poll")+ // a table appearing later is ignored: the fallback was cached+ require.NoError(t, os.WriteFile(filepath.Join(devicePath, "gpu_metrics"), metrics(2), 0o644))+ assert.False(t, amdGpuIsUnifiedMemory(devicePath, 8*gib))+ })++ t.Run("failed vram read is not taken for an apu", func(t *testing.T) {+ assert.False(t, amdGpuIsUnifiedMemory(t.TempDir(), 0))+ })++ t.Run("transient read failure is retried", func(t *testing.T) {+ devicePath := t.TempDir()+ metricsPath := filepath.Join(devicePath, "gpu_metrics")+ // opening a directory succeeds but reading it fails with EISDIR+ require.NoError(t, os.Mkdir(metricsPath, 0o755))+ assert.False(t, amdGpuIsUnifiedMemory(devicePath, 8*gib), "falls back to size while unreadable")++ require.NoError(t, os.Remove(metricsPath))+ require.NoError(t, os.WriteFile(metricsPath, metrics(2), 0o644))+ assert.True(t, amdGpuIsUnifiedMemory(devicePath, 8*gib), "table is read again after a failure")+ })++ t.Run("unknown or short table falls back to size", func(t *testing.T) {+ for _, data := range [][]byte{metrics(9), {0x68, 0x00}} {+ devicePath := t.TempDir()+ require.NoError(t, os.WriteFile(filepath.Join(devicePath, "gpu_metrics"), data, 0o644))+ assert.True(t, amdGpuIsUnifiedMemory(devicePath, gib))+ assert.False(t, amdGpuIsUnifiedMemory(devicePath, 8*gib))+ }+ })+}+func TestLookupAmdgpuNameInFile(t *testing.T) {idsPath := filepath.Join("test-data", "amdgpu.ids")