Compare commits

..
3 Commits
Author SHA1 Message Date
waoziandClaude Opus 5.5 3b32a6b3d8 Package with a local toolchain override as release CI does
Ziran refuses --locked next to ziran.local.toml, which the release job
writes for its locked toolchain, so the packaging step failed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-13 22:55:56 -03:00
waoziandClaude Opus 5.5 5a564ca3d1 Release Task Manager 0.1.3 as .deb and AppImage
The Linux tarball could not start elsewhere: the binary needs
libkryonavif.so, which it found only through an absolute RUNPATH into the
build machine's Ziran cache. scripts/package-linux.sh stages the app with
`ziran install --prefix`, moves build-produced libraries to /usr/lib/BIN,
sets RUNPATH $ORIGIN/../lib/BIN, rewrites the desktop entry and builds a
Debian package (dependencies from dpkg-shlibdeps) and a linuxdeploy
AppImage. Release assets use version-free names so
/releases/latest/download links stay stable. Task Manager gets its own
icon, which the AppImage requires.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-13 22:49:08 -03:00
waoziandClaude Opus 5.5 0e72f05ff5 Show per-window usage and NVIDIA GPU readings
The Applications tab gains CPU, Memory and GPU columns that total each
window's process tree: its _NET_WM_PID plus every descendant no nearer
listed window owns.

NVIDIA's driver has no per-process DRM fdinfo or sysfs GPU counters, and
loading NVML in-process keeps ~16 MB of private memory. The binary now
runs itself as `--gpu-helper`, a display-free NVML sampler that streams
per-process shares and whole-card usage/VRAM while the Applications or
Performance tab is open. The Performance tab matches those readings to
DRM cards by PCI address, so NVIDIA cards no longer show n/a.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-13 22:40:42 -03:00
14 changed files with 1263 additions and 34 deletions

No files matched your search

+20 -11
View File
@@ -43,7 +43,19 @@ jobs:
build-essential cmake nasm meson ninja-build pkg-config \
libsdl2-dev libgl1-mesa-dev libx11-dev \
libcairo2-dev libpango1.0-dev libfontconfig1-dev libfreetype6-dev \
xvfb xfwm4 xterm x11-utils
xvfb xfwm4 xterm x11-utils \
patchelf dpkg-dev file
- name: Fetch linuxdeploy
run: |
set -eu
mkdir -p "$RUNNER_TEMP/linuxdeploy"
tool="$RUNNER_TEMP/linuxdeploy/linuxdeploy-x86_64.AppImage"
curl -fsSL -o "$tool" \
https://github.com/linuxdeploy/linuxdeploy/releases/download/1-alpha-20251107-1/linuxdeploy-x86_64.AppImage
echo "c20cd71e3a4e3b80c3483cef793cda3f4e990aca14014d23c544ca3ce1270b4d $tool" | sha256sum -c -
chmod 755 "$tool"
echo "LINUXDEPLOY=$tool" >> "$GITHUB_ENV"
- name: Build locked Ziran
working-directory: ziran
@@ -56,18 +68,16 @@ jobs:
-u DBUS_SESSION_BUS_ADDRESS -u SESSION_MANAGER \
HARMONY_DESKTOP_RECOVERY=0 make check test x11-test
- name: Package Linux binary
# Version-free names keep /releases/latest/download/<name> links stable.
- name: Package Debian and AppImage
id: package
run: |
set -eu
version=$(cat VERSION)
tag="v$version"
package="taskmgr-linux-x86_64-$tag"
mkdir -p "dist/$package/bin"
cp build/taskmgr-desktop "dist/$package/bin/taskmgr"
cp README.md CHANGELOG.md "dist/$package/"
tar -C dist -czf "dist/$package.tar.gz" "$package"
sha256sum "dist/$package.tar.gz" > dist/SHA256SUMS
make package
(cd dist && sha256sum taskmgr-linux-amd64.deb taskmgr-linux-x86_64.AppImage > SHA256SUMS)
dpkg-deb -I dist/taskmgr-linux-amd64.deb
if git rev-parse "$tag" >/dev/null 2>&1; then
echo "release=false" >> "$GITHUB_OUTPUT"
else
@@ -75,7 +85,6 @@ jobs:
fi
echo "version=$version" >> "$GITHUB_OUTPUT"
echo "tag=$tag" >> "$GITHUB_OUTPUT"
echo "asset=dist/$package.tar.gz" >> "$GITHUB_OUTPUT"
- name: Publish new version
if: steps.package.outputs.release == 'true'
@@ -83,7 +92,6 @@ jobs:
GH_TOKEN: ${{ github.token }}
VERSION: ${{ steps.package.outputs.version }}
TAG: ${{ steps.package.outputs.tag }}
ASSET: ${{ steps.package.outputs.asset }}
run: |
set -eu
notes=$(awk -v v="$VERSION" '$0 ~ "^## \\[" v "\\]" {found=1; next} found && /^## / {exit} found' CHANGELOG.md)
@@ -92,5 +100,6 @@ jobs:
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
git tag -a "$TAG" -m "Task Manager $VERSION"
git push origin "$TAG"
gh release create "$TAG" "$ASSET" dist/SHA256SUMS \
gh release create "$TAG" dist/taskmgr-linux-amd64.deb \
dist/taskmgr-linux-x86_64.AppImage dist/SHA256SUMS \
--title "Task Manager $VERSION" --notes "$notes"
+1
View File
@@ -1,2 +1,3 @@
build/
ziran.local.toml
dist/
+19
View File
@@ -2,6 +2,25 @@
## [Unreleased]
## [0.1.3] - 2026-11-13
### Added
- Debian package (`taskmgr-linux-amd64.deb`) and AppImage
(`taskmgr-linux-x86_64.AppImage`) downloads replace the Linux tarball, which
could not start on other machines because it lacked a Kryon library. Task
Manager also has its own icon.
- The Applications tab shows CPU, memory and GPU use for each window, counting
the window's whole process tree (a browser's helper processes count toward
the browser). GPU use comes from NVIDIA's driver through a small helper that
runs only while the Applications or Performance tab is open; other GPUs
show `n/a`.
### Fixed
- The Performance tab shows GPU usage and VRAM for NVIDIA cards instead of
`n/a`.
## [0.1.2] - 2026-11-13
### Changed
+7 -1
View File
@@ -4,7 +4,7 @@ ZIRAN ?= ./scripts/ziran.sh
export LDLIBS += -lX11
SOURCES := $(wildcard src/*.zi) $(wildcard tests/*.zi) ziran.toml ziran.lock scripts/ziran.sh Makefile
.PHONY: all build run check test x11-test memory-test shot clean
.PHONY: all build run check test x11-test memory-test shot package clean
all: build
@@ -36,6 +36,12 @@ x11-test: build build/windows-test
memory-test: build
./scripts/memory-test.sh
# dist/taskmgr-linux-amd64.deb and dist/taskmgr-linux-x86_64.AppImage. The
# AppImage needs LINUXDEPLOY; see scripts/package-linux.sh.
PACKAGE_FORMAT ?= all
package: build
./scripts/package-linux.sh $(PACKAGE_FORMAT) "$$(cat VERSION)" dist
# One rendered frame without a display; useful for interface checks.
shot: build
$(ZIRAN) tool kryon run --profile shot > build/taskmgr.ppm
+21 -3
View File
@@ -13,7 +13,13 @@ bar, Applications / Processes / Performance tabs, bordered content and the
three-pane status bar.
- **Applications** lists top-level EWMH windows and can switch to one, request
that it close, or open a new command.
that it close, or open a new command. CPU, Memory and GPU columns total each
window's process tree: its `_NET_WM_PID` plus every descendant that no
nearer listed window owns. Windows without a PID show `-`. GPU shares come
from NVML on NVIDIA's driver, sampled by `taskmgr --gpu-helper`, a
display-free child of the same binary that runs only while this tab or
Performance is open,
so NVML's memory never enters the window process; other drivers show `n/a`.
- **Processes** is a sortable DataViews table with image name, PID, CPU, CPU
time and resident memory. Rows are grouped by image name by default, with all
Codex-family processes combined under `codex`; Options → Group Processes
@@ -25,8 +31,11 @@ three-pane status bar.
Windows-style colored lines on black, plus process, thread, handle,
physical-memory, commit and kernel-memory totals. Every detected DRM card
has a stable `cardN` label, distinct graph color and independent GPU/VRAM
reading; unsupported counters display `n/a`. Memory values use explicit
adaptive B, KB, MB, GB or TB units.
reading; unsupported counters display `n/a`. NVIDIA's driver has no sysfs
GPU counters, so its cards use the same `--gpu-helper` NVML samples as the
Applications tab, matched to `cardN` by PCI address, while this tab or
Applications is open. Memory values use explicit adaptive B, KB, MB, GB or
TB units.
- File, Options, View and Help menus provide Run, refresh speed, manual refresh,
kernel-time display, process grouping, end-process confirmation and About
actions.
@@ -53,8 +62,17 @@ make x11-test # native app and Applications actions on a private Xvfb display
make memory-test # steady native RSS on private Xvfb; must stay below 30 MiB
make shot # render one frame to build/taskmgr.ppm
make check # compile every module
make package # dist/taskmgr-linux-amd64.deb and dist/taskmgr-linux-x86_64.AppImage
```
`make package` stages the app with `ziran install`, moves libraries the build
produced (such as `libkryonavif.so`) to `/usr/lib/taskmgr` and points the
program's RUNPATH there. It needs `patchelf`, `dpkg-deb`, `dpkg-shlibdeps` and,
for the AppImage, `LINUXDEPLOY` set to a linuxdeploy AppImage. The release
workflow publishes both files under these version-free names, so
`https://github.com/kryonlabs/taskmgr/releases/latest/download/taskmgr-linux-amd64.deb`
and `.../taskmgr-linux-x86_64.AppImage` always fetch the newest release.
`make x11-test` never touches the current desktop. It needs `Xvfb`, `xfwm4`
(or `X11_TEST_WM`), `xterm` and `xprop`; when one is absent it reports a skip.
`make memory-test` likewise uses only a scrubbed private Xvfb display, waits for
+1 -1
View File
@@ -1 +1 @@
0.1.2
0.1.3
+9
View File
@@ -0,0 +1,9 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64">
<rect x="4" y="8" width="56" height="48" rx="7" fill="#1e2530"/>
<path d="M11 8h42a7 7 0 0 1 7 7v4H4v-4a7 7 0 0 1 7-7z" fill="#2f6fdb"/>
<circle cx="11" cy="13.5" r="2" fill="#dbe6fb"/>
<rect x="10" y="24" width="44" height="26" rx="2" fill="#05080c"/>
<path d="M10 37h44M21 24v26M32 24v26M43 24v26" stroke="#0f3d22" stroke-width="1"/>
<polyline points="12,45 19,41 25,46 32,30 38,37 44,28 52,33" fill="none" stroke="#2fd05f"
stroke-width="3" stroke-linejoin="round" stroke-linecap="round"/>
</svg>

After

Width:  |  Height:  |  Size: 599 B

+181
View File
@@ -0,0 +1,181 @@
#!/bin/sh
# Linux packages for a Kryon desktop app: a Debian package and an AppImage.
#
# scripts/package-linux.sh deb|appimage|all VERSION [OUTPUT]
#
# Run from the project root after the native build. The app is staged with
# `ziran install --prefix`, so the layout is Kryon's own: /usr/bin/BIN,
# /usr/share/kryon/BIN and a desktop entry. Libraries the build produced
# rather than the system (libkryonavif.so) move to /usr/lib/BIN, and the
# program's RUNPATH becomes $ORIGIN/../lib/BIN, so several Kryon apps install
# side by side without sharing a file.
#
# Output names carry no version, so a release's
# /releases/latest/download/BIN-linux-amd64.deb
# /releases/latest/download/BIN-linux-x86_64.AppImage
# always point at the newest build.
#
# Needs python3 and patchelf; deb also needs dpkg-deb and dpkg-shlibdeps;
# appimage needs LINUXDEPLOY, the path of a linuxdeploy AppImage, and an icon
# file in [tool.kryon.install] icon.
set -eu
usage() {
echo "usage: package-linux.sh deb|appimage|all VERSION [OUTPUT]" >&2
exit 64
}
[ $# -ge 2 ] || usage
format=$1
version=$2
output=${3:-dist}
case "$format" in deb|appimage|all) ;; *) usage ;; esac
case "$version" in ''|*[!0-9A-Za-z.+~-]*) echo "package-linux: invalid version '$version'" >&2; exit 64 ;; esac
ZIRAN=${ZIRAN:-./scripts/ziran.sh}
PATCHELF=${PATCHELF:-patchelf}
root=$(pwd)
# One shell assignment per line, values quoted for eval.
metadata=$(python3 -I - <<'PY'
import shlex, tomllib
with open("ziran.toml", "rb") as handle:
project = tomllib.load(handle)
package = project.get("package", {})
install = project.get("install", {})
kryon = project.get("tool", {}).get("kryon", {}).get("install", {})
name = package.get("name", "")
values = {
"bin": install.get("bin") or name,
"display": kryon.get("name") or install.get("bin") or name,
"comment": kryon.get("comment", ""),
"icon_file": kryon.get("icon", ""),
}
for key, value in values.items():
print(f"{key}={shlex.quote(str(value))}")
PY
)
eval "$metadata"
case "$bin" in ''|*[!0-9A-Za-z._-]*) echo "package-linux: invalid program name '$bin'" >&2; exit 65 ;; esac
mkdir -p "$output" build
output=$(CDPATH= cd -- "$output" && pwd)
stage=$(mktemp -d "$root/build/package.XXXXXX")
trap 'rm -rf "$stage"' EXIT INT TERM
prefix=$stage/root/usr
# Kryon's install also writes an autostart entry when asked; keep it inside
# the stage instead of the packager's own configuration. Ziran refuses
# --locked next to a ziran.local.toml override (as release CI uses).
lock_flag=--locked
[ ! -f ziran.local.toml ] || lock_flag=
# shellcheck disable=SC2086
XDG_CONFIG_HOME=$stage/config "$ZIRAN" install --prefix "$prefix" $lock_flag >/dev/null
program=$prefix/bin/$bin
[ -x "$program" ] || { echo "package-linux: $program was not installed" >&2; exit 66; }
# Libraries outside the system library directories came from the build.
private=$prefix/lib/$bin
mkdir -p "$private"
ldd "$program" | awk '$2 == "=>" && $3 ~ /^\// { print $3 }' | while read -r library; do
case "$library" in
/lib/*|/lib64/*|/usr/lib/*|/usr/lib64/*) ;;
*) cp -L "$library" "$private/" ;;
esac
done
missing=$(ldd "$program" | awk '/not found/ { print $1 }')
[ -z "$missing" ] || { echo "package-linux: unresolved libraries: $missing" >&2; exit 67; }
"$PATCHELF" --set-rpath "\$ORIGIN/../lib/$bin" "$program"
for library in "$private"/*; do
[ -f "$library" ] || continue
chmod 644 "$library"
"$PATCHELF" --set-rpath '$ORIGIN' "$library"
done
rmdir "$private" 2>/dev/null || true
# The desktop entry names the program and icon instead of the stage paths.
desktop=$prefix/share/applications/$bin.desktop
icon=""
if [ -n "$icon_file" ]; then
icon=$(ls "$prefix/share/pixmaps/$bin".* 2>/dev/null | head -n 1)
fi
python3 -I - "$desktop" "$prefix" "$bin" <<'PY'
import sys
path, prefix, name = sys.argv[1:4]
lines = []
with open(path, encoding="utf-8") as handle:
for line in handle.read().splitlines():
if line.startswith("Exec="):
line = "Exec=" + name
elif line.startswith("Icon=") and line[5:].startswith(prefix):
line = "Icon=" + name
elif line.startswith("Path=") or line.startswith("X-Kryon-Installed="):
continue
lines.append(line)
with open(path, "w", encoding="utf-8") as handle:
handle.write("\n".join(lines) + "\n")
PY
build_deb() {
debroot=$stage/deb
mkdir -p "$debroot/DEBIAN"
cp -a "$stage/root/usr" "$debroot/usr"
shlib=$stage/shlibdeps
mkdir -p "$shlib/debian"
printf 'Source: %s\n\nPackage: %s\nArchitecture: any\n' "$bin" "$bin" > "$shlib/debian/control"
objects="$debroot/usr/bin/$bin"
search=""
if [ -d "$debroot/usr/lib/$bin" ]; then
search="-l$debroot/usr/lib/$bin"
for library in "$debroot/usr/lib/$bin"/*; do objects="$objects $library"; done
fi
# shellcheck disable=SC2086
depends=$(cd "$shlib" && dpkg-shlibdeps -O $search $objects 2>/dev/null |
sed -n 's/^shlibs:Depends=//p')
size=$(du -sk "$debroot/usr" | cut -f1)
{
echo "Package: $bin"
echo "Version: $version"
echo "Architecture: amd64"
echo "Maintainer: Kryon Labs <https://github.com/kryonlabs>"
echo "Installed-Size: $size"
[ -z "$depends" ] || echo "Depends: $depends"
echo "Section: utils"
echo "Priority: optional"
echo "Homepage: https://github.com/kryonlabs/$bin"
echo "Description: $display${comment:+ - $comment}"
echo " $display, a Kryon desktop application."
} > "$debroot/DEBIAN/control"
find "$debroot" -type d -exec chmod 755 {} +
dpkg-deb --root-owner-group --build "$debroot" "$output/$bin-linux-amd64.deb" >/dev/null
echo "$output/$bin-linux-amd64.deb"
}
build_appimage() {
: "${LINUXDEPLOY:?set LINUXDEPLOY to a linuxdeploy AppImage}"
[ -n "$icon" ] || { echo "package-linux: an AppImage needs [tool.kryon.install] icon" >&2; exit 68; }
appdir=$stage/AppDir
mkdir -p "$appdir"
cp -a "$stage/root/usr" "$appdir/usr"
work=$stage/appimage
mkdir -p "$work"
target=$bin-linux-x86_64.AppImage
(
cd "$work"
APPIMAGE_EXTRACT_AND_RUN=1 NO_STRIP=1 ARCH=x86_64 \
LINUXDEPLOY_OUTPUT_VERSION="$version" LDAI_OUTPUT="$target" OUTPUT="$target" \
"$LINUXDEPLOY" --appdir "$appdir" --executable "$appdir/usr/bin/$bin" \
--desktop-file "$appdir/usr/share/applications/$bin.desktop" \
--icon-file "$icon" --output appimage >"$stage/linuxdeploy.log" 2>&1 ||
{ tail -n 40 "$stage/linuxdeploy.log" >&2; exit 69; }
)
mv -f "$work/$target" "$output/$target"
chmod 755 "$output/$target"
echo "$output/$target"
}
case "$format" in
deb) build_deb ;;
appimage) build_appimage ;;
all) build_deb; build_appimage ;;
esac
+57 -9
View File
@@ -1,6 +1,7 @@
using UI :: #import "Widgets";
using Model :: #import "model";
Apps :: #import "windows";
Gpu :: #import "gpu_processes";
Tables :: #import "data_views/TableView";
Theme :: #import "kryon/Theme";
SystemTheme :: #import "kryon/SystemTheme";
@@ -64,7 +65,10 @@ BUTTON_WIDTH :: 120.0;
PAD :: 10.0;
COLUMNS :: Model.COLUMNS;
APP_COLUMNS :: 2;
APP_COLUMNS :: 5;
APP_COLUMN_CPU :: 2;
APP_COLUMN_MEMORY :: 3;
APP_COLUMN_GPU :: 4;
// Ten-digit PIDs, percentages, elapsed times and adaptive byte values fit in
// 16 bytes; process/group names use the model's bounded 32-byte capacity.
CELL_WIDTH :: 16;
@@ -77,8 +81,8 @@ MAX_DISPLAY_ROWS :: Model.MAX_PROCESSES + Model.MAX_PROCESSES / 2;
process_columns: [5]string = .{"Image Name", "PID", "CPU", "CPU Time", "Memory"};
process_fractions: [5]float32 = .{0.40, 0.12, 0.10, 0.16, 0.22};
process_widths: [COLUMNS]s32;
app_columns: [2]string = .{"Task", "Status"};
app_fractions: [2]float32 = .{0.76, 0.24};
app_columns: [5]string = .{"Task", "Status", "CPU", "Memory", "GPU"};
app_fractions: [5]float32 = .{0.40, 0.20, 0.11, 0.17, 0.12};
app_widths: [APP_COLUMNS]s32;
widths_for: float32;
@@ -118,12 +122,20 @@ text_stores_a: CellText;
text_stores_b: CellText;
text_active: s32;
// Window manager task lists, also in two generations.
// Window manager task lists, also in two generations. CPU, memory and GPU are
// the window's whole process tree (see Model.AppUsages).
AppText :: struct {
list: Apps.AppList
cell: [Apps.MAX_WINDOWS * APP_COLUMNS]string
cpu: [Apps.MAX_WINDOWS * CELL_WIDTH]u8
mem: [Apps.MAX_WINDOWS * CELL_WIDTH]u8
gpu: [Apps.MAX_WINDOWS * CELL_WIDTH]u8
}
app_pids: [Apps.MAX_WINDOWS]s32;
no_external_gpus: [1]Model.GpuExternal;
app_usage: [Apps.MAX_WINDOWS]Model.AppUsage;
app_stores_a: AppText;
app_stores_b: AppText;
app_active: s32;
@@ -442,12 +454,37 @@ AppStatus :: (pid: s32) -> string {
RebuildApps :: (store: *AppText) {
Apps.AppsRefresh(*store.list)
app_selected_row = -1
if store.list.count > 0 {
for index: 0..store.list.count - 1 {
count := store.list.count
if count > 0 {
for index: 0..count - 1 { app_pids[index] = store.list.windows[index].pid }
shares := Gpu.GpuSharesCurrent()
Model.AppUsages(Model.Current(), app_pids[0:count], shares.pids[0:shares.count],
shares.percent[0:shares.count], Gpu.GpuSharesReady(), app_usage[0:count])
for index: 0..count - 1 {
entry := *store.list.windows[index]
usage := *app_usage[index]
base := index * APP_COLUMNS
text_base := index * CELL_WIDTH
if entry.id == app_selected_window { app_selected_row = index }
store.cell[index * APP_COLUMNS] = TextView(entry.title[0:entry.title_count])
store.cell[index * APP_COLUMNS + 1] = AppStatus(entry.pid)
store.cell[base] = TextView(entry.title[0:entry.title_count])
store.cell[base + 1] = AppStatus(entry.pid)
if usage.found {
store.cell[base + APP_COLUMN_CPU] = Model.FormatCpu(usage.cpu_percent,
store.cpu[text_base:text_base + CELL_WIDTH])
store.cell[base + APP_COLUMN_MEMORY] = Model.FormatBytes(usage.memory_bytes,
store.mem[text_base:text_base + CELL_WIDTH])
} else {
store.cell[base + APP_COLUMN_CPU] = "-"
store.cell[base + APP_COLUMN_MEMORY] = "-"
}
if !usage.gpu_known {
store.cell[base + APP_COLUMN_GPU] = "n/a"
} else if usage.found {
store.cell[base + APP_COLUMN_GPU] = Model.FormatCpu(usage.gpu_percent,
store.gpu[text_base:text_base + CELL_WIDTH])
} else {
store.cell[base + APP_COLUMN_GPU] = "-"
}
}
}
if app_selected_row < 0 { app_selected_window = 0 }
@@ -497,7 +534,7 @@ ColumnWidths :: (width: float32) {
}
for column: 0..APP_COLUMNS - 1 {
value := cast(s32)(usable * app_fractions[column])
if value < 60 { value = 60 }
if value < 40 { value = 40 }
app_widths[column] = value
}
}
@@ -1219,7 +1256,18 @@ Frame :: (session: Session, viewport: Rectangle) -> s32 {
if now_ms < 0 && frames_since_refresh >= REFRESH_FALLBACK_FRAMES { refreshed = true }
}
if refresh_requested { refreshed = true }
// Non-blocking: drains the GPU helper, and starts or stops it with the
// tabs that show GPU data (Applications and Performance).
Gpu.GpuSharesPoll(current_tab == TAB_APPLICATIONS || current_tab == TAB_PERFORMANCE)
if refreshed {
// NVIDIA cards have no sysfs counters; the helper's whole-card
// readings stand in for them while it runs.
if Gpu.GpuSharesReady() {
readings := Gpu.GpuDevicesCurrent()
Model.SetExternalGpus(readings.items[0:readings.count])
} else {
Model.SetExternalGpus(no_external_gpus[0:0])
}
Model.Refresh()
BuildApps()
frames_since_refresh = 0
+6 -1
View File
@@ -4,6 +4,7 @@
#import "kryon/desktop_loop";
using Kryon :: #import "kryon/Kryon";
App :: #import "app";
Gpu :: #import "gpu_processes";
// Custom hosts currently provide the bridge symbol consumed by desktop_loop.
#program_export
@@ -11,7 +12,11 @@ ProjectFrame :: (session: Session, viewport: Rectangle) -> s32 {
return App.Frame(session, viewport)
}
// `taskmgr --gpu-helper` is the display-free NVML sampler the Applications
// tab starts from this same binary (see gpu_processes.zi).
#program_export
main :: () -> s32 {
main :: (argc: s32, argv: **u8) -> s32 {
if Gpu.HelperRequested(argc, argv) { return Gpu.HelperMain() }
Gpu.GpuSharesEnable()
return RunDesktop(400, 480)
}
+541
View File
@@ -0,0 +1,541 @@
// Per-process GPU shares for the Applications tab. NVIDIA's proprietary
// driver publishes no per-process DRM fdinfo counters, so NVML is the source.
// A query is cheap (about 2.5 ms of CPU), but loading NVML keeps roughly 16 MB
// of private memory even after nvmlShutdown, and `nvidia-smi pmon` costs about
// 3% of a core. So taskmgr starts its own binary again as `--gpu-helper`: that
// child loads NVML, samples once a second and streams plain text, while the
// window process only parses lines and keeps its compact memory budget.
//
// The helper runs only while the Applications tab is visible, never touches a
// display, and exits when its parent goes away. Without an NVIDIA driver no
// helper starts and the GPU column reads n/a.
//
// The same samples also carry each card's whole-device usage and VRAM, which
// the Performance tab needs because NVIDIA's driver has no sysfs counters.
//
// Protocol, one block per sample: "T"; per device "D <domain> <bus> <slot>
// <busy%> <vram used> <vram total>" with "-" for an unsupported counter; then
// "<pid> <percent>" for each GPU process (one line per device it used); then
// "E". "X" means NVML is unusable.
Model :: #import "model";
Channel :: #import "std/process_channel_linux";
Files :: #import "std/file";
Number :: #import "std/number_text";
MAX_GPU_PROCESSES :: 256;
HELPER_ARGUMENT :: "--gpu-helper";
GpuShares :: struct {
pids: [MAX_GPU_PROCESSES]s32
percent: [MAX_GPU_PROCESSES]float64
count: s32
}
GPU_DEVICE_LIMIT :: 16;
GpuDeviceReadings :: struct {
items: [GPU_DEVICE_LIMIT]Model.GpuExternal
count: s32
}
#scope_file
c :: #system_library "c";
dl :: #system_library "dl";
DlOpen :: (path: *u8, flags: s32) -> *void #foreign dl "dlopen";
DlSymbol :: (handle: *void, name: *u8) -> *void #foreign dl "dlsym";
MemoryCopy :: (target: *void, source: *void, bytes: usize) -> *void #foreign c "memcpy";
WriteRaw :: (fd: s32, bytes: *u8, count: usize) -> isize #foreign c "write";
SleepRaw :: (micros: u32) -> s32 #foreign c "usleep";
ParentRaw :: () -> s32 #foreign c "getppid";
TimeRaw :: (output: *s64) -> s64 #foreign c "time";
NVML_SUCCESS :: 0;
MAX_DEVICES :: GPU_DEVICE_LIMIT;
MAX_SAMPLES :: 1024;
SAMPLE_MICROS :: 1000000;
// nvmlProcessUtilizationSample_t: 32 bytes with the padding after pid.
NvmlSample :: struct {
pid: u32
timestamp: u64
sm: u32
memory: u32
encoder: u32
decoder: u32
}
// nvmlPciInfo_t (v3), nvmlUtilization_t and nvmlMemory_t.
NvmlPci :: struct {
bus_id_legacy: [16]u8
domain: u32
bus: u32
device: u32
pci_device_id: u32
pci_subsystem_id: u32
bus_id: [32]u8
}
NvmlUtilization :: struct {
gpu: u32
memory: u32
}
NvmlMemory :: struct {
total: u64
free: u64
used: u64
}
FnInit :: #type () -> s32 #c_call;
FnCount :: #type (*u32) -> s32 #c_call;
FnHandle :: #type (u32, **void) -> s32 #c_call;
FnUtilization :: #type (*void, *NvmlSample, *u32, u64) -> s32 #c_call;
FnPci :: #type (*void, *NvmlPci) -> s32 #c_call;
FnRates :: #type (*void, *NvmlUtilization) -> s32 #c_call;
FnMemory :: #type (*void, *NvmlMemory) -> s32 #c_call;
nvml_init: FnInit;
nvml_count: FnCount;
nvml_handle: FnHandle;
nvml_utilization: FnUtilization;
nvml_pci: FnPci;
nvml_rates: FnRates;
nvml_memory: FnMemory;
samples: [MAX_SAMPLES]NvmlSample;
// Helper-side accumulation for one device in one tick: samples per PID are
// averaged, since NVML reports several short sampling periods per second.
device_pids: [MAX_GPU_PROCESSES]s32;
device_sums: [MAX_GPU_PROCESSES]u64;
device_samples: [MAX_GPU_PROCESSES]s32;
device_count_used: s32;
tick_text: [MAX_GPU_PROCESSES * MAX_DEVICES * 24 + 16]u8;
tick_length: s32;
// Window-side state.
enabled: bool;
running: bool;
unavailable: bool;
has_data: bool;
channel: Channel.ProcessChannel;
line: [64]u8;
line_count: s32;
line_overflow: bool;
staging: GpuShares;
current: GpuShares;
staging_devices: GpuDeviceReadings;
current_devices: GpuDeviceReadings;
CopyCString :: (text: string, output: []u8) -> bool {
if cast(s32)text.count >= cast(s32)output.count { return false }
index: s32 = 0
for byte: text {
if byte == 0 { return false }
output[index] = byte
index += 1
}
output[index] = 0
return true
}
Resolve :: (handle: *void, slot: *void, name: string) -> bool {
bytes: [64]u8
if !CopyCString(name, bytes[:]) { return false }
symbol: *void = DlSymbol(handle, *bytes[0])
if symbol == null { return false }
MemoryCopy(slot, cast(*void)*symbol, size_of(*void))
return true
}
LoadNvml :: () -> bool {
name: [32]u8
if !CopyCString("libnvidia-ml.so.1", name[:]) { return false }
// RTLD_LAZY | RTLD_LOCAL
handle: *void = DlOpen(*name[0], 1)
if handle == null { return false }
ok := Resolve(handle, cast(*void)*nvml_init, "nvmlInit_v2")
ok = ok && Resolve(handle, cast(*void)*nvml_count, "nvmlDeviceGetCount_v2")
ok = ok && Resolve(handle, cast(*void)*nvml_handle, "nvmlDeviceGetHandleByIndex_v2")
ok = ok && Resolve(handle, cast(*void)*nvml_utilization, "nvmlDeviceGetProcessUtilization")
ok = ok && Resolve(handle, cast(*void)*nvml_pci, "nvmlDeviceGetPciInfo_v3")
ok = ok && Resolve(handle, cast(*void)*nvml_rates, "nvmlDeviceGetUtilizationRates")
ok = ok && Resolve(handle, cast(*void)*nvml_memory, "nvmlDeviceGetMemoryInfo")
return ok && nvml_init() == NVML_SUCCESS
}
TickAppend :: (piece: string) {
for byte: piece {
if tick_length >= cast(s32)tick_text.count { return }
tick_text[tick_length] = byte
tick_length += 1
}
}
// Writes the pending tick text to standard output; false once the parent
// has stopped reading.
EmitTick :: () -> bool {
written: s32 = 0
while written < tick_length {
count := WriteRaw(1, *tick_text[written], cast(usize)(tick_length - written))
if count <= cast(isize)0 { return false }
written += cast(s32)count
}
return true
}
EmitUnavailable :: () {
tick_length = 0
TickAppend("X\n")
unused EmitTick()
}
Accumulate :: (pid: s32, sm: u32) {
if pid <= 0 { return }
if device_count_used > 0 {
for index: 0..device_count_used - 1 {
if device_pids[index] == pid {
device_sums[index] += cast(u64)sm
device_samples[index] += 1
return
}
}
}
if device_count_used >= MAX_GPU_PROCESSES { return }
device_pids[device_count_used] = pid
device_sums[device_count_used] = cast(u64)sm
device_samples[device_count_used] = 1
device_count_used += 1
}
TickNumber :: (value: s64) {
digits: [24]u8
if value < 0 {
TickAppend("-")
return
}
TickAppend(Number.FormatInteger(value, digits[:]))
}
// Appends one device's whole-card line: busy percent and VRAM bytes.
AppendDeviceLine :: (device: *void, pci: *NvmlPci) {
busy: s64 = -1
rates: NvmlUtilization
if nvml_rates(device, *rates) == NVML_SUCCESS { busy = cast(s64)rates.gpu }
used: s64 = -1
total: s64 = -1
memory: NvmlMemory
if nvml_memory(device, *memory) == NVML_SUCCESS && memory.total > 0 {
used = cast(s64)memory.used
total = cast(s64)memory.total
}
TickAppend("D ")
TickNumber(cast(s64)pci.domain)
TickAppend(" ")
TickNumber(cast(s64)pci.bus)
TickAppend(" ")
TickNumber(cast(s64)pci.device)
TickAppend(" ")
TickNumber(busy)
TickAppend(" ")
TickNumber(used)
TickAppend(" ")
TickNumber(total)
TickAppend("\n")
}
// Appends one device's averaged shares to the tick block.
FlushDevice :: () {
if device_count_used <= 0 { return }
digits: [24]u8
for index: 0..device_count_used - 1 {
average := (device_sums[index] + cast(u64)(device_samples[index] / 2)) /
cast(u64)device_samples[index]
TickAppend(Number.FormatInteger(cast(s64)device_pids[index], digits[:]))
TickAppend(" ")
TickAppend(Number.FormatInteger(cast(s64)average, digits[:]))
TickAppend("\n")
}
device_count_used = 0
}
ParseDigits :: (text: []u8, start: s32, limit: s64 = 2147483647) -> (value: s64, next: s32, ok: bool) {
cursor := start
value: s64 = 0
total := cast(s32)text.count
while cursor < total && text[cursor] >= 48 && text[cursor] <= 57 {
if value > (limit - cast(s64)(text[cursor] - 48)) / 10 { return 0, cursor, false }
value = value * 10 + cast(s64)(text[cursor] - 48)
cursor += 1
}
return value, cursor, cursor > start
}
// One space-separated device field: a number, or "-" for unsupported (-1).
DeviceField :: (text: []u8, start: s32) -> (value: s64, next: s32, ok: bool) {
total := cast(s32)text.count
if start >= total { return 0, start, false }
value: s64 = -1
cursor := start + 1
if text[start] != 45 {
number, after, number_ok := ParseDigits(text, start, 9223372036854775807)
if !number_ok { return 0, after, false }
value = number
cursor = after
}
if cursor < total {
if text[cursor] != 32 { return 0, cursor, false }
cursor += 1
}
return value, cursor, true
}
ParseDeviceLine :: (text: []u8) {
values: [6]s64
cursor: s32 = 2
for index: 0..5 {
value, next, ok := DeviceField(text, cursor)
if !ok { return }
values[index] = value
cursor = next
}
if cursor != cast(s32)text.count || values[0] < 0 || values[1] < 0 || values[2] < 0 { return }
if staging_devices.count >= GPU_DEVICE_LIMIT { return }
reading := *staging_devices.items[staging_devices.count]
reading.domain = cast(u32)values[0]
reading.bus = cast(u32)values[1]
reading.slot = cast(u32)values[2]
reading.busy = values[3]
reading.vram_used = values[4]
reading.vram_total = values[5]
staging_devices.count += 1
}
ParseLine :: (text: []u8) {
if text.count == 1 && text[0] == 84 { // T
staging.count = 0
staging_devices.count = 0
return
}
if text.count == 1 && text[0] == 69 { // E
current = staging
current_devices = staging_devices
has_data = true
return
}
if text.count > 2 && text[0] == 68 && text[1] == 32 { // D
ParseDeviceLine(text)
return
}
if text.count == 1 && text[0] == 88 { // X
unavailable = true
has_data = false
return
}
pid, after_pid, pid_ok := ParseDigits(text, 0)
if !pid_ok || after_pid >= cast(s32)text.count || text[after_pid] != 32 { return }
percent, after_percent, percent_ok := ParseDigits(text, after_pid + 1)
if !percent_ok || after_percent != cast(s32)text.count || pid <= 0 { return }
if staging.count >= MAX_GPU_PROCESSES { return }
staging.pids[staging.count] = cast(s32)pid
staging.percent[staging.count] = cast(float64)percent
staging.count += 1
}
StartHelper :: () -> bool {
probe := Files.OpenRead("/proc/driver/nvidia/version")
if !probe.valid {
unavailable = true
return false
}
Files.CloseFile(probe)
arguments: [2]string = .["/proc/self/exe", HELPER_ARGUMENT]
channel = Channel.StartChannel(arguments[:], false, true)
if channel.pid <= 0 {
unavailable = true
return false
}
running = true
has_data = false
line_count = 0
line_overflow = false
staging.count = 0
current.count = 0
staging_devices.count = 0
current_devices.count = 0
return true
}
StopHelper :: () {
if running { unused Channel.CancelChannel(*channel) }
running = false
has_data = false
staging.count = 0
current.count = 0
staging_devices.count = 0
current_devices.count = 0
}
#scope_export
// Whether ARGV asks this binary to run as the GPU sampling helper.
#program_export
HelperRequested :: (argc: s32, argv: **u8) -> bool {
if argc != 2 || argv == null { return false }
argument := argv[1]
if argument == null { return false }
index: s32 = 0
for byte: HELPER_ARGUMENT {
if argument[index] != byte { return false }
index += 1
}
return argument[index] == 0
}
// The helper's whole life: sample every NVIDIA device once a second and
// stream one block per sample until the parent exits or stops reading.
#program_export
HelperMain :: () -> s32 {
parent := ParentRaw()
if size_of(NvmlSample) != 32 || size_of(NvmlPci) != 68 || size_of(NvmlMemory) != 24 ||
!LoadNvml() {
EmitUnavailable()
return 1
}
device_total: u32 = 0
if nvml_count(*device_total) != NVML_SUCCESS || device_total == 0 {
EmitUnavailable()
return 1
}
if device_total > MAX_DEVICES { device_total = MAX_DEVICES }
devices: [MAX_DEVICES]*void
last_seen: [MAX_DEVICES]u64
pci: [MAX_DEVICES]NvmlPci
pci_ok: [MAX_DEVICES]bool
// NVML timestamps are wall-clock microseconds. Starting one second back
// skips the driver's older buffer, which can exceed any fixed array.
now_seconds := TimeRaw(null)
for index: 0..cast(s32)device_total - 1 {
devices[index] = null
if nvml_handle(cast(u32)index, *devices[index]) != NVML_SUCCESS { devices[index] = null }
pci_ok[index] = devices[index] != null && nvml_pci(devices[index], *pci[index]) == NVML_SUCCESS
last_seen[index] = 0
if now_seconds > 1 { last_seen[index] = cast(u64)(now_seconds - 1) * cast(u64)SAMPLE_MICROS }
}
while true {
tick_length = 0
TickAppend("T\n")
for device: 0..cast(s32)device_total - 1 {
if devices[device] == null { continue }
if pci_ok[device] { AppendDeviceLine(devices[device], *pci[device]) }
count: u32 = MAX_SAMPLES
device_count_used = 0
// NVML_ERROR_NOT_FOUND means no new samples: the device was idle.
if nvml_utilization(devices[device], *samples[0], *count, last_seen[device]) == NVML_SUCCESS {
if count > MAX_SAMPLES { count = MAX_SAMPLES }
newest := last_seen[device]
if count > 0 {
for index: 0..cast(s32)count - 1 {
sample := *samples[index]
if sample.timestamp <= last_seen[device] { continue }
if sample.timestamp > newest { newest = sample.timestamp }
Accumulate(cast(s32)(sample.pid & 0x7fffffff), sample.sm)
}
}
last_seen[device] = newest
FlushDevice()
}
}
TickAppend("E\n")
if !EmitTick() { return 0 }
if ParentRaw() != parent { return 0 }
unused SleepRaw(SAMPLE_MICROS)
if ParentRaw() != parent { return 0 }
}
return 0
}
// Allows the window process to start a helper. Only the native desktop host
// calls this, because only its main recognizes HELPER_ARGUMENT.
#program_export
GpuSharesEnable :: () {
enabled = true
}
// Starts, drains or stops the helper. ACTIVE is whether the Applications tab
// is visible; leaving it stops the child so it costs nothing elsewhere.
#program_export
GpuSharesPoll :: (active: bool) {
if !enabled || unavailable { return }
if !active {
StopHelper()
return
}
if !running && !StartHelper() { return }
buffer: [4096]u8
reads: s32 = 0
while reads < 64 {
received := Channel.ChannelReceive(channel, buffer[:], 0)
if received < 0 { break }
if received == 0 {
StopHelper()
unavailable = true
return
}
GpuSharesFeed(buffer[0:received])
reads += 1
}
if unavailable { StopHelper() }
}
// Parses helper output; partial lines wait for the rest.
#program_export
GpuSharesFeed :: (bytes: []u8) {
for byte: bytes {
if byte == 10 {
if !line_overflow { ParseLine(line[0:line_count]) }
line_count = 0
line_overflow = false
continue
}
if line_count >= cast(s32)line.count {
line_overflow = true
continue
}
line[line_count] = byte
line_count += 1
}
}
// True once a complete sample has arrived and the source is still usable.
#program_export
GpuSharesReady :: () -> bool {
return has_data && !unavailable
}
#program_export
GpuSharesCurrent :: () -> *GpuShares {
return *current
}
// Whole-card readings from the latest sample; check GpuSharesReady first.
#program_export
GpuDevicesCurrent :: () -> *GpuDeviceReadings {
return *current_devices
}
// Clears parser state; for tests.
#program_export
GpuSharesReset :: () {
has_data = false
unavailable = false
line_count = 0
line_overflow = false
staging.count = 0
current.count = 0
staging_devices.count = 0
current_devices.count = 0
}
+247 -6
View File
@@ -58,6 +58,9 @@ Process :: struct {
name_count: s32
name: [NAME_CAPACITY]u8
state: u8
// Parent PID from /proc/<pid>/stat field 4; it sits in the padding before
// cpu_percent, so the snapshot row does not grow.
ppid: s32
cpu_percent: float64
memory_bytes: u64
ticks: u64
@@ -242,8 +245,8 @@ ParsePidName :: (name_bytes: []u8) -> s32 {
}
// Parses /proc/<pid>/stat: the command name sits between the first '(' and the
// last ')'; after it come the state and the numbered fields, where utime is
// field 14, stime is field 15, num_threads is field 20, and rss is field 24.
// last ')'; after it come the state and the numbered fields, where ppid is
// field 4, utime is field 14, stime is field 15, num_threads is field 20, and rss is field 24.
#program_export
ParseStat :: (content: []u8, process: *Process) -> bool {
EnsureTiming()
@@ -285,6 +288,7 @@ ParseStat :: (content: []u8, process: *Process) -> bool {
digits += 1
}
if digits == 0 { return false }
if !negative && field == 4 { process.ppid = cast(s32)value }
if !negative && field == 14 { utime = value }
if !negative && field == 15 { stime = value }
if !negative && field == 20 { process.threads = cast(s32)value }
@@ -403,16 +407,122 @@ DrmPath :: (card: []u8, leaf: string, output: []u8) -> string {
return TextView(output[0:length])
}
// A whole-card reading from outside sysfs (NVIDIA's NVML, through the GPU
// helper), matched to a DRM card by PCI address because NVIDIA's driver
// publishes no gpu_busy_percent or mem_info_vram_* files. A negative busy or
// a non-positive vram_total marks that counter unsupported.
GpuExternal :: struct {
domain: u32
bus: u32
slot: u32
busy: s64
vram_used: s64
vram_total: s64
}
external_gpus: [MAX_GPUS]GpuExternal;
external_gpu_count: s32;
// Replaces the outside readings the next Refresh may use; an empty slice
// removes them, so a stopped source never leaves stale values behind.
#program_export
SetExternalGpus :: (readings: []GpuExternal) {
external_gpu_count = 0
for reading: readings {
if external_gpu_count >= MAX_GPUS { break }
external_gpus[external_gpu_count] = reading
external_gpu_count += 1
}
}
#program_export
ExternalGpuFor :: (domain: u32, bus: u32, slot: u32) -> s32 {
if external_gpu_count <= 0 { return -1 }
for index: 0..external_gpu_count - 1 {
reading := *external_gpus[index]
if reading.domain == domain && reading.bus == bus && reading.slot == slot { return index }
}
return -1
}
HexDigit :: (byte: u8) -> s32 {
if byte >= 48 && byte <= 57 { return cast(s32)(byte - 48) }
if byte >= 97 && byte <= 102 { return cast(s32)(byte - 87) }
if byte >= 65 && byte <= 70 { return cast(s32)(byte - 55) }
return -1
}
// Parses one hexadecimal field of a PCI address and the separator after it.
HexField :: (text: []u8, start: s32, separator: u8) -> (value: u32, next: s32, ok: bool) {
cursor := start
value: u32 = 0
total := cast(s32)text.count
while cursor < total && cursor - start < 8 {
digit := HexDigit(text[cursor])
if digit < 0 { break }
value = value * 16 + cast(u32)digit
cursor += 1
}
if cursor == start { return 0, cursor, false }
if separator != 0 {
if cursor >= total || text[cursor] != separator { return 0, cursor, false }
cursor += 1
}
return value, cursor, true
}
// Reads PCI_SLOT_NAME=dddd:bb:ss.f from a sysfs uevent file.
#program_export
PciSlotFromUevent :: (content: []u8) -> (domain: u32, bus: u32, slot: u32, function: u32, ok: bool) {
label := "PCI_SLOT_NAME="
limit := cast(s32)content.count
label_count := cast(s32)label.count
index: s32 = 0
while index < limit {
if index > 0 && content[index - 1] != 10 {
index += 1
continue
}
matched := true
offset: s32 = 0
while offset < label_count {
if index + offset >= limit || content[index + offset] != label[offset] {
matched = false
break
}
offset += 1
}
if matched {
domain, after_domain, domain_ok := HexField(content, index + offset, 58)
bus, after_bus, bus_ok := HexField(content, after_domain, 58)
slot, after_slot, slot_ok := HexField(content, after_bus, 46)
function, after_function, function_ok := HexField(content, after_slot, 0)
if domain_ok && bus_ok && slot_ok && function_ok {
return domain, bus, slot, function, true
}
return 0, 0, 0, 0, false
}
index += 1
}
return 0, 0, 0, 0, false
}
// Adds one card's independent sysfs buffers, keeping card order stable. A zero
// used counter is valid. Missing totals and inconsistent used > total pairs are
// unsupported, never interpreted as fully used.
#program_export
AddGpuCounters :: (snapshot: *Snapshot, card_index: s32,
busy_text: []u8, used_text: []u8, total_text: []u8) {
AddGpuValues(snapshot, card_index, FirstNumber(busy_text), FirstNumber(used_text),
FirstNumber(total_text))
}
// The numeric form of AddGpuCounters; negative values are missing counters.
#program_export
AddGpuValues :: (snapshot: *Snapshot, card_index: s32, busy: s64, used: s64, total: s64) {
if card_index < 0 || card_index >= GPU_CARD_LIMIT || snapshot.gpu_count >= MAX_GPUS { return }
device: GpuDevice
device.card_index = card_index
busy := FirstNumber(busy_text)
if busy >= 0 {
if busy > 100 { busy = 100 }
device.busy_supported = true
@@ -420,8 +530,6 @@ AddGpuCounters :: (snapshot: *Snapshot, card_index: s32,
snapshot.gpu_percent += device.busy_percent
snapshot.gpu_supported_count += 1
}
used := FirstNumber(used_text)
total := FirstNumber(total_text)
if used >= 0 && total > 0 && used <= total {
device.vram_supported = true
device.vram_used = cast(u64)used
@@ -457,12 +565,15 @@ GpuVramPercent :: (device: *GpuDevice) -> float64 {
// Samples every DRM card that exposes standard Linux sysfs counters. Each
// counter has its own buffer: reading total must not overwrite used before it
// is parsed (the previous alias made every adapter appear 100% full).
// is parsed (the previous alias made every adapter appear 100% full). A card
// with none of those files (NVIDIA's driver) uses the external reading for
// its PCI address when one was set.
ReadGpuStats :: (snapshot: *Snapshot) {
directory := Files.OpenDirectory("/sys/class/drm")
busy_buffer: [128]u8
used_buffer: [128]u8
total_buffer: [128]u8
uevent_buffer: [512]u8
path: [160]u8
while true {
entry := Files.NextDirectoryEntry(*directory)
@@ -473,6 +584,20 @@ ReadGpuStats :: (snapshot: *Snapshot) {
busy_length := ReadSmall(DrmPath(card, "gpu_busy_percent", path[:]), busy_buffer[:])
used_length := ReadSmall(DrmPath(card, "mem_info_vram_used", path[:]), used_buffer[:])
total_length := ReadSmall(DrmPath(card, "mem_info_vram_total", path[:]), total_buffer[:])
if busy_length <= 0 && used_length <= 0 && total_length <= 0 && external_gpu_count > 0 {
uevent_length := ReadSmall(DrmPath(card, "uevent", path[:]), uevent_buffer[:])
if uevent_length > 0 {
domain, bus, slot, function, ok := PciSlotFromUevent(uevent_buffer[0:uevent_length])
external := -1
if ok && function == 0 { external = ExternalGpuFor(domain, bus, slot) }
if external >= 0 {
reading := *external_gpus[external]
AddGpuValues(snapshot, card_index, reading.busy, reading.vram_used,
reading.vram_total)
continue
}
}
}
busy_text: []u8 = busy_buffer[0:0]
used_text: []u8 = used_buffer[0:0]
total_text: []u8 = total_buffer[0:0]
@@ -651,6 +776,122 @@ FindProcess :: (snapshot: *Snapshot, pid: s32) -> s32 {
return -1
}
// Resource use behind one Applications row: the window's own process plus
// every descendant that no nearer listed window owns. found is false when the
// window publishes no PID or that PID is not in the snapshot.
AppUsage :: struct {
found: bool
gpu_known: bool
processes: s32
cpu_percent: float64
memory_bytes: u64
gpu_percent: float64
}
// Deep enough for shells, launchers and browser helpers; also stops a
// corrupted parent chain from looping.
MAX_TREE_DEPTH :: 64;
// Snapshot indices ordered by PID, and the window slot each process directly
// represents (-1 for none). Rebuilt by AppUsages; never retained across calls.
pid_order: [MAX_PROCESSES]s32;
owner_slot: [MAX_PROCESSES]s32;
// /proc lists PIDs in ascending order, so this insertion sort is linear in
// practice and still correct when the order differs.
BuildPidOrder :: (snapshot: *Snapshot) {
count := snapshot.count
if count <= 0 { return }
for slot: 0..count - 1 {
key := slot
key_pid := snapshot.processes[key].pid
position := slot - 1
while position >= 0 && snapshot.processes[pid_order[position]].pid > key_pid {
pid_order[position + 1] = pid_order[position]
position -= 1
}
pid_order[position + 1] = key
}
}
IndexOfPid :: (snapshot: *Snapshot, pid: s32) -> s32 {
low: s32 = 0
high := snapshot.count - 1
while low <= high {
middle := low + (high - low) / 2
index := pid_order[middle]
value := snapshot.processes[index].pid
if value == pid { return index }
if value < pid { low = middle + 1 } else { high = middle - 1 }
}
return -1
}
// Sums CPU share, resident memory and GPU share per window. Each process
// counts once, toward the nearest ancestor (itself included) whose PID owns a
// listed window, so a browser started from a terminal is the browser's, not
// the terminal's. Windows that share a PID show the same totals. GPU_PIDS and
// GPU_PERCENT are per-process GPU shares; GPU_KNOWN false means no per-process
// GPU source exists and every gpu_known stays false.
#program_export
AppUsages :: (snapshot: *Snapshot, window_pids: []s32, gpu_pids: []s32,
gpu_percent: []float64, gpu_known: bool, output: []AppUsage) {
count := cast(s32)window_pids.count
if count > cast(s32)output.count { count = cast(s32)output.count }
if count <= 0 { return }
for slot: 0..count - 1 {
output[slot] = AppUsage.{}
output[slot].gpu_known = gpu_known
}
if snapshot.count <= 0 { return }
BuildPidOrder(snapshot)
for index: 0..snapshot.count - 1 { owner_slot[index] = -1 }
for slot: 0..count - 1 {
pid := window_pids[slot]
if pid <= 0 { continue }
index := IndexOfPid(snapshot, pid)
if index >= 0 && owner_slot[index] < 0 { owner_slot[index] = slot }
}
gpu_count := cast(s32)gpu_pids.count
if gpu_count > cast(s32)gpu_percent.count { gpu_count = cast(s32)gpu_percent.count }
for index: 0..snapshot.count - 1 {
cursor := index
slot: s32 = -1
depth: s32 = 0
while cursor >= 0 && depth < MAX_TREE_DEPTH {
if owner_slot[cursor] >= 0 {
slot = owner_slot[cursor]
break
}
parent := snapshot.processes[cursor].ppid
if parent <= 0 { break }
cursor = IndexOfPid(snapshot, parent)
depth += 1
}
if slot < 0 { continue }
process := *snapshot.processes[index]
usage := *output[slot]
usage.found = true
usage.processes += 1
usage.cpu_percent += process.cpu_percent
usage.memory_bytes += process.memory_bytes
if gpu_known && gpu_count > 0 {
for entry: 0..gpu_count - 1 {
if gpu_pids[entry] == process.pid { usage.gpu_percent += gpu_percent[entry] }
}
}
}
// A second window of the same process repeats the first one's totals.
for slot: 0..count - 1 {
pid := window_pids[slot]
if pid <= 0 { continue }
index := IndexOfPid(snapshot, pid)
if index < 0 { continue }
first := owner_slot[index]
if first >= 0 && first != slot { output[slot] = output[first] }
}
}
// Samples /proc into the live snapshot. CPU percentages use compact PID/tick
// arrays and system counters retained from the previous sample.
#program_export
+152 -1
View File
@@ -1,4 +1,5 @@
using Model :: #import "model";
Gpu :: #import "gpu_processes";
Shortcuts :: #import "app_shortcuts";
Files :: #import "std/file";
@@ -41,7 +42,7 @@ ParserTest :: () -> bool {
}
if TextView(process.name[0:process.name_count]) != "worker (stage) name" ||
process.state != Model.STATE_SLEEPING || process.ticks != 23 ||
process.memory_bytes == 0 || process.threads != 17 {
process.memory_bytes == 0 || process.threads != 17 || process.ppid != 1 {
print("parse: process stat fields wrong\n")
return false
}
@@ -570,6 +571,153 @@ GroupSignalTest :: () -> bool {
return true
}
AddProcess :: (snapshot: *Model.Snapshot, pid: s32, ppid: s32, cpu: float64, memory: u64) {
entry := *snapshot.processes[snapshot.count]
entry.pid = pid
entry.ppid = ppid
entry.cpu_percent = cpu
entry.memory_bytes = memory
entry.group_count = 1
snapshot.count += 1
}
// Window rows own their process tree; the nearest listed ancestor wins, so a
// browser started from a terminal is not counted twice.
AppUsageTest :: () -> bool {
snapshot: Model.Snapshot
// Deliberately out of PID order: /proc order is only usually ascending.
AddProcess(*snapshot, 500, 1, 1.0, 1000) // terminal (window 0)
AddProcess(*snapshot, 501, 500, 2.0, 200) // shell under the terminal
AddProcess(*snapshot, 900, 501, 10.0, 5000) // browser (window 1), from the shell
AddProcess(*snapshot, 901, 900, 20.0, 3000) // browser renderer
AddProcess(*snapshot, 902, 901, 5.0, 100) // grandchild of the browser
AddProcess(*snapshot, 700, 1, 50.0, 9999) // unrelated daemon
AddProcess(*snapshot, 1, 0, 0.0, 10) // init
window_pids: [5]s32 = .[500, 900, 0, 4242, 900]
gpu_pids: [3]s32 = .[901, 902, 700]
gpu_percent: [3]float64 = .[30.0, 4.0, 60.0]
usage: [5]Model.AppUsage
Model.AppUsages(*snapshot, window_pids[:], gpu_pids[:], gpu_percent[:], true, usage[:])
terminal := usage[0]
if !terminal.found || terminal.processes != 2 || terminal.cpu_percent != 3.0 ||
terminal.memory_bytes != 1200 || terminal.gpu_percent != 0.0 || !terminal.gpu_known {
print("apps: terminal tree totals wrong\n")
return false
}
browser := usage[1]
if !browser.found || browser.processes != 3 || browser.cpu_percent != 35.0 ||
browser.memory_bytes != 8100 || browser.gpu_percent != 34.0 {
print("apps: browser tree totals wrong\n")
return false
}
if usage[2].found || usage[3].found {
print("apps: windows without a live PID reported usage\n")
return false
}
if !usage[4].found || usage[4].processes != 3 || usage[4].memory_bytes != 8100 {
print("apps: second window of one process did not share its totals\n")
return false
}
Model.AppUsages(*snapshot, window_pids[:], gpu_pids[0:0], gpu_percent[0:0], false, usage[:])
if usage[1].gpu_known || usage[1].gpu_percent != 0.0 || usage[1].cpu_percent != 35.0 {
print("apps: missing GPU source not reported as unknown\n")
return false
}
return true
}
// NVIDIA cards get their whole-card readings from the helper, matched to the
// DRM card by the PCI address in its uevent file.
ExternalGpuTest :: () -> bool {
uevent := "DRIVER=nvidia\nPCI_CLASS=30000\nPCI_SLOT_NAME=0000:0a:1f.0\nMODALIAS=pci:v000010DE\n"
bytes: [128]u8
domain, bus, slot, function, ok := Model.PciSlotFromUevent(BytesOf(uevent, bytes[:]))
if !ok || domain != 0 || bus != 10 || slot != 31 || function != 0 {
print("external gpu: PCI slot parsed wrong\n")
return false
}
unused_domain, unused_bus, unused_slot, unused_function, bad := Model.PciSlotFromUevent(
BytesOf("XPCI_SLOT_NAME=0000:01:00.0\n", bytes[:]))
if bad {
print("external gpu: label matched mid-line\n")
return false
}
readings: [2]Model.GpuExternal
readings[0] = Model.GpuExternal.{domain = 0, bus = 1, slot = 0, busy = 37,
vram_used = 512, vram_total = 2048}
readings[1] = Model.GpuExternal.{domain = 0, bus = 10, slot = 31, busy = -1,
vram_used = -1, vram_total = -1}
Model.SetExternalGpus(readings[:])
if Model.ExternalGpuFor(0, 1, 0) != 0 || Model.ExternalGpuFor(0, 10, 31) != 1 ||
Model.ExternalGpuFor(1, 1, 0) != -1 {
print("external gpu: PCI match wrong\n")
return false
}
snapshot: Model.Snapshot
Model.AddGpuValues(*snapshot, 1, readings[0].busy, readings[0].vram_used, readings[0].vram_total)
Model.AddGpuValues(*snapshot, 0, readings[1].busy, readings[1].vram_used, readings[1].vram_total)
Model.FinalizeGpuStats(*snapshot)
if snapshot.gpu_count != 2 || snapshot.gpus[0].card_index != 0 ||
snapshot.gpus[0].busy_supported || snapshot.gpus[0].vram_supported ||
!snapshot.gpus[1].busy_supported || snapshot.gpus[1].busy_percent != 37.0 ||
snapshot.vram_used != 512 || snapshot.vram_total != 2048 || snapshot.gpu_percent != 37.0 {
print("external gpu: readings not applied\n")
return false
}
Model.SetExternalGpus(readings[0:0])
if Model.ExternalGpuFor(0, 1, 0) != -1 {
print("external gpu: cleared readings still matched\n")
return false
}
return true
}
GpuSharesTest :: () -> bool {
Gpu.GpuSharesReset()
if Gpu.GpuSharesReady() {
print("gpu: ready before any sample\n")
return false
}
first := "T\n2677 1\n552"
rest := "68 12\nbogus line\n9 \nE\n"
bytes: [128]u8
Gpu.GpuSharesFeed(BytesOf("T\nD 0 1 0 3 574619648 17103781888\nD 0 2 0 - - -\nD 0 x\nE\n", bytes[:]))
devices := Gpu.GpuDevicesCurrent()
if !Gpu.GpuSharesReady() || devices.count != 2 || devices.items[0].bus != 1 ||
devices.items[0].busy != 3 || devices.items[0].vram_used != 574619648 ||
devices.items[0].vram_total != 17103781888 || devices.items[1].bus != 2 ||
devices.items[1].busy != -1 || devices.items[1].vram_total != -1 {
print("gpu: device lines parsed wrong\n")
return false
}
Gpu.GpuSharesReset()
Gpu.GpuSharesFeed(BytesOf(first, bytes[:]))
if Gpu.GpuSharesReady() {
print("gpu: incomplete block published\n")
return false
}
Gpu.GpuSharesFeed(BytesOf(rest, bytes[:]))
shares := Gpu.GpuSharesCurrent()
if !Gpu.GpuSharesReady() || shares.count != 2 || shares.pids[0] != 2677 ||
shares.percent[0] != 1.0 || shares.pids[1] != 55268 || shares.percent[1] != 12.0 {
print("gpu: sample block parsed wrong\n")
return false
}
// An idle tick replaces the previous block with no processes.
Gpu.GpuSharesFeed(BytesOf("T\nE\n", bytes[:]))
if !Gpu.GpuSharesReady() || Gpu.GpuSharesCurrent().count != 0 {
print("gpu: idle sample kept stale shares\n")
return false
}
Gpu.GpuSharesFeed(BytesOf("X\n", bytes[:]))
if Gpu.GpuSharesReady() {
print("gpu: unusable source still ready\n")
return false
}
Gpu.GpuSharesReset()
return true
}
main :: (argc: s32, argv: **u8) -> s32 {
if argc != 1 {
print("usage: model_test\n")
@@ -580,6 +728,9 @@ main :: (argc: s32, argv: **u8) -> s32 {
if !ShortcutTest() { print("shortcut test failed\n"); return 75 }
if !ScanTest() { print("scan/snapshot test failed\n"); return 66 }
if !GroupingTest() { print("process grouping test failed\n"); return 72 }
if !AppUsageTest() { print("application usage test failed\n"); return 76 }
if !GpuSharesTest() { print("GPU shares test failed\n"); return 77 }
if !ExternalGpuTest() { print("external GPU test failed\n"); return 78 }
if !SortTest() { print("sort test failed\n"); return 67 }
if !FormatTest() { print("format test failed\n"); return 68 }
if !SignalTest() { print("signal binding test failed\n"); return 69 }
+1 -1
View File
@@ -49,6 +49,6 @@ backend = "pixmap"
[tool.kryon.install]
profile = "desktop"
name = "Task Manager"
icon_name = "utilities-system-monitor"
icon = "assets/taskmgr.svg"
comment = "Kryon process monitor"
categories = "Utility;System;"