* [PATCH v2 01/12] tools/arch/x86/pmtctl: Add pmtctl skeleton
2026-11-22 19:33 [PATCH v2 00/12] tools/arch/x86/pmtctl: Add Intel PMT command-line tool David E. Box
@ 2026-11-22 19:33 ` David E. Box
2026-11-22 19:33 ` [PATCH v2 02/12] tools/arch/x86/pmtctl: Add PMT telemetry device discovery David E. Box
` (10 subsequent siblings)
11 siblings, 0 replies; 13+ messages in thread
From: David E. Box @ 2026-11-22 19:33 UTC (permalink / raw)
To: Ilpo Järvinen, Hans de Goede
Cc: David E. Box, Andy Shevchenko, platform-driver-x86, linux-kernel
Intel Platform Monitoring Technology (PMT) exposes hardware telemetry
through the pmt_telemetry driver in sysfs. Each telemetry device
provides a binary data file whose layout is described by
platform-specific metric definitions that are published separately.
Add the skeleton of pmtctl, a command-line tool for discovering PMT
telemetry devices and sampling their metrics: the build, the logging
helpers and the main entry point with global option handling. The
commands are added in follow-up patches.
The tool exits with 0 on success, 1 if the request is wrong (an invalid
option or value, or nothing matches the selection) and 2 if carrying it
out fails. Library code returns 0 or a negative errno, and each command
maps errors to an exit status.
Errors and warnings go to stderr as "pmtctl: <level>: <message>".
Signed-off-by: David E. Box <david.e.box@linux.intel.com>
---
V2 changes:
- New patch: the Makefile, logging and main() from v1 03 and 12, so
the tool builds from the first patch.
- Logging is errors and warnings only; -q and --debug are dropped (v1
parsed them but never applied them).
- Library code returns 0 or -errno and never calls exit(); commands
map errors to the exit statuses 0/1/2.
- One plain Makefile, like the other tools in tools/arch/x86.
tools/arch/x86/pmtctl/.gitignore | 2 +
tools/arch/x86/pmtctl/Makefile | 25 ++++++++
tools/arch/x86/pmtctl/include/lib/log.h | 23 +++++++
tools/arch/x86/pmtctl/include/pmtctl_cli.h | 12 ++++
tools/arch/x86/pmtctl/lib/log.c | 41 ++++++++++++
tools/arch/x86/pmtctl/src/main.c | 72 ++++++++++++++++++++++
6 files changed, 175 insertions(+)
create mode 100644 tools/arch/x86/pmtctl/.gitignore
create mode 100644 tools/arch/x86/pmtctl/Makefile
create mode 100644 tools/arch/x86/pmtctl/include/lib/log.h
create mode 100644 tools/arch/x86/pmtctl/include/pmtctl_cli.h
create mode 100644 tools/arch/x86/pmtctl/lib/log.c
create mode 100644 tools/arch/x86/pmtctl/src/main.c
diff --git a/tools/arch/x86/pmtctl/.gitignore b/tools/arch/x86/pmtctl/.gitignore
new file mode 100644
index 000000000000..3bd0d7c1b61a
--- /dev/null
+++ b/tools/arch/x86/pmtctl/.gitignore
@@ -0,0 +1,2 @@
+# SPDX-License-Identifier: GPL-2.0-only
+pmtctl
diff --git a/tools/arch/x86/pmtctl/Makefile b/tools/arch/x86/pmtctl/Makefile
new file mode 100644
index 000000000000..0595d6617920
--- /dev/null
+++ b/tools/arch/x86/pmtctl/Makefile
@@ -0,0 +1,25 @@
+# SPDX-License-Identifier: GPL-2.0
+# Makefile for Intel Platform Monitoring Technology (PMT) tool
+
+BINDIR ?= /usr/sbin
+
+CFLAGS = -Wextra
+
+override CFLAGS += -O2 -Wall -D_GNU_SOURCE -Iinclude -I../../../include
+
+OBJS := \
+ lib/log.o \
+ src/main.o
+
+pmtctl: $(OBJS)
+ $(CC) $(CFLAGS) $(LDFLAGS) -o $@ $^ $(LDLIBS)
+
+$(OBJS): $(wildcard include/*.h include/lib/*.h)
+
+.PHONY: clean install
+clean:
+ @rm -f pmtctl $(OBJS)
+
+install: pmtctl
+ install -d $(DESTDIR)$(BINDIR)
+ install -m 755 -p pmtctl $(DESTDIR)$(BINDIR)/pmtctl
diff --git a/tools/arch/x86/pmtctl/include/lib/log.h b/tools/arch/x86/pmtctl/include/lib/log.h
new file mode 100644
index 000000000000..2006b5b50637
--- /dev/null
+++ b/tools/arch/x86/pmtctl/include/lib/log.h
@@ -0,0 +1,23 @@
+/* SPDX-License-Identifier: GPL-2.0-only */
+#ifndef PMTCTL_LOG_H
+#define PMTCTL_LOG_H
+
+#include <linux/compiler.h>
+
+enum pmtctl_log_level {
+ PMTCTL_LOG_ERROR,
+ PMTCTL_LOG_WARN,
+};
+
+void log_msg(enum pmtctl_log_level level, const char *fmt, ...) __printf(2, 3);
+
+/*
+ * Log an error with the strerror() text of @ret appended and return @ret.
+ * @ret must be a negative errno value.
+ */
+int log_ret(int ret, const char *fmt, ...) __printf(2, 3);
+
+#define log_err(fmt, ...) log_msg(PMTCTL_LOG_ERROR, fmt, ##__VA_ARGS__)
+#define log_warn(fmt, ...) log_msg(PMTCTL_LOG_WARN, fmt, ##__VA_ARGS__)
+
+#endif
diff --git a/tools/arch/x86/pmtctl/include/pmtctl_cli.h b/tools/arch/x86/pmtctl/include/pmtctl_cli.h
new file mode 100644
index 000000000000..550a61b97aca
--- /dev/null
+++ b/tools/arch/x86/pmtctl/include/pmtctl_cli.h
@@ -0,0 +1,12 @@
+/* SPDX-License-Identifier: GPL-2.0-only */
+#ifndef PMTCTL_CLI_H
+#define PMTCTL_CLI_H
+
+/* Process exit status, see EXIT STATUS in pmtctl(8) */
+enum pmtctl_exit {
+ PMTCTL_EXIT_OK,
+ PMTCTL_EXIT_USER,
+ PMTCTL_EXIT_SYSTEM,
+};
+
+#endif
diff --git a/tools/arch/x86/pmtctl/lib/log.c b/tools/arch/x86/pmtctl/lib/log.c
new file mode 100644
index 000000000000..87a24d076cb2
--- /dev/null
+++ b/tools/arch/x86/pmtctl/lib/log.c
@@ -0,0 +1,41 @@
+// SPDX-License-Identifier: GPL-2.0-only
+#include <stdarg.h>
+#include <stdio.h>
+#include <string.h>
+
+#include "lib/log.h"
+
+static const char * const log_tags[] = {
+ [PMTCTL_LOG_ERROR] = "error",
+ [PMTCTL_LOG_WARN] = "warning",
+};
+
+static __printf(3, 0)
+void log_vmsg(enum pmtctl_log_level level, int err, const char *fmt, va_list ap)
+{
+ fprintf(stderr, "pmtctl: %s: ", log_tags[level]);
+ vfprintf(stderr, fmt, ap);
+ if (err)
+ fprintf(stderr, ": %s", strerror(-err));
+ fputc('\n', stderr);
+}
+
+void log_msg(enum pmtctl_log_level level, const char *fmt, ...)
+{
+ va_list ap;
+
+ va_start(ap, fmt);
+ log_vmsg(level, 0, fmt, ap);
+ va_end(ap);
+}
+
+int log_ret(int ret, const char *fmt, ...)
+{
+ va_list ap;
+
+ va_start(ap, fmt);
+ log_vmsg(PMTCTL_LOG_ERROR, ret, fmt, ap);
+ va_end(ap);
+
+ return ret;
+}
diff --git a/tools/arch/x86/pmtctl/src/main.c b/tools/arch/x86/pmtctl/src/main.c
new file mode 100644
index 000000000000..25aedef59cf5
--- /dev/null
+++ b/tools/arch/x86/pmtctl/src/main.c
@@ -0,0 +1,72 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/*
+ * pmtctl: query Intel Platform Monitoring Technology (PMT) telemetry
+ */
+#include <getopt.h>
+#include <stdio.h>
+#include <string.h>
+
+#include "lib/log.h"
+#include "pmtctl_cli.h"
+
+#define PMTCTL_VERSION "2026.11.22"
+
+static void print_usage(FILE *out)
+{
+ fprintf(out,
+ "Usage: pmtctl [global options] <command> [command options] ...\n"
+ "\n"
+ "Query Intel Platform Monitoring Technology (PMT) metrics.\n"
+ "\n"
+ "Global options:\n"
+ " -h, --help Show this help and exit\n"
+ " -V, --version Show version and exit\n"
+ "\n"
+ "Run 'pmtctl <command> --help' for command-specific options.\n");
+}
+
+int main(int argc, char **argv)
+{
+ static const struct option long_opts[] = {
+ { "help", no_argument, NULL, 'h' },
+ { "version", no_argument, NULL, 'V' },
+ {}
+ };
+ const char *cmd;
+ int opt;
+
+ /* '+' stops at the first non-option: the command name */
+ while ((opt = getopt_long(argc, argv, "+hV", long_opts, NULL)) != -1) {
+ switch (opt) {
+ case 'h':
+ print_usage(stdout);
+ return PMTCTL_EXIT_OK;
+ case 'V':
+ printf("pmtctl version %s - David E. Box <david.e.box@linux.intel.com>\n",
+ PMTCTL_VERSION);
+ return PMTCTL_EXIT_OK;
+ default:
+ /* getopt_long() already printed an error */
+ fprintf(stderr, "Try 'pmtctl --help' for usage.\n");
+ return PMTCTL_EXIT_USER;
+ }
+ }
+
+ if (optind >= argc) {
+ log_err("missing command");
+ print_usage(stderr);
+ return PMTCTL_EXIT_USER;
+ }
+
+ cmd = argv[optind];
+
+ if (!strcmp(cmd, "help")) {
+ print_usage(stdout);
+ return PMTCTL_EXIT_OK;
+ }
+
+ log_err("unknown command '%s'", cmd);
+ fprintf(stderr, "Run 'pmtctl --help' for a list of commands.\n");
+
+ return PMTCTL_EXIT_USER;
+}
--
2.53.0
^ permalink raw reply related [flat|nested] 13+ messages in thread* [PATCH v2 02/12] tools/arch/x86/pmtctl: Add PMT telemetry device discovery
2026-11-22 19:33 [PATCH v2 00/12] tools/arch/x86/pmtctl: Add Intel PMT command-line tool David E. Box
2026-11-22 19:33 ` [PATCH v2 01/12] tools/arch/x86/pmtctl: Add pmtctl skeleton David E. Box
@ 2026-11-22 19:33 ` David E. Box
2026-11-22 19:33 ` [PATCH v2 03/12] tools/arch/x86/pmtctl: Add pmtxml2json conversion tool David E. Box
` (9 subsequent siblings)
11 siblings, 0 replies; 13+ messages in thread
From: David E. Box @ 2026-11-22 19:33 UTC (permalink / raw)
To: Ilpo Järvinen, Hans de Goede
Cc: David E. Box, Andy Shevchenko, platform-driver-x86, linux-kernel
The pmt_telemetry driver binds to Intel VSEC auxiliary devices and
registers one telemetry device, telemN, per telemetry region under the
auxiliary device's intel_pmt directory. Each telemetry device has a guid
attribute that identifies its metric layout and a telem file with the
sample data.
Add discovery of these telemetry devices. telem_scan() walks the
auxiliary devices bound to pmt_telemetry and records the GUID, name and
data file path of each telemetry device. A device whose GUID can't be
read is skipped with a warning. If no devices are found, an error asks
whether the driver is loaded. The devices are returned sorted by GUID
and then by name, so the commands built on them don't depend on the
order of the sysfs directories.
The results are held in struct pmtctl_ctx, which each command owns and
releases with pmtctl_ctx_free(). auto_pmtctl_ctx frees it automatically
at scope exit, and auto_free does the same for heap pointers.
Also add small helpers to lib/common.c, used by this and later patches:
pmt_grow_array() grows a dynamic array by doubling its capacity,
parse_u32() parses a whole string as an unsigned 32-bit number, and
path_printf() builds a path, failing instead of truncating.
Signed-off-by: David E. Box <david.e.box@linux.intel.com>
---
V2 changes:
- Replaces v1 05, with the context from v1 08 and pmt_grow_array()
from v1 03.
- Unused device fields and sysfs helpers dropped.
- A device whose GUID can't be read is skipped with a warning.
- Devices are returned sorted by GUID and name, independent of the
order of the sysfs directories.
- pmt_grow_array() returns the array and uses reallocarray(), with no
realloc(+1) growth or void ** cast.
- parse_u32() rejects a sign, leading whitespace and trailing
characters; path_printf() fails instead of truncating.
tools/arch/x86/pmtctl/Makefile | 3 +
tools/arch/x86/pmtctl/include/lib/common.h | 64 ++++++
tools/arch/x86/pmtctl/include/lib/device.h | 18 ++
tools/arch/x86/pmtctl/include/lib/pmtctl.h | 24 ++
tools/arch/x86/pmtctl/lib/common.c | 75 +++++++
tools/arch/x86/pmtctl/lib/device_telem.c | 248 +++++++++++++++++++++
tools/arch/x86/pmtctl/lib/pmtctl.c | 22 ++
7 files changed, 454 insertions(+)
create mode 100644 tools/arch/x86/pmtctl/include/lib/common.h
create mode 100644 tools/arch/x86/pmtctl/include/lib/device.h
create mode 100644 tools/arch/x86/pmtctl/include/lib/pmtctl.h
create mode 100644 tools/arch/x86/pmtctl/lib/common.c
create mode 100644 tools/arch/x86/pmtctl/lib/device_telem.c
create mode 100644 tools/arch/x86/pmtctl/lib/pmtctl.c
diff --git a/tools/arch/x86/pmtctl/Makefile b/tools/arch/x86/pmtctl/Makefile
index 0595d6617920..bf422b84fd34 100644
--- a/tools/arch/x86/pmtctl/Makefile
+++ b/tools/arch/x86/pmtctl/Makefile
@@ -8,7 +8,10 @@ CFLAGS = -Wextra
override CFLAGS += -O2 -Wall -D_GNU_SOURCE -Iinclude -I../../../include
OBJS := \
+ lib/common.o \
+ lib/device_telem.o \
lib/log.o \
+ lib/pmtctl.o \
src/main.o
pmtctl: $(OBJS)
diff --git a/tools/arch/x86/pmtctl/include/lib/common.h b/tools/arch/x86/pmtctl/include/lib/common.h
new file mode 100644
index 000000000000..0e1950bffc43
--- /dev/null
+++ b/tools/arch/x86/pmtctl/include/lib/common.h
@@ -0,0 +1,64 @@
+/* SPDX-License-Identifier: GPL-2.0-only */
+#ifndef PMTCTL_COMMON_H
+#define PMTCTL_COMMON_H
+
+#include <stddef.h>
+#include <stdint.h>
+#include <stdlib.h>
+
+#include <linux/compiler.h>
+
+static inline void freep(void *p)
+{
+ free(*(void **)p);
+}
+
+/* Free the pointer with free() at scope exit: char *p auto_free = NULL; */
+#define auto_free __attribute__((cleanup(freep)))
+
+/* Take ownership of an auto_free pointer so it is not freed at scope exit */
+#define no_free_ptr(p) \
+ ({ typeof(p) __ptr = (p); (p) = NULL; __ptr; })
+
+#define PMT_ARRAY_INITIAL_CAP 16
+
+/**
+ * pmt_grow_array - grow a dynamic array
+ * @array: array allocated with malloc() and friends, or NULL
+ * @cap: current capacity in elements, updated on success
+ * @min_cap: required capacity in elements
+ * @elem_size: element size in bytes
+ *
+ * The capacity starts at PMT_ARRAY_INITIAL_CAP and doubles until it
+ * reaches @min_cap.
+ *
+ * Return: the possibly moved array, or NULL on allocation failure or
+ * overflow. On failure @array and @cap are unchanged.
+ */
+void *pmt_grow_array(void *array, size_t *cap, size_t min_cap, size_t elem_size);
+
+/**
+ * parse_u32 - parse a complete string as an unsigned 32-bit number
+ * @s: string to parse
+ * @base: number base, as for strtoul()
+ * @val: returns the parsed value
+ *
+ * Unlike strtoul(), leading whitespace and a sign are not accepted.
+ *
+ * Return: 0 on success, -EINVAL if @s is not a number or has trailing
+ * characters, or -ERANGE if the value does not fit in 32 bits.
+ */
+int parse_u32(const char *s, int base, uint32_t *val);
+
+/**
+ * path_printf - format a path into a buffer
+ * @buf: buffer for the path
+ * @size: size of @buf in bytes
+ * @fmt: printf() format of the path
+ * @...: arguments for @fmt
+ *
+ * Return: 0 on success, or -ENAMETOOLONG if the path does not fit in @buf.
+ */
+int path_printf(char *buf, size_t size, const char *fmt, ...) __printf(3, 4);
+
+#endif
diff --git a/tools/arch/x86/pmtctl/include/lib/device.h b/tools/arch/x86/pmtctl/include/lib/device.h
new file mode 100644
index 000000000000..92d9603d695c
--- /dev/null
+++ b/tools/arch/x86/pmtctl/include/lib/device.h
@@ -0,0 +1,18 @@
+/* SPDX-License-Identifier: GPL-2.0-only */
+#ifndef PMTCTL_DEVICE_H
+#define PMTCTL_DEVICE_H
+
+#include <stddef.h>
+#include <stdint.h>
+
+/* A PMT telemetry device registered by the pmt_telemetry driver */
+struct pmt_device {
+ uint32_t guid;
+ char *name; /* e.g. "telem0" */
+ char *data_path; /* telemetry data file */
+};
+
+int telem_scan(struct pmt_device **devices, size_t *num_devices);
+void telem_free(struct pmt_device *devices, size_t num_devices);
+
+#endif
diff --git a/tools/arch/x86/pmtctl/include/lib/pmtctl.h b/tools/arch/x86/pmtctl/include/lib/pmtctl.h
new file mode 100644
index 000000000000..e3a2c862bc78
--- /dev/null
+++ b/tools/arch/x86/pmtctl/include/lib/pmtctl.h
@@ -0,0 +1,24 @@
+/* SPDX-License-Identifier: GPL-2.0-only */
+#ifndef PMTCTL_H
+#define PMTCTL_H
+
+#include <stddef.h>
+
+#include "lib/device.h"
+
+/* State for one pmtctl command, owned by the command */
+struct pmtctl_ctx {
+ struct pmt_device *devices;
+ size_t num_devices;
+};
+
+int pmtctl_ctx_init(struct pmtctl_ctx *ctx);
+void pmtctl_ctx_free(struct pmtctl_ctx *ctx);
+
+/*
+ * Free the context with pmtctl_ctx_free() at scope exit:
+ * struct pmtctl_ctx ctx auto_pmtctl_ctx = {};
+ */
+#define auto_pmtctl_ctx __attribute__((cleanup(pmtctl_ctx_free)))
+
+#endif
diff --git a/tools/arch/x86/pmtctl/lib/common.c b/tools/arch/x86/pmtctl/lib/common.c
new file mode 100644
index 000000000000..adf546df0911
--- /dev/null
+++ b/tools/arch/x86/pmtctl/lib/common.c
@@ -0,0 +1,75 @@
+// SPDX-License-Identifier: GPL-2.0-only
+#include <ctype.h>
+#include <errno.h>
+#include <stdarg.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+
+#include "lib/common.h"
+
+void *pmt_grow_array(void *array, size_t *cap, size_t min_cap, size_t elem_size)
+{
+ size_t new_cap;
+ void *new_array;
+
+ if (*cap >= min_cap)
+ return array;
+
+ new_cap = *cap;
+ if (!new_cap)
+ new_cap = PMT_ARRAY_INITIAL_CAP;
+
+ while (new_cap < min_cap) {
+ if (new_cap > SIZE_MAX / 2)
+ return NULL;
+ new_cap *= 2;
+ }
+
+ new_array = reallocarray(array, new_cap, elem_size);
+ if (!new_array)
+ return NULL;
+
+ *cap = new_cap;
+
+ return new_array;
+}
+
+int parse_u32(const char *s, int base, uint32_t *val)
+{
+ unsigned long v;
+ char *end;
+
+ if (!isxdigit((unsigned char)*s))
+ return -EINVAL;
+
+ errno = 0;
+ v = strtoul(s, &end, base);
+ if (errno)
+ return -errno;
+
+ if (end == s || *end != '\0')
+ return -EINVAL;
+
+ if (v > UINT32_MAX)
+ return -ERANGE;
+
+ *val = v;
+
+ return 0;
+}
+
+int path_printf(char *buf, size_t size, const char *fmt, ...)
+{
+ va_list ap;
+ int len;
+
+ va_start(ap, fmt);
+ len = vsnprintf(buf, size, fmt, ap);
+ va_end(ap);
+
+ if (len < 0 || (size_t)len >= size)
+ return -ENAMETOOLONG;
+
+ return 0;
+}
diff --git a/tools/arch/x86/pmtctl/lib/device_telem.c b/tools/arch/x86/pmtctl/lib/device_telem.c
new file mode 100644
index 000000000000..0e249f16a21a
--- /dev/null
+++ b/tools/arch/x86/pmtctl/lib/device_telem.c
@@ -0,0 +1,248 @@
+// SPDX-License-Identifier: GPL-2.0-only
+#include <ctype.h>
+#include <dirent.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <limits.h>
+#include <stdbool.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+#include "lib/common.h"
+#include "lib/device.h"
+#include "lib/log.h"
+
+#define PMT_TELEM_AUX_DIR "/sys/bus/auxiliary/drivers/pmt_telemetry"
+#define PMT_TELEM_PMT_DIR "intel_pmt"
+#define PMT_TELEM_PREFIX "telem"
+#define PMT_TELEM_DATA_FILE "telem"
+
+struct telem_scan {
+ struct pmt_device *devices;
+ size_t num_devices;
+ size_t cap;
+};
+
+/* Read sysfs attribute @dir/@name into @buf without trailing whitespace */
+static int read_attr_text(const char *dir, const char *name, char *buf, size_t buflen)
+{
+ char path[PATH_MAX];
+ ssize_t n;
+ int ret;
+ int fd;
+
+ ret = path_printf(path, sizeof(path), "%s/%s", dir, name);
+ if (ret)
+ return ret;
+
+ fd = open(path, O_RDONLY);
+ if (fd < 0)
+ return -errno;
+
+ n = read(fd, buf, buflen - 1);
+ if (n < 0) {
+ ret = -errno;
+ close(fd);
+ return ret;
+ }
+ close(fd);
+
+ while (n > 0 && isspace((unsigned char)buf[n - 1]))
+ n--;
+ buf[n] = '\0';
+
+ return 0;
+}
+
+/* Read sysfs attribute @dir/@name as a number in @base, as for parse_u32() */
+static int read_attr_u32(const char *dir, const char *name, int base, uint32_t *val)
+{
+ char buf[64];
+ int ret;
+
+ ret = read_attr_text(dir, name, buf, sizeof(buf));
+ if (ret)
+ return ret;
+
+ return parse_u32(buf, base, val);
+}
+
+/* Match "telem<N>" where <N> is a decimal number */
+static bool is_telem_name(const char *name)
+{
+ const size_t prefix_len = strlen(PMT_TELEM_PREFIX);
+ const char *num;
+
+ if (strncmp(name, PMT_TELEM_PREFIX, prefix_len))
+ return false;
+
+ num = name + prefix_len;
+
+ return *num != '\0' && num[strspn(num, "0123456789")] == '\0';
+}
+
+static int telem_add_device(struct telem_scan *scan, const char *devpath, const char *name)
+{
+ char *dev_name auto_free = NULL;
+ char *data_path auto_free = NULL;
+ struct pmt_device *devices;
+ uint32_t guid;
+ int ret;
+
+ ret = read_attr_u32(devpath, "guid", 16, &guid);
+ if (ret) {
+ log_warn("skipping %s: unable to read guid: %s", devpath, strerror(-ret));
+ return 0;
+ }
+
+ dev_name = strdup(name);
+ if (!dev_name)
+ return -ENOMEM;
+
+ if (asprintf(&data_path, "%s/%s", devpath, PMT_TELEM_DATA_FILE) < 0) {
+ /* asprintf() leaves the pointer undefined on failure */
+ data_path = NULL;
+ return -ENOMEM;
+ }
+
+ devices = pmt_grow_array(scan->devices, &scan->cap, scan->num_devices + 1,
+ sizeof(*devices));
+ if (!devices)
+ return -ENOMEM;
+
+ scan->devices = devices;
+
+ devices[scan->num_devices++] = (struct pmt_device) {
+ .guid = guid,
+ .name = no_free_ptr(dev_name),
+ .data_path = no_free_ptr(data_path),
+ };
+
+ return 0;
+}
+
+/* Add the telemetry devices under one auxiliary device's intel_pmt directory */
+static int telem_scan_pmt_dir(struct telem_scan *scan, const char *pmt_path)
+{
+ struct dirent *de;
+ DIR *dir;
+ int ret = 0;
+
+ dir = opendir(pmt_path);
+ if (!dir) {
+ /* Most driver directory entries (bind, uevent, ...) aren't devices */
+ if (errno == ENOENT || errno == ENOTDIR)
+ return 0;
+
+ return -errno;
+ }
+
+ while ((de = readdir(dir))) {
+ char devpath[PATH_MAX];
+
+ if (!is_telem_name(de->d_name))
+ continue;
+
+ ret = path_printf(devpath, sizeof(devpath), "%s/%s", pmt_path, de->d_name);
+ if (ret)
+ break;
+
+ ret = telem_add_device(scan, devpath, de->d_name);
+ if (ret)
+ break;
+ }
+
+ closedir(dir);
+
+ return ret;
+}
+
+/* Walk the auxiliary devices bound to the pmt_telemetry driver */
+static int telem_scan_aux_dir(struct telem_scan *scan)
+{
+ struct dirent *de;
+ DIR *dir;
+ int ret = 0;
+
+ /* Without the driver there are no devices, which telem_scan() reports */
+ dir = opendir(PMT_TELEM_AUX_DIR);
+ if (!dir)
+ return 0;
+
+ while ((de = readdir(dir))) {
+ char pmt_path[PATH_MAX];
+
+ if (de->d_name[0] == '.')
+ continue;
+
+ ret = path_printf(pmt_path, sizeof(pmt_path), "%s/%s/%s",
+ PMT_TELEM_AUX_DIR, de->d_name, PMT_TELEM_PMT_DIR);
+ if (ret)
+ break;
+
+ ret = telem_scan_pmt_dir(scan, pmt_path);
+ if (ret)
+ break;
+ }
+
+ closedir(dir);
+
+ return ret;
+}
+
+/* Order devices by GUID, then by name, so telem2 comes before telem10 */
+static int device_cmp(const void *a, const void *b)
+{
+ const struct pmt_device *da = a;
+ const struct pmt_device *db = b;
+
+ if (da->guid != db->guid)
+ return da->guid < db->guid ? -1 : 1;
+
+ return strverscmp(da->name, db->name);
+}
+
+/**
+ * telem_scan - discover PMT telemetry devices
+ * @devices: returns the discovered devices sorted by GUID, then by name.
+ * Freed with telem_free().
+ * @num_devices: returns the number of entries in @devices
+ *
+ * Return: 0 on success, -ENODEV if no devices were found, or another
+ * negative errno on failure.
+ */
+int telem_scan(struct pmt_device **devices, size_t *num_devices)
+{
+ struct telem_scan scan = {};
+ int ret;
+
+ ret = telem_scan_aux_dir(&scan);
+ if (ret) {
+ telem_free(scan.devices, scan.num_devices);
+ return log_ret(ret, "unable to scan PMT telemetry devices");
+ }
+
+ if (!scan.num_devices) {
+ log_err("no PMT telemetry devices found (is the pmt_telemetry driver loaded?)");
+ return -ENODEV;
+ }
+
+ qsort(scan.devices, scan.num_devices, sizeof(*scan.devices), device_cmp);
+
+ *devices = scan.devices;
+ *num_devices = scan.num_devices;
+
+ return 0;
+}
+
+void telem_free(struct pmt_device *devices, size_t num_devices)
+{
+ for (size_t i = 0; i < num_devices; i++) {
+ free(devices[i].name);
+ free(devices[i].data_path);
+ }
+ free(devices);
+}
diff --git a/tools/arch/x86/pmtctl/lib/pmtctl.c b/tools/arch/x86/pmtctl/lib/pmtctl.c
new file mode 100644
index 000000000000..9a6fd2a303f4
--- /dev/null
+++ b/tools/arch/x86/pmtctl/lib/pmtctl.c
@@ -0,0 +1,22 @@
+// SPDX-License-Identifier: GPL-2.0-only
+#include "lib/device.h"
+#include "lib/pmtctl.h"
+
+/**
+ * pmtctl_ctx_init - discover PMT devices
+ * @ctx: zero-initialized context
+ *
+ * Return: 0 on success or a negative errno. @ctx must be released with
+ * pmtctl_ctx_free() in either case.
+ */
+int pmtctl_ctx_init(struct pmtctl_ctx *ctx)
+{
+ return telem_scan(&ctx->devices, &ctx->num_devices);
+}
+
+void pmtctl_ctx_free(struct pmtctl_ctx *ctx)
+{
+ telem_free(ctx->devices, ctx->num_devices);
+ ctx->devices = NULL;
+ ctx->num_devices = 0;
+}
--
2.53.0
^ permalink raw reply related [flat|nested] 13+ messages in thread* [PATCH v2 03/12] tools/arch/x86/pmtctl: Add pmtxml2json conversion tool
2026-11-22 19:33 [PATCH v2 00/12] tools/arch/x86/pmtctl: Add Intel PMT command-line tool David E. Box
2026-11-22 19:33 ` [PATCH v2 01/12] tools/arch/x86/pmtctl: Add pmtctl skeleton David E. Box
2026-11-22 19:33 ` [PATCH v2 02/12] tools/arch/x86/pmtctl: Add PMT telemetry device discovery David E. Box
@ 2026-11-22 19:33 ` David E. Box
2026-11-22 19:33 ` [PATCH v2 04/12] tools/arch/x86/pmtctl: Add JSON metric definition loading David E. Box
` (8 subsequent siblings)
11 siblings, 0 replies; 13+ messages in thread
From: David E. Box @ 2026-11-22 19:33 UTC (permalink / raw)
To: Ilpo Järvinen, Hans de Goede
Cc: David E. Box, Andy Shevchenko, platform-driver-x86, linux-kernel
The layout of each PMT telemetry region is described by aggregator XML
files published in the Intel-PMT repository
(https://github.com/intel/Intel-PMT). Each file lists the samples of
one GUID with their sample ID, bit range and description.
Add pmtxml2json.py, which converts these files into JSON metric
definitions that pmtctl can load at runtime. Each aggregator becomes a
pmt_<guid>.json file holding the GUID, its platform and description,
and one event per sample with its name, description, sample ID and bit
range. Event names are derived from the sample names. Where a name
would collide, the samples of the subgroups involved are all prefixed
with their subgroup, so the members of a subgroup are named alike.
Reserved samples are skipped. The rules are described in
pmtxml2json.md.
The aggregator files include shared data type definitions from a
*_common.xml file through an external XML entity. pmtxml2json doesn't
need those definitions, so it parses the XML with lxml with entity
resolution turned off, leaving the entity unresolved. The standard
library parser can't do that.
Add Makefile targets to fetch the repository into a local cache and
convert it into defs/, replacing the definitions of an earlier run:
make defs-json-fetch # clone (once) and convert
make defs-json-pull # update the clone and convert again
make defs-clean # remove defs/
The fetch targets are not part of the default build, to avoid
unexpected network access.
Signed-off-by: David E. Box <david.e.box@linux.intel.com>
---
V2 changes:
- Replaces v1 15.
- New output format: one pmt_<guid>.json per GUID with only what
pmtctl uses. The perf-style PMU, ConfigCode and MetricGroup fields
and the pmt_guids.json sidecar are gone.
- GUIDs written without 0x and with decimal digits only are read as
hex; v1 converted 7 published GUIDs under the wrong number.
- Names that differ only in case are disambiguated, and all members
of a subgroup with a colliding name are prefixed together.
- XML is parsed with entity resolution turned off; lxml is checked
for and documented.
- Fetching again removes stale definitions; the Makefile has fetch
targets only, with no C code generation.
- Dead code removed.
tools/arch/x86/pmtctl/.gitignore | 1 +
tools/arch/x86/pmtctl/Makefile | 55 +-
tools/arch/x86/pmtctl/scripts/pmtxml2json.md | 189 ++++++
tools/arch/x86/pmtctl/scripts/pmtxml2json.py | 639 +++++++++++++++++++
4 files changed, 883 insertions(+), 1 deletion(-)
create mode 100644 tools/arch/x86/pmtctl/scripts/pmtxml2json.md
create mode 100755 tools/arch/x86/pmtctl/scripts/pmtxml2json.py
diff --git a/tools/arch/x86/pmtctl/.gitignore b/tools/arch/x86/pmtctl/.gitignore
index 3bd0d7c1b61a..45f94e0b3900 100644
--- a/tools/arch/x86/pmtctl/.gitignore
+++ b/tools/arch/x86/pmtctl/.gitignore
@@ -1,2 +1,3 @@
# SPDX-License-Identifier: GPL-2.0-only
pmtctl
+defs/
diff --git a/tools/arch/x86/pmtctl/Makefile b/tools/arch/x86/pmtctl/Makefile
index bf422b84fd34..2d66e4e036cc 100644
--- a/tools/arch/x86/pmtctl/Makefile
+++ b/tools/arch/x86/pmtctl/Makefile
@@ -19,7 +19,60 @@ pmtctl: $(OBJS)
$(OBJS): $(wildcard include/*.h include/lib/*.h)
-.PHONY: clean install
+# --- XML -> JSON step (network-bound; opt-in) ---
+#
+# Fetches the Intel-PMT git repo (cached under $(PMT_CACHE_DIR)) and
+# converts every aggregator XML into JSON under $(DEFS_DIR)/,
+# for use with 'pmtctl -J $(DEFS_DIR)'.
+# Not wired into 'all' on purpose: avoid surprise network access.
+PYTHON ?= python3
+DEFS_DIR ?= defs
+PMT_CACHE_DIR ?= $(HOME)/.cache/pmtctl
+
+XML2JSON_SCRIPT := scripts/pmtxml2json.py
+
+# Stamp marks "the XML->JSON conversion has run". The exact set of
+# generated files is not known up front, so we depend on a single stamp.
+# It is redone when the script changes; use defs-json-pull to update the
+# XML, or defs-clean to start over.
+DEFS_JSON_STAMP := $(DEFS_DIR)/.stamp
+
+defs-json-fetch: $(DEFS_JSON_STAMP)
+
+# Fail early, with the package to install, if python3 or lxml is missing
+XML2JSON_CHECK = @$(PYTHON) -c 'import lxml' 2>/dev/null || { \
+ echo "$(XML2JSON_SCRIPT) needs $(PYTHON) with lxml (package python3-lxml)" >&2; \
+ exit 1; }
+
+$(DEFS_JSON_STAMP): $(XML2JSON_SCRIPT)
+ @echo "defs-json-fetch: converting Intel-PMT XML from $(PMT_CACHE_DIR) (cloned if missing)"
+ $(XML2JSON_CHECK)
+ @mkdir -p $(DEFS_DIR)
+ @rm -f $(DEFS_DIR)/pmt_*.json
+ $(PYTHON) $(XML2JSON_SCRIPT) \
+ --fetch-pmt-repo \
+ --pmt-cache-dir $(PMT_CACHE_DIR) \
+ --output-dir $(DEFS_DIR)
+ @touch $@
+
+# Run 'git pull' on the cached Intel-PMT repo, then regenerate JSON.
+defs-json-pull: $(XML2JSON_SCRIPT)
+ @echo "defs-json-pull: running 'git pull' on $(PMT_CACHE_DIR)"
+ $(XML2JSON_CHECK)
+ @mkdir -p $(DEFS_DIR)
+ @rm -f $(DEFS_DIR)/pmt_*.json
+ $(PYTHON) $(XML2JSON_SCRIPT) \
+ --fetch-pmt-repo --refresh-pmt-repo \
+ --pmt-cache-dir $(PMT_CACHE_DIR) \
+ --output-dir $(DEFS_DIR)
+ @touch $(DEFS_JSON_STAMP)
+
+# Separate from 'clean' so a routine clean does not throw away the
+# (potentially slow) fetched/converted JSON tree.
+defs-clean:
+ rm -rf $(DEFS_DIR)
+
+.PHONY: clean install defs-json-fetch defs-json-pull defs-clean
clean:
@rm -f pmtctl $(OBJS)
diff --git a/tools/arch/x86/pmtctl/scripts/pmtxml2json.md b/tools/arch/x86/pmtctl/scripts/pmtxml2json.md
new file mode 100644
index 000000000000..edfaab6fd2f7
--- /dev/null
+++ b/tools/arch/x86/pmtctl/scripts/pmtxml2json.md
@@ -0,0 +1,189 @@
+# pmtxml2json: XML → JSON conversion
+
+[`pmtxml2json.py`](pmtxml2json.py) converts Intel PMT (Platform Monitoring
+Technology) Aggregator XML files into JSON metric definitions
+that `pmtctl` loads with `-J <dir>`.
+
+This document focuses on the **EventName naming convention** — the rule used
+to derive an event name from each `<TELC:sample>` element.
+
+## Requirements and usage
+
+The script needs Python 3 and [lxml](https://lxml.de). The aggregator files
+include their `*_common.xml` data types through an external entity; lxml can
+leave it unresolved, which the standard library XML parser cannot.
+
+Normally it is run by `make defs-json-fetch`, which clones the Intel-PMT
+repository into a cache directory and writes the definitions to `defs/`. It
+can also convert a local copy:
+
+```sh
+scripts/pmtxml2json.py --by-path <Intel-PMT>/xml --output-dir defs
+```
+
+See `--help` for all options. The exit status is 0 on success, 1 if any
+aggregator could not be converted, and 2 for a usage or fetch error.
+
+## Inputs
+
+For each sample, only two XML inputs participate in naming:
+
+| Input | XML source | Example value |
+| ----------------- | ----------------------------------------- | ------------------------- |
+| `name` | `name=` attribute on `<TELC:sample>` | `IA_SCALABILITY` |
+| `sampleSubGroup` | `<TELC:sampleSubGroup>` child text | `IA_SCALABILITY_CORE7` |
+
+The aggregator's `<TELEM:uniqueid>` (GUID) is used for the output filename
+(`pmt_<guid>.json`), **not** for naming.
+
+`sampleID`, `sampleGroupID`, `lsb`, `msb`, and `productid` are not used to
+build `EventName`. They describe bit layout, packaging, or platform
+identity rather than the metric's identity, and using them would either
+produce names that change when the XML is regenerated or names that
+duplicate information already stored in `guid`, `sample_id`, `lsb` and
+`msb`.
+
+## Pre-filter: reserved samples
+
+Before naming, a sample is dropped if
+
+- its `name` attribute or `<TELC:sampleSubGroup>` text contains `reserved`
+ or `rsvd` (case-insensitive, optionally with trailing digits) as a separate
+ token, or
+- its sample or group `<TELC:description>` is just `reserved` or `rsvd`
+ (optionally with digits). Descriptions are prose, so a mention elsewhere in
+ the text doesn't count.
+
+Reserved samples never receive an `EventName`.
+
+## Naming rule (lazy prefix, per subgroup)
+
+Within a single aggregator XML, a `name` **collides** if more than one
+non-reserved sample has it after `sanitize()`, so names that differ only in
+case collide. A subgroup is **prefixed** if any of its samples has a colliding
+name. For each surviving sample:
+
+1. If its subgroup is prefixed and the subgroup differs from `name`:
+ `EventName = sanitize(sampleSubGroup) + "." + sanitize(name)`
+2. Otherwise:
+ `EventName = sanitize(name)`
+
+All samples of a prefixed subgroup are named alike, so related metrics stay
+together in `pmtctl list`, which sorts them by name.
+
+### Why lazy?
+
+`sampleSubGroup` plays two different roles in practice:
+
+- A **metric-instance index** — e.g. `IA_SCALABILITY_CORE7` qualifies a
+ per-core copy of `IA_SCALABILITY`. Prefixing is meaningful and useful.
+- A **container alias** — e.g. `INTEL_VERSION_2` is just an enclosing
+ container around an already-unique `RTL_VERSION`. Prefixing here would
+ produce a confusing label like `intel_version_2.rtl_version`.
+
+The lazy rule borrows `sampleSubGroup` **only for subgroups with a colliding
+name**, yielding clean labels in the common case and disambiguated ones when
+needed.
+
+### `sanitize()`
+
+`_sanitize_token()` lowercases the text and replaces each run of characters
+other than letters and digits with a single `_`, without a leading or
+trailing `_`. A sanitized token therefore never contains `__` or `.`.
+
+When concatenating subgroup and name, **each part is sanitized
+separately** and joined with a literal `.`, so the dot is preserved in the
+final `EventName` (e.g. `ia_scalability_core7.ia_scalability`).
+
+## Worked example
+
+Consider an aggregator XML containing three samples:
+
+```xml
+<TELC:sampleGroup sampleID="0x0">
+ <TELC:sample name="RTL_VERSION" ...>
+ <TELC:sampleSubGroup>INTEL_VERSION_2</TELC:sampleSubGroup>
+ <TELC:lsb>0</TELC:lsb><TELC:msb>15</TELC:msb>
+ </TELC:sample>
+</TELC:sampleGroup>
+
+<TELC:sampleGroup sampleID="0x10">
+ <TELC:sample name="IA_SCALABILITY" ...>
+ <TELC:sampleSubGroup>IA_SCALABILITY_CORE0</TELC:sampleSubGroup>
+ <TELC:lsb>0</TELC:lsb><TELC:msb>7</TELC:msb>
+ </TELC:sample>
+</TELC:sampleGroup>
+
+<TELC:sampleGroup sampleID="0x11">
+ <TELC:sample name="IA_SCALABILITY" ...>
+ <TELC:sampleSubGroup>IA_SCALABILITY_CORE7</TELC:sampleSubGroup>
+ <TELC:lsb>0</TELC:lsb><TELC:msb>7</TELC:msb>
+ </TELC:sample>
+</TELC:sampleGroup>
+```
+
+Per-aggregator name counts:
+
+| `name` | count |
+| ---------------- | ----- |
+| `RTL_VERSION` | 1 |
+| `IA_SCALABILITY` | 2 |
+
+Resulting `EventName`s:
+
+| Sample | Rule | EventName |
+| ------------------------ | ------------------------- | ------------------------------------- |
+| `RTL_VERSION` | (2) subgroup not prefixed | `rtl_version` |
+| `IA_SCALABILITY` (CORE0) | (1) prefixed subgroup | `ia_scalability_core0.ia_scalability` |
+| `IA_SCALABILITY` (CORE7) | (1) prefixed subgroup | `ia_scalability_core7.ia_scalability` |
+
+Note that `RTL_VERSION` is **not** prefixed with its `INTEL_VERSION_2`
+container, even though `sampleSubGroup` is set — because no sample of that
+subgroup has a colliding name.
+
+The prefix applies to a whole subgroup. With samples `CORE0` and `GT` in
+subgroup `IA_CLUSTER_CSTATES`, and `CORE0` and `MODULE0` in `CDYN_LEVEL`,
+only `CORE0` collides, but both subgroups are prefixed:
+`ia_cluster_cstates.core0`, `ia_cluster_cstates.gt`, `cdyn_level.core0` and
+`cdyn_level.module0`.
+
+## Output shape
+
+Each aggregator becomes one `pmt_<guid>.json` file:
+
+```json
+{
+ "guid": "0x<guid>",
+ "platform": "<optional, from the --by-path directory>",
+ "description": "<optional, the aggregator's <TELEM:description>>",
+ "events": [
+ {
+ "EventName": "<name per rule above>",
+ "description": "<sample or group description>",
+ "sample_id": <sampleID>,
+ "lsb": <lsb>,
+ "msb": <msb>
+ }
+ ]
+}
+```
+
+`sample_id` selects a 64-bit sample of the telemetry region and `lsb` and
+`msb` give the event's bit range within it.
+
+`platform` is the first directory under the `--by-path` root, uppercased
+(`PTL/0/ptl_aggregator.xml` gives `PTL`). An event without a description in
+the XML gets one made from its name and width, such as `Core Temp (8b)`.
+
+## EventName uniqueness
+
+Within a single aggregator XML the rule above resolves the collisions in the
+Intel-PMT data. If two samples still share the same `EventName` — for example
+because neither has a usable `sampleSubGroup` — the converter applies a
+last-resort ordinal suffix
+`__0`, `__1`, … and emits a `WARN` line to stderr. The double-underscore is
+chosen to be visually distinct from any XML field so it is not mistaken for a
+meaningful part of the metric name.
+
+Across **different** GUIDs, names may repeat — they live in distinct
+files and are disambiguated by the file's `guid`.
diff --git a/tools/arch/x86/pmtctl/scripts/pmtxml2json.py b/tools/arch/x86/pmtctl/scripts/pmtxml2json.py
new file mode 100755
index 000000000000..144aed9894c4
--- /dev/null
+++ b/tools/arch/x86/pmtctl/scripts/pmtxml2json.py
@@ -0,0 +1,639 @@
+#!/usr/bin/env python3
+# SPDX-License-Identifier: GPL-2.0-only
+"""Convert Intel PMT aggregator XML files into pmtctl JSON metric definitions.
+
+Provides core XML-to-event conversion plus optional Intel-PMT repository
+fetch/cache support.
+"""
+
+import argparse
+import glob
+import json
+import os
+import re
+import subprocess
+import sys
+
+from collections import Counter
+from dataclasses import dataclass
+from typing import Dict, List, Optional, Set, Tuple
+
+from lxml import etree # pylint: disable=c-extension-no-member
+
+INTEL_PMT_REPO_URL = "https://github.com/intel/Intel-PMT"
+
+# Every PMT sample is one 64-bit word
+SAMPLE_BITS = 64
+
+
+def _expand_path(path: str) -> str:
+ """Return an absolute path with user home expansion applied."""
+ return os.path.abspath(os.path.expanduser(path))
+
+
+def _base_dir(path: str) -> str:
+ """Return path if it is a directory, else the directory containing it."""
+ if os.path.isfile(path):
+ return os.path.dirname(path) or "."
+ return path
+
+
+def _repo_dir_name_from_url(repo_url: str) -> str:
+ """Return a deterministic cache directory name for a git repository URL."""
+ cleaned = repo_url.rstrip("/")
+ if cleaned.endswith(".git"):
+ cleaned = cleaned[: -len(".git")]
+
+ base = os.path.basename(cleaned) or "repo"
+ base = re.sub(r"[^0-9A-Za-z._-]+", "-", base).strip("-")
+ return base or "repo"
+
+
+def _fetch_intel_pmt_xml_root(
+ cache_dir: str,
+ refresh: bool = False,
+ debug: bool = False,
+ repo_url: str = INTEL_PMT_REPO_URL,
+) -> Optional[str]:
+ """Ensure Intel-PMT exists in cache and return its xml root path."""
+ cache_root = _expand_path(cache_dir)
+ repo_dir = os.path.join(cache_root, _repo_dir_name_from_url(repo_url))
+
+ os.makedirs(cache_root, exist_ok=True)
+
+ try:
+ if not os.path.isdir(repo_dir):
+ if debug:
+ print(
+ f"# fetch: cloning {repo_url} into {repo_dir}",
+ file=sys.stderr,
+ )
+ subprocess.run(
+ ["git", "clone", "--depth", "1", repo_url, repo_dir],
+ check=True,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ text=True,
+ timeout=300,
+ )
+ elif refresh:
+ if debug:
+ print(f"# fetch: refreshing cached repo at {repo_dir}", file=sys.stderr)
+ subprocess.run(
+ ["git", "-C", repo_dir, "pull", "--ff-only"],
+ check=True,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ text=True,
+ timeout=300,
+ )
+ elif debug:
+ print(f"# fetch: using cached repo at {repo_dir}", file=sys.stderr)
+ except FileNotFoundError:
+ print("ERROR: git is not installed or not found in PATH.", file=sys.stderr)
+ return None
+ except subprocess.TimeoutExpired:
+ print("ERROR: fetching Intel-PMT timed out.", file=sys.stderr)
+ return None
+ except subprocess.CalledProcessError as ex:
+ err = (ex.stderr or "").strip()
+ print("ERROR: failed to fetch Intel-PMT repository.", file=sys.stderr)
+ if err:
+ print(f" git stderr: {err}", file=sys.stderr)
+ return None
+
+ xml_root = os.path.join(repo_dir, "xml")
+ if not os.path.isdir(xml_root):
+ print(
+ (
+ "ERROR: fetched repository does not contain expected xml "
+ f"directory: {xml_root}"
+ ),
+ file=sys.stderr,
+ )
+ return None
+
+ return xml_root
+
+
+# ---------- Reserved/RSVD skipping ----------
+# Name: match 'reserved' or 'rsvd' with optional digits, not embedded in larger tokens
+RESERVED_RX = re.compile(
+ r"(?<![a-z0-9])(reserved|rsvd)(?:\d+)?(?![a-z0-9])", re.IGNORECASE
+)
+# Description: exact 'reserved' or 'rsvd' with optional trailing digits/whitespace
+DESC_RESERVED_RX = re.compile(r"\s*(?:reserved|rsvd)(?:\s*\d+)?\s*$", re.IGNORECASE)
+
+
+@dataclass(frozen=True)
+class SampleDef:
+ """Normalized representation of one PMT sample field definition."""
+
+ sample_id: int
+ sample_name: str
+ lsb: int
+ msb: int
+ description: Optional[str]
+ sample_subgroup: Optional[str]
+
+
+def norm(tag) -> str:
+ """Return XML tag name without namespace prefix.
+
+ Non-element nodes (comments, unresolved entities) have no string tag
+ and return an empty name.
+ """
+ if not isinstance(tag, str):
+ return ""
+ return tag[tag.rfind("}") + 1 :] if "}" in tag else tag
+
+
+def _text(el) -> str:
+ """Return the stripped text of an XML element."""
+ return (el.text or "").strip()
+
+
+def parse_xml(xml_path: str):
+ """Parse and return the XML root element for the given file path.
+
+ The aggregator files include their *_common.xml data types through an
+ external entity. Those definitions are not needed for the conversion,
+ so entities are left unresolved.
+ """
+ # pylint: disable-next=c-extension-no-member
+ parser = etree.XMLParser(resolve_entities=False)
+ # pylint: disable-next=c-extension-no-member
+ root = etree.parse(xml_path, parser).getroot()
+
+ return root
+
+
+def get_guid(root) -> int:
+ """Extract the telemetry GUID from <uniqueid>."""
+ for e in root.iter():
+ if norm(e.tag).lower() == "uniqueid":
+ v = _text(e)
+ if not v:
+ break
+
+ # GUIDs are hex, with or without the 0x prefix
+ return int(v, 16)
+
+ raise ValueError("Missing <TELEM:uniqueid>")
+
+
+def get_description(root) -> Optional[str]:
+ """Return the aggregator's top-level <TELEM:description>, if any."""
+ for e in root:
+ if norm(e.tag).lower() == "description":
+ return _text(e) or None
+
+ return None
+
+
+def _is_reserved(sname: str, ssubgroup: Optional[str], desc: Optional[str]) -> bool:
+ """Return True for reserved/rsvd samples by name, sampleSubGroup, or description."""
+ if RESERVED_RX.search(sname):
+ return True
+ if ssubgroup and RESERVED_RX.search(ssubgroup):
+ return True
+ return bool(desc and DESC_RESERVED_RX.fullmatch(desc))
+
+
+def parse_sample(s, sample_id: int, group_desc: Optional[str]) -> Optional[SampleDef]:
+ """Parse one <Sample> element; return None for reserved samples."""
+ sname = (s.attrib.get("name") or f"sample_{sample_id}").strip()
+
+ lsb = None
+ msb = None
+ sdesc = None
+ ssubgroup = None
+
+ for ch in s:
+ t = norm(ch.tag).lower()
+ if t == "lsb":
+ lsb = int(_text(ch), 0)
+ elif t == "msb":
+ msb = int(_text(ch), 0)
+ elif t == "description":
+ sdesc = _text(ch)
+ elif t == "samplesubgroup":
+ ssubgroup = _text(ch)
+
+ if lsb is None or msb is None:
+ raise ValueError(f"{sname} (sampleID={sample_id}): missing lsb/msb")
+
+ if not 0 <= lsb <= msb < SAMPLE_BITS:
+ raise ValueError(
+ f"{sname} (sampleID={sample_id}): invalid bit range {lsb}-{msb}"
+ )
+
+ desc_text = sdesc if sdesc else group_desc
+
+ if _is_reserved(sname, ssubgroup, desc_text):
+ return None
+
+ return SampleDef(
+ sample_id=sample_id,
+ sample_name=sname,
+ lsb=lsb,
+ msb=msb,
+ description=desc_text,
+ sample_subgroup=ssubgroup,
+ )
+
+
+def parse_sample_group(sg) -> List[SampleDef]:
+ """Parse one <SampleGroup> element into its non-reserved samples."""
+ sid_txt = sg.attrib.get("sampleID") or sg.attrib.get("sampleid")
+ if sid_txt is None:
+ raise ValueError("SampleGroup missing sampleID")
+
+ sample_id = int(sid_txt, 0)
+ group_name = (sg.attrib.get("name") or "").strip() or f"group_{sample_id}"
+ group_len = None
+ group_desc = None
+
+ for child in sg:
+ t = norm(child.tag).lower()
+ if t == "length":
+ group_len = int(_text(child), 0)
+ elif t == "description":
+ group_desc = _text(child)
+
+ if group_len is not None and group_len != SAMPLE_BITS:
+ raise ValueError(
+ f"{group_name} sampleID={sample_id} length={group_len} "
+ f"(expected {SAMPLE_BITS})"
+ )
+
+ out: List[SampleDef] = []
+ for s in sg:
+ if norm(s.tag).lower() != "sample":
+ continue
+ sample = parse_sample(s, sample_id, group_desc)
+ if sample:
+ out.append(sample)
+
+ return out
+
+
+def parse_samples(root) -> List[SampleDef]:
+ """Parse SampleGroup/Sample entries into filtered SampleDef records."""
+ out: List[SampleDef] = []
+
+ for sg in root.iter():
+ if norm(sg.tag).lower() == "samplegroup":
+ out.extend(parse_sample_group(sg))
+
+ return out
+
+
+def _sanitize_token(s: str) -> str:
+ """Lowercase s, replacing each run of non-alphanumerics with one '_'."""
+ return re.sub(r"[^0-9a-zA-Z]+", "_", s).strip("_").lower()
+
+
+def event_description(s: SampleDef) -> str:
+ """Build the description of an event, with whitespace collapsed."""
+ if s.description:
+ return re.sub(r"\s+", " ", s.description)
+
+ width = s.msb - s.lsb + 1
+
+ return f"{s.sample_name.replace('_', ' ').title()} ({width}b)"
+
+
+def make_event(s: SampleDef, prefixed: Set[str]) -> Dict[str, object]:
+ """Create one event dictionary for a sample.
+
+ A sample of a subgroup in @prefixed is named subgroup.name, unless the
+ subgroup has the sample's own name.
+ """
+ name = _sanitize_token(s.sample_name)
+ group = _sanitize_token(s.sample_subgroup) if s.sample_subgroup else ""
+ if s.sample_subgroup in prefixed and group and group != name:
+ name = f"{group}.{name}"
+
+ return {
+ "EventName": name,
+ "description": event_description(s),
+ "sample_id": s.sample_id,
+ "lsb": s.lsb,
+ "msb": s.msb,
+ }
+
+
+def _resolve_duplicate_event_names(
+ out: List[Dict[str, object]], guid: int, agg_xml: str
+) -> None:
+ """Detect duplicate EventNames and rename collisions as name__0, name__1, ...
+
+ The subgroup-prefix disambiguation in make_event covers the common case.
+ This function is a last-resort safety net for names that could not be
+ disambiguated there (e.g. no usable sampleSubGroup). The double-underscore
+ suffix is intentionally distinct from any XML field so it is not mistaken
+ for a meaningful part of the metric name.
+ """
+ seen: Dict[str, List[int]] = {}
+ for i, e in enumerate(out):
+ name = e["EventName"]
+ seen.setdefault(name, []).append(i)
+
+ for name, indices in seen.items():
+ if len(indices) <= 1:
+ continue
+ print(
+ f"WARN: {agg_xml}: GUID=0x{guid:08x}: "
+ f"EventName '{name}' collision ({len(indices)} entries); "
+ f"renaming as {name}__0 .. {name}__{len(indices) - 1}",
+ file=sys.stderr,
+ )
+ for ordinal, idx in enumerate(indices):
+ out[idx]["EventName"] = f"{name}__{ordinal}"
+
+
+def _parse_args(argv: List[str]) -> argparse.Namespace:
+ """Parse command-line arguments."""
+ ap = argparse.ArgumentParser(
+ description="Convert Intel PMT Aggregator XML to pmtctl JSON metric definitions"
+ )
+ ap.add_argument(
+ "xml",
+ nargs="?",
+ help="Input PMT Aggregator XML file (optional when using --by-path)",
+ )
+ ap.add_argument(
+ "--by-path",
+ default=None,
+ help=(
+ "Directory to auto-discover PMT XMLs. When used without a "
+ "positional XML, processes all *_aggregator.xml recursively "
+ "and emits one output per directory."
+ ),
+ )
+ ap.add_argument(
+ "--output-dir",
+ default=None,
+ help=(
+ "Directory where JSON output files will be placed. Used "
+ "verbatim (files are written flat by GUID). If omitted, "
+ "the deepest folder name from --by-path is used (lowercased)."
+ ),
+ )
+ ap.add_argument(
+ "--fetch-pmt-repo",
+ action="store_true",
+ help=(
+ "Fetch Intel-PMT repository and use its xml folder when "
+ "local xml/by-path inputs are not provided."
+ ),
+ )
+ ap.add_argument(
+ "--pmt-cache-dir",
+ default="~/.cache/pmtctl",
+ help=(
+ "Cache directory for Intel-PMT repository clone "
+ "(default: ~/.cache/pmtctl)."
+ ),
+ )
+ ap.add_argument(
+ "--refresh-pmt-repo",
+ action="store_true",
+ help=(
+ "Refresh cached Intel-PMT repository before conversion "
+ "(used with --fetch-pmt-repo)."
+ ),
+ )
+ ap.add_argument(
+ "--pmt-repo-url",
+ default=INTEL_PMT_REPO_URL,
+ help=(
+ "Git URL of the Intel-PMT repository used by --fetch-pmt-repo "
+ f"(default: {INTEL_PMT_REPO_URL})."
+ ),
+ )
+ ap.add_argument("--debug", action="store_true")
+
+ return ap.parse_args(argv)
+
+
+def _rel_parts_from_root(d: str, root: str) -> List[str]:
+ """Return sanitized relative path segments from root to d."""
+ try:
+ rel = os.path.relpath(os.path.normpath(d), os.path.normpath(root))
+ except ValueError:
+ return []
+ if rel in (".", "") or rel.startswith(".."):
+ return []
+
+ def _seg(s: str) -> str:
+ s = (s or "").strip().lower()
+ s = re.sub(r"[^0-9a-z]+", "-", s)
+ return re.sub(r"-+", "-", s).strip("-")
+
+ out: List[str] = []
+ for seg in rel.split(os.sep):
+ if seg in (".", ".."):
+ continue
+ s = _seg(seg)
+ if s:
+ out.append(s)
+ return out
+
+
+def _discover_all_xml_sets_by_path(p: str) -> List[Tuple[str, List[str]]]:
+ """Return a (aggregator, rel_parts) work item for each *_aggregator.xml under p."""
+ base = _base_dir(p)
+ aggs = glob.glob(os.path.join(base, "**", "*_aggregator.xml"), recursive=True)
+
+ return [(a, _rel_parts_from_root(os.path.dirname(a), base)) for a in sorted(aggs)]
+
+
+def _collect_work_items(args: argparse.Namespace) -> List[Tuple[str, List[str]]]:
+ """Return the (aggregator, rel_parts) items selected by the arguments."""
+ if args.by_path and args.xml is None:
+ work_items = _discover_all_xml_sets_by_path(args.by_path)
+ if args.debug:
+ print(
+ f"# by-path discovered {len(work_items)} aggregator(s)",
+ file=sys.stderr,
+ )
+ return work_items
+
+ if not args.xml:
+ return []
+
+ # Single file, optionally placed relative to --by-path
+ rel_parts: List[str] = []
+ if args.by_path:
+ rel_parts = _rel_parts_from_root(os.path.dirname(args.xml) or ".", args.by_path)
+ return [(args.xml, rel_parts)]
+
+
+def _deepest_by_path_folder(by_path: str) -> str:
+ """Return the last component of the --by-path directory."""
+ return os.path.basename(os.path.normpath(_base_dir(by_path)))
+
+
+def _output_dir_for(args: argparse.Namespace) -> Optional[str]:
+ """Determine the output directory.
+
+ If --output-dir is given, use it verbatim; outputs are written flat
+ by GUID (pmt_<guid>.json). If omitted, fall back to a folder
+ named after the deepest --by-path directory (lowercased).
+ """
+ if args.output_dir:
+ return args.output_dir
+
+ if args.by_path:
+ deepest_folder = _deepest_by_path_folder(args.by_path)
+ return "jsons" if deepest_folder.lower() == "xml" else deepest_folder.lower()
+
+ return None
+
+
+def _platform_group_for(rel_parts: List[str], by_path: Optional[str]) -> Optional[str]:
+ """Return the platform group for an aggregator.
+
+ Derived from the aggregator's location under the discovery root
+ (e.g. "alderlake-s"). Falls back to the by-path basename for the
+ single-mode case.
+ """
+ if rel_parts:
+ return rel_parts[0].upper()
+
+ if by_path:
+ deepest_folder = _deepest_by_path_folder(by_path)
+ if deepest_folder and deepest_folder.lower() != "xml":
+ return deepest_folder.upper()
+
+ return None
+
+
+def make_events(root, guid: int, agg_xml: str) -> List[Dict[str, object]]:
+ """Return the events of an aggregator, with unique EventNames."""
+ samples = parse_samples(root)
+
+ # When a name is shared by several samples, every sample of their
+ # subgroups is prefixed, so the members of a subgroup are named alike
+ name_counts = Counter(_sanitize_token(s.sample_name) for s in samples)
+ prefixed = {
+ s.sample_subgroup
+ for s in samples
+ if name_counts[_sanitize_token(s.sample_name)] > 1
+ }
+
+ events = [make_event(s, prefixed) for s in samples]
+
+ _resolve_duplicate_event_names(events, guid, agg_xml)
+
+ return events
+
+
+def convert_aggregator(
+ agg_xml: str,
+ rel_parts: List[str],
+ args: argparse.Namespace,
+ output_dir: Optional[str],
+ written_by_guid: Dict[int, str],
+) -> None:
+ """Convert one aggregator XML into a pmt_<guid>.json file."""
+ root = parse_xml(agg_xml)
+ guid = get_guid(root)
+
+ out_filename = os.path.join(output_dir or "", f"pmt_{guid:08x}.json")
+
+ # GUIDs are globally unique to a telemetry layout; a duplicate
+ # across aggregators indicates a source-data bug, not something
+ # to silently paper over by namespacing the output.
+ prior = written_by_guid.get(guid)
+ if prior is not None:
+ raise ValueError(
+ f"duplicate GUID 0x{guid:08x} from {agg_xml}; "
+ f"previously emitted by {prior}"
+ )
+
+ events = make_events(root, guid, agg_xml)
+ platform_group = _platform_group_for(rel_parts, args.by_path)
+
+ doc: Dict[str, object] = {"guid": f"0x{guid:08x}"}
+ if platform_group:
+ doc["platform"] = platform_group
+ description = get_description(root)
+ if description:
+ doc["description"] = description
+ doc["events"] = events
+
+ with open(out_filename, "w", encoding="utf-8") as f:
+ json.dump(doc, f, indent=2)
+ f.write("\n")
+
+ written_by_guid[guid] = agg_xml
+ print(f"# wrote {out_filename}", file=sys.stderr)
+ print(f"# GUID=0x{guid:08x} events={len(events)}", file=sys.stderr)
+
+
+def main(argv: List[str]) -> int:
+ """CLI entry point: discover XML files, convert, and write JSON outputs."""
+ args = _parse_args(argv)
+
+ if args.refresh_pmt_repo and not args.fetch_pmt_repo:
+ print(
+ "ERROR: --refresh-pmt-repo requires --fetch-pmt-repo.",
+ file=sys.stderr,
+ )
+ return 2
+
+ fetched_xml_root: Optional[str] = None
+ if args.fetch_pmt_repo:
+ fetched_xml_root = _fetch_intel_pmt_xml_root(
+ cache_dir=args.pmt_cache_dir,
+ refresh=args.refresh_pmt_repo,
+ debug=args.debug,
+ repo_url=args.pmt_repo_url,
+ )
+ if fetched_xml_root is None:
+ return 2
+ if args.debug:
+ print(f"# fetch: xml root={fetched_xml_root}", file=sys.stderr)
+ if args.by_path is None and args.xml is None:
+ args.by_path = fetched_xml_root
+
+ work_items = _collect_work_items(args)
+
+ if not work_items:
+ print(
+ (
+ "ERROR: No aggregator XML specified or discovered. "
+ "Provide a file or use --by-path."
+ ),
+ file=sys.stderr,
+ )
+ return 2
+
+ output_dir = _output_dir_for(args)
+ if output_dir:
+ os.makedirs(output_dir, exist_ok=True)
+ if args.debug:
+ print(f"# output directory: {output_dir}", file=sys.stderr)
+
+ any_failed = False
+ written_by_guid: Dict[int, str] = {}
+
+ for agg_xml, rel_parts in work_items:
+ try:
+ convert_aggregator(agg_xml, rel_parts, args, output_dir, written_by_guid)
+ # pylint: disable-next=c-extension-no-member
+ except (ValueError, OSError, etree.XMLSyntaxError) as ex:
+ any_failed = True
+ print(
+ f"ERROR: failed processing aggregator={agg_xml}: {ex}",
+ file=sys.stderr,
+ )
+
+ return 1 if any_failed else 0
+
+
+if __name__ == "__main__":
+ sys.exit(main(sys.argv[1:]))
--
2.53.0
^ permalink raw reply related [flat|nested] 13+ messages in thread* [PATCH v2 04/12] tools/arch/x86/pmtctl: Add JSON metric definition loading
2026-11-22 19:33 [PATCH v2 00/12] tools/arch/x86/pmtctl: Add Intel PMT command-line tool David E. Box
` (2 preceding siblings ...)
2026-11-22 19:33 ` [PATCH v2 03/12] tools/arch/x86/pmtctl: Add pmtxml2json conversion tool David E. Box
@ 2026-11-22 19:33 ` David E. Box
2026-11-22 19:34 ` [PATCH v2 05/12] tools/arch/x86/pmtctl: Add 'list' command David E. Box
` (7 subsequent siblings)
11 siblings, 0 replies; 13+ messages in thread
From: David E. Box @ 2026-11-22 19:33 UTC (permalink / raw)
To: Ilpo Järvinen, Hans de Goede
Cc: David E. Box, Andy Shevchenko, platform-driver-x86, linux-kernel
The telemetry data of a PMT device is an array of 64-bit samples
whose meaning, its telemetry semantic space (TSS), is identified by the
device's GUID. pmtxml2json.py converts the published layouts into one
JSON file per GUID, listing the metrics as bit ranges of samples.
Add loading of these files with libjansson. A path may name a single
definition file or a directory of them. Each file becomes one entry of
a TSS database in struct pmtctl_ctx, holding the GUID's platform,
description and metrics, sorted by name, so the metrics of a device
are found with a single lookup of its GUID. pmt_tss_db_load_json()
loads the database, and pmtctl_ctx_free() frees it with the rest of the
context.
Definition files are validated: each must have a GUID not defined by
another file, and each event a unique name, a 32-bit sample ID and a bit
range within the 64-bit sample (lsb <= msb <= 63). Otherwise the file is
rejected with a message naming the event. In a directory every file is
checked and any bad file fails the load, so a partial set of definitions
is never used.
Building pmtctl now requires libjansson.
Signed-off-by: David E. Box <david.e.box@linux.intel.com>
---
V2 changes:
- Replaces v1 04 and 07.
- A TSS database with one entry per GUID, sorted and searched with
bsearch(), replaces the metric blocks, the flat-index accessors and
the GUID registry.
- No string pool, casts or realloc(+1) growth.
- Files are validated strictly. A bad file fails a directory load,
where v1's result depended on readdir order, and errors name the
file and event.
tools/arch/x86/pmtctl/Makefile | 13 +
tools/arch/x86/pmtctl/include/lib/pmtctl.h | 2 +
tools/arch/x86/pmtctl/include/lib/tss.h | 43 +++
tools/arch/x86/pmtctl/lib/pmtctl.c | 2 +
tools/arch/x86/pmtctl/lib/tss.c | 45 +++
tools/arch/x86/pmtctl/lib/tss_json.c | 406 +++++++++++++++++++++
6 files changed, 511 insertions(+)
create mode 100644 tools/arch/x86/pmtctl/include/lib/tss.h
create mode 100644 tools/arch/x86/pmtctl/lib/tss.c
create mode 100644 tools/arch/x86/pmtctl/lib/tss_json.c
diff --git a/tools/arch/x86/pmtctl/Makefile b/tools/arch/x86/pmtctl/Makefile
index 2d66e4e036cc..8b723f96904b 100644
--- a/tools/arch/x86/pmtctl/Makefile
+++ b/tools/arch/x86/pmtctl/Makefile
@@ -7,11 +7,24 @@ CFLAGS = -Wextra
override CFLAGS += -O2 -Wall -D_GNU_SOURCE -Iinclude -I../../../include
+# The jansson check is skipped for targets that don't compile anything
+ifneq ($(filter-out clean defs-json-fetch defs-json-pull defs-clean,$(or $(MAKECMDGOALS),pmtctl)),)
+JANSSON_CFLAGS := $(shell pkg-config --cflags jansson 2>/dev/null)
+JANSSON_LIBS := $(shell pkg-config --libs jansson 2>/dev/null)
+ifeq ($(JANSSON_LIBS),)
+$(error jansson not found: install libjansson-dev (Debian/Ubuntu) or jansson-devel (Fedora/RHEL))
+endif
+override CFLAGS += $(JANSSON_CFLAGS)
+LDLIBS += $(JANSSON_LIBS)
+endif
+
OBJS := \
lib/common.o \
lib/device_telem.o \
lib/log.o \
lib/pmtctl.o \
+ lib/tss.o \
+ lib/tss_json.o \
src/main.o
pmtctl: $(OBJS)
diff --git a/tools/arch/x86/pmtctl/include/lib/pmtctl.h b/tools/arch/x86/pmtctl/include/lib/pmtctl.h
index e3a2c862bc78..9da9e1f221ca 100644
--- a/tools/arch/x86/pmtctl/include/lib/pmtctl.h
+++ b/tools/arch/x86/pmtctl/include/lib/pmtctl.h
@@ -5,11 +5,13 @@
#include <stddef.h>
#include "lib/device.h"
+#include "lib/tss.h"
/* State for one pmtctl command, owned by the command */
struct pmtctl_ctx {
struct pmt_device *devices;
size_t num_devices;
+ struct pmt_tss_db tss;
};
int pmtctl_ctx_init(struct pmtctl_ctx *ctx);
diff --git a/tools/arch/x86/pmtctl/include/lib/tss.h b/tools/arch/x86/pmtctl/include/lib/tss.h
new file mode 100644
index 000000000000..3f5238540240
--- /dev/null
+++ b/tools/arch/x86/pmtctl/include/lib/tss.h
@@ -0,0 +1,43 @@
+/* SPDX-License-Identifier: GPL-2.0-only */
+#ifndef PMTCTL_TSS_H
+#define PMTCTL_TSS_H
+
+#include <stddef.h>
+#include <stdint.h>
+
+/* Every PMT telemetry sample is one 64-bit word */
+#define PMT_SAMPLE_BITS 64
+
+/* A metric: bits [lsb, msb] of sample sample_id */
+struct pmt_metric_def {
+ char *name;
+ char *description; /* may be NULL */
+ uint32_t sample_id;
+ unsigned int lsb;
+ unsigned int msb;
+};
+
+/*
+ * The telemetry semantic space (TSS) identified by a GUID: the meaning of
+ * the samples in a telemetry region with that GUID.
+ */
+struct pmt_tss_info {
+ uint32_t guid;
+ char *platform; /* may be NULL */
+ char *description; /* may be NULL */
+ struct pmt_metric_def *metrics; /* sorted by name */
+ size_t num_metrics;
+};
+
+/* The telemetry semantic spaces with known metric definitions */
+struct pmt_tss_db {
+ struct pmt_tss_info *tss_info; /* sorted by GUID */
+ size_t num_tss_info;
+};
+
+int pmt_tss_db_load_json(const char *path, struct pmt_tss_db *db);
+void pmt_tss_info_free(struct pmt_tss_info *info);
+void pmt_tss_db_free(struct pmt_tss_db *db);
+const struct pmt_tss_info *pmt_tss_db_lookup(const struct pmt_tss_db *db, uint32_t guid);
+
+#endif
diff --git a/tools/arch/x86/pmtctl/lib/pmtctl.c b/tools/arch/x86/pmtctl/lib/pmtctl.c
index 9a6fd2a303f4..b218bac15824 100644
--- a/tools/arch/x86/pmtctl/lib/pmtctl.c
+++ b/tools/arch/x86/pmtctl/lib/pmtctl.c
@@ -1,6 +1,7 @@
// SPDX-License-Identifier: GPL-2.0-only
#include "lib/device.h"
#include "lib/pmtctl.h"
+#include "lib/tss.h"
/**
* pmtctl_ctx_init - discover PMT devices
@@ -16,6 +17,7 @@ int pmtctl_ctx_init(struct pmtctl_ctx *ctx)
void pmtctl_ctx_free(struct pmtctl_ctx *ctx)
{
+ pmt_tss_db_free(&ctx->tss);
telem_free(ctx->devices, ctx->num_devices);
ctx->devices = NULL;
ctx->num_devices = 0;
diff --git a/tools/arch/x86/pmtctl/lib/tss.c b/tools/arch/x86/pmtctl/lib/tss.c
new file mode 100644
index 000000000000..7555b76c3ded
--- /dev/null
+++ b/tools/arch/x86/pmtctl/lib/tss.c
@@ -0,0 +1,45 @@
+// SPDX-License-Identifier: GPL-2.0-only
+#include <stdlib.h>
+
+#include "lib/tss.h"
+
+void pmt_tss_info_free(struct pmt_tss_info *info)
+{
+ for (size_t i = 0; i < info->num_metrics; i++) {
+ free(info->metrics[i].name);
+ free(info->metrics[i].description);
+ }
+ free(info->metrics);
+ free(info->platform);
+ free(info->description);
+}
+
+void pmt_tss_db_free(struct pmt_tss_db *db)
+{
+ for (size_t i = 0; i < db->num_tss_info; i++)
+ pmt_tss_info_free(&db->tss_info[i]);
+ free(db->tss_info);
+
+ *db = (struct pmt_tss_db){};
+}
+
+static int tss_info_guid_cmp(const void *key, const void *elem)
+{
+ const uint32_t *guid = key;
+ const struct pmt_tss_info *info = elem;
+
+ if (*guid != info->guid)
+ return *guid < info->guid ? -1 : 1;
+
+ return 0;
+}
+
+/* Return: the entry for @guid, or NULL if no definitions were loaded for it */
+const struct pmt_tss_info *pmt_tss_db_lookup(const struct pmt_tss_db *db, uint32_t guid)
+{
+ if (!db->num_tss_info)
+ return NULL;
+
+ return bsearch(&guid, db->tss_info, db->num_tss_info, sizeof(*db->tss_info),
+ tss_info_guid_cmp);
+}
diff --git a/tools/arch/x86/pmtctl/lib/tss_json.c b/tools/arch/x86/pmtctl/lib/tss_json.c
new file mode 100644
index 000000000000..32343f233aff
--- /dev/null
+++ b/tools/arch/x86/pmtctl/lib/tss_json.c
@@ -0,0 +1,406 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/*
+ * Load metric definitions from the JSON files written by
+ * scripts/pmtxml2json.py: one pmt_<guid>.json per telemetry semantic
+ * space, with the GUID's platform, description and events.
+ */
+#include <dirent.h>
+#include <errno.h>
+#include <jansson.h>
+#include <limits.h>
+#include <stdbool.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/stat.h>
+
+#include "lib/common.h"
+#include "lib/log.h"
+#include "lib/tss.h"
+
+static bool is_regular_file(const char *path)
+{
+ struct stat st;
+
+ if (stat(path, &st))
+ return false;
+
+ return S_ISREG(st.st_mode);
+}
+
+static const char *obj_get_string(json_t *obj, const char *key)
+{
+ return json_string_value(json_object_get(obj, key));
+}
+
+/* Read the integer @key of @obj into @val if it is in the range [0, @max] */
+static int obj_get_uint(json_t *obj, const char *key, uint32_t max, uint32_t *val)
+{
+ json_t *v = json_object_get(obj, key);
+ json_int_t n;
+
+ if (!json_is_integer(v))
+ return -EINVAL;
+
+ n = json_integer_value(v);
+ if (n < 0 || n > max)
+ return -ERANGE;
+
+ *val = n;
+
+ return 0;
+}
+
+/* Duplicate @s into @dst, or set @dst to NULL if @s is NULL */
+static int dup_optional(const char *s, char **dst)
+{
+ *dst = NULL;
+ if (!s)
+ return 0;
+
+ *dst = strdup(s);
+ if (!*dst)
+ return -ENOMEM;
+
+ return 0;
+}
+
+/* Read the sample and bit range of an event into @def */
+static int parse_location(json_t *ev, struct pmt_metric_def *def)
+{
+ uint32_t sample_id, lsb, msb;
+ int ret;
+
+ ret = obj_get_uint(ev, "sample_id", UINT32_MAX, &sample_id);
+ if (ret)
+ return ret;
+
+ ret = obj_get_uint(ev, "lsb", PMT_SAMPLE_BITS - 1, &lsb);
+ if (ret)
+ return ret;
+
+ ret = obj_get_uint(ev, "msb", PMT_SAMPLE_BITS - 1, &msb);
+ if (ret)
+ return ret;
+
+ if (lsb > msb)
+ return -EINVAL;
+
+ def->sample_id = sample_id;
+ def->lsb = lsb;
+ def->msb = msb;
+
+ return 0;
+}
+
+/* Fill @def from event @idx of @path. On failure @def may be partly filled. */
+/*
+ * Fill @def from event @ev. On failure @def may be partly filled; the
+ * caller frees it with the rest of the metrics array.
+ */
+static int parse_event(json_t *ev, const char *path, size_t idx, struct pmt_metric_def *def)
+{
+ const char *name;
+ int ret;
+
+ name = obj_get_string(ev, "EventName");
+ if (!name) {
+ log_err("%s: event %zu: missing EventName", path, idx);
+ return -EINVAL;
+ }
+
+ ret = parse_location(ev, def);
+ if (ret) {
+ log_err("%s: event %zu (%s): missing or invalid sample_id, lsb or msb",
+ path, idx, name);
+ return ret;
+ }
+
+ def->name = strdup(name);
+ if (!def->name)
+ return -ENOMEM;
+
+ return dup_optional(obj_get_string(ev, "description"), &def->description);
+}
+
+static int metric_cmp(const void *a, const void *b)
+{
+ const struct pmt_metric_def *ma = a;
+ const struct pmt_metric_def *mb = b;
+
+ return strcmp(ma->name, mb->name);
+}
+
+/* Sort the metrics of @info by name and reject duplicate names */
+static int sort_metrics(struct pmt_tss_info *info, const char *path)
+{
+ if (!info->num_metrics)
+ return 0;
+
+ qsort(info->metrics, info->num_metrics, sizeof(*info->metrics), metric_cmp);
+
+ for (size_t i = 1; i < info->num_metrics; i++) {
+ if (!strcmp(info->metrics[i - 1].name, info->metrics[i].name)) {
+ log_err("%s: event %s is defined more than once", path,
+ info->metrics[i].name);
+ return -EINVAL;
+ }
+ }
+
+ return 0;
+}
+
+static int parse_file_guid(json_t *root, const char *path, uint32_t *guid)
+{
+ const char *s;
+
+ s = obj_get_string(root, "guid");
+ if (!s || parse_u32(s, 0, guid)) {
+ log_err("%s: missing or invalid guid", path);
+ return -EINVAL;
+ }
+
+ return 0;
+}
+
+/*
+ * Add the telemetry semantic space of @root. @db->tss_info has room for one
+ * more entry. On failure nothing is added.
+ */
+static int parse_file(struct pmt_tss_db *db, json_t *root, const char *path)
+{
+ struct pmt_tss_info info = {};
+ json_t *events;
+ json_t *ev;
+ size_t idx;
+ int ret;
+
+ if (!json_is_object(root)) {
+ log_err("%s: expected an object", path);
+ return -EINVAL;
+ }
+
+ ret = parse_file_guid(root, path, &info.guid);
+ if (ret)
+ return ret;
+
+ events = json_object_get(root, "events");
+ if (!json_is_array(events)) {
+ log_err("%s: missing events array", path);
+ return -EINVAL;
+ }
+
+ if (json_array_size(events)) {
+ info.metrics = calloc(json_array_size(events), sizeof(*info.metrics));
+ if (!info.metrics)
+ return -ENOMEM;
+
+ /* Zeroed, so pmt_tss_info_free() can free a partly parsed array */
+ info.num_metrics = json_array_size(events);
+ }
+
+ ret = dup_optional(obj_get_string(root, "platform"), &info.platform);
+ if (ret)
+ goto err_free;
+
+ ret = dup_optional(obj_get_string(root, "description"), &info.description);
+ if (ret)
+ goto err_free;
+
+ json_array_foreach(events, idx, ev) {
+ ret = parse_event(ev, path, idx, &info.metrics[idx]);
+ if (ret)
+ goto err_free;
+ }
+
+ ret = sort_metrics(&info, path);
+ if (ret)
+ goto err_free;
+
+ db->tss_info[db->num_tss_info++] = info;
+
+ return 0;
+
+err_free:
+ pmt_tss_info_free(&info);
+
+ return ret;
+}
+
+/* Read @path into *@root. fopen() rather than json_load_file() keeps its errno. */
+static int read_json_file(const char *path, json_t **root)
+{
+ json_error_t error;
+ FILE *fp;
+
+ fp = fopen(path, "r");
+ if (!fp)
+ return log_ret(-errno, "unable to open %s", path);
+
+ *root = json_loadf(fp, 0, &error);
+ fclose(fp);
+ if (!*root) {
+ log_err("%s: line %d: %s", path, error.line, error.text);
+ return -EINVAL;
+ }
+
+ return 0;
+}
+
+static int load_file(struct pmt_tss_db *db, const char *path)
+{
+ json_t *root;
+ int ret;
+
+ ret = read_json_file(path, &root);
+ if (ret)
+ return ret;
+
+ ret = parse_file(db, root, path);
+ json_decref(root);
+
+ return ret;
+}
+
+/* Select the definition files of a directory: *.json, except hidden files */
+static int is_definition_file(const struct dirent *de)
+{
+ const char *ext = strrchr(de->d_name, '.');
+
+ if (de->d_name[0] == '.')
+ return 0;
+
+ return ext && !strcmp(ext, ".json");
+}
+
+static int load_dir_entry(struct pmt_tss_db *db, const char *dir, const char *name)
+{
+ char path[PATH_MAX];
+ int ret;
+
+ ret = path_printf(path, sizeof(path), "%s/%s", dir, name);
+ if (ret) {
+ log_err("%s/%s: path too long", dir, name);
+ return ret;
+ }
+
+ if (!is_regular_file(path))
+ return 0;
+
+ return load_file(db, path);
+}
+
+/*
+ * Load every definition file in @dir, in name order. A file that fails to
+ * load is reported and the remaining files are still checked, but the load
+ * as a whole fails.
+ */
+static int load_dir(struct pmt_tss_db *db, const char *dir)
+{
+ struct dirent **names;
+ int ret = 0;
+ int n;
+
+ n = scandir(dir, &names, is_definition_file, alphasort);
+ if (n < 0)
+ return log_ret(-errno, "unable to read %s", dir);
+
+ /* Each file adds at most one entry */
+ if (n) {
+ db->tss_info = calloc(n, sizeof(*db->tss_info));
+ if (!db->tss_info) {
+ ret = -ENOMEM;
+ goto out_free_names;
+ }
+ }
+
+ for (int i = 0; i < n; i++) {
+ int err;
+
+ err = load_dir_entry(db, dir, names[i]->d_name);
+ if (err == -ENOMEM) {
+ ret = err;
+ break;
+ }
+
+ if (err)
+ ret = err;
+ }
+
+out_free_names:
+ for (int i = 0; i < n; i++)
+ free(names[i]);
+ free(names);
+
+ return ret;
+}
+
+static int tss_info_cmp(const void *a, const void *b)
+{
+ const struct pmt_tss_info *ia = a;
+ const struct pmt_tss_info *ib = b;
+
+ if (ia->guid != ib->guid)
+ return ia->guid < ib->guid ? -1 : 1;
+
+ return 0;
+}
+
+/* Check that no two files of directory @path define the same GUID; @db is sorted */
+static int check_unique_guids(const struct pmt_tss_db *db, const char *path)
+{
+ for (size_t i = 1; i < db->num_tss_info; i++) {
+ if (db->tss_info[i].guid == db->tss_info[i - 1].guid) {
+ log_err("guid 0x%08x is defined by more than one file in %s",
+ db->tss_info[i].guid, path);
+ return -EINVAL;
+ }
+ }
+
+ return 0;
+}
+
+/**
+ * pmt_tss_db_load_json - load metric definitions
+ * @path: a definition file, or a directory of them
+ * @db: zero-initialized, filled on success
+ *
+ * Return: 0 on success, or a negative errno with @db left empty.
+ */
+int pmt_tss_db_load_json(const char *path, struct pmt_tss_db *db)
+{
+ struct stat st;
+ int ret;
+
+ if (stat(path, &st))
+ return log_ret(-errno, "unable to access %s", path);
+
+ if (S_ISDIR(st.st_mode)) {
+ ret = load_dir(db, path);
+ } else if (S_ISREG(st.st_mode)) {
+ db->tss_info = calloc(1, sizeof(*db->tss_info));
+ if (db->tss_info)
+ ret = load_file(db, path);
+ else
+ ret = -ENOMEM;
+ } else {
+ log_err("%s: not a file or directory", path);
+ ret = -EINVAL;
+ }
+
+ if (!ret && db->num_tss_info > 1) {
+ qsort(db->tss_info, db->num_tss_info, sizeof(*db->tss_info), tss_info_cmp);
+ ret = check_unique_guids(db, path);
+ }
+
+ if (ret) {
+ pmt_tss_db_free(db);
+ return log_ret(ret, "unable to load metric definitions from %s", path);
+ }
+
+ if (!db->num_tss_info)
+ log_warn("no metric definitions found in %s", path);
+
+ return 0;
+}
--
2.53.0
^ permalink raw reply related [flat|nested] 13+ messages in thread* [PATCH v2 05/12] tools/arch/x86/pmtctl: Add 'list' command
2026-11-22 19:33 [PATCH v2 00/12] tools/arch/x86/pmtctl: Add Intel PMT command-line tool David E. Box
` (3 preceding siblings ...)
2026-11-22 19:33 ` [PATCH v2 04/12] tools/arch/x86/pmtctl: Add JSON metric definition loading David E. Box
@ 2026-11-22 19:34 ` David E. Box
2026-11-22 19:34 ` [PATCH v2 06/12] tools/arch/x86/pmtctl: Add 'list --summary' David E. Box
` (6 subsequent siblings)
11 siblings, 0 replies; 13+ messages in thread
From: David E. Box @ 2026-11-22 19:34 UTC (permalink / raw)
To: Ilpo Järvinen, Hans de Goede
Cc: David E. Box, Andy Shevchenko, platform-driver-x86, linux-kernel
Add the 'list' command, which shows the metric definitions of the PMT
telemetry devices on the system: one group per GUID with its platform,
number of metrics and description, followed by each metric's name and
description. A GUID shared by several devices is listed once. On a
terminal, descriptions are wrapped to its width; otherwise each is
printed on one line so the output is easy to search.
Metric definitions are loaded by pmtctl_ctx_load_tss() from the path
given with -J or, without it, from the directory they are installed in
(/usr/share/pmtctl by default, set with DEFSDIR at build time).
'make install' installs the definitions converted by
'make defs-json-fetch', if any. A missing default directory is not an
error, but definitions that fail to load are.
--guid and --device restrict the listing to the devices with a GUID or
to one device. The selection is done by pmtctl_select_devices(), which
keeps the device order and is shared with the commands added later. If
none of the selected devices has metric definitions, 'list' fails with
an error rather than printing nothing.
Also add print_chars() to lib/common.c for the indents and separator
lines; 'stat' uses it as well.
Signed-off-by: David E. Box <david.e.box@linux.intel.com>
---
V2 changes:
- Replaces the metric listing of v1 13, with -J from v1 12.
- Each metric is listed once per GUID; v1 listed it once per device
sharing the GUID.
- Descriptions are wrapped only on a terminal.
- Definitions come from -J or the installed /usr/share/pmtctl.
- --guid and --device replace -d; the pager and -X/--keep are dropped.
- A selection without metric definitions is an error.
tools/arch/x86/pmtctl/Makefile | 9 +
tools/arch/x86/pmtctl/include/lib/common.h | 7 +
tools/arch/x86/pmtctl/include/lib/pmtctl.h | 26 ++
tools/arch/x86/pmtctl/include/pmtctl_cli.h | 6 +
tools/arch/x86/pmtctl/lib/common.c | 6 +
tools/arch/x86/pmtctl/lib/pmtctl.c | 90 +++++++
tools/arch/x86/pmtctl/src/cmd_list.c | 292 +++++++++++++++++++++
tools/arch/x86/pmtctl/src/main.c | 17 +-
8 files changed, 452 insertions(+), 1 deletion(-)
create mode 100644 tools/arch/x86/pmtctl/src/cmd_list.c
diff --git a/tools/arch/x86/pmtctl/Makefile b/tools/arch/x86/pmtctl/Makefile
index 8b723f96904b..bb1a92e3dd6f 100644
--- a/tools/arch/x86/pmtctl/Makefile
+++ b/tools/arch/x86/pmtctl/Makefile
@@ -2,10 +2,12 @@
# Makefile for Intel Platform Monitoring Technology (PMT) tool
BINDIR ?= /usr/sbin
+DEFSDIR ?= /usr/share/pmtctl
CFLAGS = -Wextra
override CFLAGS += -O2 -Wall -D_GNU_SOURCE -Iinclude -I../../../include
+override CFLAGS += -DPMTCTL_DEFS_DIR='"$(DEFSDIR)"'
# The jansson check is skipped for targets that don't compile anything
ifneq ($(filter-out clean defs-json-fetch defs-json-pull defs-clean,$(or $(MAKECMDGOALS),pmtctl)),)
@@ -25,6 +27,7 @@ OBJS := \
lib/pmtctl.o \
lib/tss.o \
lib/tss_json.o \
+ src/cmd_list.o \
src/main.o
pmtctl: $(OBJS)
@@ -92,3 +95,9 @@ clean:
install: pmtctl
install -d $(DESTDIR)$(BINDIR)
install -m 755 -p pmtctl $(DESTDIR)$(BINDIR)/pmtctl
+ @# Metric definitions, if 'make defs-json-fetch' was run
+ @if ls $(DEFS_DIR)/*.json >/dev/null 2>&1; then \
+ install -d $(DESTDIR)$(DEFSDIR); \
+ install -m 644 -p $(DEFS_DIR)/*.json $(DESTDIR)$(DEFSDIR); \
+ echo "Installed metric definitions to $(DESTDIR)$(DEFSDIR)"; \
+ fi
diff --git a/tools/arch/x86/pmtctl/include/lib/common.h b/tools/arch/x86/pmtctl/include/lib/common.h
index 0e1950bffc43..018b21db4e08 100644
--- a/tools/arch/x86/pmtctl/include/lib/common.h
+++ b/tools/arch/x86/pmtctl/include/lib/common.h
@@ -61,4 +61,11 @@ int parse_u32(const char *s, int base, uint32_t *val);
*/
int path_printf(char *buf, size_t size, const char *fmt, ...) __printf(3, 4);
+/**
+ * print_chars - print a character repeatedly to stdout
+ * @c: character to print
+ * @n: number of times to print it
+ */
+void print_chars(int c, size_t n);
+
#endif
diff --git a/tools/arch/x86/pmtctl/include/lib/pmtctl.h b/tools/arch/x86/pmtctl/include/lib/pmtctl.h
index 9da9e1f221ca..5d3586bf31e2 100644
--- a/tools/arch/x86/pmtctl/include/lib/pmtctl.h
+++ b/tools/arch/x86/pmtctl/include/lib/pmtctl.h
@@ -2,11 +2,18 @@
#ifndef PMTCTL_H
#define PMTCTL_H
+#include <stdbool.h>
#include <stddef.h>
+#include <stdint.h>
#include "lib/device.h"
#include "lib/tss.h"
+/* Installed metric definitions, used when no path is given */
+#ifndef PMTCTL_DEFS_DIR
+#define PMTCTL_DEFS_DIR "/usr/share/pmtctl"
+#endif
+
/* State for one pmtctl command, owned by the command */
struct pmtctl_ctx {
struct pmt_device *devices;
@@ -14,8 +21,27 @@ struct pmtctl_ctx {
struct pmt_tss_db tss;
};
+/**
+ * struct pmt_device_filter - devices a command acts on
+ * @has_guid: select only the devices whose GUID is @guid
+ * @guid: the GUID to match, used only if @has_guid is set
+ * @name: if not NULL, select only the device with this name, e.g. "telem3"
+ *
+ * A device is selected if it matches every filter that is set, so a zeroed
+ * filter selects all devices.
+ */
+struct pmt_device_filter {
+ bool has_guid;
+ uint32_t guid;
+ const char *name;
+};
+
int pmtctl_ctx_init(struct pmtctl_ctx *ctx);
+int pmtctl_ctx_load_tss(struct pmtctl_ctx *ctx, const char *json_path);
void pmtctl_ctx_free(struct pmtctl_ctx *ctx);
+int pmtctl_select_devices(const struct pmtctl_ctx *ctx, const struct pmt_device_filter *filter,
+ const struct pmt_device ***devs, size_t *num_devs);
+int pmt_device_filter_set_guid(struct pmt_device_filter *filter, const char *arg);
/*
* Free the context with pmtctl_ctx_free() at scope exit:
diff --git a/tools/arch/x86/pmtctl/include/pmtctl_cli.h b/tools/arch/x86/pmtctl/include/pmtctl_cli.h
index 550a61b97aca..9551c581cf1b 100644
--- a/tools/arch/x86/pmtctl/include/pmtctl_cli.h
+++ b/tools/arch/x86/pmtctl/include/pmtctl_cli.h
@@ -9,4 +9,10 @@ enum pmtctl_exit {
PMTCTL_EXIT_SYSTEM,
};
+struct pmt_global_opts {
+ const char *json_path; /* -J, or NULL for the default directory */
+};
+
+int cmd_list(int argc, char **argv, const struct pmt_global_opts *gopts);
+
#endif
diff --git a/tools/arch/x86/pmtctl/lib/common.c b/tools/arch/x86/pmtctl/lib/common.c
index adf546df0911..85e887b348e0 100644
--- a/tools/arch/x86/pmtctl/lib/common.c
+++ b/tools/arch/x86/pmtctl/lib/common.c
@@ -73,3 +73,9 @@ int path_printf(char *buf, size_t size, const char *fmt, ...)
return 0;
}
+
+void print_chars(int c, size_t n)
+{
+ while (n--)
+ putchar(c);
+}
diff --git a/tools/arch/x86/pmtctl/lib/pmtctl.c b/tools/arch/x86/pmtctl/lib/pmtctl.c
index b218bac15824..dba015cfb574 100644
--- a/tools/arch/x86/pmtctl/lib/pmtctl.c
+++ b/tools/arch/x86/pmtctl/lib/pmtctl.c
@@ -1,5 +1,12 @@
// SPDX-License-Identifier: GPL-2.0-only
+#include <errno.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+#include "lib/common.h"
#include "lib/device.h"
+#include "lib/log.h"
#include "lib/pmtctl.h"
#include "lib/tss.h"
@@ -15,6 +22,33 @@ int pmtctl_ctx_init(struct pmtctl_ctx *ctx)
return telem_scan(&ctx->devices, &ctx->num_devices);
}
+/**
+ * pmtctl_ctx_load_tss - load metric definitions from JSON
+ * @ctx: initialized context without definitions
+ * @json_path: a definition file, a directory of them, or NULL for PMTCTL_DEFS_DIR
+ *
+ * A missing default directory is not an error: @ctx is left without
+ * definitions.
+ *
+ * Return: 0 on success or a negative errno.
+ */
+int pmtctl_ctx_load_tss(struct pmtctl_ctx *ctx, const char *json_path)
+{
+ if (!json_path) {
+ /*
+ * Definitions are optional, so a default directory that doesn't
+ * exist just means none are installed. Any other problem with it
+ * is reported by the loader.
+ */
+ if (access(PMTCTL_DEFS_DIR, F_OK) && errno == ENOENT)
+ return 0;
+
+ json_path = PMTCTL_DEFS_DIR;
+ }
+
+ return pmt_tss_db_load_json(json_path, &ctx->tss);
+}
+
void pmtctl_ctx_free(struct pmtctl_ctx *ctx)
{
pmt_tss_db_free(&ctx->tss);
@@ -22,3 +56,59 @@ void pmtctl_ctx_free(struct pmtctl_ctx *ctx)
ctx->devices = NULL;
ctx->num_devices = 0;
}
+
+/**
+ * pmtctl_select_devices - select the devices matching a filter
+ * @ctx: initialized context
+ * @filter: the devices to select, see struct pmt_device_filter
+ * @devs: returns the selected devices in ctx->devices order, freed with free()
+ * @num_devs: returns the number of entries in @devs, which may be 0
+ *
+ * Return: 0 on success or -ENOMEM.
+ */
+int pmtctl_select_devices(const struct pmtctl_ctx *ctx, const struct pmt_device_filter *filter,
+ const struct pmt_device ***devs, size_t *num_devs)
+{
+ const struct pmt_device **sel;
+ size_t n = 0;
+
+ sel = calloc(ctx->num_devices, sizeof(*sel));
+ if (!sel)
+ return -ENOMEM;
+
+ for (size_t i = 0; i < ctx->num_devices; i++) {
+ const struct pmt_device *dev = &ctx->devices[i];
+
+ if (filter->has_guid && dev->guid != filter->guid)
+ continue;
+
+ if (filter->name && strcmp(dev->name, filter->name))
+ continue;
+
+ sel[n++] = dev;
+ }
+
+ *devs = sel;
+ *num_devs = n;
+
+ return 0;
+}
+
+/**
+ * pmt_device_filter_set_guid - restrict a filter to the devices with a GUID
+ * @filter: filter to change
+ * @arg: GUID in hex, as given on the command line
+ *
+ * Return: 0 on success, or -EINVAL with an error message if @arg isn't a GUID.
+ */
+int pmt_device_filter_set_guid(struct pmt_device_filter *filter, const char *arg)
+{
+ if (parse_u32(arg, 16, &filter->guid)) {
+ log_err("invalid GUID '%s'", arg);
+ return -EINVAL;
+ }
+
+ filter->has_guid = true;
+
+ return 0;
+}
diff --git a/tools/arch/x86/pmtctl/src/cmd_list.c b/tools/arch/x86/pmtctl/src/cmd_list.c
new file mode 100644
index 000000000000..cefcb465969a
--- /dev/null
+++ b/tools/arch/x86/pmtctl/src/cmd_list.c
@@ -0,0 +1,292 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/*
+ * pmtctl list: show the metric definitions of the PMT telemetry devices
+ */
+#include <errno.h>
+#include <getopt.h>
+#include <limits.h>
+#include <stdbool.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/ioctl.h>
+#include <unistd.h>
+
+#include <linux/kernel.h>
+
+#include "lib/common.h"
+#include "lib/device.h"
+#include "lib/log.h"
+#include "lib/pmtctl.h"
+#include "lib/tss.h"
+#include "pmtctl_cli.h"
+
+#define LIST_BASE_INDENT 2
+#define LIST_DEFAULT_COLS 80
+
+/* Indent of the description under a GUID group header and under a metric */
+#define LIST_GROUP_DESC_INDENT 4
+#define LIST_METRIC_DESC_INDENT 8
+
+/* Width limits of the line under a group header */
+#define LIST_SEP_MIN ((size_t)8)
+#define LIST_SEP_MAX ((size_t)100)
+
+/* Values for long-only options, above any short option character */
+enum {
+ OPT_LIST_GUID = CHAR_MAX + 1,
+ OPT_LIST_DEVICE,
+};
+
+struct list_opts {
+ bool show_help;
+ struct pmt_device_filter filter;
+};
+
+static void list_usage(FILE *out)
+{
+ fprintf(out,
+ "Usage: pmtctl list [options]\n"
+ "\n"
+ "List PMT metrics.\n"
+ "\n"
+ "Options:\n"
+ " -h, --help Show this help.\n"
+ " --guid <hex> Restrict to devices with this GUID.\n"
+ " --device <name> Restrict to one device, e.g. telem3.\n");
+}
+
+static int parse_list_opts(struct list_opts *opts, int argc, char **argv)
+{
+ static const struct option long_opts[] = {
+ { "help", no_argument, NULL, 'h' },
+ { "guid", required_argument, NULL, OPT_LIST_GUID },
+ { "device", required_argument, NULL, OPT_LIST_DEVICE },
+ {}
+ };
+ int opt;
+
+ optind = 1;
+
+ while ((opt = getopt_long(argc, argv, "h", long_opts, NULL)) != -1) {
+ switch (opt) {
+ case 'h':
+ opts->show_help = true;
+ break;
+ case OPT_LIST_GUID:
+ if (pmt_device_filter_set_guid(&opts->filter, optarg))
+ return -EINVAL;
+ break;
+ case OPT_LIST_DEVICE:
+ opts->filter.name = optarg;
+ break;
+ default:
+ return -EINVAL;
+ }
+ }
+
+ if (optind != argc) {
+ log_err("unexpected extra arguments to 'list'");
+ return -EINVAL;
+ }
+
+ return 0;
+}
+
+/* Return: the terminal width if stdout is a terminal, otherwise 0 (don't wrap) */
+static size_t output_columns(void)
+{
+ struct winsize ws;
+
+ if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws))
+ return 0;
+
+ if (!ws.ws_col)
+ return LIST_DEFAULT_COLS;
+
+ return ws.ws_col;
+}
+
+/*
+ * Print @s indented by @indent columns, with each run of whitespace printed
+ * as one space, or nothing if @s is empty. With @cols nonzero, wrap it at
+ * whitespace to fit @cols columns; a word longer than a line is not split.
+ * Widths are counted in bytes, which matches the ASCII definitions.
+ */
+static void print_description(const char *s, size_t indent, size_t cols)
+{
+ size_t column = indent;
+ bool line_start = true;
+
+ s += strspn(s, " \t\n");
+ if (!*s)
+ return;
+
+ print_chars(' ', indent);
+
+ while (*s) {
+ size_t wlen = strcspn(s, " \t\n");
+
+ if (cols && !line_start && column + 1 + wlen > cols) {
+ putchar('\n');
+ print_chars(' ', indent);
+ column = indent;
+ line_start = true;
+ }
+
+ if (!line_start) {
+ putchar(' ');
+ column++;
+ }
+
+ fwrite(s, 1, wlen, stdout);
+ column += wlen;
+ line_start = false;
+
+ s += wlen;
+ s += strspn(s, " \t\n");
+ }
+
+ putchar('\n');
+}
+
+/* Return: the platform of @info for display, "---" if it is unknown */
+static const char *tss_platform(const struct pmt_tss_info *info)
+{
+ if (info && info->platform)
+ return info->platform;
+
+ return "---";
+}
+
+/*
+ * Print the header of the group of @guid: its platform and, if it has metric
+ * definitions (@info is not NULL), their number and the description, wrapped
+ * at @cols if nonzero
+ */
+static void print_guid_group_line(uint32_t guid, const struct pmt_tss_info *info, size_t cols)
+{
+ print_chars(' ', LIST_BASE_INDENT);
+ printf("GUID %08x platform: %s", guid, tss_platform(info));
+ if (info)
+ printf(" %zu metric%s", info->num_metrics, info->num_metrics == 1 ? "" : "s");
+ putchar('\n');
+
+ if (info && info->description)
+ print_description(info->description, LIST_GROUP_DESC_INDENT, cols);
+}
+
+/*
+ * Underline a group header up to where its longest metric name would end at
+ * the description indent, within LIST_SEP_MIN and LIST_SEP_MAX columns
+ */
+static void print_separator(const struct pmt_tss_info *info)
+{
+ size_t width = 0;
+
+ for (size_t i = 0; i < info->num_metrics; i++)
+ width = max(width, strlen(info->metrics[i].name));
+
+ width = clamp(width + LIST_METRIC_DESC_INDENT - LIST_BASE_INDENT, LIST_SEP_MIN,
+ LIST_SEP_MAX);
+
+ print_chars(' ', LIST_BASE_INDENT);
+ print_chars('-', width);
+ putchar('\n');
+}
+
+/*
+ * List the metrics of the GUIDs of @devs, which are sorted by GUID.
+ * Return: whether any metric was listed.
+ */
+static bool do_list_metrics(const struct pmtctl_ctx *ctx, const struct pmt_device **devs,
+ size_t num_devs)
+{
+ size_t cols = output_columns();
+ bool listed = false;
+
+ for (size_t i = 0; i < num_devs; i++) {
+ const struct pmt_tss_info *info;
+
+ /* List each GUID once, however many devices have it */
+ if (i && devs[i]->guid == devs[i - 1]->guid)
+ continue;
+
+ info = pmt_tss_db_lookup(&ctx->tss, devs[i]->guid);
+ if (!info || !info->num_metrics)
+ continue;
+
+ if (listed)
+ putchar('\n');
+ listed = true;
+
+ print_guid_group_line(info->guid, info, cols);
+ print_separator(info);
+
+ for (size_t j = 0; j < info->num_metrics; j++) {
+ const struct pmt_metric_def *m = &info->metrics[j];
+
+ print_chars(' ', LIST_BASE_INDENT);
+ printf("%s\n", m->name);
+ if (m->description)
+ print_description(m->description, LIST_METRIC_DESC_INDENT, cols);
+ }
+ }
+
+ return listed;
+}
+
+int cmd_list(int argc, char **argv, const struct pmt_global_opts *gopts)
+{
+ struct pmtctl_ctx ctx auto_pmtctl_ctx = {};
+ const struct pmt_device **devs auto_free = NULL;
+ struct list_opts opts = {};
+ size_t num_devs;
+ int ret;
+
+ ret = parse_list_opts(&opts, argc, argv);
+ if (ret) {
+ list_usage(stderr);
+ return PMTCTL_EXIT_USER;
+ }
+
+ if (opts.show_help) {
+ list_usage(stdout);
+ return PMTCTL_EXIT_OK;
+ }
+
+ ret = pmtctl_ctx_init(&ctx);
+ if (ret)
+ return PMTCTL_EXIT_SYSTEM;
+
+ ret = pmtctl_ctx_load_tss(&ctx, gopts->json_path);
+ if (ret)
+ return PMTCTL_EXIT_SYSTEM;
+
+ ret = pmtctl_select_devices(&ctx, &opts.filter, &devs, &num_devs);
+ if (ret) {
+ log_ret(ret, "unable to select devices");
+ return PMTCTL_EXIT_SYSTEM;
+ }
+
+ if (!num_devs) {
+ log_err("no PMT telemetry device matches the filter");
+ return PMTCTL_EXIT_USER;
+ }
+
+ if (!ctx.tss.num_tss_info) {
+ if (gopts->json_path)
+ log_err("no metric definitions in %s", gopts->json_path);
+ else
+ log_err("no metric definitions; use -J or install them in %s",
+ PMTCTL_DEFS_DIR);
+ return PMTCTL_EXIT_USER;
+ }
+
+ if (!do_list_metrics(&ctx, devs, num_devs)) {
+ log_err("no metric definitions for the selected devices");
+ return PMTCTL_EXIT_USER;
+ }
+
+ return PMTCTL_EXIT_OK;
+}
diff --git a/tools/arch/x86/pmtctl/src/main.c b/tools/arch/x86/pmtctl/src/main.c
index 25aedef59cf5..d4a7ae464cb8 100644
--- a/tools/arch/x86/pmtctl/src/main.c
+++ b/tools/arch/x86/pmtctl/src/main.c
@@ -7,6 +7,7 @@
#include <string.h>
#include "lib/log.h"
+#include "lib/pmtctl.h"
#include "pmtctl_cli.h"
#define PMTCTL_VERSION "2026.11.22"
@@ -22,6 +23,12 @@ static void print_usage(FILE *out)
" -h, --help Show this help and exit\n"
" -V, --version Show version and exit\n"
"\n"
+ " -J, --json-file <path> Metrics JSON file or directory\n"
+ " If omitted, " PMTCTL_DEFS_DIR " is used if it exists.\n"
+ "\n"
+ "Commands:\n"
+ " list List available PMT metrics\n"
+ "\n"
"Run 'pmtctl <command> --help' for command-specific options.\n");
}
@@ -30,13 +37,15 @@ int main(int argc, char **argv)
static const struct option long_opts[] = {
{ "help", no_argument, NULL, 'h' },
{ "version", no_argument, NULL, 'V' },
+ { "json-file", required_argument, NULL, 'J' },
{}
};
+ struct pmt_global_opts gopts = {};
const char *cmd;
int opt;
/* '+' stops at the first non-option: the command name */
- while ((opt = getopt_long(argc, argv, "+hV", long_opts, NULL)) != -1) {
+ while ((opt = getopt_long(argc, argv, "+hVJ:", long_opts, NULL)) != -1) {
switch (opt) {
case 'h':
print_usage(stdout);
@@ -45,6 +54,9 @@ int main(int argc, char **argv)
printf("pmtctl version %s - David E. Box <david.e.box@linux.intel.com>\n",
PMTCTL_VERSION);
return PMTCTL_EXIT_OK;
+ case 'J':
+ gopts.json_path = optarg;
+ break;
default:
/* getopt_long() already printed an error */
fprintf(stderr, "Try 'pmtctl --help' for usage.\n");
@@ -60,6 +72,9 @@ int main(int argc, char **argv)
cmd = argv[optind];
+ if (!strcmp(cmd, "list"))
+ return cmd_list(argc - optind, argv + optind, &gopts);
+
if (!strcmp(cmd, "help")) {
print_usage(stdout);
return PMTCTL_EXIT_OK;
--
2.53.0
^ permalink raw reply related [flat|nested] 13+ messages in thread* [PATCH v2 06/12] tools/arch/x86/pmtctl: Add 'list --summary'
2026-11-22 19:33 [PATCH v2 00/12] tools/arch/x86/pmtctl: Add Intel PMT command-line tool David E. Box
` (4 preceding siblings ...)
2026-11-22 19:34 ` [PATCH v2 05/12] tools/arch/x86/pmtctl: Add 'list' command David E. Box
@ 2026-11-22 19:34 ` David E. Box
2026-11-22 19:34 ` [PATCH v2 07/12] tools/arch/x86/pmtctl: Add 'stat' command David E. Box
` (5 subsequent siblings)
11 siblings, 0 replies; 13+ messages in thread
From: David E. Box @ 2026-11-22 19:34 UTC (permalink / raw)
To: Ilpo Järvinen, Hans de Goede
Cc: David E. Box, Andy Shevchenko, platform-driver-x86, linux-kernel
Add the --summary mode to 'list', which shows the GUIDs of the PMT
telemetry devices on the system, each with its platform and description
when its definitions are available, and the devices that have it.
Unlike the metric listing it works without metric definitions, and like
it, it can be restricted with --guid and --device.
Signed-off-by: David E. Box <david.e.box@linux.intel.com>
---
V2 changes:
- Replaces 'list --devices' from v1 13; v1's 'list --guids' is
dropped.
- Works without metric definitions (v1's failed without built-in
ones), is sorted, and honors --guid and --device.
tools/arch/x86/pmtctl/src/cmd_list.c | 40 +++++++++++++++++++++++++++-
tools/arch/x86/pmtctl/src/main.c | 2 +-
2 files changed, 40 insertions(+), 2 deletions(-)
diff --git a/tools/arch/x86/pmtctl/src/cmd_list.c b/tools/arch/x86/pmtctl/src/cmd_list.c
index cefcb465969a..35a610909558 100644
--- a/tools/arch/x86/pmtctl/src/cmd_list.c
+++ b/tools/arch/x86/pmtctl/src/cmd_list.c
@@ -28,6 +28,9 @@
#define LIST_GROUP_DESC_INDENT 4
#define LIST_METRIC_DESC_INDENT 8
+/* Indent of a device name under its GUID group header */
+#define LIST_DEVICE_INDENT 6
+
/* Width limits of the line under a group header */
#define LIST_SEP_MIN ((size_t)8)
#define LIST_SEP_MAX ((size_t)100)
@@ -36,11 +39,13 @@
enum {
OPT_LIST_GUID = CHAR_MAX + 1,
OPT_LIST_DEVICE,
+ OPT_LIST_SUMMARY,
};
struct list_opts {
bool show_help;
struct pmt_device_filter filter;
+ bool summary;
};
static void list_usage(FILE *out)
@@ -53,7 +58,8 @@ static void list_usage(FILE *out)
"Options:\n"
" -h, --help Show this help.\n"
" --guid <hex> Restrict to devices with this GUID.\n"
- " --device <name> Restrict to one device, e.g. telem3.\n");
+ " --device <name> Restrict to one device, e.g. telem3.\n"
+ " --summary List GUIDs and their devices.\n");
}
static int parse_list_opts(struct list_opts *opts, int argc, char **argv)
@@ -62,6 +68,7 @@ static int parse_list_opts(struct list_opts *opts, int argc, char **argv)
{ "help", no_argument, NULL, 'h' },
{ "guid", required_argument, NULL, OPT_LIST_GUID },
{ "device", required_argument, NULL, OPT_LIST_DEVICE },
+ { "summary", no_argument, NULL, OPT_LIST_SUMMARY },
{}
};
int opt;
@@ -80,6 +87,9 @@ static int parse_list_opts(struct list_opts *opts, int argc, char **argv)
case OPT_LIST_DEVICE:
opts->filter.name = optarg;
break;
+ case OPT_LIST_SUMMARY:
+ opts->summary = true;
+ break;
default:
return -EINVAL;
}
@@ -176,6 +186,29 @@ static void print_guid_group_line(uint32_t guid, const struct pmt_tss_info *info
print_description(info->description, LIST_GROUP_DESC_INDENT, cols);
}
+/* List @devs, which are sorted by GUID as ctx->devices is */
+static void do_list_summary(const struct pmtctl_ctx *ctx, const struct pmt_device **devs,
+ size_t num_devs)
+{
+ size_t cols = output_columns();
+
+ printf("PMT devices on this system:\n\n");
+
+ for (size_t i = 0; i < num_devs; i++) {
+ uint32_t guid = devs[i]->guid;
+
+ if (!i || guid != devs[i - 1]->guid)
+ print_guid_group_line(guid, pmt_tss_db_lookup(&ctx->tss, guid), cols);
+
+ print_chars(' ', LIST_DEVICE_INDENT);
+ printf("%s\n", devs[i]->name);
+
+ /* A blank line ends each GUID group */
+ if (i + 1 == num_devs || devs[i + 1]->guid != guid)
+ printf("\n");
+ }
+}
+
/*
* Underline a group header up to where its longest metric name would end at
* the description indent, within LIST_SEP_MIN and LIST_SEP_MAX columns
@@ -274,6 +307,11 @@ int cmd_list(int argc, char **argv, const struct pmt_global_opts *gopts)
return PMTCTL_EXIT_USER;
}
+ if (opts.summary) {
+ do_list_summary(&ctx, devs, num_devs);
+ return PMTCTL_EXIT_OK;
+ }
+
if (!ctx.tss.num_tss_info) {
if (gopts->json_path)
log_err("no metric definitions in %s", gopts->json_path);
diff --git a/tools/arch/x86/pmtctl/src/main.c b/tools/arch/x86/pmtctl/src/main.c
index d4a7ae464cb8..081c33aeb649 100644
--- a/tools/arch/x86/pmtctl/src/main.c
+++ b/tools/arch/x86/pmtctl/src/main.c
@@ -27,7 +27,7 @@ static void print_usage(FILE *out)
" If omitted, " PMTCTL_DEFS_DIR " is used if it exists.\n"
"\n"
"Commands:\n"
- " list List available PMT metrics\n"
+ " list List available PMT devices and metrics\n"
"\n"
"Run 'pmtctl <command> --help' for command-specific options.\n");
}
--
2.53.0
^ permalink raw reply related [flat|nested] 13+ messages in thread* [PATCH v2 07/12] tools/arch/x86/pmtctl: Add 'stat' command
2026-11-22 19:33 [PATCH v2 00/12] tools/arch/x86/pmtctl: Add Intel PMT command-line tool David E. Box
` (5 preceding siblings ...)
2026-11-22 19:34 ` [PATCH v2 06/12] tools/arch/x86/pmtctl: Add 'list --summary' David E. Box
@ 2026-11-22 19:34 ` David E. Box
2026-11-22 19:34 ` [PATCH v2 08/12] tools/arch/x86/pmtctl: Add 'stat --hex' David E. Box
` (4 subsequent siblings)
11 siblings, 0 replies; 13+ messages in thread
From: David E. Box @ 2026-11-22 19:34 UTC (permalink / raw)
To: Ilpo Järvinen, Hans de Goede
Cc: David E. Box, Andy Shevchenko, platform-driver-x86, linux-kernel
Add the 'stat' command, which samples metrics of the PMT telemetry
devices at an interval, similar to 'perf stat'. Metrics are given by
name with -e. The default layout has one row per device with the
metric's value; --vertical has one row per device and metric, and is
needed to view more than one metric. A device that has none of the
requested metrics is left out; with --vertical, a metric a device
doesn't have is shown as '-'. A value that can't be read is shown as
NaN; stat only fails if no value could be read at all. --guid and
--device restrict the devices, -i and -c set the interval and number of
samples, and --no-header leaves out the header.
Samples are scheduled from the start time with CLOCK_MONOTONIC, so the
interval doesn't drift, and the time column shows when each sample was
taken. SIGINT (Ctrl-C) ends the sampling without waiting out the
interval, whether it arrives during the wait or while values are being
read. Before sampling, every requested sample is checked against the
size of its telemetry region, and the data files are opened once, so a
permission problem is reported up front.
Discovery also records the size of each device's telemetry region,
from its size attribute, so that samples can be checked against it. A
device whose size can't be read is skipped with a warning, like one
whose GUID can't be read.
Signed-off-by: David E. Box <david.e.box@linux.intel.com>
---
V2 changes:
- Replaces v1 14, without --hex and --raw, which follow.
- -i and -c are parsed strictly; v1 accepted '10abc'.
- The time column is measured and sampling doesn't drift; v1 printed
sample x interval. SIGINT ends sampling without waiting out the
interval.
- Columns fit the names; v1 cut them at 20 or 28 characters.
- Samples are checked against the region size before sampling, and
the data files are opened once, up front.
- telem_read() rewritten.
- --once, --header and -d dropped in favor of -c 1, --no-header and
--guid/--device.
tools/arch/x86/pmtctl/Makefile | 1 +
tools/arch/x86/pmtctl/include/lib/device.h | 3 +
tools/arch/x86/pmtctl/include/pmtctl_cli.h | 1 +
tools/arch/x86/pmtctl/lib/device_telem.c | 49 ++
tools/arch/x86/pmtctl/src/cmd_stat.c | 753 +++++++++++++++++++++
tools/arch/x86/pmtctl/src/main.c | 4 +
6 files changed, 811 insertions(+)
create mode 100644 tools/arch/x86/pmtctl/src/cmd_stat.c
diff --git a/tools/arch/x86/pmtctl/Makefile b/tools/arch/x86/pmtctl/Makefile
index bb1a92e3dd6f..564931794086 100644
--- a/tools/arch/x86/pmtctl/Makefile
+++ b/tools/arch/x86/pmtctl/Makefile
@@ -28,6 +28,7 @@ OBJS := \
lib/tss.o \
lib/tss_json.o \
src/cmd_list.o \
+ src/cmd_stat.o \
src/main.o
pmtctl: $(OBJS)
diff --git a/tools/arch/x86/pmtctl/include/lib/device.h b/tools/arch/x86/pmtctl/include/lib/device.h
index 92d9603d695c..59a4e5b352e7 100644
--- a/tools/arch/x86/pmtctl/include/lib/device.h
+++ b/tools/arch/x86/pmtctl/include/lib/device.h
@@ -10,9 +10,12 @@ struct pmt_device {
uint32_t guid;
char *name; /* e.g. "telem0" */
char *data_path; /* telemetry data file */
+ uint32_t size; /* telemetry region size in bytes */
};
int telem_scan(struct pmt_device **devices, size_t *num_devices);
void telem_free(struct pmt_device *devices, size_t num_devices);
+int telem_open(const struct pmt_device *dev);
+int telem_read(int fd, uint32_t sample_id, unsigned int lsb, unsigned int msb, uint64_t *val);
#endif
diff --git a/tools/arch/x86/pmtctl/include/pmtctl_cli.h b/tools/arch/x86/pmtctl/include/pmtctl_cli.h
index 9551c581cf1b..eb8537c794b4 100644
--- a/tools/arch/x86/pmtctl/include/pmtctl_cli.h
+++ b/tools/arch/x86/pmtctl/include/pmtctl_cli.h
@@ -14,5 +14,6 @@ struct pmt_global_opts {
};
int cmd_list(int argc, char **argv, const struct pmt_global_opts *gopts);
+int cmd_stat(int argc, char **argv, const struct pmt_global_opts *gopts);
#endif
diff --git a/tools/arch/x86/pmtctl/lib/device_telem.c b/tools/arch/x86/pmtctl/lib/device_telem.c
index 0e249f16a21a..2f728514abe5 100644
--- a/tools/arch/x86/pmtctl/lib/device_telem.c
+++ b/tools/arch/x86/pmtctl/lib/device_telem.c
@@ -11,6 +11,8 @@
#include <string.h>
#include <unistd.h>
+#include <linux/bits.h>
+
#include "lib/common.h"
#include "lib/device.h"
#include "lib/log.h"
@@ -90,6 +92,7 @@ static int telem_add_device(struct telem_scan *scan, const char *devpath, const
char *data_path auto_free = NULL;
struct pmt_device *devices;
uint32_t guid;
+ uint32_t size;
int ret;
ret = read_attr_u32(devpath, "guid", 16, &guid);
@@ -98,6 +101,12 @@ static int telem_add_device(struct telem_scan *scan, const char *devpath, const
return 0;
}
+ ret = read_attr_u32(devpath, "size", 10, &size);
+ if (ret) {
+ log_warn("skipping %s: unable to read size: %s", devpath, strerror(-ret));
+ return 0;
+ }
+
dev_name = strdup(name);
if (!dev_name)
return -ENOMEM;
@@ -119,6 +128,7 @@ static int telem_add_device(struct telem_scan *scan, const char *devpath, const
.guid = guid,
.name = no_free_ptr(dev_name),
.data_path = no_free_ptr(data_path),
+ .size = size,
};
return 0;
@@ -246,3 +256,42 @@ void telem_free(struct pmt_device *devices, size_t num_devices)
}
free(devices);
}
+
+/* Return: a file descriptor for reading the telemetry of @dev, or a negative errno */
+int telem_open(const struct pmt_device *dev)
+{
+ int fd;
+
+ fd = open(dev->data_path, O_RDONLY);
+ if (fd < 0)
+ return -errno;
+
+ return fd;
+}
+
+/**
+ * telem_read - read a field of a telemetry sample
+ * @fd: file descriptor from telem_open()
+ * @sample_id: index of the 64-bit sample in the telemetry region
+ * @lsb: lowest bit of the field
+ * @msb: highest bit of the field, at most 63
+ * @val: returns the field, shifted down to bit 0
+ *
+ * Return: 0 on success, or a negative errno if the sample can't be read.
+ */
+int telem_read(int fd, uint32_t sample_id, unsigned int lsb, unsigned int msb, uint64_t *val)
+{
+ uint64_t sample;
+ ssize_t n;
+
+ n = pread(fd, &sample, sizeof(sample), sample_id * sizeof(sample));
+ if (n < 0)
+ return -errno;
+
+ if ((size_t)n != sizeof(sample))
+ return -EIO;
+
+ *val = (sample & GENMASK_ULL(msb, lsb)) >> lsb;
+
+ return 0;
+}
diff --git a/tools/arch/x86/pmtctl/src/cmd_stat.c b/tools/arch/x86/pmtctl/src/cmd_stat.c
new file mode 100644
index 000000000000..11a2ab1fa341
--- /dev/null
+++ b/tools/arch/x86/pmtctl/src/cmd_stat.c
@@ -0,0 +1,753 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/*
+ * pmtctl stat: sample metrics of the PMT telemetry devices over time
+ */
+#include <errno.h>
+#include <getopt.h>
+#include <inttypes.h>
+#include <limits.h>
+#include <signal.h>
+#include <stdbool.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <time.h>
+#include <unistd.h>
+
+#include <linux/kernel.h>
+#include <linux/time64.h>
+
+#include "lib/common.h"
+#include "lib/device.h"
+#include "lib/log.h"
+#include "lib/pmtctl.h"
+#include "lib/tss.h"
+#include "pmtctl_cli.h"
+
+#define STAT_DEFAULT_INTERVAL_MS 1000
+
+/* Printed instead of a value the device doesn't have, or that couldn't be read */
+#define STAT_VAL_ABSENT "-"
+#define STAT_VAL_FAILED "NaN"
+
+/* Room for any formatted value: the digits of UINT64_MAX, or a marker above */
+#define STAT_VALUE_LEN 20
+#define STAT_NUM_BUF (STAT_VALUE_LEN + 1)
+
+/* Column titles; each column is at least as wide as its title */
+#define STAT_COL_SAMPLE "sample"
+#define STAT_COL_TIME "time_ms"
+#define STAT_COL_DEVICE "device"
+#define STAT_COL_METRIC "metric"
+#define STAT_COL_VALUE "value"
+
+#define STAT_COL_GAP " "
+
+/* Values for long-only options, above any short option character */
+enum {
+ OPT_STAT_GUID = CHAR_MAX + 1,
+ OPT_STAT_DEVICE,
+ OPT_STAT_NO_HEADER,
+ OPT_STAT_VERTICAL,
+};
+
+/* A value to sample on each device */
+struct stat_request {
+ const char *name; /* metric name */
+};
+
+struct stat_opts {
+ bool show_help;
+ struct stat_request *requests;
+ size_t num_requests;
+ size_t requests_cap;
+ struct pmt_device_filter filter;
+ uint32_t interval_ms;
+ uint32_t count; /* number of samples, 0 until interrupted */
+ bool no_header;
+ bool vertical;
+};
+
+/* The value of one request on one device */
+struct stat_cell {
+ bool present; /* the device has the requested value */
+ uint32_t sample_id;
+ unsigned int lsb;
+ unsigned int msb;
+ bool valid; /* false if the last read failed */
+ bool reported; /* a read failure has been reported */
+ uint64_t value;
+};
+
+/* A device and the cells of its requests */
+struct stat_row {
+ const struct pmt_device *dev;
+ int fd;
+ struct stat_cell *cells;
+};
+
+struct stat_run {
+ struct stat_opts opts;
+ struct pmtctl_ctx ctx;
+ struct stat_row *rows;
+ size_t num_rows;
+ struct stat_cell *cells;
+ size_t dev_width; /* width of the device column */
+ size_t label_width; /* width of the metric column in --vertical */
+};
+
+static void stat_run_free(struct stat_run *run)
+{
+ for (size_t i = 0; i < run->num_rows; i++) {
+ if (run->rows[i].fd >= 0)
+ close(run->rows[i].fd);
+ }
+ free(run->rows);
+ free(run->cells);
+ free(run->opts.requests);
+ pmtctl_ctx_free(&run->ctx);
+}
+
+/* Free the run with stat_run_free() at scope exit */
+#define auto_stat_run __attribute__((cleanup(stat_run_free)))
+
+static void stat_usage_full(FILE *out)
+{
+ fprintf(out,
+ "Usage: pmtctl stat [options] -e <metric>[,<metric>...] ...\n"
+ "\n"
+ "Collect metric values over time (similar to 'perf stat').\n"
+ "\n"
+ "Options:\n"
+ " -h, --help Show this help.\n"
+ " -e, --event <spec> Metric name or comma-separated list; may be repeated.\n"
+ " --guid <hex> Restrict to devices with this GUID.\n"
+ " --device <name> Restrict to one device, e.g. telem3.\n"
+ " -i, --interval <ms> Sampling interval (default 1000 ms).\n"
+ " -c, --count <N> Number of samples (default infinite).\n"
+ " --no-header Don't print the header.\n"
+ " --vertical One line per value per sample: sample time_ms device\n"
+ " metric value. Required for more than one value.\n"
+ "\n"
+ "Devices without any requested value are left out. With --vertical, a\n"
+ "value a device doesn't have prints as -; one that can't be read, NaN.\n"
+ "\n"
+ "Examples:\n"
+ " pmtctl stat -e package_energy\n"
+ " pmtctl stat -e package_energy --interval 500\n"
+ " pmtctl stat -e firmware_version -c 1\n"
+ " pmtctl stat -e pch_temp --guid 03086000\n"
+ " pmtctl stat --vertical -e package_energy,pch_temp\n"
+ );
+}
+
+static void stat_usage_short(FILE *out)
+{
+ fprintf(out,
+ "Usage: pmtctl stat [options] -e <metric>[,<metric>...] ...\n"
+ "\n"
+ "Run 'pmtctl stat --help' for full help.\n"
+ );
+}
+
+static int add_request(struct stat_opts *opts, const struct stat_request *req)
+{
+ struct stat_request *requests;
+
+ requests = pmt_grow_array(opts->requests, &opts->requests_cap, opts->num_requests + 1,
+ sizeof(*requests));
+ if (!requests)
+ return -ENOMEM;
+
+ opts->requests = requests;
+ requests[opts->num_requests++] = *req;
+
+ return 0;
+}
+
+/* Add the metrics of an -e argument, which is split in place at the commas */
+static int add_metric_requests(struct stat_opts *opts, char *arg)
+{
+ char *saveptr;
+ char *name;
+ int ret;
+
+ for (name = strtok_r(arg, ",", &saveptr); name; name = strtok_r(NULL, ",", &saveptr)) {
+ ret = add_request(opts, &(struct stat_request){ .name = name });
+ if (ret)
+ return ret;
+ }
+
+ return 0;
+}
+
+/* Parse a positive number of option @opt */
+static int parse_positive(const char *arg, const char *opt, uint32_t *val)
+{
+ if (parse_u32(arg, 10, val) || !*val) {
+ log_err("%s must be a positive number, not '%s'", opt, arg);
+ return -EINVAL;
+ }
+
+ return 0;
+}
+
+static int stat_parse_options(struct stat_opts *opts, int argc, char **argv)
+{
+ static const struct option long_opts[] = {
+ { "help", no_argument, NULL, 'h' },
+ { "event", required_argument, NULL, 'e' },
+ { "guid", required_argument, NULL, OPT_STAT_GUID },
+ { "device", required_argument, NULL, OPT_STAT_DEVICE },
+ { "interval", required_argument, NULL, 'i' },
+ { "count", required_argument, NULL, 'c' },
+ { "no-header", no_argument, NULL, OPT_STAT_NO_HEADER },
+ { "vertical", no_argument, NULL, OPT_STAT_VERTICAL },
+ {}
+ };
+ int opt;
+ int ret;
+
+ optind = 1;
+
+ while ((opt = getopt_long(argc, argv, "he:i:c:", long_opts, NULL)) != -1) {
+ switch (opt) {
+ case 'h':
+ opts->show_help = true;
+ return 0;
+ case 'e':
+ ret = add_metric_requests(opts, optarg);
+ if (ret)
+ return log_ret(ret, "unable to add metrics");
+ break;
+ case OPT_STAT_GUID:
+ if (pmt_device_filter_set_guid(&opts->filter, optarg))
+ return -EINVAL;
+ break;
+ case OPT_STAT_DEVICE:
+ opts->filter.name = optarg;
+ break;
+ case 'i':
+ ret = parse_positive(optarg, "interval", &opts->interval_ms);
+ if (ret)
+ return ret;
+ break;
+ case 'c':
+ ret = parse_positive(optarg, "count", &opts->count);
+ if (ret)
+ return ret;
+ break;
+ case OPT_STAT_NO_HEADER:
+ opts->no_header = true;
+ break;
+ case OPT_STAT_VERTICAL:
+ opts->vertical = true;
+ break;
+ default:
+ return -EINVAL;
+ }
+ }
+
+ if (optind != argc) {
+ log_err("unexpected extra arguments to 'stat'");
+ return -EINVAL;
+ }
+
+ if (!opts->num_requests) {
+ log_err("requires -e/--event");
+ return -EINVAL;
+ }
+
+ if (opts->num_requests > 1 && !opts->vertical) {
+ log_err("more than one value needs --vertical");
+ return -EINVAL;
+ }
+
+ return 0;
+}
+
+static int metric_name_cmp(const void *key, const void *elem)
+{
+ const struct pmt_metric_def *def = elem;
+
+ return strcmp(key, def->name);
+}
+
+/* Return: whether 64-bit sample @sample_id is inside the telemetry region of @dev */
+static bool sample_in_region(const struct pmt_device *dev, uint32_t sample_id)
+{
+ return (sample_id + 1ULL) * sizeof(uint64_t) <= dev->size;
+}
+
+/* Find where the value of @req is in the telemetry of @dev */
+static void resolve_request(const struct pmtctl_ctx *ctx, const struct pmt_device *dev,
+ const struct stat_request *req, struct stat_cell *cell)
+{
+ const struct pmt_tss_info *info;
+ const struct pmt_metric_def *def;
+
+ *cell = (struct stat_cell){};
+
+ info = pmt_tss_db_lookup(&ctx->tss, dev->guid);
+ if (!info || !info->num_metrics)
+ return;
+
+ def = bsearch(req->name, info->metrics, info->num_metrics, sizeof(*info->metrics),
+ metric_name_cmp);
+ if (!def)
+ return;
+
+ cell->present = true;
+ cell->sample_id = def->sample_id;
+ cell->lsb = def->lsb;
+ cell->msb = def->msb;
+}
+
+/*
+ * Build a row for each of @devs that has at least one of the requested
+ * values. Every request must be present on some device. On success the
+ * rows are handed to @run.
+ */
+static int build_rows(struct stat_run *run, const struct pmt_device **devs, size_t num_devs)
+{
+ struct stat_cell *cells auto_free = NULL;
+ struct stat_row *rows auto_free = NULL;
+ bool *found auto_free = NULL;
+ const size_t num_requests = run->opts.num_requests;
+ size_t num_rows = 0;
+
+ rows = calloc(num_devs, sizeof(*rows));
+ cells = calloc(num_devs * num_requests, sizeof(*cells));
+ found = calloc(num_requests, sizeof(*found));
+ if (!rows || !cells || !found)
+ return -ENOMEM;
+
+ for (size_t d = 0; d < num_devs; d++) {
+ /* A device without any requested value gives its slot to the next one */
+ struct stat_row *row = &rows[num_rows];
+ bool any = false;
+
+ row->dev = devs[d];
+ row->fd = -1;
+ row->cells = &cells[num_rows * num_requests];
+
+ for (size_t r = 0; r < num_requests; r++) {
+ resolve_request(&run->ctx, devs[d], &run->opts.requests[r], &row->cells[r]);
+ if (row->cells[r].present) {
+ found[r] = true;
+ any = true;
+ }
+ }
+
+ if (any)
+ num_rows++;
+ }
+
+ for (size_t r = 0; r < num_requests; r++) {
+ if (!found[r]) {
+ log_err("no selected device has metric '%s'",
+ run->opts.requests[r].name);
+ return -ENOENT;
+ }
+ }
+
+ run->rows = no_free_ptr(rows);
+ run->cells = no_free_ptr(cells);
+ run->num_rows = num_rows;
+
+ return 0;
+}
+
+/* Check that every value to sample is inside the telemetry region of its device */
+static int check_bounds(const struct stat_run *run)
+{
+ for (size_t d = 0; d < run->num_rows; d++) {
+ const struct stat_row *row = &run->rows[d];
+
+ for (size_t r = 0; r < run->opts.num_requests; r++) {
+ const struct stat_cell *cell = &row->cells[r];
+
+ if (!cell->present)
+ continue;
+
+ if (!sample_in_region(row->dev, cell->sample_id)) {
+ log_err("%s: sample %" PRIu32 " of '%s' is beyond the %" PRIu32
+ "-byte telemetry region", row->dev->name, cell->sample_id,
+ run->opts.requests[r].name, row->dev->size);
+ return -ERANGE;
+ }
+ }
+ }
+
+ return 0;
+}
+
+/*
+ * Open the telemetry file of each row's device, once for the whole run. The
+ * files are closed by stat_run_free().
+ */
+static int open_telem_files(struct stat_run *run)
+{
+ for (size_t d = 0; d < run->num_rows; d++) {
+ struct stat_row *row = &run->rows[d];
+
+ row->fd = telem_open(row->dev);
+ if (row->fd == -EACCES || row->fd == -EPERM) {
+ log_err("permission denied reading %s; reading telemetry requires root",
+ row->dev->data_path);
+ return row->fd;
+ }
+
+ if (row->fd < 0)
+ return log_ret(row->fd, "unable to open %s", row->dev->data_path);
+ }
+
+ return 0;
+}
+
+/* Print @s in a column of @width, aligned to the right if @right */
+static void print_column(const char *s, size_t width, bool right)
+{
+ size_t len = strlen(s);
+ size_t pad = len < width ? width - len : 0;
+
+ if (right)
+ print_chars(' ', pad);
+ fputs(s, stdout);
+ if (!right)
+ print_chars(' ', pad);
+}
+
+static const char *format_value(const struct stat_cell *cell, char *buf, size_t len)
+{
+ if (!cell->present)
+ return STAT_VAL_ABSENT;
+
+ if (!cell->valid)
+ return STAT_VAL_FAILED;
+
+ snprintf(buf, len, "%" PRIu64, cell->value);
+
+ return buf;
+}
+
+/* In the horizontal layout the value column is headed by its one value's label */
+static size_t value_width(const struct stat_run *run)
+{
+ size_t width = STAT_VALUE_LEN;
+ size_t len = strlen(run->opts.requests[0].name);
+
+ if (!run->opts.vertical && len > width)
+ width = len;
+
+ return width;
+}
+
+/* Print the start of a line: sample, time and device columns */
+static void print_line_start(const struct stat_run *run, const char *sample, const char *time,
+ const char *dev)
+{
+ print_column(sample, strlen(STAT_COL_SAMPLE), false);
+ fputs(STAT_COL_GAP, stdout);
+ print_column(time, strlen(STAT_COL_TIME), false);
+ fputs(STAT_COL_GAP, stdout);
+ print_column(dev, run->dev_width, false);
+ fputs(STAT_COL_GAP, stdout);
+}
+
+static void print_header_dashes(const struct stat_run *run)
+{
+ print_chars('-', strlen(STAT_COL_SAMPLE));
+ fputs(STAT_COL_GAP, stdout);
+ print_chars('-', strlen(STAT_COL_TIME));
+ fputs(STAT_COL_GAP, stdout);
+ print_chars('-', run->dev_width);
+ fputs(STAT_COL_GAP, stdout);
+}
+
+static void print_header(const struct stat_run *run)
+{
+ if (run->opts.no_header)
+ return;
+
+ print_line_start(run, STAT_COL_SAMPLE, STAT_COL_TIME, STAT_COL_DEVICE);
+ if (run->opts.vertical) {
+ print_column(STAT_COL_METRIC, run->label_width, false);
+ fputs(STAT_COL_GAP STAT_COL_VALUE "\n", stdout);
+ } else {
+ print_column(run->opts.requests[0].name, value_width(run), true);
+ putchar('\n');
+ }
+
+ print_header_dashes(run);
+ if (run->opts.vertical) {
+ print_chars('-', run->label_width);
+ fputs(STAT_COL_GAP, stdout);
+ }
+ print_chars('-', value_width(run));
+ putchar('\n');
+ fflush(stdout);
+}
+
+static void print_sample(const struct stat_run *run, uint64_t sample, uint64_t time_ms)
+{
+ char sample_buf[STAT_NUM_BUF];
+ char time_buf[STAT_NUM_BUF];
+ char value_buf[STAT_NUM_BUF];
+
+ snprintf(sample_buf, sizeof(sample_buf), "%" PRIu64, sample);
+ snprintf(time_buf, sizeof(time_buf), "%" PRIu64, time_ms);
+
+ for (size_t d = 0; d < run->num_rows; d++) {
+ const struct stat_row *row = &run->rows[d];
+
+ for (size_t r = 0; r < run->opts.num_requests; r++) {
+ const char *value;
+
+ value = format_value(&row->cells[r], value_buf, sizeof(value_buf));
+
+ print_line_start(run, sample_buf, time_buf, row->dev->name);
+ if (run->opts.vertical) {
+ print_column(run->opts.requests[r].name, run->label_width, false);
+ fputs(STAT_COL_GAP, stdout);
+ fputs(value, stdout);
+ } else {
+ print_column(value, value_width(run), true);
+ }
+ putchar('\n');
+ }
+ }
+
+ fflush(stdout);
+}
+
+static void set_column_widths(struct stat_run *run)
+{
+ run->dev_width = strlen(STAT_COL_DEVICE);
+ for (size_t d = 0; d < run->num_rows; d++)
+ run->dev_width = max(run->dev_width, strlen(run->rows[d].dev->name));
+
+ run->label_width = strlen(STAT_COL_METRIC);
+ for (size_t r = 0; r < run->opts.num_requests; r++)
+ run->label_width = max(run->label_width, strlen(run->opts.requests[r].name));
+}
+
+/* Read every present cell; return the last read error, or 0 */
+/* Read the present values of every row. Return: whether any value was read */
+static bool read_cells(struct stat_run *run)
+{
+ bool any_read = false;
+
+ for (size_t d = 0; d < run->num_rows; d++) {
+ struct stat_row *row = &run->rows[d];
+
+ for (size_t r = 0; r < run->opts.num_requests; r++) {
+ struct stat_cell *cell = &row->cells[r];
+ int ret;
+
+ if (!cell->present)
+ continue;
+
+ ret = telem_read(row->fd, cell->sample_id, cell->lsb, cell->msb,
+ &cell->value);
+ cell->valid = !ret;
+ if (!ret) {
+ any_read = true;
+ continue;
+ }
+
+ /* Report each failing value once, not on every sample */
+ if (!cell->reported) {
+ log_warn("%s: unable to read sample %" PRIu32 ": %s",
+ row->dev->name, cell->sample_id, strerror(-ret));
+ cell->reported = true;
+ }
+ }
+ }
+
+ return any_read;
+}
+
+/* Return: @a - @b. @a must not be earlier than @b. */
+static struct timespec timespec_sub(const struct timespec *a, const struct timespec *b)
+{
+ struct timespec d = {
+ .tv_sec = a->tv_sec - b->tv_sec,
+ .tv_nsec = a->tv_nsec - b->tv_nsec,
+ };
+
+ if (d.tv_nsec < 0) {
+ d.tv_sec--;
+ d.tv_nsec += NSEC_PER_SEC;
+ }
+
+ return d;
+}
+
+/*
+ * Return: the milliseconds from @start to @now. @now must not be earlier
+ * than @start, as with two readings of CLOCK_MONOTONIC.
+ */
+static uint64_t ms_between(const struct timespec *start, const struct timespec *now)
+{
+ struct timespec d = timespec_sub(now, start);
+ uint64_t sec = d.tv_sec;
+
+ return sec * MSEC_PER_SEC + d.tv_nsec / NSEC_PER_MSEC;
+}
+
+static void timespec_add_ms(struct timespec *ts, uint32_t ms)
+{
+ ts->tv_sec += ms / MSEC_PER_SEC;
+ ts->tv_nsec += ms % MSEC_PER_SEC * NSEC_PER_MSEC;
+ if (ts->tv_nsec >= NSEC_PER_SEC) {
+ ts->tv_sec++;
+ ts->tv_nsec -= NSEC_PER_SEC;
+ }
+}
+
+static bool timespec_before(const struct timespec *a, const struct timespec *b)
+{
+ if (a->tv_sec != b->tv_sec)
+ return a->tv_sec < b->tv_sec;
+
+ return a->tv_nsec < b->tv_nsec;
+}
+
+/*
+ * Wait until @deadline, with the signals of @sigint blocked.
+ * Return: true if SIGINT arrived first.
+ */
+static bool wait_until(const struct timespec *deadline, const sigset_t *sigint)
+{
+ struct timespec now, timeout;
+
+ for (;;) {
+ clock_gettime(CLOCK_MONOTONIC, &now);
+ if (!timespec_before(&now, deadline))
+ return false;
+
+ timeout = timespec_sub(deadline, &now);
+ /* Otherwise timed out, or interrupted by a stop and continue */
+ if (sigtimedwait(sigint, NULL, &timeout) == SIGINT)
+ return true;
+ }
+}
+
+/*
+ * Sample every interval until the count is reached or SIGINT. Samples are
+ * scheduled from the start time, so the interval doesn't drift; a sample
+ * that is due before the previous one finished is skipped. SIGINT is
+ * blocked while sampling, so one that arrives during a read is not lost
+ * but ends the wait for the next sample.
+ */
+static int stat_loop(struct stat_run *run)
+{
+ struct timespec start, next, now;
+ sigset_t sigint, old_mask;
+ bool any_read = false;
+
+ sigemptyset(&sigint);
+ sigaddset(&sigint, SIGINT);
+ sigprocmask(SIG_BLOCK, &sigint, &old_mask);
+
+ print_header(run);
+
+ clock_gettime(CLOCK_MONOTONIC, &start);
+ next = start;
+
+ for (uint64_t sample = 0; ; sample++) {
+ clock_gettime(CLOCK_MONOTONIC, &now);
+
+ if (read_cells(run))
+ any_read = true;
+
+ print_sample(run, sample, ms_between(&start, &now));
+
+ if (run->opts.count && sample + 1 == run->opts.count)
+ break;
+
+ timespec_add_ms(&next, run->opts.interval_ms);
+ clock_gettime(CLOCK_MONOTONIC, &now);
+ while (timespec_before(&next, &now))
+ timespec_add_ms(&next, run->opts.interval_ms);
+
+ if (wait_until(&next, &sigint))
+ break;
+ }
+
+ sigprocmask(SIG_SETMASK, &old_mask, NULL);
+
+ /* Failed reads show as NaN and are each reported once; fail only if none succeeded */
+ if (!any_read) {
+ log_err("unable to read any telemetry");
+ return -EIO;
+ }
+
+ return 0;
+}
+
+int cmd_stat(int argc, char **argv, const struct pmt_global_opts *gopts)
+{
+ struct stat_run run auto_stat_run = {
+ .opts = { .interval_ms = STAT_DEFAULT_INTERVAL_MS },
+ };
+ const struct pmt_device **devs auto_free = NULL;
+ size_t num_devs;
+ int ret;
+
+ ret = stat_parse_options(&run.opts, argc, argv);
+ if (ret) {
+ stat_usage_short(stderr);
+ return PMTCTL_EXIT_USER;
+ }
+
+ if (run.opts.show_help) {
+ stat_usage_full(stdout);
+ return PMTCTL_EXIT_OK;
+ }
+
+ ret = pmtctl_ctx_init(&run.ctx);
+ if (ret)
+ return PMTCTL_EXIT_SYSTEM;
+
+ ret = pmtctl_ctx_load_tss(&run.ctx, gopts->json_path);
+ if (ret)
+ return PMTCTL_EXIT_SYSTEM;
+
+ ret = pmtctl_select_devices(&run.ctx, &run.opts.filter, &devs, &num_devs);
+ if (ret) {
+ log_ret(ret, "unable to select devices");
+ return PMTCTL_EXIT_SYSTEM;
+ }
+
+ if (!num_devs) {
+ log_err("no PMT telemetry device matches the filter");
+ return PMTCTL_EXIT_USER;
+ }
+
+ ret = build_rows(&run, devs, num_devs);
+ if (ret == -ENOMEM) {
+ log_ret(ret, "unable to set up sampling");
+ return PMTCTL_EXIT_SYSTEM;
+ }
+ if (ret)
+ return PMTCTL_EXIT_USER;
+
+ ret = check_bounds(&run);
+ if (ret)
+ return PMTCTL_EXIT_USER;
+
+ ret = open_telem_files(&run);
+ if (ret)
+ return PMTCTL_EXIT_SYSTEM;
+
+ set_column_widths(&run);
+
+ ret = stat_loop(&run);
+ if (ret)
+ return PMTCTL_EXIT_SYSTEM;
+
+ return PMTCTL_EXIT_OK;
+}
diff --git a/tools/arch/x86/pmtctl/src/main.c b/tools/arch/x86/pmtctl/src/main.c
index 081c33aeb649..dff05c30c7d1 100644
--- a/tools/arch/x86/pmtctl/src/main.c
+++ b/tools/arch/x86/pmtctl/src/main.c
@@ -28,6 +28,7 @@ static void print_usage(FILE *out)
"\n"
"Commands:\n"
" list List available PMT devices and metrics\n"
+ " stat Sample metrics over time (perf stat-like)\n"
"\n"
"Run 'pmtctl <command> --help' for command-specific options.\n");
}
@@ -75,6 +76,9 @@ int main(int argc, char **argv)
if (!strcmp(cmd, "list"))
return cmd_list(argc - optind, argv + optind, &gopts);
+ if (!strcmp(cmd, "stat"))
+ return cmd_stat(argc - optind, argv + optind, &gopts);
+
if (!strcmp(cmd, "help")) {
print_usage(stdout);
return PMTCTL_EXIT_OK;
--
2.53.0
^ permalink raw reply related [flat|nested] 13+ messages in thread* [PATCH v2 08/12] tools/arch/x86/pmtctl: Add 'stat --hex'
2026-11-22 19:33 [PATCH v2 00/12] tools/arch/x86/pmtctl: Add Intel PMT command-line tool David E. Box
` (6 preceding siblings ...)
2026-11-22 19:34 ` [PATCH v2 07/12] tools/arch/x86/pmtctl: Add 'stat' command David E. Box
@ 2026-11-22 19:34 ` David E. Box
2026-11-22 19:34 ` [PATCH v2 09/12] tools/arch/x86/pmtctl: Add 'stat --raw' David E. Box
` (3 subsequent siblings)
11 siblings, 0 replies; 13+ messages in thread
From: David E. Box @ 2026-11-22 19:34 UTC (permalink / raw)
To: Ilpo Järvinen, Hans de Goede
Cc: David E. Box, Andy Shevchenko, platform-driver-x86, linux-kernel
Add --hex to 'stat' to print the sampled values in hexadecimal, which
is easier to read for fields that hold flags, IDs or packed data.
Signed-off-by: David E. Box <david.e.box@linux.intel.com>
---
V2 changes:
- Split out of v1 14; no change in behavior.
tools/arch/x86/pmtctl/src/cmd_stat.c | 17 +++++++++++++++--
1 file changed, 15 insertions(+), 2 deletions(-)
diff --git a/tools/arch/x86/pmtctl/src/cmd_stat.c b/tools/arch/x86/pmtctl/src/cmd_stat.c
index 11a2ab1fa341..8377c2d1d194 100644
--- a/tools/arch/x86/pmtctl/src/cmd_stat.c
+++ b/tools/arch/x86/pmtctl/src/cmd_stat.c
@@ -50,6 +50,7 @@ enum {
OPT_STAT_DEVICE,
OPT_STAT_NO_HEADER,
OPT_STAT_VERTICAL,
+ OPT_STAT_HEX,
};
/* A value to sample on each device */
@@ -67,6 +68,7 @@ struct stat_opts {
uint32_t count; /* number of samples, 0 until interrupted */
bool no_header;
bool vertical;
+ bool hex;
};
/* The value of one request on one device */
@@ -127,6 +129,7 @@ static void stat_usage_full(FILE *out)
" -i, --interval <ms> Sampling interval (default 1000 ms).\n"
" -c, --count <N> Number of samples (default infinite).\n"
" --no-header Don't print the header.\n"
+ " --hex Output values in hex.\n"
" --vertical One line per value per sample: sample time_ms device\n"
" metric value. Required for more than one value.\n"
"\n"
@@ -204,6 +207,7 @@ static int stat_parse_options(struct stat_opts *opts, int argc, char **argv)
{ "count", required_argument, NULL, 'c' },
{ "no-header", no_argument, NULL, OPT_STAT_NO_HEADER },
{ "vertical", no_argument, NULL, OPT_STAT_VERTICAL },
+ { "hex", no_argument, NULL, OPT_STAT_HEX },
{}
};
int opt;
@@ -244,6 +248,9 @@ static int stat_parse_options(struct stat_opts *opts, int argc, char **argv)
case OPT_STAT_VERTICAL:
opts->vertical = true;
break;
+ case OPT_STAT_HEX:
+ opts->hex = true;
+ break;
default:
return -EINVAL;
}
@@ -419,7 +426,7 @@ static void print_column(const char *s, size_t width, bool right)
print_chars(' ', pad);
}
-static const char *format_value(const struct stat_cell *cell, char *buf, size_t len)
+static const char *format_value(const struct stat_cell *cell, bool hex, char *buf, size_t len)
{
if (!cell->present)
return STAT_VAL_ABSENT;
@@ -427,6 +434,11 @@ static const char *format_value(const struct stat_cell *cell, char *buf, size_t
if (!cell->valid)
return STAT_VAL_FAILED;
+ if (hex) {
+ snprintf(buf, len, "0x%" PRIx64, cell->value);
+ return buf;
+ }
+
snprintf(buf, len, "%" PRIu64, cell->value);
return buf;
@@ -505,7 +517,8 @@ static void print_sample(const struct stat_run *run, uint64_t sample, uint64_t t
for (size_t r = 0; r < run->opts.num_requests; r++) {
const char *value;
- value = format_value(&row->cells[r], value_buf, sizeof(value_buf));
+ value = format_value(&row->cells[r], run->opts.hex, value_buf,
+ sizeof(value_buf));
print_line_start(run, sample_buf, time_buf, row->dev->name);
if (run->opts.vertical) {
--
2.53.0
^ permalink raw reply related [flat|nested] 13+ messages in thread* [PATCH v2 09/12] tools/arch/x86/pmtctl: Add 'stat --raw'
2026-11-22 19:33 [PATCH v2 00/12] tools/arch/x86/pmtctl: Add Intel PMT command-line tool David E. Box
` (7 preceding siblings ...)
2026-11-22 19:34 ` [PATCH v2 08/12] tools/arch/x86/pmtctl: Add 'stat --hex' David E. Box
@ 2026-11-22 19:34 ` David E. Box
2026-11-22 19:34 ` [PATCH v2 10/12] tools/arch/x86/pmtctl: Add README David E. Box
` (2 subsequent siblings)
11 siblings, 0 replies; 13+ messages in thread
From: David E. Box @ 2026-11-22 19:34 UTC (permalink / raw)
To: Ilpo Järvinen, Hans de Goede
Cc: David E. Box, Andy Shevchenko, platform-driver-x86, linux-kernel
Add --raw to 'stat' to sample a bit range of a telemetry sample by its
position, id=<n>[,lsb=<n>][,msb=<n>], instead of by metric name. This
works without metric definitions, for example for a GUID that has none
or to check a definition against the data. --raw may be repeated and
combined with -e; as for metrics, more than one value needs --vertical.
A raw sample is read on each selected device whose telemetry region
contains it. A device whose region is too small is treated like one
without a requested metric: it is left out, or shows '-' with
--vertical. Requesting a sample that no selected device has is an error.
Signed-off-by: David E. Box <david.e.box@linux.intel.com>
---
V2 changes:
- Split out of v1 14.
- Follows the -e rules: may be repeated and combined with -e, and more
than one value needs --vertical. v1 allowed several raw columns in
the one-value layout.
- A sample outside a device's region is treated like a metric the
device doesn't have.
- One strict parser for id, lsb and msb (v1 had three copies that
accepted a sign); its errors name --raw.
tools/arch/x86/pmtctl/src/cmd_stat.c | 145 +++++++++++++++++++++++++--
1 file changed, 138 insertions(+), 7 deletions(-)
diff --git a/tools/arch/x86/pmtctl/src/cmd_stat.c b/tools/arch/x86/pmtctl/src/cmd_stat.c
index 8377c2d1d194..643686d067e6 100644
--- a/tools/arch/x86/pmtctl/src/cmd_stat.c
+++ b/tools/arch/x86/pmtctl/src/cmd_stat.c
@@ -44,6 +44,9 @@
#define STAT_COL_GAP " "
+/* Room for the label of a --raw request: "raw[id=4294967295,lsb=63,msb=63]" */
+#define STAT_RAW_LABEL_LEN 40
+
/* Values for long-only options, above any short option character */
enum {
OPT_STAT_GUID = CHAR_MAX + 1,
@@ -51,11 +54,19 @@ enum {
OPT_STAT_NO_HEADER,
OPT_STAT_VERTICAL,
OPT_STAT_HEX,
+ OPT_STAT_RAW,
};
/* A value to sample on each device */
struct stat_request {
const char *name; /* metric name */
+
+ /* For --raw, which reads bits [lsb, msb] of sample sample_id instead */
+ bool raw;
+ uint32_t sample_id;
+ unsigned int lsb;
+ unsigned int msb;
+ char raw_label[STAT_RAW_LABEL_LEN];
};
struct stat_opts {
@@ -118,12 +129,18 @@ static void stat_usage_full(FILE *out)
{
fprintf(out,
"Usage: pmtctl stat [options] -e <metric>[,<metric>...] ...\n"
+ " pmtctl stat [options] --raw id=<n>[,lsb=<n>][,msb=<n>] ...\n"
"\n"
"Collect metric values over time (similar to 'perf stat').\n"
"\n"
"Options:\n"
" -h, --help Show this help.\n"
" -e, --event <spec> Metric name or comma-separated list; may be repeated.\n"
+ " --raw <spec> Read a raw sample value by sample id, with optional\n"
+ " bit slicing; may be repeated and combined with -e.\n"
+ " <spec> is id=<n>[,lsb=<n>][,msb=<n>] without\n"
+ " spaces, where 0 <= lsb <= msb <= 63 (defaults:\n"
+ " lsb=0, msb=63).\n"
" --guid <hex> Restrict to devices with this GUID.\n"
" --device <name> Restrict to one device, e.g. telem3.\n"
" -i, --interval <ms> Sampling interval (default 1000 ms).\n"
@@ -142,6 +159,9 @@ static void stat_usage_full(FILE *out)
" pmtctl stat -e firmware_version -c 1\n"
" pmtctl stat -e pch_temp --guid 03086000\n"
" pmtctl stat --vertical -e package_energy,pch_temp\n"
+ " pmtctl stat --raw id=2\n"
+ " pmtctl stat --raw id=2,lsb=16,msb=31\n"
+ " pmtctl stat --vertical --raw id=2,msb=7 --raw id=3,lsb=8,msb=15\n"
);
}
@@ -149,6 +169,7 @@ static void stat_usage_short(FILE *out)
{
fprintf(out,
"Usage: pmtctl stat [options] -e <metric>[,<metric>...] ...\n"
+ " pmtctl stat [options] --raw id=<n>[,lsb=<n>][,msb=<n>] ...\n"
"\n"
"Run 'pmtctl stat --help' for full help.\n"
);
@@ -196,6 +217,88 @@ static int parse_positive(const char *arg, const char *opt, uint32_t *val)
return 0;
}
+/* Parse the value of --raw key @key, which must be given once and be at most @max */
+static int parse_raw_value(const char *key, const char *val, uint32_t max, bool *seen,
+ uint32_t *out)
+{
+ if (*seen) {
+ log_err("duplicate key '%s' in --raw argument", key);
+ return -EINVAL;
+ }
+ *seen = true;
+
+ if (parse_u32(val, 10, out)) {
+ log_err("--raw %s must be a decimal integer, got '%s'", key, val);
+ return -EINVAL;
+ }
+
+ if (*out > max) {
+ log_err("--raw %s must be at most %" PRIu32, key, max);
+ return -EINVAL;
+ }
+
+ return 0;
+}
+
+/* Add the request of a --raw argument, which is split in place at the commas */
+static int add_raw_request(struct stat_opts *opts, char *arg)
+{
+ struct stat_request req = { .raw = true };
+ uint32_t msb = PMT_SAMPLE_BITS - 1;
+ uint32_t lsb = 0;
+ bool seen_id = false;
+ bool seen_lsb = false;
+ bool seen_msb = false;
+ char *tok;
+ int ret;
+
+ while ((tok = strsep(&arg, ","))) {
+ char *val = strchr(tok, '=');
+
+ if (!val) {
+ log_err("invalid --raw token '%s' (expected key=value)", tok);
+ return -EINVAL;
+ }
+ *val++ = '\0';
+
+ if (!strcmp(tok, "id")) {
+ ret = parse_raw_value(tok, val, UINT32_MAX, &seen_id, &req.sample_id);
+ } else if (!strcmp(tok, "lsb")) {
+ ret = parse_raw_value(tok, val, PMT_SAMPLE_BITS - 1, &seen_lsb, &lsb);
+ } else if (!strcmp(tok, "msb")) {
+ ret = parse_raw_value(tok, val, PMT_SAMPLE_BITS - 1, &seen_msb, &msb);
+ } else {
+ log_err("unknown key '%s' in --raw argument", tok);
+ ret = -EINVAL;
+ }
+
+ if (ret)
+ return ret;
+ }
+
+ if (!seen_id) {
+ log_err("--raw requires at least 'id=<num>'");
+ return -EINVAL;
+ }
+
+ if (lsb > msb) {
+ log_err("--raw lsb (%" PRIu32 ") cannot be greater than msb (%" PRIu32 ")",
+ lsb, msb);
+ return -EINVAL;
+ }
+
+ req.lsb = lsb;
+ req.msb = msb;
+ snprintf(req.raw_label, sizeof(req.raw_label), "raw[id=%" PRIu32 ",lsb=%u,msb=%u]",
+ req.sample_id, req.lsb, req.msb);
+
+ ret = add_request(opts, &req);
+ if (ret)
+ return log_ret(ret, "unable to add --raw request");
+
+ return 0;
+}
+
static int stat_parse_options(struct stat_opts *opts, int argc, char **argv)
{
static const struct option long_opts[] = {
@@ -208,6 +311,7 @@ static int stat_parse_options(struct stat_opts *opts, int argc, char **argv)
{ "no-header", no_argument, NULL, OPT_STAT_NO_HEADER },
{ "vertical", no_argument, NULL, OPT_STAT_VERTICAL },
{ "hex", no_argument, NULL, OPT_STAT_HEX },
+ { "raw", required_argument, NULL, OPT_STAT_RAW },
{}
};
int opt;
@@ -251,6 +355,11 @@ static int stat_parse_options(struct stat_opts *opts, int argc, char **argv)
case OPT_STAT_HEX:
opts->hex = true;
break;
+ case OPT_STAT_RAW:
+ ret = add_raw_request(opts, optarg);
+ if (ret)
+ return ret;
+ break;
default:
return -EINVAL;
}
@@ -262,7 +371,7 @@ static int stat_parse_options(struct stat_opts *opts, int argc, char **argv)
}
if (!opts->num_requests) {
- log_err("requires -e/--event");
+ log_err("requires -e/--event or --raw");
return -EINVAL;
}
@@ -274,6 +383,14 @@ static int stat_parse_options(struct stat_opts *opts, int argc, char **argv)
return 0;
}
+static const char *request_label(const struct stat_request *req)
+{
+ if (req->raw)
+ return req->raw_label;
+
+ return req->name;
+}
+
static int metric_name_cmp(const void *key, const void *elem)
{
const struct pmt_metric_def *def = elem;
@@ -296,6 +413,18 @@ static void resolve_request(const struct pmtctl_ctx *ctx, const struct pmt_devic
*cell = (struct stat_cell){};
+ /* A raw request names its location, which a device has if it's in its region */
+ if (req->raw) {
+ if (!sample_in_region(dev, req->sample_id))
+ return;
+
+ cell->present = true;
+ cell->sample_id = req->sample_id;
+ cell->lsb = req->lsb;
+ cell->msb = req->msb;
+ return;
+ }
+
info = pmt_tss_db_lookup(&ctx->tss, dev->guid);
if (!info || !info->num_metrics)
return;
@@ -354,7 +483,7 @@ static int build_rows(struct stat_run *run, const struct pmt_device **devs, size
for (size_t r = 0; r < num_requests; r++) {
if (!found[r]) {
log_err("no selected device has metric '%s'",
- run->opts.requests[r].name);
+ request_label(&run->opts.requests[r]));
return -ENOENT;
}
}
@@ -381,7 +510,7 @@ static int check_bounds(const struct stat_run *run)
if (!sample_in_region(row->dev, cell->sample_id)) {
log_err("%s: sample %" PRIu32 " of '%s' is beyond the %" PRIu32
"-byte telemetry region", row->dev->name, cell->sample_id,
- run->opts.requests[r].name, row->dev->size);
+ request_label(&run->opts.requests[r]), row->dev->size);
return -ERANGE;
}
}
@@ -448,7 +577,7 @@ static const char *format_value(const struct stat_cell *cell, bool hex, char *bu
static size_t value_width(const struct stat_run *run)
{
size_t width = STAT_VALUE_LEN;
- size_t len = strlen(run->opts.requests[0].name);
+ size_t len = strlen(request_label(&run->opts.requests[0]));
if (!run->opts.vertical && len > width)
width = len;
@@ -488,7 +617,7 @@ static void print_header(const struct stat_run *run)
print_column(STAT_COL_METRIC, run->label_width, false);
fputs(STAT_COL_GAP STAT_COL_VALUE "\n", stdout);
} else {
- print_column(run->opts.requests[0].name, value_width(run), true);
+ print_column(request_label(&run->opts.requests[0]), value_width(run), true);
putchar('\n');
}
@@ -522,7 +651,8 @@ static void print_sample(const struct stat_run *run, uint64_t sample, uint64_t t
print_line_start(run, sample_buf, time_buf, row->dev->name);
if (run->opts.vertical) {
- print_column(run->opts.requests[r].name, run->label_width, false);
+ print_column(request_label(&run->opts.requests[r]),
+ run->label_width, false);
fputs(STAT_COL_GAP, stdout);
fputs(value, stdout);
} else {
@@ -543,7 +673,8 @@ static void set_column_widths(struct stat_run *run)
run->label_width = strlen(STAT_COL_METRIC);
for (size_t r = 0; r < run->opts.num_requests; r++)
- run->label_width = max(run->label_width, strlen(run->opts.requests[r].name));
+ run->label_width = max(run->label_width,
+ strlen(request_label(&run->opts.requests[r])));
}
/* Read every present cell; return the last read error, or 0 */
--
2.53.0
^ permalink raw reply related [flat|nested] 13+ messages in thread* [PATCH v2 10/12] tools/arch/x86/pmtctl: Add README
2026-11-22 19:33 [PATCH v2 00/12] tools/arch/x86/pmtctl: Add Intel PMT command-line tool David E. Box
` (8 preceding siblings ...)
2026-11-22 19:34 ` [PATCH v2 09/12] tools/arch/x86/pmtctl: Add 'stat --raw' David E. Box
@ 2026-11-22 19:34 ` David E. Box
2026-11-22 19:34 ` [PATCH v2 11/12] tools/arch/x86/pmtctl: Add man page David E. Box
2026-11-22 19:34 ` [PATCH v2 12/12] tools/arch/x86/pmtctl: Add MAINTAINERS entry David E. Box
11 siblings, 0 replies; 13+ messages in thread
From: David E. Box @ 2026-11-22 19:34 UTC (permalink / raw)
To: Ilpo Järvinen, Hans de Goede
Cc: David E. Box, Andy Shevchenko, platform-driver-x86, linux-kernel
Add a README that describes how to build and install pmtctl, how to
get the metric definitions from the Intel-PMT repository, and how to
use the 'list' and 'stat' commands, including the privileges they need
and the exit status.
Signed-off-by: David E. Box <david.e.box@linux.intel.com>
---
V2 changes:
- Replaces v1 16 (README.md), rewritten for v2 as plain text like the
other READMEs in tools/.
tools/arch/x86/pmtctl/README | 96 ++++++++++++++++++++++++++++++++++++
1 file changed, 96 insertions(+)
create mode 100644 tools/arch/x86/pmtctl/README
diff --git a/tools/arch/x86/pmtctl/README b/tools/arch/x86/pmtctl/README
new file mode 100644
index 000000000000..7d9a57cf3925
--- /dev/null
+++ b/tools/arch/x86/pmtctl/README
@@ -0,0 +1,96 @@
+pmtctl
+======
+
+pmtctl lists and samples the telemetry of Intel Platform Monitoring
+Technology (PMT) devices. The pmt_telemetry driver registers a telemetry
+device, telemN, for each telemetry region of a platform. Its data is an
+array of 64-bit samples, and its GUID identifies the layout: which bits
+of which sample hold which metric. pmtctl uses metric definitions
+generated from the layouts Intel publishes to name and decode the data.
+
+
+Building
+--------
+
+ make
+
+This needs libjansson and its development files (libjansson-dev on
+Debian and Ubuntu, jansson-devel on Fedora and RHEL).
+
+ make install
+
+installs pmtctl to /usr/sbin, and the metric definitions, if they were
+fetched, to /usr/share/pmtctl. BINDIR and DEFSDIR change the locations,
+and DESTDIR is prefixed to both.
+
+
+Metric definitions
+------------------
+
+The layouts are published as XML in the Intel-PMT repository
+(https://github.com/intel/Intel-PMT). scripts/pmtxml2json.py converts
+them into one JSON file per GUID:
+
+ make defs-json-fetch # clone Intel-PMT once and convert it into defs/
+ make defs-json-pull # update the clone and convert again
+ make defs-clean # remove defs/
+
+These targets need Python 3 with lxml, and are not part of the default
+build, so a plain 'make' never accesses the network. The clone is kept in
+~/.cache/pmtctl (PMT_CACHE_DIR). The JSON format and how event names are
+derived from the XML are described in scripts/pmtxml2json.md.
+
+pmtctl reads the definitions from the installed directory, or from the
+file or directory given with -J:
+
+ pmtctl -J defs list
+
+
+Usage
+-----
+
+ pmtctl [global options] <command> [command options]
+
+'list' shows the metrics of the telemetry devices on the system, grouped
+by GUID. 'list --summary' shows the GUIDs and their devices instead:
+
+ pmtctl list
+ pmtctl list --summary
+
+'stat' samples metrics at an interval, once a second by default. -i sets
+the interval in milliseconds and -c the number of samples:
+
+ pmtctl stat -e package_energy
+ pmtctl stat -e package_energy -i 500 -c 10
+
+The default layout has one row per device. More than one value needs
+--vertical, which prints one line per device and value:
+
+ pmtctl stat --vertical -e package_energy,pch_temp
+
+--raw samples a bit range of a sample by its position, without metric
+definitions. --hex prints values in hex:
+
+ pmtctl stat --raw id=2,lsb=16,msb=31
+ pmtctl stat --raw id=0,msb=31 --hex
+
+--guid and --device restrict both commands to the devices with a GUID
+or to one device:
+
+ pmtctl list --guid 03086000
+ pmtctl stat -e pch_temp --device telem3
+
+The telemetry data files can only be read by root, so 'stat' must run
+as root; 'list' doesn't need to.
+
+'pmtctl --help' and 'pmtctl <command> --help' describe all options.
+
+
+Exit status
+-----------
+
+ 0 success
+ 1 the request is wrong: an invalid option or value, or nothing
+ matches the selection
+ 2 something failed while carrying it out, such as reading the devices
+ or the metric definitions
--
2.53.0
^ permalink raw reply related [flat|nested] 13+ messages in thread* [PATCH v2 11/12] tools/arch/x86/pmtctl: Add man page
2026-11-22 19:33 [PATCH v2 00/12] tools/arch/x86/pmtctl: Add Intel PMT command-line tool David E. Box
` (9 preceding siblings ...)
2026-11-22 19:34 ` [PATCH v2 10/12] tools/arch/x86/pmtctl: Add README David E. Box
@ 2026-11-22 19:34 ` David E. Box
2026-11-22 19:34 ` [PATCH v2 12/12] tools/arch/x86/pmtctl: Add MAINTAINERS entry David E. Box
11 siblings, 0 replies; 13+ messages in thread
From: David E. Box @ 2026-11-22 19:34 UTC (permalink / raw)
To: Ilpo Järvinen, Hans de Goede
Cc: David E. Box, Andy Shevchenko, platform-driver-x86, linux-kernel
Add the pmtctl(8) man page, which describes the global options, the
'list' and 'stat' commands with their options and output, the metric
definition files and the exit status. 'make install' installs it to
$(MANDIR)/man8, /usr/share/man/man8 by default, and the README refers
to it.
Signed-off-by: David E. Box <david.e.box@linux.intel.com>
---
V2 changes:
- Replaces v1 17, rewritten for v2. v1 wrongly said -e and --raw were
mutually exclusive.
- Installed by 'make install'.
tools/arch/x86/pmtctl/Makefile | 3 +
tools/arch/x86/pmtctl/README | 3 +
tools/arch/x86/pmtctl/pmtctl.8 | 284 +++++++++++++++++++++++++++++++++
3 files changed, 290 insertions(+)
create mode 100644 tools/arch/x86/pmtctl/pmtctl.8
diff --git a/tools/arch/x86/pmtctl/Makefile b/tools/arch/x86/pmtctl/Makefile
index 564931794086..5f07c3345b78 100644
--- a/tools/arch/x86/pmtctl/Makefile
+++ b/tools/arch/x86/pmtctl/Makefile
@@ -3,6 +3,7 @@
BINDIR ?= /usr/sbin
DEFSDIR ?= /usr/share/pmtctl
+MANDIR ?= /usr/share/man
CFLAGS = -Wextra
@@ -96,6 +97,8 @@ clean:
install: pmtctl
install -d $(DESTDIR)$(BINDIR)
install -m 755 -p pmtctl $(DESTDIR)$(BINDIR)/pmtctl
+ install -d $(DESTDIR)$(MANDIR)/man8
+ install -m 644 -p pmtctl.8 $(DESTDIR)$(MANDIR)/man8/pmtctl.8
@# Metric definitions, if 'make defs-json-fetch' was run
@if ls $(DEFS_DIR)/*.json >/dev/null 2>&1; then \
install -d $(DESTDIR)$(DEFSDIR); \
diff --git a/tools/arch/x86/pmtctl/README b/tools/arch/x86/pmtctl/README
index 7d9a57cf3925..296dccba52ff 100644
--- a/tools/arch/x86/pmtctl/README
+++ b/tools/arch/x86/pmtctl/README
@@ -22,6 +22,8 @@ Debian and Ubuntu, jansson-devel on Fedora and RHEL).
installs pmtctl to /usr/sbin, and the metric definitions, if they were
fetched, to /usr/share/pmtctl. BINDIR and DEFSDIR change the locations,
and DESTDIR is prefixed to both.
+The pmtctl(8) man page is installed to /usr/share/man/man8, under
+DESTDIR too, and MANDIR changes its location.
Metric definitions
@@ -84,6 +86,7 @@ The telemetry data files can only be read by root, so 'stat' must run
as root; 'list' doesn't need to.
'pmtctl --help' and 'pmtctl <command> --help' describe all options.
+The pmtctl(8) man page describes them in more detail.
Exit status
diff --git a/tools/arch/x86/pmtctl/pmtctl.8 b/tools/arch/x86/pmtctl/pmtctl.8
new file mode 100644
index 000000000000..c547af73db1d
--- /dev/null
+++ b/tools/arch/x86/pmtctl/pmtctl.8
@@ -0,0 +1,284 @@
+.\" SPDX-License-Identifier: GPL-2.0-only
+.TH PMTCTL 8 "November 2026" "Linux" "System Administration"
+.SH NAME
+pmtctl \- query Intel Platform Monitoring Technology (PMT) telemetry metrics
+.SH SYNOPSIS
+.B pmtctl
+.RI [ "global options" ]
+.B list
+.RI [ options ]
+.br
+.B pmtctl
+.RI [ "global options" ]
+.B stat
+.RI [ options ]
+.BR \-e\ \fImetric\fR[,\fImetric\fR...]\ ...
+.br
+.B pmtctl
+.RI [ "global options" ]
+.B stat
+.RI [ options ]
+.BR \-\-raw\ id= \fIN\fR [,lsb= \fIN\fR ][,msb= \fIN\fR ]\ ...
+.SH DESCRIPTION
+.B pmtctl
+is a command-line tool for inspecting and sampling Intel Platform
+Monitoring Technology (PMT) telemetry exposed through the kernel
+.B pmt_telemetry
+auxiliary driver
+.RB ( /sys/bus/auxiliary/drivers/pmt_telemetry ).
+.PP
+The driver registers a telemetry device,
+.BI telem N\fR,
+for each telemetry region of the platform. Its data is an array of
+64-bit samples, and its GUID identifies the layout: which bits of
+which sample hold which metric.
+.B pmtctl
+uses metric definitions, one JSON file per GUID, to name and decode
+the data. The definitions are generated from the layouts published in
+the Intel-PMT repository; see
+.BR FILES .
+.PP
+The telemetry data files can only be read by
+.BR root ,
+so
+.B stat
+must run as root.
+.B list
+does not need to.
+.SH GLOBAL OPTIONS
+.TP
+.BR \-h ", " \-\-help
+Show help and exit.
+.TP
+.BR \-V ", " \-\-version
+Show version and exit.
+.TP
+.BR \-J ", " "\-\-json\-file " \fIpath\fR
+Load the metric definitions from
+.IR path ,
+a definition file or a directory of them. Without
+.BR \-J ,
+the definitions installed in
+.I /usr/share/pmtctl
+(set with DEFSDIR at build time) are used, if that directory exists.
+.SH COMMANDS
+.SS list
+.B pmtctl list
+.RI [ options ]
+.PP
+List the metrics of the telemetry devices on the system. The metrics
+are grouped by GUID, each group with its platform, number of metrics
+and description, and a GUID shared by several devices is listed once.
+On a terminal, descriptions are wrapped to its width.
+.TP
+.BR \-h ", " \-\-help
+Show help for
+.B list
+and exit.
+.TP
+.BI "\-\-guid " hex
+Restrict the listing to the devices with this GUID.
+.TP
+.BI "\-\-device " name
+Restrict the listing to one device, for example
+.BR telem3 .
+.TP
+.B \-\-summary
+List the GUIDs and their devices instead of the metrics. This works
+without metric definitions.
+.SS stat
+.B pmtctl stat
+.RI [ options ]
+.B \-e
+.IR metric [,\fImetric\fR...]
+\&...
+.br
+.B pmtctl stat
+.RI [ options ]
+.BR \-\-raw\ id= \fIN\fR [,lsb= \fIN\fR ][,msb= \fIN\fR ]\ ...
+.PP
+Sample metrics, or raw sample values, of the telemetry devices at an
+interval, in a manner similar to
+.BR "perf stat" .
+Samples are scheduled from the start time, so the interval doesn't
+drift, and the time column shows when each sample was taken. A sample
+that is due before the previous one finished is skipped. Sampling ends
+after the given number of samples or on
+.BR SIGINT ,
+which takes effect immediately, even during a long interval.
+.TP
+.BR \-h ", " \-\-help
+Show help for
+.B stat
+and exit.
+.TP
+.BR \-e ", " "\-\-event " \fIspec\fR
+Metric name, or a comma-separated list of metric names. May be
+repeated and combined with
+.BR \-\-raw .
+.TP
+.B \-\-raw \fBid=\fIN\fR[\fB,lsb=\fIN\fR][\fB,msb=\fIN\fR]
+Read bits
+.B lsb
+to
+.B msb
+of sample
+.B id
+of each device, without metric definitions. The items are separated by
+commas, without spaces.
+.B lsb
+defaults to 0 and
+.B msb
+to 63, and 0 \(<=
+.B lsb
+\(<=
+.B msb
+\(<= 63. May be repeated and combined with
+.BR \-e .
+.TP
+.BI "\-\-guid " hex
+Restrict sampling to the devices with this GUID.
+.TP
+.BI "\-\-device " name
+Restrict sampling to one device, for example
+.BR telem3 .
+.TP
+.BR \-i ", " "\-\-interval " \fIms\fR
+Sampling interval in milliseconds. Must be greater than 0. Default
+is 1000 ms.
+.TP
+.BR \-c ", " "\-\-count " \fIN\fR
+Number of samples to take. Must be greater than 0. Default is to
+sample until interrupted.
+.TP
+.B \-\-no\-header
+Don't print the header.
+.TP
+.B \-\-hex
+Print sample values in hexadecimal.
+.TP
+.B \-\-vertical
+One line per value per sample: the sample number, the time in ms, the
+device, the metric and the value. Required when more than one value is
+requested. The default layout has one line per device per sample.
+.PP
+Metric names are looked up in the definitions of each device's GUID, so
+a metric is sampled on every selected device that has it, at that
+device's location. A device that has none of the requested values is
+left out. With
+.BR \-\-vertical ,
+a value that a device doesn't have is printed as
+.BR \- ,
+as is a
+.B \-\-raw
+sample outside the device's telemetry region. A metric or raw sample
+that no selected device has is an error. A value that can't be read is
+printed as
+.BR NaN ;
+.B stat
+fails only if no value could be read at all.
+.SH EXAMPLES
+List the metrics, using the installed definitions:
+.PP
+.RS 4
+.nf
+pmtctl list
+.fi
+.RE
+.PP
+List the GUIDs and devices of the system, with definitions from
+.IR defs/ :
+.PP
+.RS 4
+.nf
+pmtctl \-J defs list \-\-summary
+.fi
+.RE
+.PP
+Sample a metric every 500 ms until interrupted:
+.PP
+.RS 4
+.nf
+sudo pmtctl stat \-e package_energy \-\-interval 500
+.fi
+.RE
+.PP
+Take a single sample of a metric on the devices with one GUID:
+.PP
+.RS 4
+.nf
+sudo pmtctl stat \-e pch_temp \-\-guid 03086000 \-c 1
+.fi
+.RE
+.PP
+Sample two metrics five times (requires \fB\-\-vertical\fR):
+.PP
+.RS 4
+.nf
+sudo pmtctl stat \-e package_energy,pch_temp \-\-vertical \-c 5
+.fi
+.RE
+.PP
+Print a value in hexadecimal:
+.PP
+.RS 4
+.nf
+sudo pmtctl stat \-e firmware_version \-c 1 \-\-hex
+.fi
+.RE
+.PP
+Read raw sample values, slicing bit fields out of two samples:
+.PP
+.RS 4
+.nf
+sudo pmtctl stat \-\-vertical \-\-raw id=2,msb=7 \-\-raw id=3,lsb=8,msb=15
+.fi
+.RE
+.SH FILES
+.TP
+.B /sys/bus/auxiliary/drivers/pmt_telemetry
+Sysfs entry point for the kernel
+.B pmt_telemetry
+auxiliary driver that
+.B pmtctl
+reads from.
+.TP
+.I /usr/share/pmtctl
+The installed metric definitions,
+.BI pmt_ guid .json
+for each GUID. They are generated from the Intel-PMT repository with
+.B make defs\-json\-fetch
+in the
+.B pmtctl
+source directory and installed with
+.BR "make install" .
+.SH EXIT STATUS
+.TP
+.B 0
+Success.
+.TP
+.B 1
+The request is wrong: an invalid option or value, or nothing matches
+the selection.
+.TP
+.B 2
+Something failed while carrying out the request, such as reading the
+devices or the metric definitions.
+.SH SEE ALSO
+.BR perf (1),
+.BR turbostat (8)
+.PP
+Intel Platform Monitoring Technology XML metric definitions:
+.UR https://github.com/intel/Intel-PMT
+.UE .
+.SH AUTHORS
+.B pmtctl
+was written by David E. Box <david.e.box@linux.intel.com>.
+.SH REPORTING BUGS
+Report bugs via the Linux kernel mailing lists; see the
+.B MAINTAINERS
+file in the kernel source tree for current maintainers of the
+Intel PMT subsystem.
+.SH COPYRIGHT
+.B pmtctl
+is licensed under GPL-2.0-only.
--
2.53.0
^ permalink raw reply related [flat|nested] 13+ messages in thread* [PATCH v2 12/12] tools/arch/x86/pmtctl: Add MAINTAINERS entry
2026-11-22 19:33 [PATCH v2 00/12] tools/arch/x86/pmtctl: Add Intel PMT command-line tool David E. Box
` (10 preceding siblings ...)
2026-11-22 19:34 ` [PATCH v2 11/12] tools/arch/x86/pmtctl: Add man page David E. Box
@ 2026-11-22 19:34 ` David E. Box
11 siblings, 0 replies; 13+ messages in thread
From: David E. Box @ 2026-11-22 19:34 UTC (permalink / raw)
To: Ilpo Järvinen, Hans de Goede
Cc: David E. Box, Andy Shevchenko, platform-driver-x86, linux-kernel
Add tools/arch/x86/pmtctl/ to the INTEL PMT DRIVERS entry, so that
patches to the tool reach the maintainer of the drivers it uses.
Also list platform-driver-x86@vger.kernel.org in the entry. The PMT
driver files already reach the list through X86 PLATFORM DRIVERS, but
tools/ is not covered by it, so without this the tool's patches would
not be sent to the list where the drivers are reviewed.
Signed-off-by: David E. Box <david.e.box@linux.intel.com>
---
V2 changes:
- Replaces v1 01, moved last so the path exists. The section is now
INTEL PMT DRIVERS.
- Also lists platform-driver-x86, which tools/ otherwise doesn't
reach.
MAINTAINERS | 2 ++
1 file changed, 2 insertions(+)
diff --git a/MAINTAINERS b/MAINTAINERS
index bd31e734669e..7d70fb0ef0d3 100644
--- a/MAINTAINERS
+++ b/MAINTAINERS
@@ -13716,10 +13716,12 @@ F: include/linux/mfd/intel_soc_pmic*
INTEL PMT DRIVERS
M: David E. Box <david.e.box@linux.intel.com>
+L: platform-driver-x86@vger.kernel.org
S: Supported
F: Documentation/ABI/testing/sysfs-class-intel_pmt
F: Documentation/ABI/testing/sysfs-class-intel_pmt-features
F: drivers/platform/x86/intel/pmt/
+F: tools/arch/x86/pmtctl/
INTEL PRO/WIRELESS 2100, 2200BG, 2915ABG NETWORK CONNECTION SUPPORT
M: Stanislav Yakovlev <stas.yakovlev@gmail.com>
--
2.53.0
^ permalink raw reply related [flat|nested] 13+ messages in thread