From nobody Tue Nov 24 11:43:49 2026 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=192.198.163.18 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1795376059; b=eqU4PdMbYjheNDdaRKQZICEMAFS+jH6sKVIkiSw489FWLDCTmndClMzV7wEHJcrv2DHD 1YrHuKoH1iW3lvJjQcOwhIzXUbse2zfG1vWJW8OiGQCj6xeFLNecsT2hpNr/Z7ZjtUWNT JFxL1RYT43ngPT6qD5zALlOaOGxxJaQalk/ZG4lg7nduxlAbuVhPgGQnhfsPbj/Xf1uWh s/g/iUU7J41UR4eSZI0sz0puMi6I/Mk97HMYtb7Vv08BIBqE2s4ZrI4uJguFSIoFvieIo DiCnh4LnsDbXurWUVvTCliVRRhNqouIf0JRN0OJAL3CU1fDTdzl9J/neyO3Ki+51t2w== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1795376059; h=DMARC-Filter:DKIM-Signature:X-CSE-ConnectionGUID:X-CSE-MsgGUID: X-IronPort-AV:X-IronPort-AV:Received:X-CSE-ConnectionGUID: X-CSE-MsgGUID:X-ExtLoop1:X-IronPort-AV:Received:From:To:Cc:Subject: Date:Message-ID:X-Mailer:In-Reply-To:References:MIME-Version: Content-Transfer-Encoding; bh=qX+JO5jC90ne1w9GzA8sIhprGIiKji7c9YgmThPrmfk=; b=SJPlMLOC8Fmb7EC4nQWK1R+mu8WbCn5VHRbE9nnmMnB2SJQWpPQqyk9GD4D5amf/fvkh PX3oxCn6fJHgH0MFrveURdZBeQ6ERJ1sdp4psLorwg0SHFm7wQnpmIkgy841WmLfEDpd9 11bjMIBVAnibhE1ggxbFiPjC8fzcmlxBIdb2gNp4l1vriG/AXHnxKuaGZZtMjlaMO9JO0 aOzUjvTJK5qdOq/jTQbNiUKeHQmaSLeFKlp4k82zQxjV6VeqDGZRRCXRodCKQI+Pd5CaI 7ASBK+5AifaqD/WBrTGvWng3x4l7AsXVsgdRNn8AcqZMuMem0Ui5jEKLnlYmxXr6vGQ== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass header.from=linux.intel.com; spf=pass smtp.mailfrom=linux.intel.com; dkim=pass header.d=intel.com header.i=@intel.com header.a=rsa-sha256 header.s=Intel header.b=gl1jsn4d; arc=none smtp.remote-ip=192.198.163.18 Received: from mgamail.intel.com (mgamail.intel.com [192.198.163.18]) (using TLSv1.2 with cipher ECDHE-ECDSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id A017D606A31D; Sun, 22 Nov 2026 19:34:18 +0000 (UTC) DMARC-Filter: OpenDMARC Filter v1.4.2 smtp.subspace.kernel.org A017D606A31D Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=linux.intel.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=linux.intel.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=intel.com header.i=@intel.com header.a=rsa-sha256 header.s=Intel header.b=gl1jsn4d DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=intel.com; i=@intel.com; q=dns/txt; s=Intel; t=1795376058; x=1826912058; h=from:to:cc:subject:date:message-id:in-reply-to: references:mime-version:content-transfer-encoding; bh=OcnOgggz80lchgDCsw/UJF5qzDMq15FfU00b6PbHsOA=; b=gl1jsn4dp9bQ0YvUu+3Y60RR+ZnMYMBLH33+BmyZQBfFU3JGWA4h3d2T PaLijjZ6IMKGYV+4d7WwpGJyUT5JFNModGK+9JwgOYKpVH4lYmCYTugI6 vcm+iQvt9BM20xQhD76HCdRV2B7ln0MTADB3jiRHLacgM+OXywZkFcdSx 3GsPK9tcSglfTDKjFZ9GJeumTQe49M1iSkBXwb+n/8sYyEdTNwF3yQbKs kpXbBxZkeC2pjbm3wvuksomzIeFQYzKAGCPwHou46BZ1KMUe8oZ29Sqjy +e7bZVRwicJZXwU4NVq1Rb8ymfb8lM5W5sCHIAxWfINaSY9DFN/hLaake Q==; X-CSE-ConnectionGUID: HJldRj4ISHmBopBI7zlipw== X-CSE-MsgGUID: +Sqd6I87SdqolVXeWHaHWQ== X-IronPort-AV: E=McAfee;i="6800,10657,11974"; a="4217503" X-IronPort-AV: E=Sophos;i="6.27,227,1787036400"; d="scan'208";a="4217503" Received: from fmviesa004.fm.intel.com ([10.60.135.144]) by fmvoesa112.fm.intel.com with ESMTP/TLS/ECDHE-RSA-AES256-GCM-SHA384; 22 Nov 2026 11:34:17 -0800 X-CSE-ConnectionGUID: gAq2B6slQ0+lEYWOW6A/mg== X-CSE-MsgGUID: I+HzzRtrS9+9rAWJCGKcEg== X-ExtLoop1: 1 X-IronPort-AV: E=Sophos;i="6.27,227,1787036400"; d="scan'208";a="11109787" Received: from debox1-desk4.jf.intel.com (HELO localhost) ([10.54.77.98]) by smtpauth.intel.com with ESMTP/TLS/ECDHE-RSA-AES256-GCM-SHA384; 22 Nov 2026 11:34:18 -0800 From: "David E. Box" To: =?UTF-8?q?Ilpo=20J=C3=A4rvinen?= , Hans de Goede Cc: "David E. Box" , Andy Shevchenko , platform-driver-x86@vger.kernel.org, linux-kernel@vger.kernel.org Subject: [PATCH v2 01/12] tools/arch/x86/pmtctl: Add pmtctl skeleton Date: Sun, 22 Nov 2026 11:33:56 -0800 Message-ID: X-Mailer: git-send-email 2.53.0 In-Reply-To: References: X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Post: List-Help: List-Subscribe: List-Unsubscribe: List-Owner: Precedence: list MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" 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: : ". Signed-off-by: David E. Box --- 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/.giti= gnore 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 ?=3D /usr/sbin + +CFLAGS =3D -Wextra + +override CFLAGS +=3D -O2 -Wall -D_GNU_SOURCE -Iinclude -I../../../include + +OBJS :=3D \ + 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/pmtct= l/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 + +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/pm= tctl/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/lo= g.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 +#include +#include + +#include "lib/log.h" + +static const char * const log_tags[] =3D { + [PMTCTL_LOG_ERROR] =3D "error", + [PMTCTL_LOG_WARN] =3D "warning", +}; + +static __printf(3, 0) +void log_vmsg(enum pmtctl_log_level level, int err, const char *fmt, va_li= st 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/m= ain.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 +#include +#include + +#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 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 --help' for command-specific options.\n"); +} + +int main(int argc, char **argv) +{ + static const struct option long_opts[] =3D { + { "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 =3D getopt_long(argc, argv, "+hV", long_opts, NULL)) !=3D -1)= { + switch (opt) { + case 'h': + print_usage(stdout); + return PMTCTL_EXIT_OK; + case 'V': + printf("pmtctl version %s - David E. Box \= 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 >=3D argc) { + log_err("missing command"); + print_usage(stderr); + return PMTCTL_EXIT_USER; + } + + cmd =3D 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; +} --=20 2.53.0 From nobody Tue Nov 24 11:43:49 2026 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=192.198.163.18 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1795376059; b=e+zNmAdIM/BRFKYJs3qrUjPM/Dw4FNL2fdLWbU5KFv/yOUY5hUbxhsSqOIf7y0RP+UQX UJQmUrGvwhZOKSKTDOsLIM9kzEJkhti8GA3KZkJ157Sn+GITXvCk+4jjiaGNPcmntS34E ddYzsBfwXyN9+oqcBeSVf8HMPqX7AHva0TkLPx012KkDvgClbHrSg/ObGw4BDTQ2F4mht bxIu5VA0OTPFdgNY7DYy0odTv9CZzu4xwgaCadU6WjUllMVVKsKiPMrQ6E0equj4gwRso KvN1C2oxQaF4FbvXJCtrMU2TUEGbjnG4+a5bxRUGNsyhKId9Fx6Rldg2NKaDi/IIfqQ== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1795376059; h=DMARC-Filter:DKIM-Signature:X-CSE-ConnectionGUID:X-CSE-MsgGUID: X-IronPort-AV:X-IronPort-AV:Received:X-CSE-ConnectionGUID: X-CSE-MsgGUID:X-ExtLoop1:X-IronPort-AV:Received:From:To:Cc:Subject: Date:Message-ID:X-Mailer:In-Reply-To:References:MIME-Version: Content-Transfer-Encoding; bh=SZfX6GqA97KrTyfThiMFH/SSOzB8FMyr8wecHzrn23c=; b=cYGmh9oM4FggpEjhcSM0gv6Pwq5L71l+SZbZ1O5lBwbwKkR5rVnQCaWTk+tm71n/Ura/ 8DLLal6u+rYcCqgFwofbso7j85eh3WoB0XRwEjF1fTd/jAgQEZf+z7Ig6dT5/zJxNJ8LL L1lopPjP9OK3eQMHDgiHyvRkEP0AHo6cUtHLDPA1c5J63qxjCGwIaePY2S2FxYXckCnpB Z+Cmaflx5UtIsLrUx3KAERE8d1kk+wJxtZGvIv8bu57pl/9q5Lmnx+/E+8b6xNorBsoOv T3wKdCcZ9CApjTUW2o4v6ppLz/pT1UyXeSLjP8df2r71r13/+fF+zy/tgK9UpOamhzQ== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass header.from=linux.intel.com; spf=pass smtp.mailfrom=linux.intel.com; dkim=pass header.d=intel.com header.i=@intel.com header.a=rsa-sha256 header.s=Intel header.b=XI15yrSg; arc=none smtp.remote-ip=192.198.163.18 Received: from mgamail.intel.com (mgamail.intel.com [192.198.163.18]) (using TLSv1.2 with cipher ECDHE-ECDSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 160A6606A327; Sun, 22 Nov 2026 19:34:19 +0000 (UTC) DMARC-Filter: OpenDMARC Filter v1.4.2 smtp.subspace.kernel.org 160A6606A327 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=linux.intel.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=linux.intel.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=intel.com header.i=@intel.com header.a=rsa-sha256 header.s=Intel header.b=XI15yrSg DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=intel.com; i=@intel.com; q=dns/txt; s=Intel; t=1795376059; x=1826912059; h=from:to:cc:subject:date:message-id:in-reply-to: references:mime-version:content-transfer-encoding; bh=8iddT5HjDYJt3X5bz+LJhsoeGXlDcluRY/tTUylnwHI=; b=XI15yrSgk8ZnaW/DGIb0HY+5bb5UTMrmdA89izxA5DlV7SoXkiM7U4+8 aU1vNtCg4U7BHdE6TbW6DUAnQrRkJSL0QrykxXiZBCI5tliM7Gy7+j8jW k6WcmEOosB9fGGkW1wovk9tcxae6YMJRj7KOwp44QAKxOxTMu7xCoa/Nu TWQENbwRh8c3832xlYcKM0IYxSnu/+j9yYuGywTgLnCdkVdtmd3SEZJ35 B/Qpz/7SbPKUPSl0FA3c/rX8FLPFKPMYNJiA2IfHH+MU1Thf8ewUirVnj OF1UUU8gV0OmLqz4JJRXWDMSZThJKtDbHQ9+0UR3kfWuJMiZKAko92xm/ A==; X-CSE-ConnectionGUID: nZty6iYnR7+QenF+9JY1Jg== X-CSE-MsgGUID: ctCe88PBTmeKARub8QSl3w== X-IronPort-AV: E=McAfee;i="6800,10657,11974"; a="4217505" X-IronPort-AV: E=Sophos;i="6.27,227,1787036400"; d="scan'208";a="4217505" Received: from fmviesa004.fm.intel.com ([10.60.135.144]) by fmvoesa112.fm.intel.com with ESMTP/TLS/ECDHE-RSA-AES256-GCM-SHA384; 22 Nov 2026 11:34:18 -0800 X-CSE-ConnectionGUID: pmlmR//GS0qPa9O7PrkHvg== X-CSE-MsgGUID: Kj5431ZURQemtDJck572Tg== X-ExtLoop1: 1 X-IronPort-AV: E=Sophos;i="6.27,227,1787036400"; d="scan'208";a="11109788" Received: from debox1-desk4.jf.intel.com (HELO localhost) ([10.54.77.98]) by smtpauth.intel.com with ESMTP/TLS/ECDHE-RSA-AES256-GCM-SHA384; 22 Nov 2026 11:34:18 -0800 From: "David E. Box" To: =?UTF-8?q?Ilpo=20J=C3=A4rvinen?= , Hans de Goede Cc: "David E. Box" , Andy Shevchenko , platform-driver-x86@vger.kernel.org, linux-kernel@vger.kernel.org Subject: [PATCH v2 02/12] tools/arch/x86/pmtctl: Add PMT telemetry device discovery Date: Sun, 22 Nov 2026 11:33:57 -0800 Message-ID: <65c24797e5d631463d0db4316fdb61625f09b3ff.1795374925.git.david.e.box@linux.intel.com> X-Mailer: git-send-email 2.53.0 In-Reply-To: References: X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Post: List-Help: List-Subscribe: List-Unsubscribe: List-Owner: Precedence: list MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" 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 --- 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 =3D -Wextra override CFLAGS +=3D -O2 -Wall -D_GNU_SOURCE -Iinclude -I../../../include =20 OBJS :=3D \ + lib/common.o \ + lib/device_telem.o \ lib/log.o \ + lib/pmtctl.o \ src/main.o =20 pmtctl: $(OBJS) diff --git a/tools/arch/x86/pmtctl/include/lib/common.h b/tools/arch/x86/pm= tctl/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 +#include +#include + +#include + +static inline void freep(void *p) +{ + free(*(void **)p); +} + +/* Free the pointer with free() at scope exit: char *p auto_free =3D 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 =3D (p); (p) =3D 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/pm= tctl/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 +#include + +/* 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/pm= tctl/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 + +#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 =3D {}; + */ +#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 +#include +#include +#include +#include +#include + +#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 >=3D min_cap) + return array; + + new_cap =3D *cap; + if (!new_cap) + new_cap =3D PMT_ARRAY_INITIAL_CAP; + + while (new_cap < min_cap) { + if (new_cap > SIZE_MAX / 2) + return NULL; + new_cap *=3D 2; + } + + new_array =3D reallocarray(array, new_cap, elem_size); + if (!new_array) + return NULL; + + *cap =3D 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 =3D 0; + v =3D strtoul(s, &end, base); + if (errno) + return -errno; + + if (end =3D=3D s || *end !=3D '\0') + return -EINVAL; + + if (v > UINT32_MAX) + return -ERANGE; + + *val =3D v; + + return 0; +} + +int path_printf(char *buf, size_t size, const char *fmt, ...) +{ + va_list ap; + int len; + + va_start(ap, fmt); + len =3D vsnprintf(buf, size, fmt, ap); + va_end(ap); + + if (len < 0 || (size_t)len >=3D size) + return -ENAMETOOLONG; + + return 0; +} diff --git a/tools/arch/x86/pmtctl/lib/device_telem.c b/tools/arch/x86/pmtc= tl/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 +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#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, si= ze_t buflen) +{ + char path[PATH_MAX]; + ssize_t n; + int ret; + int fd; + + ret =3D path_printf(path, sizeof(path), "%s/%s", dir, name); + if (ret) + return ret; + + fd =3D open(path, O_RDONLY); + if (fd < 0) + return -errno; + + n =3D read(fd, buf, buflen - 1); + if (n < 0) { + ret =3D -errno; + close(fd); + return ret; + } + close(fd); + + while (n > 0 && isspace((unsigned char)buf[n - 1])) + n--; + buf[n] =3D '\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, uint= 32_t *val) +{ + char buf[64]; + int ret; + + ret =3D read_attr_text(dir, name, buf, sizeof(buf)); + if (ret) + return ret; + + return parse_u32(buf, base, val); +} + +/* Match "telem" where is a decimal number */ +static bool is_telem_name(const char *name) +{ + const size_t prefix_len =3D strlen(PMT_TELEM_PREFIX); + const char *num; + + if (strncmp(name, PMT_TELEM_PREFIX, prefix_len)) + return false; + + num =3D name + prefix_len; + + return *num !=3D '\0' && num[strspn(num, "0123456789")] =3D=3D '\0'; +} + +static int telem_add_device(struct telem_scan *scan, const char *devpath, = const char *name) +{ + char *dev_name auto_free =3D NULL; + char *data_path auto_free =3D NULL; + struct pmt_device *devices; + uint32_t guid; + int ret; + + ret =3D 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 =3D 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 =3D NULL; + return -ENOMEM; + } + + devices =3D pmt_grow_array(scan->devices, &scan->cap, scan->num_devices += 1, + sizeof(*devices)); + if (!devices) + return -ENOMEM; + + scan->devices =3D devices; + + devices[scan->num_devices++] =3D (struct pmt_device) { + .guid =3D guid, + .name =3D no_free_ptr(dev_name), + .data_path =3D no_free_ptr(data_path), + }; + + return 0; +} + +/* Add the telemetry devices under one auxiliary device's intel_pmt direct= ory */ +static int telem_scan_pmt_dir(struct telem_scan *scan, const char *pmt_pat= h) +{ + struct dirent *de; + DIR *dir; + int ret =3D 0; + + dir =3D opendir(pmt_path); + if (!dir) { + /* Most driver directory entries (bind, uevent, ...) aren't devices */ + if (errno =3D=3D ENOENT || errno =3D=3D ENOTDIR) + return 0; + + return -errno; + } + + while ((de =3D readdir(dir))) { + char devpath[PATH_MAX]; + + if (!is_telem_name(de->d_name)) + continue; + + ret =3D path_printf(devpath, sizeof(devpath), "%s/%s", pmt_path, de->d_n= ame); + if (ret) + break; + + ret =3D 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 =3D 0; + + /* Without the driver there are no devices, which telem_scan() reports */ + dir =3D opendir(PMT_TELEM_AUX_DIR); + if (!dir) + return 0; + + while ((de =3D readdir(dir))) { + char pmt_path[PATH_MAX]; + + if (de->d_name[0] =3D=3D '.') + continue; + + ret =3D 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 =3D 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 =3D a; + const struct pmt_device *db =3D b; + + if (da->guid !=3D 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 na= me. + * 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 =3D {}; + int ret; + + ret =3D 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 loa= ded?)"); + return -ENODEV; + } + + qsort(scan.devices, scan.num_devices, sizeof(*scan.devices), device_cmp); + + *devices =3D scan.devices; + *num_devices =3D scan.num_devices; + + return 0; +} + +void telem_free(struct pmt_device *devices, size_t num_devices) +{ + for (size_t i =3D 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 =3D NULL; + ctx->num_devices =3D 0; +} --=20 2.53.0 From nobody Tue Nov 24 11:43:49 2026 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=192.198.163.18 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1795376060; b=uIsKv/FL8k7z4N85baJ0R3rHlAbZUxQxEaBc3fUNNmdySMR1Ey/XcTTzhQkN+m4Qz78N 6USl26hYaUnilxhk8HuYKozkVBNcs0dEDeYwAywTP2hpet7NXjwa1FSJBsywRGZmZbiqE h3Z28tPZoeRVMXjLsUGjia9ECq1ypqf7iEG64YK3Gq6oLZHFxti42CSbWzH7h+g3Jn/ST QRqxnkwCQA6uw0OORJ47CjzzuPDyfuYqKIRynMB4MPpdfJbcL28Teqs9T0IJdvZXoJBJy z2pRSRJWizXqm7F/SADEX+0q11bBi1NDBwVXjmsXxRDOEeF9YmiYAZmOLIAd57sW7og== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1795376060; h=DMARC-Filter:DKIM-Signature:X-CSE-ConnectionGUID:X-CSE-MsgGUID: X-IronPort-AV:X-IronPort-AV:Received:X-CSE-ConnectionGUID: X-CSE-MsgGUID:X-ExtLoop1:X-IronPort-AV:Received:From:To:Cc:Subject: Date:Message-ID:X-Mailer:In-Reply-To:References:MIME-Version: Content-Type:Content-Transfer-Encoding; bh=ULicIa4N045djpBg+N+owj6l70eR+oLJUtpQhb3nDCc=; b=Jt5zcRP36dz0uDDRErld/Ky6nixN7EAj2LmZjH1Pm7bQJNIRI+6krRGigMrXr7/SgKBg soMti+wvQgrSdXImk0OHD7gNTurNPnUIC3EYhXnAoeNWWjI6qnI40WOhokzXv3VOaMg23 Tt6g43si979aBlK604qBVZ2PsgI4FD7sqod90Jiurvfp9WHQaTQzKJYRPEshATLTKUgvG XiTPJatpPb8tGxiEKj9hxmScbmlgRHBzYxDRrprrEZYwOJNeZomfjNn7JXiVmSqwtaj+n tjKVgOd0UQT2fHZV+0yiHo9+/iBTHNbJRcxlM2zWKNfyRORJJd9nJd00hf+XjgzenIQ== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass header.from=linux.intel.com; spf=pass smtp.mailfrom=linux.intel.com; dkim=pass header.d=intel.com header.i=@intel.com header.a=rsa-sha256 header.s=Intel header.b=VBulqJDK; arc=none smtp.remote-ip=192.198.163.18 Received: from mgamail.intel.com (mgamail.intel.com [192.198.163.18]) (using TLSv1.2 with cipher ECDHE-ECDSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 47090606A330; Sun, 22 Nov 2026 19:34:19 +0000 (UTC) DMARC-Filter: OpenDMARC Filter v1.4.2 smtp.subspace.kernel.org 47090606A330 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=linux.intel.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=linux.intel.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=intel.com header.i=@intel.com header.a=rsa-sha256 header.s=Intel header.b=VBulqJDK DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=intel.com; i=@intel.com; q=dns/txt; s=Intel; t=1795376059; x=1826912059; h=from:to:cc:subject:date:message-id:in-reply-to: references:mime-version:content-transfer-encoding; bh=tTd8+9TE00/MiwfqfbLFpR/3N6T7UxU8CbZI6vWOf6I=; b=VBulqJDKiUsTyEna/0Sp9rDicaQxcjD3jmDVuCzZirGVHW0H+yapLFHU KIK3EG9E0ridAZBOScMt13cZSrFZoNbxnXormLY7DBovteVAfJ8aGANaJ KC3og41JtLBMffvY/R6e9GjasodrQbaJuwky8FWPqz/sHJRHdD1D3dTxK cdvL5n5Mg2vv6soMcalsb/BM7y3LemBnMgpGLiKVqouwoJ2ysi519mNjh 3Iop6PMxGWWDYjX0SE1QUOlQv5s5xRwK7oJpY3EyRvKnMb1Sm6cJkYSOB /teXNn5nvBRp+fmmaSy6Zf2TUxzhVW2l03OeDNV8SnRY4+1AwDHoGXWGa A==; X-CSE-ConnectionGUID: 3a9MYWlwSqaDrNUpIAjmSQ== X-CSE-MsgGUID: MgB9ifh1RZS1OPfvFD29VQ== X-IronPort-AV: E=McAfee;i="6800,10657,11974"; a="4217507" X-IronPort-AV: E=Sophos;i="6.27,227,1787036400"; d="scan'208";a="4217507" Received: from fmviesa004.fm.intel.com ([10.60.135.144]) by fmvoesa112.fm.intel.com with ESMTP/TLS/ECDHE-RSA-AES256-GCM-SHA384; 22 Nov 2026 11:34:18 -0800 X-CSE-ConnectionGUID: JS8zkJP3QlWYVYBoWF6USQ== X-CSE-MsgGUID: RhVISWzURuSAc9MUbame4A== X-ExtLoop1: 1 X-IronPort-AV: E=Sophos;i="6.27,227,1787036400"; d="scan'208";a="11109789" Received: from debox1-desk4.jf.intel.com (HELO localhost) ([10.54.77.98]) by smtpauth.intel.com with ESMTP/TLS/ECDHE-RSA-AES256-GCM-SHA384; 22 Nov 2026 11:34:19 -0800 From: "David E. Box" To: =?UTF-8?q?Ilpo=20J=C3=A4rvinen?= , Hans de Goede Cc: "David E. Box" , Andy Shevchenko , platform-driver-x86@vger.kernel.org, linux-kernel@vger.kernel.org Subject: [PATCH v2 03/12] tools/arch/x86/pmtctl: Add pmtxml2json conversion tool Date: Sun, 22 Nov 2026 11:33:58 -0800 Message-ID: <82b74c6bcc8da5d08bce4cec8757b048d69dac17.1795374925.git.david.e.box@linux.intel.com> X-Mailer: git-send-email 2.53.0 In-Reply-To: References: X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Post: List-Help: List-Subscribe: List-Unsubscribe: List-Owner: Precedence: list MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" 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_.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 --- V2 changes: - Replaces v1 15. - New output format: one pmt_.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/.giti= gnore 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) =20 $(OBJS): $(wildcard include/*.h include/lib/*.h) =20 -.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 ?=3D python3 +DEFS_DIR ?=3D defs +PMT_CACHE_DIR ?=3D $(HOME)/.cache/pmtctl + +XML2JSON_SCRIPT :=3D 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 :=3D $(DEFS_DIR)/.stamp + +defs-json-fetch: $(DEFS_JSON_STAMP) + +# Fail early, with the package to install, if python3 or lxml is missing +XML2JSON_CHECK =3D @$(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) (c= loned 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) =20 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 =E2=86=92 JSON conversion + +[`pmtxml2json.py`](pmtxml2json.py) converts Intel PMT (Platform Monitoring +Technology) Aggregator XML files into JSON metric definitions +that `pmtctl` loads with `-J `. + +This document focuses on the **EventName naming convention** =E2=80=94 the= rule used +to derive an event name from each `` 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 c= an +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 /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=3D` attribute on `` | `IA_SC= ALABILITY` | +| `sampleSubGroup` | `` child text | `IA_SCAL= ABILITY_CORE7` | + +The aggregator's `` (GUID) is used for the output filename +(`pmt_.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 `` text contains `reserved` + or `rsvd` (case-insensitive, optionally with trailing digits) as a separ= ate + token, or +- its sample or group `` 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 colli= ding +name. For each surviving sample: + +1. If its subgroup is prefixed and the subgroup differs from `name`: + `EventName =3D sanitize(sampleSubGroup) + "." + sanitize(name)` +2. Otherwise: + `EventName =3D 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** =E2=80=94 e.g. `IA_SCALABILITY_CORE7` qualif= ies a + per-core copy of `IA_SCALABILITY`. Prefixing is meaningful and useful. +- A **container alias** =E2=80=94 e.g. `INTEL_VERSION_2` is just an enclos= ing + 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 collidi= ng +name**, yielding clean labels in the common case and disambiguated ones wh= en +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 + + + INTEL_VERSION_2 + 015 + + + + + + IA_SCALABILITY_CORE0 + 07 + + + + + + IA_SCALABILITY_CORE7 + 07 + + +``` + +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_c= ore0.ia_scalability` | +| `IA_SCALABILITY` (CORE7) | (1) prefixed subgroup | `ia_scalability_c= ore7.ia_scalability` | + +Note that `RTL_VERSION` is **not** prefixed with its `INTEL_VERSION_2` +container, even though `sampleSubGroup` is set =E2=80=94 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_.json` file: + +```json +{ + "guid": "0x", + "platform": "", + "description": ">", + "events": [ + { + "EventName": "", + "description": "", + "sample_id": , + "lsb": , + "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 t= he +Intel-PMT data. If two samples still share the same `EventName` =E2=80=94 = for example +because neither has a usable `sampleSubGroup` =E2=80=94 the converter appl= ies a +last-resort ordinal suffix +`__0`, `__1`, =E2=80=A6 and emits a `WARN` line to stderr. The double-und= erscore is +chosen to be visually distinct from any XML field so it is not mistaken fo= r a +meaningful part of the metric name. + +Across **different** GUIDs, names may repeat =E2=80=94 they live in distin= ct +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 definiti= ons. + +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=3Dc-extension-no-member + +INTEL_PMT_REPO_URL =3D "https://github.com/intel/Intel-PMT" + +# Every PMT sample is one 64-bit word +SAMPLE_BITS =3D 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 UR= L.""" + cleaned =3D repo_url.rstrip("/") + if cleaned.endswith(".git"): + cleaned =3D cleaned[: -len(".git")] + + base =3D os.path.basename(cleaned) or "repo" + base =3D re.sub(r"[^0-9A-Za-z._-]+", "-", base).strip("-") + return base or "repo" + + +def _fetch_intel_pmt_xml_root( + cache_dir: str, + refresh: bool =3D False, + debug: bool =3D False, + repo_url: str =3D INTEL_PMT_REPO_URL, +) -> Optional[str]: + """Ensure Intel-PMT exists in cache and return its xml root path.""" + cache_root =3D _expand_path(cache_dir) + repo_dir =3D os.path.join(cache_root, _repo_dir_name_from_url(repo_url= )) + + os.makedirs(cache_root, exist_ok=3DTrue) + + try: + if not os.path.isdir(repo_dir): + if debug: + print( + f"# fetch: cloning {repo_url} into {repo_dir}", + file=3Dsys.stderr, + ) + subprocess.run( + ["git", "clone", "--depth", "1", repo_url, repo_dir], + check=3DTrue, + stdout=3Dsubprocess.PIPE, + stderr=3Dsubprocess.PIPE, + text=3DTrue, + timeout=3D300, + ) + elif refresh: + if debug: + print(f"# fetch: refreshing cached repo at {repo_dir}", fi= le=3Dsys.stderr) + subprocess.run( + ["git", "-C", repo_dir, "pull", "--ff-only"], + check=3DTrue, + stdout=3Dsubprocess.PIPE, + stderr=3Dsubprocess.PIPE, + text=3DTrue, + timeout=3D300, + ) + elif debug: + print(f"# fetch: using cached repo at {repo_dir}", file=3Dsys.= stderr) + except FileNotFoundError: + print("ERROR: git is not installed or not found in PATH.", file=3D= sys.stderr) + return None + except subprocess.TimeoutExpired: + print("ERROR: fetching Intel-PMT timed out.", file=3Dsys.stderr) + return None + except subprocess.CalledProcessError as ex: + err =3D (ex.stderr or "").strip() + print("ERROR: failed to fetch Intel-PMT repository.", file=3Dsys.s= tderr) + if err: + print(f" git stderr: {err}", file=3Dsys.stderr) + return None + + xml_root =3D 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=3Dsys.stderr, + ) + return None + + return xml_root + + +# ---------- Reserved/RSVD skipping ---------- +# Name: match 'reserved' or 'rsvd' with optional digits, not embedded in l= arger tokens +RESERVED_RX =3D re.compile( + r"(? 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=3Dc-extension-no-member + parser =3D etree.XMLParser(resolve_entities=3DFalse) + # pylint: disable-next=3Dc-extension-no-member + root =3D etree.parse(xml_path, parser).getroot() + + return root + + +def get_guid(root) -> int: + """Extract the telemetry GUID from .""" + for e in root.iter(): + if norm(e.tag).lower() =3D=3D "uniqueid": + v =3D _text(e) + if not v: + break + + # GUIDs are hex, with or without the 0x prefix + return int(v, 16) + + raise ValueError("Missing ") + + +def get_description(root) -> Optional[str]: + """Return the aggregator's top-level , if any.""" + for e in root: + if norm(e.tag).lower() =3D=3D "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 d= escription.""" + 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 element; return None for reserved samples.""" + sname =3D (s.attrib.get("name") or f"sample_{sample_id}").strip() + + lsb =3D None + msb =3D None + sdesc =3D None + ssubgroup =3D None + + for ch in s: + t =3D norm(ch.tag).lower() + if t =3D=3D "lsb": + lsb =3D int(_text(ch), 0) + elif t =3D=3D "msb": + msb =3D int(_text(ch), 0) + elif t =3D=3D "description": + sdesc =3D _text(ch) + elif t =3D=3D "samplesubgroup": + ssubgroup =3D _text(ch) + + if lsb is None or msb is None: + raise ValueError(f"{sname} (sampleID=3D{sample_id}): missing lsb/m= sb") + + if not 0 <=3D lsb <=3D msb < SAMPLE_BITS: + raise ValueError( + f"{sname} (sampleID=3D{sample_id}): invalid bit range {lsb}-{m= sb}" + ) + + desc_text =3D sdesc if sdesc else group_desc + + if _is_reserved(sname, ssubgroup, desc_text): + return None + + return SampleDef( + sample_id=3Dsample_id, + sample_name=3Dsname, + lsb=3Dlsb, + msb=3Dmsb, + description=3Ddesc_text, + sample_subgroup=3Dssubgroup, + ) + + +def parse_sample_group(sg) -> List[SampleDef]: + """Parse one element into its non-reserved samples.""" + sid_txt =3D sg.attrib.get("sampleID") or sg.attrib.get("sampleid") + if sid_txt is None: + raise ValueError("SampleGroup missing sampleID") + + sample_id =3D int(sid_txt, 0) + group_name =3D (sg.attrib.get("name") or "").strip() or f"group_{sampl= e_id}" + group_len =3D None + group_desc =3D None + + for child in sg: + t =3D norm(child.tag).lower() + if t =3D=3D "length": + group_len =3D int(_text(child), 0) + elif t =3D=3D "description": + group_desc =3D _text(child) + + if group_len is not None and group_len !=3D SAMPLE_BITS: + raise ValueError( + f"{group_name} sampleID=3D{sample_id} length=3D{group_len} " + f"(expected {SAMPLE_BITS})" + ) + + out: List[SampleDef] =3D [] + for s in sg: + if norm(s.tag).lower() !=3D "sample": + continue + sample =3D 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] =3D [] + + for sg in root.iter(): + if norm(sg.tag).lower() =3D=3D "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 =3D 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 =3D _sanitize_token(s.sample_name) + group =3D _sanitize_token(s.sample_subgroup) if s.sample_subgroup else= "" + if s.sample_subgroup in prefixed and group and group !=3D name: + name =3D 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 cas= e. + This function is a last-resort safety net for names that could not be + disambiguated there (e.g. no usable sampleSubGroup). The double-under= score + suffix is intentionally distinct from any XML field so it is not mista= ken + for a meaningful part of the metric name. + """ + seen: Dict[str, List[int]] =3D {} + for i, e in enumerate(out): + name =3D e["EventName"] + seen.setdefault(name, []).append(i) + + for name, indices in seen.items(): + if len(indices) <=3D 1: + continue + print( + f"WARN: {agg_xml}: GUID=3D0x{guid:08x}: " + f"EventName '{name}' collision ({len(indices)} entries); " + f"renaming as {name}__0 .. {name}__{len(indices) - 1}", + file=3Dsys.stderr, + ) + for ordinal, idx in enumerate(indices): + out[idx]["EventName"] =3D f"{name}__{ordinal}" + + +def _parse_args(argv: List[str]) -> argparse.Namespace: + """Parse command-line arguments.""" + ap =3D argparse.ArgumentParser( + description=3D"Convert Intel PMT Aggregator XML to pmtctl JSON met= ric definitions" + ) + ap.add_argument( + "xml", + nargs=3D"?", + help=3D"Input PMT Aggregator XML file (optional when using --by-pa= th)", + ) + ap.add_argument( + "--by-path", + default=3DNone, + help=3D( + "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=3DNone, + help=3D( + "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=3D"store_true", + help=3D( + "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=3D"~/.cache/pmtctl", + help=3D( + "Cache directory for Intel-PMT repository clone " + "(default: ~/.cache/pmtctl)." + ), + ) + ap.add_argument( + "--refresh-pmt-repo", + action=3D"store_true", + help=3D( + "Refresh cached Intel-PMT repository before conversion " + "(used with --fetch-pmt-repo)." + ), + ) + ap.add_argument( + "--pmt-repo-url", + default=3DINTEL_PMT_REPO_URL, + help=3D( + "Git URL of the Intel-PMT repository used by --fetch-pmt-repo " + f"(default: {INTEL_PMT_REPO_URL})." + ), + ) + ap.add_argument("--debug", action=3D"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 =3D 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 =3D (s or "").strip().lower() + s =3D re.sub(r"[^0-9a-z]+", "-", s) + return re.sub(r"-+", "-", s).strip("-") + + out: List[str] =3D [] + for seg in rel.split(os.sep): + if seg in (".", ".."): + continue + s =3D _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.xm= l under p.""" + base =3D _base_dir(p) + aggs =3D glob.glob(os.path.join(base, "**", "*_aggregator.xml"), recur= sive=3DTrue) + + return [(a, _rel_parts_from_root(os.path.dirname(a), base)) for a in s= orted(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 =3D _discover_all_xml_sets_by_path(args.by_path) + if args.debug: + print( + f"# by-path discovered {len(work_items)} aggregator(s)", + file=3Dsys.stderr, + ) + return work_items + + if not args.xml: + return [] + + # Single file, optionally placed relative to --by-path + rel_parts: List[str] =3D [] + if args.by_path: + rel_parts =3D _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_.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 =3D _deepest_by_path_folder(args.by_path) + return "jsons" if deepest_folder.lower() =3D=3D "xml" else deepest= _folder.lower() + + return None + + +def _platform_group_for(rel_parts: List[str], by_path: Optional[str]) -> O= ptional[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 =3D _deepest_by_path_folder(by_path) + if deepest_folder and deepest_folder.lower() !=3D "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 =3D 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 =3D Counter(_sanitize_token(s.sample_name) for s in sample= s) + prefixed =3D { + s.sample_subgroup + for s in samples + if name_counts[_sanitize_token(s.sample_name)] > 1 + } + + events =3D [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_.json file.""" + root =3D parse_xml(agg_xml) + guid =3D get_guid(root) + + out_filename =3D 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 =3D 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 =3D make_events(root, guid, agg_xml) + platform_group =3D _platform_group_for(rel_parts, args.by_path) + + doc: Dict[str, object] =3D {"guid": f"0x{guid:08x}"} + if platform_group: + doc["platform"] =3D platform_group + description =3D get_description(root) + if description: + doc["description"] =3D description + doc["events"] =3D events + + with open(out_filename, "w", encoding=3D"utf-8") as f: + json.dump(doc, f, indent=3D2) + f.write("\n") + + written_by_guid[guid] =3D agg_xml + print(f"# wrote {out_filename}", file=3Dsys.stderr) + print(f"# GUID=3D0x{guid:08x} events=3D{len(events)}", file=3Dsys.stde= rr) + + +def main(argv: List[str]) -> int: + """CLI entry point: discover XML files, convert, and write JSON output= s.""" + args =3D _parse_args(argv) + + if args.refresh_pmt_repo and not args.fetch_pmt_repo: + print( + "ERROR: --refresh-pmt-repo requires --fetch-pmt-repo.", + file=3Dsys.stderr, + ) + return 2 + + fetched_xml_root: Optional[str] =3D None + if args.fetch_pmt_repo: + fetched_xml_root =3D _fetch_intel_pmt_xml_root( + cache_dir=3Dargs.pmt_cache_dir, + refresh=3Dargs.refresh_pmt_repo, + debug=3Dargs.debug, + repo_url=3Dargs.pmt_repo_url, + ) + if fetched_xml_root is None: + return 2 + if args.debug: + print(f"# fetch: xml root=3D{fetched_xml_root}", file=3Dsys.st= derr) + if args.by_path is None and args.xml is None: + args.by_path =3D fetched_xml_root + + work_items =3D _collect_work_items(args) + + if not work_items: + print( + ( + "ERROR: No aggregator XML specified or discovered. " + "Provide a file or use --by-path." + ), + file=3Dsys.stderr, + ) + return 2 + + output_dir =3D _output_dir_for(args) + if output_dir: + os.makedirs(output_dir, exist_ok=3DTrue) + if args.debug: + print(f"# output directory: {output_dir}", file=3Dsys.stderr) + + any_failed =3D False + written_by_guid: Dict[int, str] =3D {} + + for agg_xml, rel_parts in work_items: + try: + convert_aggregator(agg_xml, rel_parts, args, output_dir, writt= en_by_guid) + # pylint: disable-next=3Dc-extension-no-member + except (ValueError, OSError, etree.XMLSyntaxError) as ex: + any_failed =3D True + print( + f"ERROR: failed processing aggregator=3D{agg_xml}: {ex}", + file=3Dsys.stderr, + ) + + return 1 if any_failed else 0 + + +if __name__ =3D=3D "__main__": + sys.exit(main(sys.argv[1:])) --=20 2.53.0 From nobody Tue Nov 24 11:43:49 2026 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=192.198.163.18 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1795376060; b=HO0DBT0KRQf+LbrudWA8UaYQ8PMhJtr6JMmic2C0p09LvkSJ578cQRorFacBFJUZD5Uu hsN5URaulRQTQkDP6CHUBmszcZzPCZNLc9vbTzU9rHidi0/YWpxDrEjDOTbDjF4LrOGs7 RRTmk9Mp1S451cfszfzmS52w02UWw3mQSK4NnvukwYRL0hwGdfQeRIfUoKbjjvns9dMst 2y4sLXa86a2Fy0tjENLoDpmQ/NwfBEr9PDuqXBxBKgtsB94iPfuXnGiBNZbFBWj723FZb enBdCE86NlP7SVpuP8kDTkb3EFUYpCzUbBEHGv2ZU1Zpg/QEKpfQjcwj+PtF+nHViwg== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1795376060; h=DMARC-Filter:DKIM-Signature:X-CSE-ConnectionGUID:X-CSE-MsgGUID: X-IronPort-AV:X-IronPort-AV:Received:X-CSE-ConnectionGUID: X-CSE-MsgGUID:X-ExtLoop1:X-IronPort-AV:Received:From:To:Cc:Subject: Date:Message-ID:X-Mailer:In-Reply-To:References:MIME-Version: Content-Transfer-Encoding; bh=5P+7tBedBIdwQSGY2GkLGv3XTyNXbKGIOLqLjYKCNQ4=; b=zGCetfEs3uk478LSDFRJp8ro0nCF+Ck0P9cyhDEAh/D+uUqF+MfAGfmA9TbkzChSFbVl KPji3urTkX+Wgk4MpSc03BClPJR7vbuE/SDZtXmc7aVCHCY7uQhZplfMwrOb7VLG82ySR uvxV/LOELLoNVsygetzhY5WOQ/KlkIncZKRrB6msxxAEBe/V5c3kWJvwGXo7+qBmadEbb 6DUvObzdmcRT94Tdwurw3m/r9mForFVrZC3RpZ+IfAXK5iikXLN/HCdf/8gVcJ9s9jy9K 3kkgX4uU2w2GTidKwW6DbuikZGG8egnYGZZzkECj8huSUEKrfvi72dV2axV8SOYbbyA== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass header.from=linux.intel.com; spf=pass smtp.mailfrom=linux.intel.com; dkim=pass header.d=intel.com header.i=@intel.com header.a=rsa-sha256 header.s=Intel header.b=U8TzuuMw; arc=none smtp.remote-ip=192.198.163.18 Received: from mgamail.intel.com (mgamail.intel.com [192.198.163.18]) (using TLSv1.2 with cipher ECDHE-ECDSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id C63E6606A33B; Sun, 22 Nov 2026 19:34:19 +0000 (UTC) DMARC-Filter: OpenDMARC Filter v1.4.2 smtp.subspace.kernel.org C63E6606A33B Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=linux.intel.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=linux.intel.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=intel.com header.i=@intel.com header.a=rsa-sha256 header.s=Intel header.b=U8TzuuMw DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=intel.com; i=@intel.com; q=dns/txt; s=Intel; t=1795376059; x=1826912059; h=from:to:cc:subject:date:message-id:in-reply-to: references:mime-version:content-transfer-encoding; bh=BG2gzCHnt9oFAjZiqbSwnEbVMvdnKd/0xby1+p5ZVl8=; b=U8TzuuMwL1W44wryWwDEaDGfGdx85DS3Zsp+FrRdHjfp7NdslltAtbSZ re+EOld744JgsNDa+ZHO0uaZulU4MVajUbeUVb/KufSqKYPMcfgCV0B4z BIzD8QJ0H2pMNJnyBkx6nSOmVHEe9+qZKAkvDx1ZikiJLLFMAGB5UhE21 PNXMTGhsNp9NsKyrA59x0C7PJtGrHKf6FjENLlJDsP/oqQ2WnJWgjR4Wl ZX/17xIfFShydD0vq6A7Q9blTfpyQsJUlHOzf7fqoVvazl149mwFhc1mA uYMfwM3ODpTkNJ06lKEThQcsirG2zGv9x4YzfrxeCSSMx6VGsvvmNfYyS g==; X-CSE-ConnectionGUID: 3nw2GBVeSzW8fHMlmKg+jg== X-CSE-MsgGUID: 0UKwMLYbQWmQFO3rIFmODQ== X-IronPort-AV: E=McAfee;i="6800,10657,11974"; a="4217510" X-IronPort-AV: E=Sophos;i="6.27,227,1787036400"; d="scan'208";a="4217510" Received: from fmviesa004.fm.intel.com ([10.60.135.144]) by fmvoesa112.fm.intel.com with ESMTP/TLS/ECDHE-RSA-AES256-GCM-SHA384; 22 Nov 2026 11:34:19 -0800 X-CSE-ConnectionGUID: FHMOa7JITg2E18fpr20kKQ== X-CSE-MsgGUID: tl8NZPL7S86cPCEHTAS+OQ== X-ExtLoop1: 1 X-IronPort-AV: E=Sophos;i="6.27,227,1787036400"; d="scan'208";a="11109794" Received: from debox1-desk4.jf.intel.com (HELO localhost) ([10.54.77.98]) by smtpauth.intel.com with ESMTP/TLS/ECDHE-RSA-AES256-GCM-SHA384; 22 Nov 2026 11:34:19 -0800 From: "David E. Box" To: =?UTF-8?q?Ilpo=20J=C3=A4rvinen?= , Hans de Goede Cc: "David E. Box" , Andy Shevchenko , platform-driver-x86@vger.kernel.org, linux-kernel@vger.kernel.org Subject: [PATCH v2 04/12] tools/arch/x86/pmtctl: Add JSON metric definition loading Date: Sun, 22 Nov 2026 11:33:59 -0800 Message-ID: <57cd5d4e4774ba815decccdd3d62a4abacfad1ea.1795374925.git.david.e.box@linux.intel.com> X-Mailer: git-send-email 2.53.0 In-Reply-To: References: X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Post: List-Help: List-Subscribe: List-Unsubscribe: List-Owner: Precedence: list MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" 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 <=3D msb <=3D 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 --- 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 =3D -Wextra =20 override CFLAGS +=3D -O2 -Wall -D_GNU_SOURCE -Iinclude -I../../../include =20 +# 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 :=3D $(shell pkg-config --cflags jansson 2>/dev/null) +JANSSON_LIBS :=3D $(shell pkg-config --libs jansson 2>/dev/null) +ifeq ($(JANSSON_LIBS),) +$(error jansson not found: install libjansson-dev (Debian/Ubuntu) or janss= on-devel (Fedora/RHEL)) +endif +override CFLAGS +=3D $(JANSSON_CFLAGS) +LDLIBS +=3D $(JANSSON_LIBS) +endif + OBJS :=3D \ lib/common.o \ lib/device_telem.o \ lib/log.o \ lib/pmtctl.o \ + lib/tss.o \ + lib/tss_json.o \ src/main.o =20 pmtctl: $(OBJS) diff --git a/tools/arch/x86/pmtctl/include/lib/pmtctl.h b/tools/arch/x86/pm= tctl/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 =20 #include "lib/device.h" +#include "lib/tss.h" =20 /* 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; }; =20 int pmtctl_ctx_init(struct pmtctl_ctx *ctx); diff --git a/tools/arch/x86/pmtctl/include/lib/tss.h b/tools/arch/x86/pmtct= l/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 +#include + +/* 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" =20 /** * pmtctl_ctx_init - discover PMT devices @@ -16,6 +17,7 @@ int pmtctl_ctx_init(struct pmtctl_ctx *ctx) =20 void pmtctl_ctx_free(struct pmtctl_ctx *ctx) { + pmt_tss_db_free(&ctx->tss); telem_free(ctx->devices, ctx->num_devices); ctx->devices =3D NULL; ctx->num_devices =3D 0; diff --git a/tools/arch/x86/pmtctl/lib/tss.c b/tools/arch/x86/pmtctl/lib/ts= s.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 + +#include "lib/tss.h" + +void pmt_tss_info_free(struct pmt_tss_info *info) +{ + for (size_t i =3D 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 =3D 0; i < db->num_tss_info; i++) + pmt_tss_info_free(&db->tss_info[i]); + free(db->tss_info); + + *db =3D (struct pmt_tss_db){}; +} + +static int tss_info_guid_cmp(const void *key, const void *elem) +{ + const uint32_t *guid =3D key; + const struct pmt_tss_info *info =3D elem; + + if (*guid !=3D 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_inf= o), + tss_info_guid_cmp); +} diff --git a/tools/arch/x86/pmtctl/lib/tss_json.c b/tools/arch/x86/pmtctl/l= ib/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_.json per telemetry semantic + * space, with the GUID's platform, description and events. + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#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 =3D json_object_get(obj, key); + json_int_t n; + + if (!json_is_integer(v)) + return -EINVAL; + + n =3D json_integer_value(v); + if (n < 0 || n > max) + return -ERANGE; + + *val =3D 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 =3D NULL; + if (!s) + return 0; + + *dst =3D 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 =3D obj_get_uint(ev, "sample_id", UINT32_MAX, &sample_id); + if (ret) + return ret; + + ret =3D obj_get_uint(ev, "lsb", PMT_SAMPLE_BITS - 1, &lsb); + if (ret) + return ret; + + ret =3D obj_get_uint(ev, "msb", PMT_SAMPLE_BITS - 1, &msb); + if (ret) + return ret; + + if (lsb > msb) + return -EINVAL; + + def->sample_id =3D sample_id; + def->lsb =3D lsb; + def->msb =3D msb; + + return 0; +} + +/* Fill @def from event @idx of @path. On failure @def may be partly fille= d. */ +/* + * 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 pm= t_metric_def *def) +{ + const char *name; + int ret; + + name =3D obj_get_string(ev, "EventName"); + if (!name) { + log_err("%s: event %zu: missing EventName", path, idx); + return -EINVAL; + } + + ret =3D 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 =3D 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 =3D a; + const struct pmt_metric_def *mb =3D 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_cm= p); + + for (size_t i =3D 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 =3D 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 o= ne + * more entry. On failure nothing is added. + */ +static int parse_file(struct pmt_tss_db *db, json_t *root, const char *pat= h) +{ + struct pmt_tss_info info =3D {}; + 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 =3D parse_file_guid(root, path, &info.guid); + if (ret) + return ret; + + events =3D 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 =3D 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 =3D json_array_size(events); + } + + ret =3D dup_optional(obj_get_string(root, "platform"), &info.platform); + if (ret) + goto err_free; + + ret =3D dup_optional(obj_get_string(root, "description"), &info.descripti= on); + if (ret) + goto err_free; + + json_array_foreach(events, idx, ev) { + ret =3D parse_event(ev, path, idx, &info.metrics[idx]); + if (ret) + goto err_free; + } + + ret =3D sort_metrics(&info, path); + if (ret) + goto err_free; + + db->tss_info[db->num_tss_info++] =3D 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 =3D fopen(path, "r"); + if (!fp) + return log_ret(-errno, "unable to open %s", path); + + *root =3D 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 =3D read_json_file(path, &root); + if (ret) + return ret; + + ret =3D 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 =3D strrchr(de->d_name, '.'); + + if (de->d_name[0] =3D=3D '.') + return 0; + + return ext && !strcmp(ext, ".json"); +} + +static int load_dir_entry(struct pmt_tss_db *db, const char *dir, const ch= ar *name) +{ + char path[PATH_MAX]; + int ret; + + ret =3D 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 =3D 0; + int n; + + n =3D 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 =3D calloc(n, sizeof(*db->tss_info)); + if (!db->tss_info) { + ret =3D -ENOMEM; + goto out_free_names; + } + } + + for (int i =3D 0; i < n; i++) { + int err; + + err =3D load_dir_entry(db, dir, names[i]->d_name); + if (err =3D=3D -ENOMEM) { + ret =3D err; + break; + } + + if (err) + ret =3D err; + } + +out_free_names: + for (int i =3D 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 =3D a; + const struct pmt_tss_info *ib =3D b; + + if (ia->guid !=3D 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 *pat= h) +{ + for (size_t i =3D 1; i < db->num_tss_info; i++) { + if (db->tss_info[i].guid =3D=3D 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 =3D load_dir(db, path); + } else if (S_ISREG(st.st_mode)) { + db->tss_info =3D calloc(1, sizeof(*db->tss_info)); + if (db->tss_info) + ret =3D load_file(db, path); + else + ret =3D -ENOMEM; + } else { + log_err("%s: not a file or directory", path); + ret =3D -EINVAL; + } + + if (!ret && db->num_tss_info > 1) { + qsort(db->tss_info, db->num_tss_info, sizeof(*db->tss_info), tss_info_cm= p); + ret =3D 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; +} --=20 2.53.0 From nobody Tue Nov 24 11:43:49 2026 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=192.198.163.18 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1795376060; b=3TG9X4U28fOeOJyaJRhKi11T7xDw4foYWbuO1r9ATgUs1TquzmPUWEaK3eAPZMXhuXD1 /yYCIeaWWMmsGWb8EWOd+PGRjZEMLDem0YBAsjJFMKKlbcKAb9vwFV4gTvEqMLeXpbeVA LjGVECUPl9wH2P+eEx4XPHU5RJ+rKOnteocnbdOhk+9+5fDbdlXWjISSI3Q7twSY3kRGr +CQPjXi3Qli/55cvofDzpSLfgQeipldjdgYODBBJ/GFO/iYTBFA7Nh9atjE4kHO/sfPi4 zyRgu9EuZTfu6Jg5YUJJIg12nJEP/kVigdQ5dkHc8g+F0XS0NbGfIXHsDfFJPb37NgQ== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1795376060; h=DMARC-Filter:DKIM-Signature:X-CSE-ConnectionGUID:X-CSE-MsgGUID: X-IronPort-AV:X-IronPort-AV:Received:X-CSE-ConnectionGUID: X-CSE-MsgGUID:X-ExtLoop1:X-IronPort-AV:Received:From:To:Cc:Subject: Date:Message-ID:X-Mailer:In-Reply-To:References:MIME-Version: Content-Transfer-Encoding; bh=dWPDKYsa+uLDhZgp40POBUinX7C6AP2xiUyASvrK2Rk=; b=nQQ9q4uCeq2P+cBDAB6rPaBq+vxhjUAOvkaCTvXxOePQ8805xFa2/C1kSSO//SU1b6M7 dbgqKrqMGidHtAUkmZlKpEHl0EJoC/CmZl1+/G4MJxmFrCfw5eDZT3vM30LAvJHZhk9pu h8IwcAGG5EPFBbV1fqKXJ56Hn+d7bFXXWc0tCjSVsjiC3aLWutLePZ9T2jjfNCo/IkSxm Hb1JmfUOq/C9ZwrjFQO4jBWMI2z6GlK2Zamb5V/M/mxperhpxhvA7yb96xt4+rr+RE/NG 6+2iLtGMxX9y4TA87+gc0N71e/WXmZn2gFJNtFTgf6k5VxCfLrA4Bz8/sKZ/1pdsqIA== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass header.from=linux.intel.com; spf=pass smtp.mailfrom=linux.intel.com; dkim=pass header.d=intel.com header.i=@intel.com header.a=rsa-sha256 header.s=Intel header.b=Nn6Q2vxR; arc=none smtp.remote-ip=192.198.163.18 Received: from mgamail.intel.com (mgamail.intel.com [192.198.163.18]) (using TLSv1.2 with cipher ECDHE-ECDSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 16383606A681; Sun, 22 Nov 2026 19:34:20 +0000 (UTC) DMARC-Filter: OpenDMARC Filter v1.4.2 smtp.subspace.kernel.org 16383606A681 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=linux.intel.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=linux.intel.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=intel.com header.i=@intel.com header.a=rsa-sha256 header.s=Intel header.b=Nn6Q2vxR DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=intel.com; i=@intel.com; q=dns/txt; s=Intel; t=1795376060; x=1826912060; h=from:to:cc:subject:date:message-id:in-reply-to: references:mime-version:content-transfer-encoding; bh=InsIHKgOtB79EvnOrZmSszfcqrGa2e84XxKWmsq7AyQ=; b=Nn6Q2vxRgRkIF9flVlnRpLqS4blAG3h+xm/ukv1HZ5BmZp90QpdN98Os syCpdwaSx9UEDFV6dCbuZ/B5PcpsXElzda9boZwU6R3lKmriEIRk941Jr Bq26fKEDA1Y6JE68jT573/Xnm474UoJTL6ASRDmSpjuYfNwlq48poCdGy qMfoWHLZv++ejcIlc9LxPJrpGm18tuaMxrdbnY0jsUrpnIb/IFhOMjmcu YPbBGHTFIVJ8QmA+NM/kTaslLPsIO3+W/r4P5Pd9aRz7iI9BC10yeGphp FsFvAwoU2mHXkzbmCVnSaqHw+QxaqxuoOcpeKrdKgP9iqJMOlpyFTAXFD g==; X-CSE-ConnectionGUID: jpNKWLUmQzCtN0hxrjC40A== X-CSE-MsgGUID: AE6u1RCQSai+GisaHJzyrA== X-IronPort-AV: E=McAfee;i="6800,10657,11974"; a="4217512" X-IronPort-AV: E=Sophos;i="6.27,227,1787036400"; d="scan'208";a="4217512" Received: from fmviesa004.fm.intel.com ([10.60.135.144]) by fmvoesa112.fm.intel.com with ESMTP/TLS/ECDHE-RSA-AES256-GCM-SHA384; 22 Nov 2026 11:34:19 -0800 X-CSE-ConnectionGUID: U+kN5gnWTtGWX0HSS1ruCw== X-CSE-MsgGUID: NvWcumEbS7alLLftI6n1/w== X-ExtLoop1: 1 X-IronPort-AV: E=Sophos;i="6.27,227,1787036400"; d="scan'208";a="11109798" Received: from debox1-desk4.jf.intel.com (HELO localhost) ([10.54.77.98]) by smtpauth.intel.com with ESMTP/TLS/ECDHE-RSA-AES256-GCM-SHA384; 22 Nov 2026 11:34:20 -0800 From: "David E. Box" To: =?UTF-8?q?Ilpo=20J=C3=A4rvinen?= , Hans de Goede Cc: "David E. Box" , Andy Shevchenko , platform-driver-x86@vger.kernel.org, linux-kernel@vger.kernel.org Subject: [PATCH v2 05/12] tools/arch/x86/pmtctl: Add 'list' command Date: Sun, 22 Nov 2026 11:34:00 -0800 Message-ID: <770cd5933dd8288d95dfabf9342877c8860c8624.1795374925.git.david.e.box@linux.intel.com> X-Mailer: git-send-email 2.53.0 In-Reply-To: References: X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Post: List-Help: List-Subscribe: List-Unsubscribe: List-Owner: Precedence: list MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" 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 --- 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 =20 BINDIR ?=3D /usr/sbin +DEFSDIR ?=3D /usr/share/pmtctl =20 CFLAGS =3D -Wextra =20 override CFLAGS +=3D -O2 -Wall -D_GNU_SOURCE -Iinclude -I../../../include +override CFLAGS +=3D -DPMTCTL_DEFS_DIR=3D'"$(DEFSDIR)"' =20 # 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 :=3D \ lib/pmtctl.o \ lib/tss.o \ lib/tss_json.o \ + src/cmd_list.o \ src/main.o =20 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/pm= tctl/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); =20 +/** + * 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/pm= tctl/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 =20 +#include #include +#include =20 #include "lib/device.h" #include "lib/tss.h" =20 +/* 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; }; =20 +/** + * 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. "te= lem3" + * + * 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_d= evice_filter *filter, + const struct pmt_device ***devs, size_t *num_devs); +int pmt_device_filter_set_guid(struct pmt_device_filter *filter, const cha= r *arg); =20 /* * 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/pm= tctl/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, }; =20 +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, = ...) =20 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 +#include +#include +#include + +#include "lib/common.h" #include "lib/device.h" +#include "lib/log.h" #include "lib/pmtctl.h" #include "lib/tss.h" =20 @@ -15,6 +22,33 @@ int pmtctl_ctx_init(struct pmtctl_ctx *ctx) return telem_scan(&ctx->devices, &ctx->num_devices); } =20 +/** + * 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 =3D=3D ENOENT) + return 0; + + json_path =3D 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 =3D NULL; ctx->num_devices =3D 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 wi= th 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_d= evice_filter *filter, + const struct pmt_device ***devs, size_t *num_devs) +{ + const struct pmt_device **sel; + size_t n =3D 0; + + sel =3D calloc(ctx->num_devices, sizeof(*sel)); + if (!sel) + return -ENOMEM; + + for (size_t i =3D 0; i < ctx->num_devices; i++) { + const struct pmt_device *dev =3D &ctx->devices[i]; + + if (filter->has_guid && dev->guid !=3D filter->guid) + continue; + + if (filter->name && strcmp(dev->name, filter->name)) + continue; + + sel[n++] =3D dev; + } + + *devs =3D sel; + *num_devs =3D n; + + return 0; +} + +/** + * pmt_device_filter_set_guid - restrict a filter to the devices with a GU= ID + * @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 cha= r *arg) +{ + if (parse_u32(arg, 16, &filter->guid)) { + log_err("invalid GUID '%s'", arg); + return -EINVAL; + } + + filter->has_guid =3D true; + + return 0; +} diff --git a/tools/arch/x86/pmtctl/src/cmd_list.c b/tools/arch/x86/pmtctl/s= rc/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 +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#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 =3D 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 Restrict to devices with this GUID.\n" + " --device 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[] =3D { + { "help", no_argument, NULL, 'h' }, + { "guid", required_argument, NULL, OPT_LIST_GUID }, + { "device", required_argument, NULL, OPT_LIST_DEVICE }, + {} + }; + int opt; + + optind =3D 1; + + while ((opt =3D getopt_long(argc, argv, "h", long_opts, NULL)) !=3D -1) { + switch (opt) { + case 'h': + opts->show_help =3D 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 =3D optarg; + break; + default: + return -EINVAL; + } + } + + if (optind !=3D 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 print= ed + * 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 =3D indent; + bool line_start =3D true; + + s +=3D strspn(s, " \t\n"); + if (!*s) + return; + + print_chars(' ', indent); + + while (*s) { + size_t wlen =3D strcspn(s, " \t\n"); + + if (cols && !line_start && column + 1 + wlen > cols) { + putchar('\n'); + print_chars(' ', indent); + column =3D indent; + line_start =3D true; + } + + if (!line_start) { + putchar(' '); + column++; + } + + fwrite(s, 1, wlen, stdout); + column +=3D wlen; + line_start =3D false; + + s +=3D wlen; + s +=3D 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 met= ric + * definitions (@info is not NULL), their number and the description, wrap= ped + * 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 =3D=3D 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 =3D 0; + + for (size_t i =3D 0; i < info->num_metrics; i++) + width =3D max(width, strlen(info->metrics[i].name)); + + width =3D 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 =3D output_columns(); + bool listed =3D false; + + for (size_t i =3D 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 =3D=3D devs[i - 1]->guid) + continue; + + info =3D pmt_tss_db_lookup(&ctx->tss, devs[i]->guid); + if (!info || !info->num_metrics) + continue; + + if (listed) + putchar('\n'); + listed =3D true; + + print_guid_group_line(info->guid, info, cols); + print_separator(info); + + for (size_t j =3D 0; j < info->num_metrics; j++) { + const struct pmt_metric_def *m =3D &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 =3D {}; + const struct pmt_device **devs auto_free =3D NULL; + struct list_opts opts =3D {}; + size_t num_devs; + int ret; + + ret =3D 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 =3D pmtctl_ctx_init(&ctx); + if (ret) + return PMTCTL_EXIT_SYSTEM; + + ret =3D pmtctl_ctx_load_tss(&ctx, gopts->json_path); + if (ret) + return PMTCTL_EXIT_SYSTEM; + + ret =3D 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/m= ain.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 =20 #include "lib/log.h" +#include "lib/pmtctl.h" #include "pmtctl_cli.h" =20 #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 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 --help' for command-specific options.\n"); } =20 @@ -30,13 +37,15 @@ int main(int argc, char **argv) static const struct option long_opts[] =3D { { "help", no_argument, NULL, 'h' }, { "version", no_argument, NULL, 'V' }, + { "json-file", required_argument, NULL, 'J' }, {} }; + struct pmt_global_opts gopts =3D {}; const char *cmd; int opt; =20 /* '+' stops at the first non-option: the command name */ - while ((opt =3D getopt_long(argc, argv, "+hV", long_opts, NULL)) !=3D -1)= { + while ((opt =3D getopt_long(argc, argv, "+hVJ:", long_opts, NULL)) !=3D -= 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 \= n", PMTCTL_VERSION); return PMTCTL_EXIT_OK; + case 'J': + gopts.json_path =3D 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) =20 cmd =3D argv[optind]; =20 + if (!strcmp(cmd, "list")) + return cmd_list(argc - optind, argv + optind, &gopts); + if (!strcmp(cmd, "help")) { print_usage(stdout); return PMTCTL_EXIT_OK; --=20 2.53.0 From nobody Tue Nov 24 11:43:49 2026 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=192.198.163.18 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1795376061; b=Zxro1QiJdfKnFKfmDJyagP/Aja/c0oWCP5rp/MDjpGOK6m+RwvblUBb1Mtm91REAPYNP sAwk06RJUUVZpGagY/JQBhQOD+zRUBOZjMiT4hjpmsHGpAHpRGiLD1V876/s7xYsg1TGB Q6+3TQJV+bFuv482cmV4cGmlvhhEfFhz7qFiN5SAXHM4/9gmLAQEs92MhT6OEZcX5z+up 64xTj4NzXRi0KeVsI8wJ7aJ0pr8EQDYARhEMq18KaIJolM3xgHZADAXkIe/Rio5yUWisW vfNU3Hn2K42bwWl4t272FTvXijF/rMP3jMZV9+5piZYDl5y7ivFNuKC6TYXwUxzoV2A== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1795376061; h=DMARC-Filter:DKIM-Signature:X-CSE-ConnectionGUID:X-CSE-MsgGUID: X-IronPort-AV:X-IronPort-AV:Received:X-CSE-ConnectionGUID: X-CSE-MsgGUID:X-ExtLoop1:X-IronPort-AV:Received:From:To:Cc:Subject: Date:Message-ID:X-Mailer:In-Reply-To:References:MIME-Version: Content-Transfer-Encoding; bh=H4TarzeyH5qu+GIwDF1jfI83SrY4JzfpWABfYv3yCjM=; b=5gr6oOhAGiEyKwI24s5/wJ93zERncDi6XmSTCZx0DxzPImKEUqPgbjKjU1sE86VVGboL 1TPKzhsbvi+mWnUDMXGpj16Ut6O/T4fHxYV+D5DCFUnFzHZrcHFNisRswj7zJQah7WGnK /APEE+cXcCVmmDByiVvRIItCEwqsva6tY62+suLSb6+4ugyhZpyJkaZSJ4PclBr5/aBfL cbK8ntPIouTlFnYntWyjqVSf/V+Ieh2k/I6f5PL5RriHuvSHjnipERd0tWy1GnjzyW3v8 ioTeOimod4pb1v3dwNSQlHc7+3wzvV2WMbO7qUPNIVMbPGPMgRSqVTwymXsyx4zgqkg== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass header.from=linux.intel.com; spf=pass smtp.mailfrom=linux.intel.com; dkim=pass header.d=intel.com header.i=@intel.com header.a=rsa-sha256 header.s=Intel header.b="N2/RgAj8"; arc=none smtp.remote-ip=192.198.163.18 Received: from mgamail.intel.com (mgamail.intel.com [192.198.163.18]) (using TLSv1.2 with cipher ECDHE-ECDSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 85B25606A687; Sun, 22 Nov 2026 19:34:20 +0000 (UTC) DMARC-Filter: OpenDMARC Filter v1.4.2 smtp.subspace.kernel.org 85B25606A687 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=linux.intel.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=linux.intel.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=intel.com header.i=@intel.com header.a=rsa-sha256 header.s=Intel header.b=N2/RgAj8 DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=intel.com; i=@intel.com; q=dns/txt; s=Intel; t=1795376060; x=1826912060; h=from:to:cc:subject:date:message-id:in-reply-to: references:mime-version:content-transfer-encoding; bh=UXDDUD5g74yKM9r7RcyqBcygNztCv1XOVouVA3/BrLE=; b=N2/RgAj8wQ2zS0rp5sFJ5sYR5Sm6K0USMf0MMvH9gnSzIdyCagt6FRhX zwgIyihDaMYIOG+XR9Z3YhRlMiH2kxMY5rIu6QelTNR0W55kLw5Av9HJB DgOGFT/gshrbqS71Wr6ALsXNvJeNBm75f8yjRfxBxWy4HL45VhmlzSeh1 e51OJ5MiAjK/v3koxmBXGd2iHbHn2Cas2Eeh51Wl/U8nOjn28ChvrI9bA 0FaIz7E3NynhN6pCTAnkvXMoQSUph5DMCIairf7qFKMM+0PZNYpjfJseR WDoGca1x2TqPujnesMfNkM2PSE+tbEymHnCkI2i6XNiZeTLjkQ3dFzikL Q==; X-CSE-ConnectionGUID: xhDwaecXQragLrajwcN9AQ== X-CSE-MsgGUID: i9o4DwSmRLORG0RWnw+bDQ== X-IronPort-AV: E=McAfee;i="6800,10657,11974"; a="4217514" X-IronPort-AV: E=Sophos;i="6.27,227,1787036400"; d="scan'208";a="4217514" Received: from fmviesa004.fm.intel.com ([10.60.135.144]) by fmvoesa112.fm.intel.com with ESMTP/TLS/ECDHE-RSA-AES256-GCM-SHA384; 22 Nov 2026 11:34:20 -0800 X-CSE-ConnectionGUID: UMkYhrQ+Sj+iPGSZp/6fPg== X-CSE-MsgGUID: yQvncKosSn+WPJY3b3z6yA== X-ExtLoop1: 1 X-IronPort-AV: E=Sophos;i="6.27,227,1787036400"; d="scan'208";a="11109799" Received: from debox1-desk4.jf.intel.com (HELO localhost) ([10.54.77.98]) by smtpauth.intel.com with ESMTP/TLS/ECDHE-RSA-AES256-GCM-SHA384; 22 Nov 2026 11:34:21 -0800 From: "David E. Box" To: =?UTF-8?q?Ilpo=20J=C3=A4rvinen?= , Hans de Goede Cc: "David E. Box" , Andy Shevchenko , platform-driver-x86@vger.kernel.org, linux-kernel@vger.kernel.org Subject: [PATCH v2 06/12] tools/arch/x86/pmtctl: Add 'list --summary' Date: Sun, 22 Nov 2026 11:34:01 -0800 Message-ID: <0f77cacbead1815624aa72ca6160012fd08010c6.1795374925.git.david.e.box@linux.intel.com> X-Mailer: git-send-email 2.53.0 In-Reply-To: References: X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Post: List-Help: List-Subscribe: List-Unsubscribe: List-Owner: Precedence: list MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" 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 --- 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/s= rc/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 =20 +/* 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 =3D CHAR_MAX + 1, OPT_LIST_DEVICE, + OPT_LIST_SUMMARY, }; =20 struct list_opts { bool show_help; struct pmt_device_filter filter; + bool summary; }; =20 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 Restrict to devices with this GUID.\n" - " --device Restrict to one device, e.g. telem3.\n"); + " --device Restrict to one device, e.g. telem3.\n" + " --summary List GUIDs and their devices.\n"); } =20 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 ar= gc, 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 ar= gc, char **argv) case OPT_LIST_DEVICE: opts->filter.name =3D optarg; break; + case OPT_LIST_SUMMARY: + opts->summary =3D 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); } =20 +/* 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 =3D output_columns(); + + printf("PMT devices on this system:\n\n"); + + for (size_t i =3D 0; i < num_devs; i++) { + uint32_t guid =3D devs[i]->guid; + + if (!i || guid !=3D 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 =3D=3D num_devs || devs[i + 1]->guid !=3D 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_g= lobal_opts *gopts) return PMTCTL_EXIT_USER; } =20 + 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/m= ain.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 --help' for command-specific options.\n"); } --=20 2.53.0 From nobody Tue Nov 24 11:43:49 2026 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=192.198.163.18 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1795376062; b=F4RM6HszP06J/nEwQykQhifie1piR7MhwTz59G6XXjhmr/EkvH0KZ/Y22LyCcW0rKUte aBnEm4Y6hWJwUJ3NDtZUeO8nt0BZstrSZGz9aQBCWvn0iLfRjbzH2vkYruL2snTvSH17M GZ6LF7/xlqm2Ooq0k1q1dz/94ZpI1N78nG1niZ+OqTQqWjEGUXwy9K/ctD0LSfRIktLB/ HvpZ/lrBI1YvL0v5LeAE1se5lg6EoKAIJzsFh5Ck+3QQ4r9/s9i1oqToG1X8wDy6mhqE2 Uvm9R9UuJWDlHr78wy53u/itJ031YC9mVeyMCBYsFvwg1cT9PB5lwSsWL3wOwK70ZUw== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1795376062; h=DMARC-Filter:DKIM-Signature:X-CSE-ConnectionGUID:X-CSE-MsgGUID: X-IronPort-AV:X-IronPort-AV:Received:X-CSE-ConnectionGUID: X-CSE-MsgGUID:X-ExtLoop1:X-IronPort-AV:Received:From:To:Cc:Subject: Date:Message-ID:X-Mailer:In-Reply-To:References:MIME-Version: Content-Transfer-Encoding; bh=lS3tK9GbltiK8NPg/SK88lXpAQtYdZiM/ncR69mcFNk=; b=A34LHToPyNi9AbZZijaUs90ShdMr0HSWkOmy/cwiW8TvAgC5+UnE1Hxn0pix22XefCg7 jnWRIIX4dLutgEluyJ7ZnWaAnelyk1AOO3Lq9yIEABBRRdxpfx5Dofled5dr06qfqXbDu jIYQVjS8jpiRCCrK+qLy0fWR7DhDyQ7Q5KkudEdH7ub4cCGWOp/Q+E2ni1Cvb7piyaGiJ TBzElz0xoysMR0l81KXrEjJsgUdEqAdxP9x/FI556vnVJqMFTp6R8T+2tCe7dSj4bGTa6 xwskUrcjoGvVr/1s1x7L4KdIGo+bvzumt2mAP3az/j8g0uFsExDfJ/uBtzSQng+2iyg== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass header.from=linux.intel.com; spf=pass smtp.mailfrom=linux.intel.com; dkim=pass header.d=intel.com header.i=@intel.com header.a=rsa-sha256 header.s=Intel header.b=StEVJEWU; arc=none smtp.remote-ip=192.198.163.18 Received: from mgamail.intel.com (mgamail.intel.com [192.198.163.18]) (using TLSv1.2 with cipher ECDHE-ECDSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 21550606A68D; Sun, 22 Nov 2026 19:34:21 +0000 (UTC) DMARC-Filter: OpenDMARC Filter v1.4.2 smtp.subspace.kernel.org 21550606A68D Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=linux.intel.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=linux.intel.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=intel.com header.i=@intel.com header.a=rsa-sha256 header.s=Intel header.b=StEVJEWU DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=intel.com; i=@intel.com; q=dns/txt; s=Intel; t=1795376061; x=1826912061; h=from:to:cc:subject:date:message-id:in-reply-to: references:mime-version:content-transfer-encoding; bh=mzXbDEnLI1QQzmEVf/XXyC7OqkvkyV24SJUCntmmni4=; b=StEVJEWU34cx04m+xzAIrF1+lEH7NzejnY/yQrZ883t8/WwqaIa1E4E1 Jo6Nc6hSui4IwQDcq/vSmWi/WllP24LppEs61XW22RLCxPh9SOkPBcyS9 QN0MArMCr/rDduOT/iPVS+Ro/x+Uc2MG1A0W+KjIr+okzX7VvryPQlbun 1Jhr3uXfIvVFLdUIZ5MejgW6M18Sl5Yi0oNVAj6uWiNMAwmLNEzsjGiUF zfZ5/SgihuErTN6qkxDGJKhJXz2+g7mS2R+gfV4vqnpmRNUciWD0NF3ax eqGc1rkaI4WA1lUoBEjdBIMiSLGzMsr887jWSkiPHi+7exFMJUTjGTd7H Q==; X-CSE-ConnectionGUID: LwC9MeOPS4u51IRNYz5E/w== X-CSE-MsgGUID: ybJy6JlYRR2wKXVB9gVKPw== X-IronPort-AV: E=McAfee;i="6800,10657,11974"; a="4217516" X-IronPort-AV: E=Sophos;i="6.27,227,1787036400"; d="scan'208";a="4217516" Received: from fmviesa004.fm.intel.com ([10.60.135.144]) by fmvoesa112.fm.intel.com with ESMTP/TLS/ECDHE-RSA-AES256-GCM-SHA384; 22 Nov 2026 11:34:21 -0800 X-CSE-ConnectionGUID: pu21JxZDTYaNtguDHW9PDA== X-CSE-MsgGUID: +/Etj6bzRNubrN6B+HTsLw== X-ExtLoop1: 1 X-IronPort-AV: E=Sophos;i="6.27,227,1787036400"; d="scan'208";a="11109801" Received: from debox1-desk4.jf.intel.com (HELO localhost) ([10.54.77.98]) by smtpauth.intel.com with ESMTP/TLS/ECDHE-RSA-AES256-GCM-SHA384; 22 Nov 2026 11:34:21 -0800 From: "David E. Box" To: =?UTF-8?q?Ilpo=20J=C3=A4rvinen?= , Hans de Goede Cc: "David E. Box" , Andy Shevchenko , platform-driver-x86@vger.kernel.org, linux-kernel@vger.kernel.org Subject: [PATCH v2 07/12] tools/arch/x86/pmtctl: Add 'stat' command Date: Sun, 22 Nov 2026 11:34:02 -0800 Message-ID: <2d4566e76b319e2ad0ccc55b59d023ba51473511.1795374925.git.david.e.box@linux.intel.com> X-Mailer: git-send-email 2.53.0 In-Reply-To: References: X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Post: List-Help: List-Subscribe: List-Unsubscribe: List-Owner: Precedence: list MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" 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 --- 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 :=3D \ lib/tss.o \ lib/tss_json.o \ src/cmd_list.o \ + src/cmd_stat.o \ src/main.o =20 pmtctl: $(OBJS) diff --git a/tools/arch/x86/pmtctl/include/lib/device.h b/tools/arch/x86/pm= tctl/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 */ }; =20 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); =20 #endif diff --git a/tools/arch/x86/pmtctl/include/pmtctl_cli.h b/tools/arch/x86/pm= tctl/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 { }; =20 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); =20 #endif diff --git a/tools/arch/x86/pmtctl/lib/device_telem.c b/tools/arch/x86/pmtc= tl/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 #include =20 +#include + #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, cons= t char *devpath, const char *data_path auto_free =3D NULL; struct pmt_device *devices; uint32_t guid; + uint32_t size; int ret; =20 ret =3D read_attr_u32(devpath, "guid", 16, &guid); @@ -98,6 +101,12 @@ static int telem_add_device(struct telem_scan *scan, co= nst char *devpath, const return 0; } =20 + ret =3D 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 =3D strdup(name); if (!dev_name) return -ENOMEM; @@ -119,6 +128,7 @@ static int telem_add_device(struct telem_scan *scan, co= nst char *devpath, const .guid =3D guid, .name =3D no_free_ptr(dev_name), .data_path =3D no_free_ptr(data_path), + .size =3D size, }; =20 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 negat= ive errno */ +int telem_open(const struct pmt_device *dev) +{ + int fd; + + fd =3D 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 =3D pread(fd, &sample, sizeof(sample), sample_id * sizeof(sample)); + if (n < 0) + return -errno; + + if ((size_t)n !=3D sizeof(sample)) + return -EIO; + + *val =3D (sample & GENMASK_ULL(msb, lsb)) >> lsb; + + return 0; +} diff --git a/tools/arch/x86/pmtctl/src/cmd_stat.c b/tools/arch/x86/pmtctl/s= rc/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 +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#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 abo= ve */ +#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 =3D 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 =3D 0; i < run->num_rows; i++) { + if (run->rows[i].fd >=3D 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 [,...] ...\n" + "\n" + "Collect metric values over time (similar to 'perf stat').\n" + "\n" + "Options:\n" + " -h, --help Show this help.\n" + " -e, --event Metric name or comma-separated list; may be r= epeated.\n" + " --guid Restrict to devices with this GUID.\n" + " --device Restrict to one device, e.g. telem3.\n" + " -i, --interval Sampling interval (default 1000 ms).\n" + " -c, --count 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 valu= e.\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 [,...] ...\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 =3D pmt_grow_array(opts->requests, &opts->requests_cap, opts->nu= m_requests + 1, + sizeof(*requests)); + if (!requests) + return -ENOMEM; + + opts->requests =3D requests; + requests[opts->num_requests++] =3D *req; + + return 0; +} + +/* Add the metrics of an -e argument, which is split in place at the comma= s */ +static int add_metric_requests(struct stat_opts *opts, char *arg) +{ + char *saveptr; + char *name; + int ret; + + for (name =3D strtok_r(arg, ",", &saveptr); name; name =3D strtok_r(NULL,= ",", &saveptr)) { + ret =3D add_request(opts, &(struct stat_request){ .name =3D 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 **arg= v) +{ + static const struct option long_opts[] =3D { + { "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 =3D 1; + + while ((opt =3D getopt_long(argc, argv, "he:i:c:", long_opts, NULL)) !=3D= -1) { + switch (opt) { + case 'h': + opts->show_help =3D true; + return 0; + case 'e': + ret =3D 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 =3D optarg; + break; + case 'i': + ret =3D parse_positive(optarg, "interval", &opts->interval_ms); + if (ret) + return ret; + break; + case 'c': + ret =3D parse_positive(optarg, "count", &opts->count); + if (ret) + return ret; + break; + case OPT_STAT_NO_HEADER: + opts->no_header =3D true; + break; + case OPT_STAT_VERTICAL: + opts->vertical =3D true; + break; + default: + return -EINVAL; + } + } + + if (optind !=3D 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 =3D 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) <=3D 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 =3D (struct stat_cell){}; + + info =3D pmt_tss_db_lookup(&ctx->tss, dev->guid); + if (!info || !info->num_metrics) + return; + + def =3D bsearch(req->name, info->metrics, info->num_metrics, sizeof(*info= ->metrics), + metric_name_cmp); + if (!def) + return; + + cell->present =3D true; + cell->sample_id =3D def->sample_id; + cell->lsb =3D def->lsb; + cell->msb =3D 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 =3D NULL; + struct stat_row *rows auto_free =3D NULL; + bool *found auto_free =3D NULL; + const size_t num_requests =3D run->opts.num_requests; + size_t num_rows =3D 0; + + rows =3D calloc(num_devs, sizeof(*rows)); + cells =3D calloc(num_devs * num_requests, sizeof(*cells)); + found =3D calloc(num_requests, sizeof(*found)); + if (!rows || !cells || !found) + return -ENOMEM; + + for (size_t d =3D 0; d < num_devs; d++) { + /* A device without any requested value gives its slot to the next one */ + struct stat_row *row =3D &rows[num_rows]; + bool any =3D false; + + row->dev =3D devs[d]; + row->fd =3D -1; + row->cells =3D &cells[num_rows * num_requests]; + + for (size_t r =3D 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] =3D true; + any =3D true; + } + } + + if (any) + num_rows++; + } + + for (size_t r =3D 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 =3D no_free_ptr(rows); + run->cells =3D no_free_ptr(cells); + run->num_rows =3D 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 =3D 0; d < run->num_rows; d++) { + const struct stat_row *row =3D &run->rows[d]; + + for (size_t r =3D 0; r < run->opts.num_requests; r++) { + const struct stat_cell *cell =3D &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. T= he + * files are closed by stat_run_free(). + */ +static int open_telem_files(struct stat_run *run) +{ + for (size_t d =3D 0; d < run->num_rows; d++) { + struct stat_row *row =3D &run->rows[d]; + + row->fd =3D telem_open(row->dev); + if (row->fd =3D=3D -EACCES || row->fd =3D=3D -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 =3D strlen(s); + size_t pad =3D 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, s= ize_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 =3D STAT_VALUE_LEN; + size_t len =3D strlen(run->opts.requests[0].name); + + if (!run->opts.vertical && len > width) + width =3D 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 *sampl= e, 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, uint= 64_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 =3D 0; d < run->num_rows; d++) { + const struct stat_row *row =3D &run->rows[d]; + + for (size_t r =3D 0; r < run->opts.num_requests; r++) { + const char *value; + + value =3D 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 =3D strlen(STAT_COL_DEVICE); + for (size_t d =3D 0; d < run->num_rows; d++) + run->dev_width =3D max(run->dev_width, strlen(run->rows[d].dev->name)); + + run->label_width =3D strlen(STAT_COL_METRIC); + for (size_t r =3D 0; r < run->opts.num_requests; r++) + run->label_width =3D 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 rea= d */ +static bool read_cells(struct stat_run *run) +{ + bool any_read =3D false; + + for (size_t d =3D 0; d < run->num_rows; d++) { + struct stat_row *row =3D &run->rows[d]; + + for (size_t r =3D 0; r < run->opts.num_requests; r++) { + struct stat_cell *cell =3D &row->cells[r]; + int ret; + + if (!cell->present) + continue; + + ret =3D telem_read(row->fd, cell->sample_id, cell->lsb, cell->msb, + &cell->value); + cell->valid =3D !ret; + if (!ret) { + any_read =3D 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 =3D 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 =3D { + .tv_sec =3D a->tv_sec - b->tv_sec, + .tv_nsec =3D a->tv_nsec - b->tv_nsec, + }; + + if (d.tv_nsec < 0) { + d.tv_sec--; + d.tv_nsec +=3D 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 time= spec *now) +{ + struct timespec d =3D timespec_sub(now, start); + uint64_t sec =3D 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 +=3D ms / MSEC_PER_SEC; + ts->tv_nsec +=3D ms % MSEC_PER_SEC * NSEC_PER_MSEC; + if (ts->tv_nsec >=3D NSEC_PER_SEC) { + ts->tv_sec++; + ts->tv_nsec -=3D NSEC_PER_SEC; + } +} + +static bool timespec_before(const struct timespec *a, const struct timespe= c *b) +{ + if (a->tv_sec !=3D 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 *si= gint) +{ + struct timespec now, timeout; + + for (;;) { + clock_gettime(CLOCK_MONOTONIC, &now); + if (!timespec_before(&now, deadline)) + return false; + + timeout =3D timespec_sub(deadline, &now); + /* Otherwise timed out, or interrupted by a stop and continue */ + if (sigtimedwait(sigint, NULL, &timeout) =3D=3D 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 =3D false; + + sigemptyset(&sigint); + sigaddset(&sigint, SIGINT); + sigprocmask(SIG_BLOCK, &sigint, &old_mask); + + print_header(run); + + clock_gettime(CLOCK_MONOTONIC, &start); + next =3D start; + + for (uint64_t sample =3D 0; ; sample++) { + clock_gettime(CLOCK_MONOTONIC, &now); + + if (read_cells(run)) + any_read =3D true; + + print_sample(run, sample, ms_between(&start, &now)); + + if (run->opts.count && sample + 1 =3D=3D 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 =3D { + .opts =3D { .interval_ms =3D STAT_DEFAULT_INTERVAL_MS }, + }; + const struct pmt_device **devs auto_free =3D NULL; + size_t num_devs; + int ret; + + ret =3D 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 =3D pmtctl_ctx_init(&run.ctx); + if (ret) + return PMTCTL_EXIT_SYSTEM; + + ret =3D pmtctl_ctx_load_tss(&run.ctx, gopts->json_path); + if (ret) + return PMTCTL_EXIT_SYSTEM; + + ret =3D pmtctl_select_devices(&run.ctx, &run.opts.filter, &devs, &num_dev= s); + 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 =3D build_rows(&run, devs, num_devs); + if (ret =3D=3D -ENOMEM) { + log_ret(ret, "unable to set up sampling"); + return PMTCTL_EXIT_SYSTEM; + } + if (ret) + return PMTCTL_EXIT_USER; + + ret =3D check_bounds(&run); + if (ret) + return PMTCTL_EXIT_USER; + + ret =3D open_telem_files(&run); + if (ret) + return PMTCTL_EXIT_SYSTEM; + + set_column_widths(&run); + + ret =3D 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/m= ain.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 --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); =20 + if (!strcmp(cmd, "stat")) + return cmd_stat(argc - optind, argv + optind, &gopts); + if (!strcmp(cmd, "help")) { print_usage(stdout); return PMTCTL_EXIT_OK; --=20 2.53.0 From nobody Tue Nov 24 11:43:49 2026 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=192.198.163.18 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1795376062; b=J8lEPqrWYcWVfr1f+BXrKK3p4xqWvH6D+Sj/Z/f/oiefXKbAyf7ObfCPD2fyJjg7L6MO V6aVi3nHVsBeRGcH76SF/3+BXnKhB2W8aYt/2zkoIPyQylGWyzpXYGrM4BoEc1GK+h2F6 QoPP48E58aZOkDF1XrMOEd+9shOfeJVAFPo/mnWF5avNje8LCkofUHIaa2JjU/z0sTnoU 5dCoOKGdYDds1+OG1fIh1kF93lHDL9yx0/FbGt3la6RB2tfY7DWWwfGdeyjGvn9THZyX0 ekJbn9IS8dwa/qvXBDx0bOnQZebC4lbxIm71NnMPQ4AFaFqQEZa2G055ZA2X9xrd1qg== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1795376062; h=DMARC-Filter:DKIM-Signature:X-CSE-ConnectionGUID:X-CSE-MsgGUID: X-IronPort-AV:X-IronPort-AV:Received:X-CSE-ConnectionGUID: X-CSE-MsgGUID:X-ExtLoop1:X-IronPort-AV:Received:From:To:Cc:Subject: Date:Message-ID:X-Mailer:In-Reply-To:References:MIME-Version: Content-Transfer-Encoding; bh=WoDH317/3NZg/rD7xE2uFaRlVP3aJ7CI4ZPBY6MpUnQ=; b=2ZaG+y1z+U82yWBClFHA/xZJRbgdkT1wC27/6iMu5YBFET2cL60K8w63EshBbsgEQuch G+bu/OqhLAViYC7O7ipbnMF0mFb53z9TlimTDRr3HrH39LZcD39bXVPoi3QpScNa7uPbh wTv8G3HsSWjaKIf5EGNFlkR/7hCvoWPUe4xb04wp6uwTtJ1lrHx6B4yKXnfkPo+AVw3h4 dhzuqgG25l0bpkcKnEnrWEclD5a3CGo5ggJz7ErOLuqaNAwXuB6hEZQ/JBLCYF2Hwv2YD ZZeTRjYqq3o2EURlxe6pZ/OvSsn7teLXEAP77t8wigFDNutm/lEbhSaIJT9Km6hhZpg== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass header.from=linux.intel.com; spf=pass smtp.mailfrom=linux.intel.com; dkim=pass header.d=intel.com header.i=@intel.com header.a=rsa-sha256 header.s=Intel header.b=ixH2QoM5; arc=none smtp.remote-ip=192.198.163.18 Received: from mgamail.intel.com (mgamail.intel.com [192.198.163.18]) (using TLSv1.2 with cipher ECDHE-ECDSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id B8004606A33A; Sun, 22 Nov 2026 19:34:21 +0000 (UTC) DMARC-Filter: OpenDMARC Filter v1.4.2 smtp.subspace.kernel.org B8004606A33A Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=linux.intel.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=linux.intel.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=intel.com header.i=@intel.com header.a=rsa-sha256 header.s=Intel header.b=ixH2QoM5 DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=intel.com; i=@intel.com; q=dns/txt; s=Intel; t=1795376061; x=1826912061; h=from:to:cc:subject:date:message-id:in-reply-to: references:mime-version:content-transfer-encoding; bh=HYP3/JOoTFkWBhqjnJf/9iX6pqTHjzdTPjENXjlsX/c=; b=ixH2QoM5JDIcPLTmHBv8WJMelka2/ZsJH3FavAkiMifBvmGl9knsjOCP OHXZMluG35+CBv8bp8AnuVr4q0VpgKn/BCkWAf3AoegIwv9vbhT7E/I0M LCYhKxJdOAXpo8A02bkOiJ6TGaYmwCiBMYJtV/XYWXMHStcj4nL070p3W XOh80nzWwBGn4/9MwrIOyJtFOyuSFlj3mULrOtcnt+OU3pkhCfgRRuT01 F8SYiROzJf8XgRU8hNRiZ8TBeU/RY/2+E+rjPNU9bB/5sfbd8b2GXMGsR vhW/CB1ww/50/cu15+zJquo+AvyhzExXJKqL+5xj0fLFEHAezbTo2hEEc w==; X-CSE-ConnectionGUID: Zva6g11eT3aHBwfw3Bbxvg== X-CSE-MsgGUID: l/MULkA1RCC72sbtN8pv5A== X-IronPort-AV: E=McAfee;i="6800,10657,11974"; a="4217518" X-IronPort-AV: E=Sophos;i="6.27,227,1787036400"; d="scan'208";a="4217518" Received: from fmviesa004.fm.intel.com ([10.60.135.144]) by fmvoesa112.fm.intel.com with ESMTP/TLS/ECDHE-RSA-AES256-GCM-SHA384; 22 Nov 2026 11:34:21 -0800 X-CSE-ConnectionGUID: PftWmrIQRTmiQHEq1h8wOw== X-CSE-MsgGUID: Ko7i/e23R1CfvVHPOXQ2/Q== X-ExtLoop1: 1 X-IronPort-AV: E=Sophos;i="6.27,227,1787036400"; d="scan'208";a="11109802" Received: from debox1-desk4.jf.intel.com (HELO localhost) ([10.54.77.98]) by smtpauth.intel.com with ESMTP/TLS/ECDHE-RSA-AES256-GCM-SHA384; 22 Nov 2026 11:34:22 -0800 From: "David E. Box" To: =?UTF-8?q?Ilpo=20J=C3=A4rvinen?= , Hans de Goede Cc: "David E. Box" , Andy Shevchenko , platform-driver-x86@vger.kernel.org, linux-kernel@vger.kernel.org Subject: [PATCH v2 08/12] tools/arch/x86/pmtctl: Add 'stat --hex' Date: Sun, 22 Nov 2026 11:34:03 -0800 Message-ID: X-Mailer: git-send-email 2.53.0 In-Reply-To: References: X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Post: List-Help: List-Subscribe: List-Unsubscribe: List-Owner: Precedence: list MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" 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 --- 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/s= rc/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, }; =20 /* 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; }; =20 /* The value of one request on one device */ @@ -127,6 +129,7 @@ static void stat_usage_full(FILE *out) " -i, --interval Sampling interval (default 1000 ms).\n" " -c, --count 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 valu= e.\n" "\n" @@ -204,6 +207,7 @@ static int stat_parse_options(struct stat_opts *opts, i= nt 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, i= nt argc, char **argv) case OPT_STAT_VERTICAL: opts->vertical =3D true; break; + case OPT_STAT_HEX: + opts->hex =3D true; + break; default: return -EINVAL; } @@ -419,7 +426,7 @@ static void print_column(const char *s, size_t width, b= ool right) print_chars(' ', pad); } =20 -static const char *format_value(const struct stat_cell *cell, char *buf, s= ize_t len) +static const char *format_value(const struct stat_cell *cell, bool hex, ch= ar *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; =20 + if (hex) { + snprintf(buf, len, "0x%" PRIx64, cell->value); + return buf; + } + snprintf(buf, len, "%" PRIu64, cell->value); =20 return buf; @@ -505,7 +517,8 @@ static void print_sample(const struct stat_run *run, ui= nt64_t sample, uint64_t t for (size_t r =3D 0; r < run->opts.num_requests; r++) { const char *value; =20 - value =3D format_value(&row->cells[r], value_buf, sizeof(value_buf)); + value =3D format_value(&row->cells[r], run->opts.hex, value_buf, + sizeof(value_buf)); =20 print_line_start(run, sample_buf, time_buf, row->dev->name); if (run->opts.vertical) { --=20 2.53.0 From nobody Tue Nov 24 11:43:49 2026 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=192.198.163.18 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1795376062; b=XJHS+Pz8AMoFB4iOBpDloUAoMyVVNNhTEL/A+eVcfcvHl0ZnA08JT9HMWfAOgP7UycTF 8Y9CZY6/hU1odK9wlDEZLQbYAyL8uRVMSCDUfWhq9JfWfs0v0GzcCyPuVl9Gjngv3eCmp 9wqaHaS3oljw5qIxjnAfklRS4IGTLTFVMK76H/NFXVj2cTiUTn08T4AVbOJm3Ly8WiZtQ zA9ADUuBFGU8DBQTwg3pbVXwW01bZNZCnUKcqZsk9ik3D4NdSgFoXK31CAskH1HZcsFw9 mExvRcimKmpn3cj7tCKbQXRAJAzoySxJR/n2+46NhaRBnzH537gTWK3a85mslflRmtg== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1795376062; h=DMARC-Filter:DKIM-Signature:X-CSE-ConnectionGUID:X-CSE-MsgGUID: X-IronPort-AV:X-IronPort-AV:Received:X-CSE-ConnectionGUID: X-CSE-MsgGUID:X-ExtLoop1:X-IronPort-AV:Received:From:To:Cc:Subject: Date:Message-ID:X-Mailer:In-Reply-To:References:MIME-Version: Content-Transfer-Encoding; bh=nLzJDfWQU3Cb6v+75iwXdDzx/XV+Tet5c7iQdPS46xU=; b=svYYAQcc1VRc7diAS1MZfRprnHZcNZbpKoiI5VF4IMybCaAyB3Nql4WY77Njh183Dn6x MNJyyvlTzhFjSpKJSAap6u0w4jLGfIlpRQOoxUUqPAVRRKWDcj+Nww3rLLuDDkmKlVZmH VnfGquA3H2oVIySdnpRDfjtNV8RFR5wxmCeBLRbq7efMT7cxTeT1xgM26qoSipSu7YZEB diJp95UY4cy018Tqrw3FIQ8MJC7Q7XmsJFOCwDQvAPwao7PDcDnNjAPcNzLkFLipeBGWU ZY7XLVTdVS/0Qas17svqGBcni7EGFzodMUyKX9eUgP9rUYyKnGQti8nJLO0yTXor+wg== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass header.from=linux.intel.com; spf=pass smtp.mailfrom=linux.intel.com; dkim=pass header.d=intel.com header.i=@intel.com header.a=rsa-sha256 header.s=Intel header.b=gCBM97Vd; arc=none smtp.remote-ip=192.198.163.18 Received: from mgamail.intel.com (mgamail.intel.com [192.198.163.18]) (using TLSv1.2 with cipher ECDHE-ECDSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 2836A606A33C; Sun, 22 Nov 2026 19:34:22 +0000 (UTC) DMARC-Filter: OpenDMARC Filter v1.4.2 smtp.subspace.kernel.org 2836A606A33C Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=linux.intel.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=linux.intel.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=intel.com header.i=@intel.com header.a=rsa-sha256 header.s=Intel header.b=gCBM97Vd DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=intel.com; i=@intel.com; q=dns/txt; s=Intel; t=1795376062; x=1826912062; h=from:to:cc:subject:date:message-id:in-reply-to: references:mime-version:content-transfer-encoding; bh=/xszF5m6efGlOIj86OJAhxDonBTqecf+Eeb0vqVW98M=; b=gCBM97VdLcmPNprcVJ6ZeRxKj79khvCo2I3Cbmp8bbZnmvkBC117g0F6 h80mlc/bOrwVGvRfadKpYyG7T5kUf3qNz7s6iNKhY2dhM1LcYeLO0T+KB QIHUeIkeYAzTKULeAA0iKrMAet+YCBmDnQpUIq08tEaVDvQA06JjDAwrc JP+z7ZhBzjR95R7Ztc5Thpdp4cVtST5yox6EdMO7o4DsDw29/SiJgDMW+ 7DQgVrt9zfOn7vIcc+8V3ty+dlQsghoMmub114HOszIgnOQoBQJuFDMCY pC4IMNJxtz8u7iQsEGUuKJv9CIo9lEDOSUskVUAfk2GBjl3dFOqduUk6B w==; X-CSE-ConnectionGUID: d0WGDuLTRQScIl+LeI6gNg== X-CSE-MsgGUID: optZeD5cRvqa0pwBV01VPQ== X-IronPort-AV: E=McAfee;i="6800,10657,11974"; a="4217520" X-IronPort-AV: E=Sophos;i="6.27,227,1787036400"; d="scan'208";a="4217520" Received: from fmviesa004.fm.intel.com ([10.60.135.144]) by fmvoesa112.fm.intel.com with ESMTP/TLS/ECDHE-RSA-AES256-GCM-SHA384; 22 Nov 2026 11:34:22 -0800 X-CSE-ConnectionGUID: hSw07ErRQymn0vXoljEOqA== X-CSE-MsgGUID: pxO5LpnKRH268dMGeUFKMQ== X-ExtLoop1: 1 X-IronPort-AV: E=Sophos;i="6.27,227,1787036400"; d="scan'208";a="11109803" Received: from debox1-desk4.jf.intel.com (HELO localhost) ([10.54.77.98]) by smtpauth.intel.com with ESMTP/TLS/ECDHE-RSA-AES256-GCM-SHA384; 22 Nov 2026 11:34:22 -0800 From: "David E. Box" To: =?UTF-8?q?Ilpo=20J=C3=A4rvinen?= , Hans de Goede Cc: "David E. Box" , Andy Shevchenko , platform-driver-x86@vger.kernel.org, linux-kernel@vger.kernel.org Subject: [PATCH v2 09/12] tools/arch/x86/pmtctl: Add 'stat --raw' Date: Sun, 22 Nov 2026 11:34:04 -0800 Message-ID: <328af41f2dabd8ea2b3cb73e53b3569cb700a752.1795374925.git.david.e.box@linux.intel.com> X-Mailer: git-send-email 2.53.0 In-Reply-To: References: X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Post: List-Help: List-Subscribe: List-Unsubscribe: List-Owner: Precedence: list MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" Add --raw to 'stat' to sample a bit range of a telemetry sample by its position, id=3D[,lsb=3D][,msb=3D], 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 --- 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/s= rc/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 @@ =20 #define STAT_COL_GAP " " =20 +/* Room for the label of a --raw request: "raw[id=3D4294967295,lsb=3D63,ms= b=3D63]" */ +#define STAT_RAW_LABEL_LEN 40 + /* Values for long-only options, above any short option character */ enum { OPT_STAT_GUID =3D CHAR_MAX + 1, @@ -51,11 +54,19 @@ enum { OPT_STAT_NO_HEADER, OPT_STAT_VERTICAL, OPT_STAT_HEX, + OPT_STAT_RAW, }; =20 /* 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]; }; =20 struct stat_opts { @@ -118,12 +129,18 @@ static void stat_usage_full(FILE *out) { fprintf(out, "Usage: pmtctl stat [options] -e [,...] ...\n" + " pmtctl stat [options] --raw id=3D[,lsb=3D][,msb=3D] ...= \n" "\n" "Collect metric values over time (similar to 'perf stat').\n" "\n" "Options:\n" " -h, --help Show this help.\n" " -e, --event Metric name or comma-separated list; may be r= epeated.\n" + " --raw Read a raw sample value by sample id, with op= tional\n" + " bit slicing; may be repeated and combined wit= h -e.\n" + " is id=3D[,lsb=3D][,msb=3D] wi= thout\n" + " spaces, where 0 <=3D lsb <=3D msb <=3D 63 (de= faults:\n" + " lsb=3D0, msb=3D63).\n" " --guid Restrict to devices with this GUID.\n" " --device Restrict to one device, e.g. telem3.\n" " -i, --interval 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=3D2\n" + " pmtctl stat --raw id=3D2,lsb=3D16,msb=3D31\n" + " pmtctl stat --vertical --raw id=3D2,msb=3D7 --raw id=3D3,lsb=3D8,msb= =3D15\n" ); } =20 @@ -149,6 +169,7 @@ static void stat_usage_short(FILE *out) { fprintf(out, "Usage: pmtctl stat [options] -e [,...] ...\n" + " pmtctl stat [options] --raw id=3D[,lsb=3D][,msb=3D] ...= \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; } =20 +/* Parse the value of --raw key @key, which must be given once and be at m= ost @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 =3D 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 com= mas */ +static int add_raw_request(struct stat_opts *opts, char *arg) +{ + struct stat_request req =3D { .raw =3D true }; + uint32_t msb =3D PMT_SAMPLE_BITS - 1; + uint32_t lsb =3D 0; + bool seen_id =3D false; + bool seen_lsb =3D false; + bool seen_msb =3D false; + char *tok; + int ret; + + while ((tok =3D strsep(&arg, ","))) { + char *val =3D strchr(tok, '=3D'); + + if (!val) { + log_err("invalid --raw token '%s' (expected key=3Dvalue)", tok); + return -EINVAL; + } + *val++ =3D '\0'; + + if (!strcmp(tok, "id")) { + ret =3D parse_raw_value(tok, val, UINT32_MAX, &seen_id, &req.sample_id); + } else if (!strcmp(tok, "lsb")) { + ret =3D parse_raw_value(tok, val, PMT_SAMPLE_BITS - 1, &seen_lsb, &lsb); + } else if (!strcmp(tok, "msb")) { + ret =3D parse_raw_value(tok, val, PMT_SAMPLE_BITS - 1, &seen_msb, &msb); + } else { + log_err("unknown key '%s' in --raw argument", tok); + ret =3D -EINVAL; + } + + if (ret) + return ret; + } + + if (!seen_id) { + log_err("--raw requires at least 'id=3D'"); + return -EINVAL; + } + + if (lsb > msb) { + log_err("--raw lsb (%" PRIu32 ") cannot be greater than msb (%" PRIu32 "= )", + lsb, msb); + return -EINVAL; + } + + req.lsb =3D lsb; + req.msb =3D msb; + snprintf(req.raw_label, sizeof(req.raw_label), "raw[id=3D%" PRIu32 ",lsb= =3D%u,msb=3D%u]", + req.sample_id, req.lsb, req.msb); + + ret =3D 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 **arg= v) { static const struct option long_opts[] =3D { @@ -208,6 +311,7 @@ static int stat_parse_options(struct stat_opts *opts, i= nt 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 =3D true; break; + case OPT_STAT_RAW: + ret =3D 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, i= nt argc, char **argv) } =20 if (!opts->num_requests) { - log_err("requires -e/--event"); + log_err("requires -e/--event or --raw"); return -EINVAL; } =20 @@ -274,6 +383,14 @@ static int stat_parse_options(struct stat_opts *opts, = int argc, char **argv) return 0; } =20 +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 =3D elem; @@ -296,6 +413,18 @@ static void resolve_request(const struct pmtctl_ctx *c= tx, const struct pmt_devic =20 *cell =3D (struct stat_cell){}; =20 + /* A raw request names its location, which a device has if it's in its re= gion */ + if (req->raw) { + if (!sample_in_region(dev, req->sample_id)) + return; + + cell->present =3D true; + cell->sample_id =3D req->sample_id; + cell->lsb =3D req->lsb; + cell->msb =3D req->msb; + return; + } + info =3D 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 struc= t pmt_device **devs, size for (size_t r =3D 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 =3D STAT_VALUE_LEN; - size_t len =3D strlen(run->opts.requests[0].name); + size_t len =3D strlen(request_label(&run->opts.requests[0])); =20 if (!run->opts.vertical && len > width) width =3D 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), tr= ue); putchar('\n'); } =20 @@ -522,7 +651,8 @@ static void print_sample(const struct stat_run *run, ui= nt64_t sample, uint64_t t =20 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) =20 run->label_width =3D strlen(STAT_COL_METRIC); for (size_t r =3D 0; r < run->opts.num_requests; r++) - run->label_width =3D max(run->label_width, strlen(run->opts.requests[r].= name)); + run->label_width =3D max(run->label_width, + strlen(request_label(&run->opts.requests[r]))); } =20 /* Read every present cell; return the last read error, or 0 */ --=20 2.53.0 From nobody Tue Nov 24 11:43:49 2026 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=192.198.163.18 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1795376063; b=w1uWnK3BFqtKB3ctpp/G6ebqYRhRXeQQk/sP8VArv8gIyXLPAnQgC0m05z3osezKJH+n jBeuaC3L0s98e/+bmWDdlf4O4oi+GVpN0Xzi46MEHoh1yysrViICVPPAQHbDqcXBVa6oL OjOQLxl1gTWz1ddFpjicGziK7xMqnJhaJo63tNVk8UPJm0hcbu6+sXgPLd2isCIPKmw86 QUs0xWOBTPZs4Nzi5A7VViIKdd2SAkmitKYYTSLhpP3OxhL4mn/RRJKbt8e1fdsbEY5ZE Esej7MfCekFOUyOauQNjbR2kgV4JYeo1Z6gRx6kbbX2KlDZ3hMF90TFVFqANcsCymhg== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1795376063; h=DMARC-Filter:DKIM-Signature:X-CSE-ConnectionGUID:X-CSE-MsgGUID: X-IronPort-AV:X-IronPort-AV:Received:X-CSE-ConnectionGUID: X-CSE-MsgGUID:X-ExtLoop1:X-IronPort-AV:Received:From:To:Cc:Subject: Date:Message-ID:X-Mailer:In-Reply-To:References:MIME-Version: Content-Transfer-Encoding; bh=Yt76KQlD640Muqv2+yYVkgsdhiZxjiGfT2O2endhm3o=; b=zktMl0g/Q+xCBCys06AaotKGyBvduJ65mtD8yy1tNmf2btU/tyA0TPXUix+1KHSFBk7n FlWUvWZYNpS7CsKeStwzlZqvhn0lHTKh8vhkKYgZ31KWySkTL64XB75sYAzykvzaBFmgy yEbf0NCALSGR8Ssoqw347K/oitBwlLumz1FDNLcIOuT7jb+NPl+LHB9Ozn4dV3SfA9Jnc oF+WgjfJf+OO+MeuhRh4Py75bypTyyJEBAm90cFkYcG23snv0jmKdwn1e9R0C9YekBifl w/Wib0u7XLIGDhfqBGWne5r9gSi0Fzt3D5mJgT2DVhFhkYj0JwiQtXRfQhBt261FXHA== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass header.from=linux.intel.com; spf=pass smtp.mailfrom=linux.intel.com; dkim=pass header.d=intel.com header.i=@intel.com header.a=rsa-sha256 header.s=Intel header.b=Dy7Ma3YK; arc=none smtp.remote-ip=192.198.163.18 Received: from mgamail.intel.com (mgamail.intel.com [192.198.163.18]) (using TLSv1.2 with cipher ECDHE-ECDSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id A37B1606A69E; Sun, 22 Nov 2026 19:34:22 +0000 (UTC) DMARC-Filter: OpenDMARC Filter v1.4.2 smtp.subspace.kernel.org A37B1606A69E Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=linux.intel.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=linux.intel.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=intel.com header.i=@intel.com header.a=rsa-sha256 header.s=Intel header.b=Dy7Ma3YK DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=intel.com; i=@intel.com; q=dns/txt; s=Intel; t=1795376062; x=1826912062; h=from:to:cc:subject:date:message-id:in-reply-to: references:mime-version:content-transfer-encoding; bh=NF4LDqLI5TNwz2MEuGNyEjN81+EUAaFBq/cTEkWdjww=; b=Dy7Ma3YKln9a4dkDg/TkKeVO4ktFNqnj9cRTGEOeagveZTLn+PuopI+g ta9XM/DnZAbvwj/ZuvA5mtPpL1gunJfRaCNyuqQkUPSTCIN3skThlzw2W z8gZKHQnugFoAudoxtOMJ8baIWh5m9yiXISzMp4mEgkqB+VTyXPUnI6/6 37p68Y2fjuyebDnwF3SeU+mI6NBXROL7+udu9jevnlLPk6iarENF9GXxM obxLfUCd0vgHhCWTZIiA9nFU1UMov6H+7j0tYgHidEgKi05pNN6PGx5rH Yv0bmArOl0haenRm9StCJUlvDXyulRhGfAZ8kXC5WkaMqbEuGasao0AUo w==; X-CSE-ConnectionGUID: wXCEp4x+T6WNpl0zPZWTYg== X-CSE-MsgGUID: s1SEJ5yhTqqQRBZsNWfsgA== X-IronPort-AV: E=McAfee;i="6800,10657,11974"; a="4217522" X-IronPort-AV: E=Sophos;i="6.27,227,1787036400"; d="scan'208";a="4217522" Received: from fmviesa004.fm.intel.com ([10.60.135.144]) by fmvoesa112.fm.intel.com with ESMTP/TLS/ECDHE-RSA-AES256-GCM-SHA384; 22 Nov 2026 11:34:22 -0800 X-CSE-ConnectionGUID: 3Sk0wfhsRsuwnI2f4MG9Ug== X-CSE-MsgGUID: nchoBspaSF2QnW1lxGtG1w== X-ExtLoop1: 1 X-IronPort-AV: E=Sophos;i="6.27,227,1787036400"; d="scan'208";a="11109805" Received: from debox1-desk4.jf.intel.com (HELO localhost) ([10.54.77.98]) by smtpauth.intel.com with ESMTP/TLS/ECDHE-RSA-AES256-GCM-SHA384; 22 Nov 2026 11:34:23 -0800 From: "David E. Box" To: =?UTF-8?q?Ilpo=20J=C3=A4rvinen?= , Hans de Goede Cc: "David E. Box" , Andy Shevchenko , platform-driver-x86@vger.kernel.org, linux-kernel@vger.kernel.org Subject: [PATCH v2 10/12] tools/arch/x86/pmtctl: Add README Date: Sun, 22 Nov 2026 11:34:05 -0800 Message-ID: <00e4e34485ad03a608a20b199264111c1cc5116f.1795374925.git.david.e.box@linux.intel.com> X-Mailer: git-send-email 2.53.0 In-Reply-To: References: X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Post: List-Help: List-Subscribe: List-Unsubscribe: List-Owner: Precedence: list MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" 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 --- 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 +=3D=3D=3D=3D=3D=3D + +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 def= s/ + 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 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=3D2,lsb=3D16,msb=3D31 + pmtctl stat --raw id=3D0,msb=3D31 --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 --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 --=20 2.53.0 From nobody Tue Nov 24 11:43:49 2026 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=192.198.163.18 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1795376063; b=t6O2SCM30jDMMVK6EwH4AJUExF88H773ejfczt6I8ozhWopT2rOimc4vm0ouEg//u9x7 NiBP4hPeO/Mxz7wcSVrPgSzdBwm8q2x3yCLDV1id8bvVknlrDDoxQPEJMbmOg4tnYMMk6 fDa18rqrjdCaf/v3rq6p8bqluvQ6KwTE53eXpC5wgzzos85QVxzum7NydGKN5KqTRKIm7 G9xDO4y4D6/bqTYcSCo3dnvpucsUFGQC5XeLJbQKHnAwbTSWrc+18OIqFXiY/e6o7mdq/ YEFaRjHLJAfYOCIib0QEaeRQpSoakMN5miQBWsom0N4SC/LBQ2zkgL5c+7Cr68He+UA== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1795376063; h=DMARC-Filter:DKIM-Signature:X-CSE-ConnectionGUID:X-CSE-MsgGUID: X-IronPort-AV:X-IronPort-AV:Received:X-CSE-ConnectionGUID: X-CSE-MsgGUID:X-ExtLoop1:X-IronPort-AV:Received:From:To:Cc:Subject: Date:Message-ID:X-Mailer:In-Reply-To:References:MIME-Version: Content-Transfer-Encoding; bh=ebxGRomDKancW4IdiZSc5iww/0mlTa9i37BIgRGP0Hk=; b=gN14/Aqks9OzaAelVtwvAMHuwYBECcB4b3tpFUhYh/70QtaX8jSrT4/bOz0Y3/Er9zS8 2lT4+2ESau81PczB/lRrOpqYHbA4RlY+XcZqXfq/VvcoIQ0I6jdIGE9yjiwe465L0K9k1 rSZpxqKTeJTDc1mcZXqS4TN4/Zkq+2QXtASD/PCpB5dqJP4tCNQ+z5gO+ZG+q7WNL/TVy 2c0iQ/HgOD+AQjr2l058otyriHaScLCuU5WMKzN2s5hgGbSRJvKUvLWj2wn22QbV9NLER HrARtupcl+OHHV1ezP7YBmyh0p4PbHpfJMg+EkNV+UA5d282J4UQe1YJHTTmJ46BEtA== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass header.from=linux.intel.com; spf=pass smtp.mailfrom=linux.intel.com; dkim=pass header.d=intel.com header.i=@intel.com header.a=rsa-sha256 header.s=Intel header.b=GiJ+eyeI; arc=none smtp.remote-ip=192.198.163.18 Received: from mgamail.intel.com (mgamail.intel.com [192.198.163.18]) (using TLSv1.2 with cipher ECDHE-ECDSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 37AE0606A6A5; Sun, 22 Nov 2026 19:34:23 +0000 (UTC) DMARC-Filter: OpenDMARC Filter v1.4.2 smtp.subspace.kernel.org 37AE0606A6A5 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=linux.intel.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=linux.intel.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=intel.com header.i=@intel.com header.a=rsa-sha256 header.s=Intel header.b=GiJ+eyeI DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=intel.com; i=@intel.com; q=dns/txt; s=Intel; t=1795376063; x=1826912063; h=from:to:cc:subject:date:message-id:in-reply-to: references:mime-version:content-transfer-encoding; bh=fi/Ij34JtIirolXUTTzqq59KMgnjgz4bYUi8kuxSMFo=; b=GiJ+eyeI7vrL5jUIjyEHjtgAr/K4KA0Y3uFlf/Z7TPvQB/YzpCKzNFvg FZoxYdANp4PYYEfcLcOAwxS59H0EDuWfH7HRFuQFNjmXkbL86f8JtB/LG sZAbiMCjH6tLqJvkGAOqj2ilPnki/xVw4kJOogUSlFOQ7h0E+7MZO/3hc lNSakJFHGlBEC8pj4cUhTKuKCMrdINHmncI8taD2KRBbgq7Rlg9IS1+q4 Q04L4f8rbRkJZssghlTUIFh2xesxZiav8SBkbmWVAR6JE1tjAO1MzDlzG xIaCnLlPVLUiJ0+bkTOitn4QFrNwq8TYXtd2bY5uxBk+vTGZ8iUfxpl0C Q==; X-CSE-ConnectionGUID: hNdtKHsbTKOrfp6A1Nh5mA== X-CSE-MsgGUID: W2W1fYgQQa6D7Echor8umA== X-IronPort-AV: E=McAfee;i="6800,10657,11974"; a="4217524" X-IronPort-AV: E=Sophos;i="6.27,227,1787036400"; d="scan'208";a="4217524" Received: from fmviesa004.fm.intel.com ([10.60.135.144]) by fmvoesa112.fm.intel.com with ESMTP/TLS/ECDHE-RSA-AES256-GCM-SHA384; 22 Nov 2026 11:34:23 -0800 X-CSE-ConnectionGUID: /rz/EzE+SWaX2EFOE85pZQ== X-CSE-MsgGUID: L8iqB5gkT6O1SK/amTIHDA== X-ExtLoop1: 1 X-IronPort-AV: E=Sophos;i="6.27,227,1787036400"; d="scan'208";a="11109806" Received: from debox1-desk4.jf.intel.com (HELO localhost) ([10.54.77.98]) by smtpauth.intel.com with ESMTP/TLS/ECDHE-RSA-AES256-GCM-SHA384; 22 Nov 2026 11:34:23 -0800 From: "David E. Box" To: =?UTF-8?q?Ilpo=20J=C3=A4rvinen?= , Hans de Goede Cc: "David E. Box" , Andy Shevchenko , platform-driver-x86@vger.kernel.org, linux-kernel@vger.kernel.org Subject: [PATCH v2 11/12] tools/arch/x86/pmtctl: Add man page Date: Sun, 22 Nov 2026 11:34:06 -0800 Message-ID: X-Mailer: git-send-email 2.53.0 In-Reply-To: References: X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Post: List-Help: List-Subscribe: List-Unsubscribe: List-Owner: Precedence: list MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" 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 --- 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 @@ =20 BINDIR ?=3D /usr/sbin DEFSDIR ?=3D /usr/share/pmtctl +MANDIR ?=3D /usr/share/man =20 CFLAGS =3D -Wextra =20 @@ -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. =20 =20 Metric definitions @@ -84,6 +86,7 @@ The telemetry data files can only be read by root, so 'st= at' must run as root; 'list' doesn't need to. =20 'pmtctl --help' and 'pmtctl --help' describe all options. +The pmtctl(8) man page describes them in more detail. =20 =20 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 metri= cs +.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=3D \fIN\fR [,lsb=3D \fIN\fR ][,msb=3D \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=3D \fIN\fR [,lsb=3D \fIN\fR ][,msb=3D \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=3D\fIN\fR[\fB,lsb=3D\fIN\fR][\fB,msb=3D\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 \(<=3D +.B lsb +\(<=3D +.B msb +\(<=3D 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=3D2,msb=3D7 \-\-raw id=3D3,lsb=3D= 8,msb=3D15 +.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 . +.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. --=20 2.53.0 From nobody Tue Nov 24 11:43:49 2026 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=192.198.163.18 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1795376064; b=lL9HUl5jAKYBggKq57TUXp0oLBRUBUPAYZHi4q9SUYWwU0WsqINUO2PZZearo8sUwaGY 4F2VBRC2Il4UJeKE+fUWCVZ1T1Wi0IOW6fx1Ld4yLeeyteYUixL5Aop2BPpVunHfz9qWF TZuL4xlHW3b87Jg2s3fT5ZqM+qj0ThyYOfXY1Pq9yo0br/hPUBs4xNLw7Nk4luQjlVkZB 0s6Q0oNoATQ2Ez7unxWVZZlfCN/yIH/4Mq+yViCiwanJTNKcd9DRi3XYcAfh2CuHiHkVD lvrLkvU88kVeicht4Jn4LR/JkGfxYAPLwPBpCrccxYG3vHnWWBCblIKXJUr4ptKB6hg== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1795376064; h=DMARC-Filter:DKIM-Signature:X-CSE-ConnectionGUID:X-CSE-MsgGUID: X-IronPort-AV:X-IronPort-AV:Received:X-CSE-ConnectionGUID: X-CSE-MsgGUID:X-ExtLoop1:X-IronPort-AV:Received:From:To:Cc:Subject: Date:Message-ID:X-Mailer:In-Reply-To:References:MIME-Version: Content-Transfer-Encoding; bh=PGUuGOQnjR3rfIadjBjNpVzEj/lo15ufRHraqrJBqvo=; b=x99BtZxQG6LWK02PEHuk2iFLdxVW4ecJBEkF0wJCBE8/jt89GBEvySUOFD0xoyqghgXk bDn30zYXNrTy9jcyaPCYPX+kV/vlSpWo9WbJPB40NLqmF32nemgNyi/6HzIQuaYkM1Ofl ojVmbC0pb2OgOMoD33RWJN1WTzeVSCPQ7EKglh6plMBuC7bSVNYB6CtQ34aJURXw00cLH huc2dFwMy1cDBQC9+8ZSupAdZqtiJhMOZyB4ZhLPsPCk3qrrEr5lHFErs7M1Eq2d9L9FW as2rgbYokmfnN31Ht2Vr6HsbmWFyjA2526RjOAi7ihZOg5ilhen3qoL5r+fiz+tTSVQ== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass header.from=linux.intel.com; spf=pass smtp.mailfrom=linux.intel.com; dkim=pass header.d=intel.com header.i=@intel.com header.a=rsa-sha256 header.s=Intel header.b=lD9s+QnC; arc=none smtp.remote-ip=192.198.163.18 Received: from mgamail.intel.com (mgamail.intel.com [192.198.163.18]) (using TLSv1.2 with cipher ECDHE-ECDSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id A586C606A68C; Sun, 22 Nov 2026 19:34:23 +0000 (UTC) DMARC-Filter: OpenDMARC Filter v1.4.2 smtp.subspace.kernel.org A586C606A68C Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=linux.intel.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=linux.intel.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=intel.com header.i=@intel.com header.a=rsa-sha256 header.s=Intel header.b=lD9s+QnC DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=intel.com; i=@intel.com; q=dns/txt; s=Intel; t=1795376063; x=1826912063; h=from:to:cc:subject:date:message-id:in-reply-to: references:mime-version:content-transfer-encoding; bh=7vI5DusgjmMbcxjb2F44Of9/jzy9vzRwrfnvmHO2wSg=; b=lD9s+QnCHgspHvjXPn0O+mLkkrUij5Nm9AyqmCBnA8TDy7CY3VbHcQwx jB0/xL2aAA9UY3wXEXXcs7QBwf2UzN3srMyI4CarmvOAHIXKJ8DiSEjA7 rEdk1nsteORke6Ojoma8Vdyg5vYvHvLAJE2drkTTGXKfV3c18FoaFFFgH VzSZ5Vy+yqNrxunHnJ4jb8pzHGqOp/fq7z9RkjnDZU1zFLg5FCjP2aIo+ MMwtwYEBCkofkTDD8vmBb1jf26cTejOzxgySsTAykrTXexMm/HYCcgHC6 kOw8h5Cq4Mg37QxO0m4yh278yiuqC4GxZ/iU22lnQQOCSkyYzkNP/vAi/ A==; X-CSE-ConnectionGUID: pdsTMaQJQtSsfwe+OhFzQg== X-CSE-MsgGUID: 2R+mZIevQkS48FsvUzzWag== X-IronPort-AV: E=McAfee;i="6800,10657,11974"; a="4217527" X-IronPort-AV: E=Sophos;i="6.27,227,1787036400"; d="scan'208";a="4217527" Received: from fmviesa004.fm.intel.com ([10.60.135.144]) by fmvoesa112.fm.intel.com with ESMTP/TLS/ECDHE-RSA-AES256-GCM-SHA384; 22 Nov 2026 11:34:23 -0800 X-CSE-ConnectionGUID: 11PmWD0uS72idJWn3JbXmg== X-CSE-MsgGUID: F7kQqovbTLe6mEIhv/JCNg== X-ExtLoop1: 1 X-IronPort-AV: E=Sophos;i="6.27,227,1787036400"; d="scan'208";a="11109809" Received: from debox1-desk4.jf.intel.com (HELO localhost) ([10.54.77.98]) by smtpauth.intel.com with ESMTP/TLS/ECDHE-RSA-AES256-GCM-SHA384; 22 Nov 2026 11:34:24 -0800 From: "David E. Box" To: =?UTF-8?q?Ilpo=20J=C3=A4rvinen?= , Hans de Goede Cc: "David E. Box" , Andy Shevchenko , platform-driver-x86@vger.kernel.org, linux-kernel@vger.kernel.org Subject: [PATCH v2 12/12] tools/arch/x86/pmtctl: Add MAINTAINERS entry Date: Sun, 22 Nov 2026 11:34:07 -0800 Message-ID: <1260e5fdfeb2a6326ac1ba4fb9ab942fa3ff3002.1795374925.git.david.e.box@linux.intel.com> X-Mailer: git-send-email 2.53.0 In-Reply-To: References: X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Post: List-Help: List-Subscribe: List-Unsubscribe: List-Owner: Precedence: list MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" 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 --- 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* =20 INTEL PMT DRIVERS M: David E. Box +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/ =20 INTEL PRO/WIRELESS 2100, 2200BG, 2915ABG NETWORK CONNECTION SUPPORT M: Stanislav Yakovlev --=20 2.53.0