tools/arch/x86/pmtctl: Add Intel PMT command-line tool
PATCH 1/17 tools/arch/x86/pmtctl: Add MAINTAINERS entry
In reply to David E. BoxAdd tools/arch/x86/pmtctl/ to the INTEL PLATFORM MONITORING TECHNOLOGY (PMT) MAINTAINERS section so patches against the pmtctl userspace tool and its libpmtctl_core library are routed alongside the kernel PMT driver.
--- MAINTAINERS | 1 + 1 file changed, 1 insertion(+)
MAINTAINERS +1 -0
@@ -13198,6 +13198,7 @@ S: Supported F: Documentation/ABI/testing/sysfs-class-intel_pmt F: Documentation/ABI/testing/sysfs-class-intel_pmt-features F: drivers/platform/x86/intel/pmt/ +F: tools/arch/x86/pmtctl/ INTEL PRO/WIRELESS 2100, 2200BG, 2915ABG NETWORK CONNECTION SUPPORT M: Stanislav Yakovlev <[email protected]>
Signature · 1 line
2.43.0
cover tools/arch/x86/pmtctl: Add Intel PMT command-line tool
Intel Platform Monitoring Technology (PMT) exposes per-component telemetry counters through sysfs via the pmt_telemetry auxiliary bus driver. Each telemetry device provides a data file that can be read to sample the underlying hardware telemetry data. The meaning of each field within a sample is described by platform-specific metric definitions.
This series adds pmtctl, a command-line tool for querying PMT metrics on x86 Linux systems. It lives under tools/arch/x86/pmtctl/ alongside other platform-specific userspace tools.
The series introduces approximately 7k lines across the library, CLI frontend, code generation scripts, and documentation. The changes are intentionally split into small logical components so the architecture and dependencies can be reviewed incrementally.
The implementation is split into a reusable library (libpmtctl_core) and a thin CLI frontend:
libpmtctl_core (lib/)
- Device enumeration: scans /sys/bus/auxiliary/drivers/pmt_telemetry and reads GUID and telem data path from sysfs attributes.
- Metric definitions: supports two loading modes:
built-in -- a C struct array compiled in at build time, generated
from perf-style JSON by scripts/gen_builtin_defs.py.
runtime -- loaded at invocation via -J/--json-file (requires
libjansson).
- Metric DB: block-based container with flat-index accessors.
- GUID intern table: canonical struct pmt_guid pointers shared between the built-in and JSON providers.
CLI frontend (src/)
- list: enumerate discovered PMT devices and/or metric definitions, with optional GUID intersection report (--guids) and device-only mode (--devices).
- stat: perf-stat-like metric sampling with configurable interval, count, event selection, and raw-register mode.
Metric JSON files are not included in the tree. Users obtain them from the Intel-PMT repository using Makefile targets that fetch XML metric definitions over the network and convert them into the JSON format expected by the tool.
Testing: functional testing requires a system with PMT-capable hardware and /sys/bus/auxiliary/drivers/pmt_telemetry populated. Reading telemetry data (stat) requires elevated privileges (CAP_SYS_ADMIN / sudo); listing metrics and devices (list) does not.
Summary
1. Infrastructure and meta:
0001: Adds the MAINTAINERS entry for the new tool.
2. Library (libpmtctl_core, under lib/):
0002–0008: Introduce the core library, including shared types, logging,
metric definitions, device enumeration, built-in and JSON metric providers, public API, and core logic.
0009: Adds the libpmtctl Makefile, pkg-config file, and README for
the library.
0010–0011: Add usage samples and further built-in metric support for the
library.
3. CLI tool (under src/):
0012: Introduces the pmtctl CLI entry point, option parsing, and
pager helpers.
0013: Adds the 'list' command.
0014: Adds the 'stat' command.
4. Scripts/codegen:
0015: Adds the pmtxml2json.py conversion tool for XML→JSON metric
definitions.
5. Documentation and other:
0016: Adds README.md.
0017: Adds the man page.
David E. Box (17):
tools/arch/x86/pmtctl: Add MAINTAINERS entry tools/arch/x86/pmtctl: Add libpmtctl shared type enumerations tools/arch/x86/pmtctl: Add libpmtctl internal logging and utility
functions
tools/arch/x86/pmtctl: Add libpmtctl metric definition database tools/arch/x86/pmtctl: Add libpmtctl device enumeration backend tools/arch/x86/pmtctl: Add libpmtctl built-in metric provider tools/arch/x86/pmtctl: Add libpmtctl JSON metric provider tools/arch/x86/pmtctl: Add libpmtctl public API and context tools/arch/x86/pmtctl: Add libpmtctl Makefile + pc + README tools/arch/x86/pmtctl: Add libpmtctl usage sample tools/arch/x86/pmtctl: Add libpmtctl built-in metric definition
support
tools/arch/x86/pmtctl: Add pmtctl CLI entry point and pager tools/arch/x86/pmtctl: Add pmtctl 'list' command tools/arch/x86/pmtctl: Add pmtctl 'stat' command tools/arch/x86/pmtctl: Add pmtxml2json conversion tool tools/arch/x86/pmtctl: Add README.md tools/arch/x86/pmtctl: Add man page
MAINTAINERS | 1 + tools/arch/x86/pmtctl/Makefile | 204 ++++ tools/arch/x86/pmtctl/README.md | 279 ++++++ tools/arch/x86/pmtctl/include/cmd_stat.h | 75 ++ .../arch/x86/pmtctl/include/cmd_stat_format.h | 11 + .../x86/pmtctl/include/lib/builtin_defs.h | 14 + tools/arch/x86/pmtctl/include/lib/common.h | 34 + tools/arch/x86/pmtctl/include/lib/device.h | 53 ++ tools/arch/x86/pmtctl/include/lib/log.h | 80 ++ .../arch/x86/pmtctl/include/lib/metrics_db.h | 69 ++ .../x86/pmtctl/include/lib/metrics_provider.h | 21 + tools/arch/x86/pmtctl/include/lib/pmt_guid.h | 63 ++ tools/arch/x86/pmtctl/include/lib/pmtctl.h | 90 ++ .../x86/pmtctl/include/lib/pmtctl_context.h | 21 + .../x86/pmtctl/include/lib/pmtctl_types.h | 16 + tools/arch/x86/pmtctl/include/pmtctl_cli.h | 16 + tools/arch/x86/pmtctl/lib/Makefile | 138 +++ tools/arch/x86/pmtctl/lib/README | 116 +++ .../arch/x86/pmtctl/lib/builtin_defs_empty.c | 13 + tools/arch/x86/pmtctl/lib/common.c | 178 ++++ tools/arch/x86/pmtctl/lib/device_telem.c | 371 ++++++++ tools/arch/x86/pmtctl/lib/log.c | 80 ++ tools/arch/x86/pmtctl/lib/metrics_db.c | 62 ++ tools/arch/x86/pmtctl/lib/metrics_provider.c | 42 + .../x86/pmtctl/lib/metrics_provider_json.c | 459 +++++++++ tools/arch/x86/pmtctl/lib/pmt_guid.c | 200 ++++ tools/arch/x86/pmtctl/lib/pmtctl.c | 327 +++++++ tools/arch/x86/pmtctl/libpmtctl-core.pc.in | 11 + tools/arch/x86/pmtctl/pmtctl.8 | 317 +++++++ .../x86/pmtctl/samples/libpmtctl_sample.c | 30 + .../x86/pmtctl/scripts/gen_builtin_defs.py | 405 ++++++++ tools/arch/x86/pmtctl/scripts/pmtxml2json.md | 158 ++++ tools/arch/x86/pmtctl/scripts/pmtxml2json.py | 883 ++++++++++++++++++ tools/arch/x86/pmtctl/src/cmd_list.c | 786 ++++++++++++++++ tools/arch/x86/pmtctl/src/cmd_stat.c | 501 ++++++++++ tools/arch/x86/pmtctl/src/cmd_stat_format.c | 205 ++++ tools/arch/x86/pmtctl/src/cmd_stat_run.c | 528 +++++++++++ tools/arch/x86/pmtctl/src/main.c | 151 +++ tools/arch/x86/pmtctl/src/pager.c | 140 +++ 39 files changed, 7148 insertions(+) create mode 100644 tools/arch/x86/pmtctl/Makefile create mode 100644 tools/arch/x86/pmtctl/README.md create mode 100644 tools/arch/x86/pmtctl/include/cmd_stat.h create mode 100644 tools/arch/x86/pmtctl/include/cmd_stat_format.h create mode 100644 tools/arch/x86/pmtctl/include/lib/builtin_defs.h 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/log.h create mode 100644 tools/arch/x86/pmtctl/include/lib/metrics_db.h create mode 100644 tools/arch/x86/pmtctl/include/lib/metrics_provider.h create mode 100644 tools/arch/x86/pmtctl/include/lib/pmt_guid.h create mode 100644 tools/arch/x86/pmtctl/include/lib/pmtctl.h create mode 100644 tools/arch/x86/pmtctl/include/lib/pmtctl_context.h create mode 100644 tools/arch/x86/pmtctl/include/lib/pmtctl_types.h create mode 100644 tools/arch/x86/pmtctl/include/pmtctl_cli.h create mode 100644 tools/arch/x86/pmtctl/lib/Makefile create mode 100644 tools/arch/x86/pmtctl/lib/README create mode 100644 tools/arch/x86/pmtctl/lib/builtin_defs_empty.c 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/log.c create mode 100644 tools/arch/x86/pmtctl/lib/metrics_db.c create mode 100644 tools/arch/x86/pmtctl/lib/metrics_provider.c create mode 100644 tools/arch/x86/pmtctl/lib/metrics_provider_json.c create mode 100644 tools/arch/x86/pmtctl/lib/pmt_guid.c create mode 100644 tools/arch/x86/pmtctl/lib/pmtctl.c create mode 100644 tools/arch/x86/pmtctl/libpmtctl-core.pc.in create mode 100644 tools/arch/x86/pmtctl/pmtctl.8 create mode 100644 tools/arch/x86/pmtctl/samples/libpmtctl_sample.c create mode 100755 tools/arch/x86/pmtctl/scripts/gen_builtin_defs.py create mode 100644 tools/arch/x86/pmtctl/scripts/pmtxml2json.md create mode 100755 tools/arch/x86/pmtctl/scripts/pmtxml2json.py create mode 100644 tools/arch/x86/pmtctl/src/cmd_list.c create mode 100644 tools/arch/x86/pmtctl/src/cmd_stat.c create mode 100644 tools/arch/x86/pmtctl/src/cmd_stat_format.c create mode 100644 tools/arch/x86/pmtctl/src/cmd_stat_run.c create mode 100644 tools/arch/x86/pmtctl/src/main.c create mode 100644 tools/arch/x86/pmtctl/src/pager.c
base-commit: 5200f5f493f79f14bbdc349e402a40dfb32f23c8
Signature · 1 line
2.43.0
PATCH 2/17 tools/arch/x86/pmtctl: Add libpmtctl shared type enumerations
Add pmtctl_types.h to centralize shared libpmtctl type definitions used across both the public and internal library interfaces.
This provides a common definition point for core library-facing types, including device backend classification and logging verbosity levels, avoiding duplication across API boundaries.
--- tools/arch/x86/pmtctl/include/lib/pmtctl_types.h | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 tools/arch/x86/pmtctl/include/lib/pmtctl_types.h
tools/arch/x86/pmtctl/include/lib/pmtctl_types.h new file +16 -0
@@ -0,0 +1,16 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#ifndef PMTCTL_TYPES_H +#define PMTCTL_TYPES_H + +enum pmt_device_type { +PMT_DEVICE_TELEM +}; + +enum pmtctl_log_level { +PMTCTL_LOG_ERROR =0 , +PMTCTL_LOG_WARN , +PMTCTL_LOG_INFO , +PMTCTL_LOG_DEBUG , +}; + +#endif
Signature · 1 line
2.43.0
PATCH 3/17 tools/arch/x86/pmtctl: Add libpmtctl internal logging and utility functions
In reply to David E. BoxAdd the internal logging infrastructure and shared utility helpers used by libpmtctl_core.
The logging layer provides consistent level-filtered diagnostics across the library, while the utility helpers centralize common sysfs access, string handling, and scoped resource cleanup functionality used across backend implementations.
Logging levels mirror the public pmtctl_log_level enum and can be used to control library verbosity.
--- tools/arch/x86/pmtctl/include/lib/common.h | 34 ++++ tools/arch/x86/pmtctl/include/lib/log.h | 80 ++++++++ tools/arch/x86/pmtctl/include/lib/pmt_guid.h | 63 ++++++ tools/arch/x86/pmtctl/lib/common.c | 178 +++++++++++++++++ tools/arch/x86/pmtctl/lib/log.c | 80 ++++++++ tools/arch/x86/pmtctl/lib/pmt_guid.c | 200 +++++++++++++++++++ 6 files changed, 635 insertions(+) create mode 100644 tools/arch/x86/pmtctl/include/lib/common.h create mode 100644 tools/arch/x86/pmtctl/include/lib/log.h create mode 100644 tools/arch/x86/pmtctl/include/lib/pmt_guid.h create mode 100644 tools/arch/x86/pmtctl/lib/common.c create mode 100644 tools/arch/x86/pmtctl/lib/log.c create mode 100644 tools/arch/x86/pmtctl/lib/pmt_guid.c
tools/arch/x86/pmtctl/include/lib/common.h new file +34 -0
@@ -0,0 +1,34 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#ifndef PMTCTL_COMMON_H +#define PMTCTL_COMMON_H + +#include <stdlib.h> +#include <stdio.h> +#include <stdint.h> + +#ifndef __GNUC__ +#error "pmtctl: cleanup helpers require GCC/Clang (__GNUC__)." +#endif + +static inline void freep (void *p) +{ +void **ptr = (void **)p; + +if (*ptr) { +free (*ptr); + *ptr =NULL ; + } +} + +#define auto_free __attribute__((cleanup(freep))) + +#ifndef ARRAY_SIZE +#define ARRAY_SIZE (arr) (sizeof(arr) / sizeof((arr)[0])) +#endif + +char *xstrdup (const char *s); +int read_attr_text (const char *dir,const char *name,char *buf,size_t buflen); +int read_optional_int_attr (const char *devpath,const char *attr,int *out_id); +int read_int_attr (const char *devpath,const char *attr,int *out_id); +int read_u32_hex_attr (const char *devpath,const char *attr,uint32_t *out,int err_invalid); +#endif
tools/arch/x86/pmtctl/include/lib/log.h new file +80 -0
80 lines not on this page · raw message
tools/arch/x86/pmtctl/include/lib/pmt_guid.h new file +63 -0
63 lines not on this page · raw message
tools/arch/x86/pmtctl/lib/common.c new file +178 -0
178 lines not on this page · raw message
tools/arch/x86/pmtctl/lib/log.c new file +80 -0
80 lines not on this page · raw message
tools/arch/x86/pmtctl/lib/pmt_guid.c new file +200 -0
200 lines not on this page · raw message
Signature · 1 line
2.43.0
PATCH 4/17 tools/arch/x86/pmtctl: Add libpmtctl metric definition database
In reply to David E. BoxAdd a growable container for PMT metric definitions to support loading and querying hardware metric descriptors at runtime.
PMT metrics vary by platform and are discovered dynamically from sysfs. A block-based database allows metric definitions to be appended as they are parsed, without requiring the final size to be known in advance, while bounding individual memory allocations.
--- .../arch/x86/pmtctl/include/lib/metrics_db.h | 69 +++++++++++++++++++ tools/arch/x86/pmtctl/lib/metrics_db.c | 62 +++++++++++++++++ 2 files changed, 131 insertions(+) create mode 100644 tools/arch/x86/pmtctl/include/lib/metrics_db.h create mode 100644 tools/arch/x86/pmtctl/lib/metrics_db.c
tools/arch/x86/pmtctl/include/lib/metrics_db.h new file +69 -0
@@ -0,0 +1,69 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#ifndef PMTCTL_METRICS_DB_H +#define PMTCTL_METRICS_DB_H + +#include <stdbool.h> +#include <stddef.h> +#include <stdint.h> + +#include "lib/pmt_guid.h" + +/* Metric definition from builtin or JSON */ +struct pmt_metric_def { +const char *event_name; +const char *description; +const char *group; +const char *platform_group; + +const struct pmt_guid *guid; +uint32_t sample_id; +uint8_t lsb; +uint8_t msb; +}; + +struct pmt_metrics_block { +const struct pmt_metric_def *defs; +int count; +bool is_builtin; +}; + +struct pmt_metrics_db { +struct pmt_metrics_block *blocks; +int nblocks; +int total;/* sum of all block->count */ +}; + +/* Treat DB as a flat array [0..total-1] */ +static inline const struct pmt_metric_def *pmt_metrics_at (const struct pmt_metrics_db *db,int idx) +{ +if (!db || idx <0 || idx >= db->total) +return NULL ; + +for (int i =0 ; i < db->nblocks; i++) { +if (idx < db->blocks[i].count) +return &db->blocks[i].defs[idx]; + idx -= db->blocks[i].count; + } +return NULL ; +} + +static inline const struct pmt_metrics_block * +pmt_metrics_block_for (const struct pmt_metrics_db *db,int idx) +{ +if (!db || idx <0 || idx >= db->total) +return NULL ; + +for (int i =0 ; i < db->nblocks; i++) { +if (idx < db->blocks[i].count) +return &db->blocks[i]; + idx -= db->blocks[i].count; + } + +return NULL ; +} + +int pmt_metrics_add_block (struct pmt_metrics_db *db,const struct pmt_metric_def *defs, +int count,bool is_builtin); +void pmt_metrics_free (struct pmt_metrics_db *db); + +#endif
tools/arch/x86/pmtctl/lib/metrics_db.c new file +62 -0
62 lines not on this page · raw message
Signature · 1 line
2.43.0
PATCH 5/17 tools/arch/x86/pmtctl: Add libpmtctl device enumeration backend
In reply to David E. BoxAdd a sysfs-based backend for enumerating Intel PMT telemetry devices, enabling libpmtctl to discover and access hardware telemetry data at runtime without hardcoded device paths.
Intel PMT telemetry devices are exposed under /sys/bus/auxiliary/drivers/pmt_telemetry. This backend walks those sysfs entries to discover device metadata and data paths, populating per-device descriptors used by the metric access layer.
Introduce a pmt_device_ops vtable to allow additional enumeration backends or PMT transport types to be added without changing the calling code.
--- tools/arch/x86/pmtctl/include/lib/device.h | 53 +++ tools/arch/x86/pmtctl/lib/device_telem.c | 371 +++++++++++++++++++++ 2 files changed, 424 insertions(+) create mode 100644 tools/arch/x86/pmtctl/include/lib/device.h create mode 100644 tools/arch/x86/pmtctl/lib/device_telem.c
tools/arch/x86/pmtctl/include/lib/device.h new file +53 -0
@@ -0,0 +1,53 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#ifndef PMTCTL_DEVICES_H +#define PMTCTL_DEVICES_H + +#include <stdint.h> + +#include "metrics_db.h" +#include "pmtctl_types.h" + +#define PMT_SAMPLE_SIZE 8 + +/* --- Device representation returned by any device --- */ +struct pmt_device { +const struct pmt_guid *guid;/* per-GUID metadata (interned) */ +int guid_inst;/* global guid instance */ +int dev_inst;/* local device instance */ + +char *name;/* e.g. "pmt_ep_27971628_0" or "telem0" */ +char *path;/* e.g. "/sys/class/intel_pmt/telem0" */ +char *data_path;/* readable metric data path for this device */ +int instance;/* 0, 1, etc. */ + +int pkg_id;/* Package/Socket ID if known, else -1 */ +int die_id;/* Die ID if known, else -1 */ + +int fd;/* telem file fd */ +}; + +struct pmt_metric_desc { +const struct pmt_metric_def *def; +struct pmt_device *dev; + +const char *name;/* JSON name */ +int guid_inst;/* global GUID instance (matches pmt_device.guid_inst) */ + +/* raw mode fields */ +uint32_t raw_sample_id; +uint8_t raw_lsb; +uint8_t raw_msb; + +}; + +struct pmt_device_ops { +enum pmt_device_type dev_type; +int (*init)(void ); +void (*cleanup)(void ); +int (*read)(struct pmt_metric_desc *m,uint64_t *val); +struct pmt_device *(*device_list)(int *count); +}; + +extern struct pmt_device_ops device_telem_ops; + +#endif
tools/arch/x86/pmtctl/lib/device_telem.c new file +371 -0
371 lines not on this page · raw message
Signature · 1 line
2.43.0
PATCH 6/17 tools/arch/x86/pmtctl: Add libpmtctl built-in metric provider
In reply to David E. BoxAdd a unified metric definition provider interface to libpmtctl_core, giving callers a single entry point for loading PMT metric definitions regardless of their source.
pmt_metrics_load() abstracts whether definitions come from a built-in table or an external JSON file. When no path is provided, the built-in definitions are loaded. When a path is provided, loading is delegated to the JSON provider when built with HAVE_JANSSON, otherwise PMTCTL_ERR_UNSUPPORTED is returned.
Provide a stub built-in definition table so the library can build and run before platform-specific definitions are generated. In that case, pmt_metrics_load() returns PMTCTL_ERR_NOMETRICS, allowing callers to report a meaningful error.
Add the remaining build-system integration in a later patch to keep the library split into logically separate changes.
--- .../x86/pmtctl/include/lib/builtin_defs.h | 14 +++++++ .../x86/pmtctl/include/lib/metrics_provider.h | 21 ++++++++++ .../arch/x86/pmtctl/lib/builtin_defs_empty.c | 13 ++++++ tools/arch/x86/pmtctl/lib/metrics_provider.c | 42 +++++++++++++++++++ 4 files changed, 90 insertions(+) create mode 100644 tools/arch/x86/pmtctl/include/lib/builtin_defs.h create mode 100644 tools/arch/x86/pmtctl/include/lib/metrics_provider.h create mode 100644 tools/arch/x86/pmtctl/lib/builtin_defs_empty.c create mode 100644 tools/arch/x86/pmtctl/lib/metrics_provider.c
tools/arch/x86/pmtctl/include/lib/builtin_defs.h new file +14 -0
@@ -0,0 +1,14 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#ifndef PMTCTL_BUILTIN_DEFS_H +#define PMTCTL_BUILTIN_DEFS_H + +#include "lib/metrics_db.h" +#include "lib/pmt_guid.h" + +extern const struct pmt_metric_def builtin_defs[]; +extern const int builtin_defs_count; + +extern const struct pmt_guid builtin_guids[]; +extern const int builtin_guids_count; + +#endif
tools/arch/x86/pmtctl/include/lib/metrics_provider.h new file +21 -0
@@ -0,0 +1,21 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#ifndef PMTCTL_METRICS_PROVIDER_H +#define PMTCTL_METRICS_PROVIDER_H + +#include "lib/metrics_db.h" + +/* +* Populate @db with metric definitions. +* +* If @json_path is NULL, the built-in provider is used (definitions linked +* into the library via builtin_defs[]). If @json_path is non-NULL, the JSON +* provider is used; that provider is only available when the library is +* built with HAVE_JANSSON. +*/ +int pmt_metrics_load (const char *json_path,struct pmt_metrics_db *db); + +#ifdef HAVE_JANSSON +int pmt_metrics_load_json (const char *json_path,struct pmt_metrics_db *db); +#endif + +#endif
tools/arch/x86/pmtctl/lib/builtin_defs_empty.c new file +13 -0
@@ -0,0 +1,13 @@ +// SPDX-License-Identifier: GPL-2.0-only +#include "lib/builtin_defs.h" + +/* +* Empty stub used when no generated/builtin_defs.c is present. +* The build system will pick this file unless a generated one exists. +*/ + +const struct pmt_guid builtin_guids[1 ]; +const int builtin_guids_count; + +const struct pmt_metric_def builtin_defs[1 ]; +const int builtin_defs_count;
tools/arch/x86/pmtctl/lib/metrics_provider.c new file +42 -0
42 lines not on this page · raw message
Signature · 1 line
2.43.0
PATCH 7/17 tools/arch/x86/pmtctl: Add libpmtctl JSON metric provider
In reply to David E. BoxAdd an optional JSON-based metric definition provider to libpmtctl_core, allowing PMT metric definitions to be supplied at runtime from external files rather than compiled into the library.
This allows platform-specific metric definitions to be maintained separately from the kernel tree and updated without rebuilding the library. The provider accepts either a single JSON file or a directory of JSON files, loading discovered definitions into the metric database.
When built with HAVE_JANSSON, pmt_metrics_load() dispatches non-NULL path arguments to the JSON provider. Otherwise, PMTCTL_ERR_UNSUPPORTED is returned so callers can detect that JSON-backed loading is unavailable.
Build-system wiring is added in a later patch of the series.
--- .../x86/pmtctl/lib/metrics_provider_json.c | 459 ++++++++++++++++++ 1 file changed, 459 insertions(+) create mode 100644 tools/arch/x86/pmtctl/lib/metrics_provider_json.c
tools/arch/x86/pmtctl/lib/metrics_provider_json.c new file +459 -0
@@ -0,0 +1,459 @@ +// SPDX-License-Identifier: GPL-2.0-only +#define LOG_PREFIX "metrics_provider_json" +#include <dirent.h> +#include <errno.h> +#include <jansson.h> +#include <limits.h> +#include <stdbool.h> +#include <stdlib.h> +#include <string.h> +#include <sys/stat.h> + +#include "lib/log.h" +#include "lib/metrics_db.h" +#include "lib/metrics_provider.h" + +static bool is_regular (const char *path) +{ +struct stat st; + +if (stat (path, &st) <0 ) +return false; + +return !!S_ISREG (st.st_mode); +} + +static bool is_dir (const char *path) +{ +struct stat st; + +if (stat (path, &st) <0 ) +return false; + +return !!S_ISDIR (st.st_mode); +} + +static const char *pool_copy (char **pool,const char *s) +{ +char *dst; +size_t len; + +if (!pool || !s) +return NULL ; + + len =strlen (s) +1 ; + dst = *pool; + +memcpy (dst, s, len); + *pool += len; + +return dst; +} + +/* +* Example PMU name: "pmt_ep_3d4bb41a" +* Extract GUID = 0x3d4bb41a +*/ +static uint32_t parse_guid_from_pmu (const char *pmu) +{ +unsigned long val; +const char *last; +const char *p; +char *end; + +if (!pmu) +return 0 ; + + last =strrchr (pmu,'_' ); + p = last ? last +1 : pmu; + + end =NULL ; + val =strtoul (p, &end,16 ); + +if (end == p || val >0xffffffffUL ) +return 0 ; + +return (uint32_t )val; +} + +/* +* Decode a perf-style ConfigCode string into (sample_id, lsb, msb). +* +* Bit layout (matches scripts/gen_builtin_defs.py::decode_config_code() +* and scripts/pmtxml2json.py::pack_config()): +* +* bits[15:0] sample_id +* bits[23:16] lsb +* bits[31:24] msb +* +* Returns 0 on success, or -EINVAL if the string is malformed or the +* decoded range is out of bounds. A missing ConfigCode (NULL) decodes +* to (0, 0, 0) successfully so callers don't need to special-case it. +*/ +static int parse_config_code (const char *s,uint32_t *sample_id, +uint8_t *lsb,uint8_t *msb) +{ +unsigned long val; +char *end; +uint8_t l, m; + + *sample_id =0 ; + *lsb =0 ; + *msb =0 ; + +if (!s) +return 0 ; + + end =NULL ; + val =strtoul (s, &end,0 ); + +if (end == s || *end !='\0' || val >0xffffffffUL ) +return -EINVAL ; + + l = (val >>16 ) &0xff ; + m = (val >>24 ) &0xff ; + +if (m >63 || l > m) +return -EINVAL ; + + *sample_id = val &0xffff ; + *lsb = l; + *msb = m; +return 0 ; +} + +static int json_count_root (json_t *root,size_t *metric_count,size_t *string_bytes) +{ +size_t n; + +if (!json_is_array (root)) +return -EINVAL ; + + n =json_array_size (root); + +for (size_t i =0 ; i < n; i++) { +const char *name, *brief, *group, *platform_group; +json_t *ev; + + ev =json_array_get (root, i); + +if (!json_is_object (ev)) +continue ; + + name =json_string_value (json_object_get (ev,"EventName" )); + brief =json_string_value (json_object_get (ev,"BriefDescription" )); + group =json_string_value (json_object_get (ev,"MetricGroup" )); + platform_group =json_string_value (json_object_get (ev,"PlatformGroup" )); + +if (name) + *string_bytes +=strlen (name) +1 ; +if (brief) + *string_bytes +=strlen (brief) +1 ; +if (group) + *string_bytes +=strlen (group) +1 ; +if (platform_group) + *string_bytes +=strlen (platform_group) +1 ; + + (*metric_count)++; + } + +if (*metric_count ==0 ) +return PMTCTL_ERR_NOMETRICS ; + +return 0 ; +} + +static int json_fill_root (json_t *root,struct pmt_metric_def *defs,char **pool) +{ +int idx =0 ; +size_t n; + +if (!json_is_array (root)) +return -EINVAL ; + + n =json_array_size (root); + +for (size_t i =0 ; i < n; i++) { +const char *pmu, *name, *brief, *group, *platform_group, *cfg; +json_t *ev; +struct pmt_metric_def *m; +int ret; + + ev =json_array_get (root, i); + +if (!json_is_object (ev)) +continue ; + + m = &defs[idx++]; + + pmu =json_string_value (json_object_get (ev,"PMU" )); + name =json_string_value (json_object_get (ev,"EventName" )); + brief =json_string_value (json_object_get (ev,"BriefDescription" )); + group =json_string_value (json_object_get (ev,"MetricGroup" )); + platform_group =json_string_value (json_object_get (ev,"PlatformGroup" )); + cfg =json_string_value (json_object_get (ev,"ConfigCode" )); + + m->event_name =pool_copy (pool, name); + m->description =pool_copy (pool, brief); + m->group =pool_copy (pool, group); + m->platform_group =pool_copy (pool, platform_group); + m->guid =pmt_guid_intern (parse_guid_from_pmu (pmu)); +if (!m->guid) +return -ENOMEM ; + + ret =parse_config_code (cfg, &m->sample_id, &m->lsb, &m->msb); +if (ret) +return log_ret (ret,"metric \"%s\" (PMU %s): invalid ConfigCode \"%s\"" , + name ? name :"(null)" , + pmu ? pmu :"(null)" , + cfg ? cfg :"(null)" ); + } + +return 0 ; +} + +static struct pmt_metric_def *load_metrics_from_json_single (const char *path,int *count) +{ +json_error_t error; +json_t *root; +struct pmt_metric_def *defs; +void *block; +char *pool; +size_t metric_count =0 ; +size_t string_bytes =0 ; +size_t def_bytes; +size_t total_bytes; +int ret; + +if (!count) +return NULL ; + + *count =0 ; + + root =json_load_file (path,0 , &error); +if (!root) { +log_err (PMTCTL_ERR_METRICS ,"JSON parse error in %s: %s\n" , path, error.text); +return NULL ; + } + + ret =json_count_root (root, &metric_count, &string_bytes); +if (ret <0 ) { +json_decref (root); +return NULL ; + } + + def_bytes = metric_count *sizeof (struct pmt_metric_def ); + total_bytes = def_bytes + string_bytes; + + block =malloc (total_bytes); +if (!block) { +json_decref (root); +return NULL ; + } + + defs = block; +memset (defs,0 , def_bytes); + pool = (char *)block + def_bytes; + + ret =json_fill_root (root, defs, &pool); +json_decref (root); +if (ret <0 ) { +free (block); +return NULL ; + } + + *count = (int )metric_count; + +return defs; +} + +static int load_pmt_guids_sidecar (const char *path) +{ +json_error_t error; +json_t *root; +struct pmt_guid *table; +char *pool; +size_t string_bytes =0 ; +size_t n; +int ret = -EINVAL ; + + root =json_load_file (path,0 , &error); +if (!root) { +log_warn ("pmt_guids JSON parse error in %s: %s\n" , path, error.text); +return -EINVAL ; + } + +if (!json_is_array (root)) { +json_decref (root); +return -EINVAL ; + } + + n =json_array_size (root); +if (n ==0 ) { +json_decref (root); +return 0 ; + } + +for (size_t i =0 ; i < n; i++) { +json_t *e =json_array_get (root, i); +const char *s; + +if (!json_is_object (e)) +continue ; + s =json_string_value (json_object_get (e,"name" )); +if (s) + string_bytes +=strlen (s) +1 ; + s =json_string_value (json_object_get (e,"description" )); +if (s) + string_bytes +=strlen (s) +1 ; + } + + table =calloc (1 , n *sizeof (*table) + string_bytes); +if (!table) { +json_decref (root); +return -ENOMEM ; + } + + pool = (char *)table + n *sizeof (*table); + +for (size_t i =0 ; i < n; i++) { +json_t *e =json_array_get (root, i); +const char *guid_s, *name, *desc; +unsigned long guid_val; +char *end; + +if (!json_is_object (e)) +continue ; + + guid_s =json_string_value (json_object_get (e,"guid" )); +if (!guid_s) +continue ; + + errno =0 ; + guid_val =strtoul (guid_s, &end,0 ); +if (errno || end == guid_s || *end !='\0' || guid_val >UINT32_MAX ) +continue ; + + name =json_string_value (json_object_get (e,"name" )); + desc =json_string_value (json_object_get (e,"description" )); + + table[i].guid = (uint32_t )guid_val; + table[i].name = name ?pool_copy (&pool, name) :NULL ; + table[i].description = desc ?pool_copy (&pool, desc) :NULL ; + } + + ret =pmt_guid_register_owned (table, table, (int )n); + +json_decref (root); +if (ret <0 ) +free (table); + +return ret; +} + +static int load_metrics_from_json_dir (const char *dir_path,struct pmt_metrics_db *db) +{ +DIR *d =opendir (dir_path); +struct dirent *de; +char guids_path[PATH_MAX ]; +int len; +int ret =0 ; + +if (!d) +return log_ret (-errno,"could not open %s" , dir_path); + +/* +* Load the optional pmt_guids.json sidecar first so any subsequent +* intern calls in json_fill_root() resolve to the registered +* struct pmt_guid entries (with name/description populated). +*/ + len =snprintf (guids_path,sizeof (guids_path),"%s/%s" , dir_path,"pmt_guids.json" ); +if (len >0 && (size_t )len <sizeof (guids_path) &&is_regular (guids_path)) + (void )load_pmt_guids_sidecar (guids_path); + +while ((de =readdir (d)) !=NULL ) { +struct pmt_metric_def *defs; +const char *name = de->d_name; +const char *dot =strrchr (name,'.' ); +char pathbuf[PATH_MAX ]; +int count =0 ; + +if (name[0 ] =='.' ) +continue ; + +if (!dot ||strcmp (dot,".json" )) +continue ; + +/* Sidecar already handled above. */ +if (!strcmp (name,"pmt_guids.json" )) +continue ; + +if (snprintf (pathbuf,sizeof (pathbuf),"%s/%s" , dir_path, name) >= + (int )sizeof (pathbuf)) +continue ; +if (!is_regular (pathbuf)) +continue ; + + defs =load_metrics_from_json_single (pathbuf, &count); +if (!defs) { +log_warn ("unable to load JSON %s\n" , pathbuf); + ret = -EINVAL ; +continue ; + } + + ret =pmt_metrics_add_block (db, defs, count, false); +if (ret <0 ) { +free (defs); +log_ret (ret,"unable to add json %s" , pathbuf); +break ; + } + } +closedir (d); + +if (ret <0 ) { +pmt_metrics_free (db); +return ret; + } + +/* +* Successfully scanned the directory. A zero count is reported via +* db->total == 0 to the caller; the dir itself was not broken, so +* do not invent an error rc here. pmtctl_init() distinguishes +* "broken source" (negative rc) from "empty source" (rc == 0 with +* db->total == 0) and only fails the init in the former case. +*/ +return 0 ; +} + +int pmt_metrics_load_json (const char *json_path,struct pmt_metrics_db *db) +{ +int ret; + +if (!db) +log_bug_and_exit ("invalid metric db pointer" ); + +if (!json_path) +return PMTCTL_ERR_METRICS ; + +if (is_regular (json_path)) { +struct pmt_metric_def *defs; +int count =0 ; + + defs =load_metrics_from_json_single (json_path, &count); +if (!defs) +return log_ret (PMTCTL_ERR_METRICS ,"unable to load json %s" , json_path); + + ret =pmt_metrics_add_block (db, defs, count, false); +if (ret <0 ) { +free (defs); +return log_ret (ret,"unable to add json %s" , json_path); + } + +return 0 ; + } + +if (is_dir (json_path)) +return load_metrics_from_json_dir (json_path, db); + +return PMTCTL_ERR_METRICS ; +}
Signature · 1 line
2.43.0
PATCH 8/17 tools/arch/x86/pmtctl: Add libpmtctl public API and context
In reply to David E. BoxAdd the public API for libpmtctl_core and the context object that backs it, providing callers with a stable, opaque interface for discovering Intel PMT telemetry devices and querying their metrics without depending on internal library structures.
This patch adds the primary lifecycle and query interfaces used by library consumers. pmtctl_init() performs device enumeration and metric database loading once during initialization so subsequent queries operate on cached state rather than re-scanning sysfs. pmtctl_cleanup() releases associated resources.
The library context (struct pmtctl_context) remains opaque to callers. pmtctl_get_ctx() provides controlled access for consumers that need to pass library context across translation units.
Add PMTCTL_SCOPE_GUARD() as a convenience macro for deterministic cleanup of library-managed resources in single-exit C code paths.
Build-system wiring is added a later patch of the series.
--- tools/arch/x86/pmtctl/include/lib/pmtctl.h | 90 +++++ .../x86/pmtctl/include/lib/pmtctl_context.h | 21 ++ tools/arch/x86/pmtctl/lib/pmtctl.c | 327 ++++++++++++++++++ 3 files changed, 438 insertions(+) create mode 100644 tools/arch/x86/pmtctl/include/lib/pmtctl.h create mode 100644 tools/arch/x86/pmtctl/include/lib/pmtctl_context.h create mode 100644 tools/arch/x86/pmtctl/lib/pmtctl.c
tools/arch/x86/pmtctl/include/lib/pmtctl.h new file +90 -0
@@ -0,0 +1,90 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#ifndef PMTCTL_H +#define PMTCTL_H + +#include <stdbool.h> +#include <stdint.h> + +#include <linux/compiler.h> +#include "pmtctl_types.h" + +enum pmt_selector_kind { +PMT_SEL_ANY =0 ,/* no selector provided */ +PMT_SEL_GUID ,/* guid=27971628 */ +PMT_SEL_EP_NAME ,/* ep=pmt_ep_27971628_0 OR ep=telem1 */ +}; + +struct pmt_ep_selector { +enum pmt_selector_kind kind; + +uint32_t guid; + +/* For SEL_EP_NAME */ +const char *str; +}; + +struct pmt_binding { +int metric_idx;/* index into defs[] */ +int device_idx;/* index into devices[] */ +}; + +struct pmtctl_context ; + +struct pmt_global_opts { +const char *json_path;/* -J / --json-file */ +const char *device_selector;/* -d / --device (raw) */ +bool quiet;/* -q / --quiet */ +bool debug;/* --debug */ +}; + +/* +* Initialize library-global PMT state. +* +* This may return success even if no metric definitions are available. +* In that case, device enumeration is still usable and raw mode remains +* supported (raw reads do not require metric definitions). +*/ +int pmtctl_init (const struct pmt_global_opts *gopts); +const struct pmtctl_context *pmtctl_get_ctx (void ); +enum pmt_device_type pmtctl_get_device_type (void ); +int pmtctl_get_num_devices (void ); +int pmtctl_get_num_metrics (void ); +int pmtctl_get_num_bindings (void ); + +/* +* Set process-global library logging verbosity. +* +* Invalid values are clamped to PMTCTL_LOG_INFO. +*/ +void pmtctl_set_log_level (enum pmtctl_log_level level); + +/* +* Thread-safety note: +* +* libpmtctl_core is generally not thread-safe. Callers should serialize +* pmtctl_init()/pmtctl_cleanup() and API usage around shared library state. +*/ +void pmtctl_cleanup (void ); + +static inline __always_unused void pmtctl_scope_cleanup (int *unused) +{ + (void )unused; +pmtctl_cleanup (); +} + +#define PMTCTL_SCOPE_GUARD \ + __attribute__((cleanup(pmtctl_scope_cleanup))) \ + int _pmtctl_scope_guard __always_unused \ + +int pmt_select_devices (const struct pmtctl_context *ctx,const struct pmt_ep_selector *sel, +int *out_idx,int max_out); + +/* +* Parse an ep selector string like "guid=27971628" or "ep=pmt_ep_...". +* For selectors that set a string (ep/name) the implementation will +* allocate a copy into sel->str; the caller is responsible for freeing +* sel->str if non-NULL. +*/ +int pmtctl_parse_ep_selector (const char *s,struct pmt_ep_selector *out); + +#endif
tools/arch/x86/pmtctl/include/lib/pmtctl_context.h new file +21 -0
@@ -0,0 +1,21 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#ifndef PMTCTL_CONTEXT_H +#define PMTCTL_CONTEXT_H + +#include "lib/device.h" +#include "lib/metrics_db.h" +#include "lib/pmtctl.h" + +struct pmtctl_context { +const struct pmt_device_ops *ops; + +struct pmt_device *devices; +int num_devices; + +struct pmt_metrics_db metrics; + +struct pmt_binding *bindings; +int num_bindings; +}; + +#endif
tools/arch/x86/pmtctl/lib/pmtctl.c new file +327 -0
327 lines not on this page · raw message
Signature · 1 line
2.43.0
PATCH 9/17 tools/arch/x86/pmtctl: Add libpmtctl Makefile + pc + README
In reply to David E. BoxAdd build infrastructure for libpmtctl_core, allowing the library to be built standalone and consumed by downstream tools via pkg-config.
Provide separate release and debug build variants so optimized and development builds can coexist within the same checkout without overwriting each other.
JSON metric definition support is optional at build time. When built with HAVE_JANSSON, the JSON metric provider is enabled and linked against libjansson. Otherwise, JSON-backed metric loading remains unavailable and pmt_metrics_load() returns PMTCTL_ERR_UNSUPPORTED for non-NULL path arguments.
Add a pkg-config template for discovering the library's compile and link flags, along with a README describing the library purpose and build options.
--- tools/arch/x86/pmtctl/lib/Makefile | 108 +++++++++++++++++++ tools/arch/x86/pmtctl/lib/README | 116 +++++++++++++++++++++ tools/arch/x86/pmtctl/libpmtctl-core.pc.in | 11 ++ 3 files changed, 235 insertions(+) create mode 100644 tools/arch/x86/pmtctl/lib/Makefile create mode 100644 tools/arch/x86/pmtctl/lib/README create mode 100644 tools/arch/x86/pmtctl/libpmtctl-core.pc.in
tools/arch/x86/pmtctl/lib/Makefile new file +108 -0
@@ -0,0 +1,108 @@ +# SPDX-License-Identifier: GPL-2.0-only + +CC := gcc +AR := ar +RANLIB := ranlib + +BUILD ?= release + +CPPFLAGS += -I../include -I../../../../include -D_GNU_SOURCE +CFLAGS += -std=gnu11 -Wall -Wextra + +WEXTRA_WARN := -Wpedantic -Wmissing-prototypes -Wstrict-prototypes \ + -Wunused-function -Wunused-variable -Wunused-parameter \ + -Wunused-but-set-variable -Wunreachable-code + +ifeq ($(BUILD),debug) + CFLAGS += -O0 -g3 -fno-omit-frame-pointer + CFLAGS += $(WEXTRA_WARN) + CPPFLAGS += -DDEBUG +else ifeq ($(BUILD),release) + CFLAGS += -O2 -g0 -DNDEBUG +else + $(error unknown BUILD '$(BUILD)' (use release or debug)) +endif + +BUILDDIR := ../build/$(BUILD)/lib +CORE_TARGET := $(BUILDDIR)/libpmtctl_core.a + +CORE_SRC := \ + log.c \ + common.c \ + device_telem.c \ + metrics_db.c \ + pmt_guid.c \ + pmtctl.c \ + metrics_provider.c \ + builtin_defs_empty.c + +HAVE_JANSSON ?= 0 +ifeq ($(HAVE_JANSSON),1) + CORE_SRC += metrics_provider_json.c + CPPFLAGS += -DHAVE_JANSSON + LDLIBS += -ljansson +endif + +CORE_OBJ := $(patsubst %.c,$(BUILDDIR)/%.o,$(CORE_SRC)) + +PREFIX ?= /usr/local +DESTDIR ?= +INCLUDEDIR ?= $(PREFIX)/include/pmtctl +LIBINSTALLDIR ?= $(PREFIX)/lib +PKGCONFIGDIR ?= $(LIBINSTALLDIR)/pkgconfig + +PC_CORE := ../libpmtctl-core.pc +PC_FILES := $(PC_CORE) + +PUBLIC_HEADERS := \ + ../include/lib/pmtctl.h \ + ../include/lib/metrics_db.h \ + ../include/lib/pmt_guid.h \ + ../include/lib/device.h + +.PHONY: all clean install install-lib install-headers install-pkgconfig uninstall uninstall-lib uninstall-headers uninstall-pkgconfig + +all: $(CORE_TARGET) + +$(CORE_TARGET): $(CORE_OBJ) + $(AR) rcs $@ $(CORE_OBJ) + $(RANLIB) $@ + +$(PC_CORE): ../libpmtctl-core.pc.in + @sed -e 's|@PREFIX@|$(PREFIX)|g' \ + -e 's|@JANSSON_LIBS@|$(if $(filter 1,$(HAVE_JANSSON)), -ljansson,)|g' \ + $< > $@ + +$(BUILDDIR)/%.o: %.c + @mkdir -p $(BUILDDIR) + $(CC) $(CPPFLAGS) $(CFLAGS) -c $< -o $@ + +install: all install-lib install-headers install-pkgconfig + +install-lib: all + install -d $(DESTDIR)$(LIBINSTALLDIR) + install -m 0644 $(CORE_TARGET) $(DESTDIR)$(LIBINSTALLDIR) + +install-headers: + install -d $(DESTDIR)$(INCLUDEDIR) + install -m 0644 $(PUBLIC_HEADERS) $(DESTDIR)$(INCLUDEDIR) + +install-pkgconfig: $(PC_FILES) + install -d $(DESTDIR)$(PKGCONFIGDIR) + install -m 0644 $(PC_FILES) $(DESTDIR)$(PKGCONFIGDIR) + +uninstall: uninstall-lib uninstall-headers uninstall-pkgconfig + +uninstall-lib: + rm -f $(DESTDIR)$(LIBINSTALLDIR)/libpmtctl_core.a + +uninstall-headers: + rm -f $(DESTDIR)$(INCLUDEDIR)/pmtctl.h + rm -f $(DESTDIR)$(INCLUDEDIR)/metrics_db.h + rm -f $(DESTDIR)$(INCLUDEDIR)/device.h + +uninstall-pkgconfig: + rm -f $(DESTDIR)$(PKGCONFIGDIR)/libpmtctl-core.pc + +clean: + rm -rf $(BUILDDIR) $(PC_FILES)
tools/arch/x86/pmtctl/lib/README new file +116 -0
116 lines not on this page · raw message
tools/arch/x86/pmtctl/libpmtctl-core.pc.in new file +11 -0
@@ -0,0 +1,11 @@ +# SPDX-License-Identifier: GPL-2.0-only +prefix=@PREFIX@ +exec_prefix=${prefix} +libdir=${exec_prefix}/lib +includedir=${prefix}/include + +Name: libpmtctl-core +Description: Intel PMT core access library (transport/enumeration/bindings) +Version: 0.1 +Libs: -L${libdir} -lpmtctl_core @JANSSON_LIBS@ +Cflags: -I${includedir}/pmtctl
Signature · 1 line
2.43.0
PATCH 10/17 tools/arch/x86/pmtctl: Add libpmtctl usage sample
In reply to David E. BoxAdd a small sample program under samples/ that demonstrates how an out-of-tree consumer links against libpmtctl, plus the corresponding 'sample' Makefile target.
--- .../x86/pmtctl/samples/libpmtctl_sample.c | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 tools/arch/x86/pmtctl/samples/libpmtctl_sample.c
tools/arch/x86/pmtctl/samples/libpmtctl_sample.c new file +30 -0
@@ -0,0 +1,30 @@ +// SPDX-License-Identifier: GPL-2.0-only +#include <stdio.h> + +#include "pmtctl.h" + +int main (void ) +{ +struct pmt_global_opts opts = { + .json_path =NULL , + .device_selector =NULL , + .quiet = false, + .debug = false, + }; +int ret; + + ret =pmtctl_init (&opts); +if (ret !=0 ) { +fprintf (stderr,"pmtctl_init failed: %d\n" , ret); +return 1 ; + } + +printf ("devices=%d metrics=%d bindings=%d\n" , +pmtctl_get_num_devices (), +pmtctl_get_num_metrics (), +pmtctl_get_num_bindings ()); + +pmtctl_cleanup (); + +return 0 ; +}
Signature · 1 line
2.43.0
PATCH 11/17 tools/arch/x86/pmtctl: Add libpmtctl built-in metric definition support
In reply to David E. BoxAdd support for compiling PMT metric definitions directly into libpmtctl_core so tools can operate without requiring external JSON definition files at runtime.
Built-in definitions avoid a runtime dependency on host filesystem data by embedding generated metric definition tables directly into the library. When no path argument is provided, pmt_metrics_load() serves definitions from the built-in table.
Add a Python generator script to convert defs/*.json into a generated C definition table used by the library build. An empty stub table remains available for builds where generation is skipped, preserving the existing runtime contract where pmt_metrics_load() returns PMTCTL_ERR_NOMETRICS when no definitions are present.
Add a top-level 'make defs' target and update the README and CLI documentation to describe the built-in definition workflow.
--- tools/arch/x86/pmtctl/lib/Makefile | 34 +- .../x86/pmtctl/scripts/gen_builtin_defs.py | 405 ++++++++++++++++++ 2 files changed, 437 insertions(+), 2 deletions(-) create mode 100755 tools/arch/x86/pmtctl/scripts/gen_builtin_defs.py
tools/arch/x86/pmtctl/lib/Makefile +32 -2
@@ -1,5 +1,9 @@ # SPDX-License-Identifier: GPL-2.0-only +# Remove targets whose recipe exited non-zero so a failed codegen step +# does not leave a truncated $@ behind that fools the next build. +.DELETE_ON_ERROR: + CC := gcc AR := ar RANLIB := ranlib
@@ -33,8 +37,7 @@ CORE_SRC := \ metrics_db.c \ pmt_guid.c \ pmtctl.c \ - metrics_provider.c \ - builtin_defs_empty.c + metrics_provider.c HAVE_JANSSON ?= 0 ifeq ($(HAVE_JANSSON),1)
@@ -45,6 +48,17 @@ endif CORE_OBJ := $(patsubst %.c,$(BUILDDIR)/%.o,$(CORE_SRC)) +# Built-in metric definitions: use the generated table when available, +# otherwise fall back to the empty stub. Both sources export builtin_defs[] +# and builtin_defs_count and are compiled to a fixed object name so the +# choice is transparent to the rest of the library. +# Use 'find' (recursive) to match the top-level Makefile; $(wildcard) would +# silently miss any JSON files placed in defs/ subdirectories. +DEFS_JSON ?= $(shell find ../defs -name '*.json' 2>/dev/null) +BUILTIN_DEFS_SRC := $(if $(wildcard ../generated/builtin_defs.c),../generated/builtin_defs.c,builtin_defs_empty.c) +BUILTIN_DEFS_OBJ := $(BUILDDIR)/builtin_defs.o +CORE_OBJ += $(BUILTIN_DEFS_OBJ) + PREFIX ?= /usr/local DESTDIR ?= INCLUDEDIR ?= $(PREFIX)/include/pmtctl
@@ -77,6 +91,22 @@ $(BUILDDIR)/%.o: %.c @mkdir -p $(BUILDDIR) $(CC) $(CPPFLAGS) $(CFLAGS) -c $< -o $@ +$(BUILTIN_DEFS_OBJ): $(BUILTIN_DEFS_SRC) + @mkdir -p $(BUILDDIR) + $(CC) $(CPPFLAGS) $(CFLAGS) -c $< -o $@ + +../generated/builtin_defs.c: ../scripts/gen_builtin_defs.py $(DEFS_JSON) + @mkdir -p ../generated + @if [ -z "$(DEFS_JSON)" ]; then \ + echo "No JSON files in defs/. Nothing to generate."; \ + else \ + if ! command -v python3 >/dev/null 2>&1; then \ + echo "python3 is required to generate builtin defs but was not found." >&2; \ + exit 1; \ + fi; \ + python3 ../scripts/gen_builtin_defs.py $(DEFS_JSON) > $@; \ + fi + install: all install-lib install-headers install-pkgconfig install-lib: all
tools/arch/x86/pmtctl/scripts/gen_builtin_defs.py new file +405 -0
405 lines not on this page · raw message
Signature · 1 line
2.43.0
PATCH 12/17 tools/arch/x86/pmtctl: Add pmtctl CLI entry point and pager
In reply to David E. BoxAdd the pmtctl command-line frontend, a user-facing binary built on top of libpmtctl_core for discovering and inspecting Intel PMT telemetry devices.
Add a built-in pager so wide or lengthy telemetry output remains readable without requiring users to pipe output through an external pager. The pager is automatically disabled when output is redirected, preserving scriptability.
This patch establishes the shared CLI infrastructure and global option handling used by later subcommands. Subsequent patches add the 'list' and 'stat' commands for device enumeration and live telemetry sampling.
Add top-level Makefile integration so a single 'make' invocation builds both the library and CLI.
--- tools/arch/x86/pmtctl/Makefile | 114 +++++++++++++++++ tools/arch/x86/pmtctl/include/pmtctl_cli.h | 12 ++ tools/arch/x86/pmtctl/src/main.c | 134 ++++++++++++++++++++ tools/arch/x86/pmtctl/src/pager.c | 140 +++++++++++++++++++++ 4 files changed, 400 insertions(+) create mode 100644 tools/arch/x86/pmtctl/Makefile create mode 100644 tools/arch/x86/pmtctl/include/pmtctl_cli.h create mode 100644 tools/arch/x86/pmtctl/src/main.c create mode 100644 tools/arch/x86/pmtctl/src/pager.c
tools/arch/x86/pmtctl/Makefile new file +114 -0
@@ -0,0 +1,114 @@ +# SPDX-License-Identifier: GPL-2.0-only + +CC ?= gcc + +BUILD ?= release + +CPPFLAGS += -Iinclude -Ilib -I../../../include -D_GNU_SOURCE +CFLAGS += -std=gnu11 -Wall -Wextra + +WEXTRA_WARN := -Wpedantic -Wmissing-prototypes -Wstrict-prototypes \ + -Wunused-function -Wunused-variable -Wunused-parameter \ + -Wunused-but-set-variable -Wunreachable-code + +ifeq ($(BUILD),debug) + CFLAGS += -O0 -g3 -fno-omit-frame-pointer + CFLAGS += $(WEXTRA_WARN) + CPPFLAGS += -DDEBUG +else ifeq ($(BUILD),release) + CFLAGS += -O2 -g0 -DNDEBUG +else + $(error unknown BUILD '$(BUILD)' (use release or debug)) +endif + +JANSSON_CFLAGS := $(shell pkg-config --cflags jansson 2>/dev/null) +JANSSON_LIBS := $(shell pkg-config --libs jansson 2>/dev/null) +ifeq ($(JANSSON_LIBS),) + $(error jansson not found: install libjansson-dev (Debian/Ubuntu) or jansson-devel (Fedora/RHEL)) +endif +CPPFLAGS += $(JANSSON_CFLAGS) +LDLIBS := $(JANSSON_LIBS) -lm + +SRCDIR := src +BUILDDIR:= build/$(BUILD) +TARGET := pmtctl +LIBDIR := lib +LIBPMTCTL_CORE := $(BUILDDIR)/lib/libpmtctl_core.a +LIBPMTCTL_ARTIFACTS := $(LIBPMTCTL_CORE) +LIBPMTCTL_STAMP := $(BUILDDIR)/lib/.built +SAMPLE_SRC := samples/libpmtctl_sample.c +SAMPLE_TARGET := $(BUILDDIR)/samples/libpmtctl_sample + +SRC := \ + $(SRCDIR)/main.c \ + $(SRCDIR)/pager.c + +OBJ := $(patsubst $(SRCDIR)/%.c,$(BUILDDIR)/%.o,$(SRC)) +CLEAN_BUILDS := release debug + +.PHONY: all clean libpmtctl_core sample FORCE + +all: $(TARGET) + +$(TARGET): $(OBJ) $(LIBPMTCTL_ARTIFACTS) + $(CC) $(CFLAGS) -o $@ $(OBJ) $(LIBPMTCTL_ARTIFACTS) $(LDLIBS) + +libpmtctl_core: $(LIBPMTCTL_CORE) + +sample: $(SAMPLE_TARGET) + +# Build the sample with the public-header search path only, so its +# `#include "pmtctl.h"` resolves the same way it would for an external +# consumer linking against the installed libpmtctl_core. +$(SAMPLE_TARGET): CPPFLAGS += -Iinclude/lib +$(SAMPLE_TARGET): $(SAMPLE_SRC) $(LIBPMTCTL_ARTIFACTS) + @mkdir -p $(dir $@) + $(CC) $(CPPFLAGS) $(CFLAGS) -o $@ $< $(LIBPMTCTL_ARTIFACTS) $(LDLIBS) + +$(LIBPMTCTL_ARTIFACTS): $(LIBPMTCTL_STAMP) + +$(LIBPMTCTL_STAMP): FORCE + $(MAKE) -C $(LIBDIR) BUILD=$(BUILD) + @mkdir -p $(dir $@) + @touch $@ + +FORCE: + +# Install settings +PREFIX ?= /usr/local +DESTDIR ?= + + +.PHONY: install uninstall install-lib install-headers install-pkgconfig uninstall-lib uninstall-headers uninstall-pkgconfig + +install: $(TARGET) install-lib install-headers install-pkgconfig + install -d $(DESTDIR)$(PREFIX)/bin + install -m 0755 $(TARGET) $(DESTDIR)$(PREFIX)/bin + @echo "Installed $(TARGET) to $(DESTDIR)$(PREFIX)/bin/" + +install-lib: + $(MAKE) -C $(LIBDIR) BUILD=$(BUILD) PREFIX=$(PREFIX) DESTDIR=$(DESTDIR) install-lib + +install-headers: + $(MAKE) -C $(LIBDIR) BUILD=$(BUILD) PREFIX=$(PREFIX) DESTDIR=$(DESTDIR) install-headers + +install-pkgconfig: + $(MAKE) -C $(LIBDIR) BUILD=$(BUILD) PREFIX=$(PREFIX) DESTDIR=$(DESTDIR) install-pkgconfig + +uninstall: + rm -f $(DESTDIR)$(PREFIX)/bin/$(TARGET) + $(MAKE) -C $(LIBDIR) BUILD=$(BUILD) PREFIX=$(PREFIX) DESTDIR=$(DESTDIR) uninstall-lib + $(MAKE) -C $(LIBDIR) BUILD=$(BUILD) PREFIX=$(PREFIX) DESTDIR=$(DESTDIR) uninstall-headers + $(MAKE) -C $(LIBDIR) BUILD=$(BUILD) PREFIX=$(PREFIX) DESTDIR=$(DESTDIR) uninstall-pkgconfig + @echo "Removed $(DESTDIR)$(PREFIX)/bin/$(TARGET) (if present)" + +$(BUILDDIR)/%.o: $(SRCDIR)/%.c + @mkdir -p $(BUILDDIR) + $(CC) $(CPPFLAGS) $(CFLAGS) -c $< -o $@ + +clean: + @for build_type in $(CLEAN_BUILDS); do \ + $(MAKE) -C $(LIBDIR) BUILD=$$build_type clean; \ + rm -rf build/$$build_type; \ + done + rm -rf $(BUILDDIR) $(TARGET)
tools/arch/x86/pmtctl/include/pmtctl_cli.h new file +12 -0
@@ -0,0 +1,12 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#ifndef PMTCTL_CLI_H +#define PMTCTL_CLI_H + +#include <stdio.h> + +#include "lib/pmtctl.h" + +FILE *pmtctl_start_pager (const struct pmt_global_opts *gopts); +void pmtctl_finish_pager (FILE *out); + +#endif
tools/arch/x86/pmtctl/src/main.c new file +134 -0
134 lines not on this page · raw message
tools/arch/x86/pmtctl/src/pager.c new file +140 -0
140 lines not on this page · raw message
Signature · 1 line
2.43.0
PATCH 13/17 tools/arch/x86/pmtctl: Add pmtctl 'list' command
In reply to David E. BoxRegister the 'list' subcommand in the CLI dispatcher and add its implementation in src/cmd_list.c. The command enumerates PMT devices and metrics, with optional filtering by GUID or endpoint name.
Per-command --help, JSON output, and tabular formatting are handled locally inside cmd_list.
--- tools/arch/x86/pmtctl/Makefile | 1 + tools/arch/x86/pmtctl/include/pmtctl_cli.h | 2 + tools/arch/x86/pmtctl/src/cmd_list.c | 786 +++++++++++++++++++++ tools/arch/x86/pmtctl/src/main.c | 13 + 4 files changed, 802 insertions(+) create mode 100644 tools/arch/x86/pmtctl/src/cmd_list.c
tools/arch/x86/pmtctl/Makefile +1 -0
@@ -41,6 +41,7 @@ SAMPLE_TARGET := $(BUILDDIR)/samples/libpmtctl_sample SRC := \ $(SRCDIR)/main.c \ + $(SRCDIR)/cmd_list.c \ $(SRCDIR)/pager.c OBJ := $(patsubst $(SRCDIR)/%.c,$(BUILDDIR)/%.o,$(SRC))
tools/arch/x86/pmtctl/include/pmtctl_cli.h +2 -0
@@ -9,4 +9,6 @@FILE *pmtctl_start_pager (const struct pmt_global_opts *gopts);void pmtctl_finish_pager (FILE *out); +int cmd_list (int argc,char **argv,const struct pmt_global_opts *gopts); +#endif
tools/arch/x86/pmtctl/src/cmd_list.c new file +786 -0
786 lines not on this page · raw message
tools/arch/x86/pmtctl/src/main.c +13 -0
@@ -42,6 +42,11 @@ static void print_usage(FILE *out)"\n" " -q, --quiet Suppress non-essential messages\n" " --debug Enable debug logging\n" +"\n" +"Commands:\n" +" list List available PMT devices and metrics\n" +"\n" +"Run 'pmtctl <command> --help' for command-specific options.\n" ); }
@@ -64,6 +69,8 @@ static int cmd_dispatch(int argc, char **argv)const char *cmd;int option_index =0 ;int opt; +int cmd_argc; +char **cmd_argv;while ((opt =getopt_long (argc, argv,"+hVJ:qd:" , long_options, &option_index)) !=-1 ) {switch (opt) {
@@ -103,6 +110,12 @@ static int cmd_dispatch(int argc, char **argv) } cmd = argv[optind]; + cmd_argc = argc - optind; + cmd_argv = &argv[optind]; + +if (!strcmp (cmd,"list" )) +return cmd_list (cmd_argc, cmd_argv, &gopts); +if (!strcmp (cmd,"--help" ) || !strcmp (cmd,"help" )) {print_usage (stdout);return 0 ;
Signature · 1 line
2.43.0
PATCH 14/17 tools/arch/x86/pmtctl: Add pmtctl 'stat' command
In reply to David E. BoxRegister the 'stat' subcommand, giving pmtctl users a perf stat-like mode for repeatedly sampling Intel PMT telemetry metrics at a configurable interval and iteration count. Where the earlier 'list' command shows what the platform exposes, 'stat' read metrics over time.
Metrics can be selected by name or sampled in 'raw' mode at fixes bit positions, the latter which doesn't require metric definitions. Output is available in human-readable tabular form.
--- tools/arch/x86/pmtctl/Makefile | 3 + tools/arch/x86/pmtctl/include/cmd_stat.h | 75 +++ .../arch/x86/pmtctl/include/cmd_stat_format.h | 11 + tools/arch/x86/pmtctl/include/pmtctl_cli.h | 2 + tools/arch/x86/pmtctl/src/cmd_stat.c | 501 +++++++++++++++++ tools/arch/x86/pmtctl/src/cmd_stat_format.c | 205 +++++++ tools/arch/x86/pmtctl/src/cmd_stat_run.c | 528 ++++++++++++++++++ tools/arch/x86/pmtctl/src/main.c | 4 + 8 files changed, 1329 insertions(+) create mode 100644 tools/arch/x86/pmtctl/include/cmd_stat.h create mode 100644 tools/arch/x86/pmtctl/include/cmd_stat_format.h create mode 100644 tools/arch/x86/pmtctl/src/cmd_stat.c create mode 100644 tools/arch/x86/pmtctl/src/cmd_stat_format.c create mode 100644 tools/arch/x86/pmtctl/src/cmd_stat_run.c
tools/arch/x86/pmtctl/Makefile +3 -0
@@ -42,6 +42,9 @@ SAMPLE_TARGET := $(BUILDDIR)/samples/libpmtctl_sample SRC := \ $(SRCDIR)/main.c \ $(SRCDIR)/cmd_list.c \ + $(SRCDIR)/cmd_stat.c \ + $(SRCDIR)/cmd_stat_format.c \ + $(SRCDIR)/cmd_stat_run.c \ $(SRCDIR)/pager.c OBJ := $(patsubst $(SRCDIR)/%.c,$(BUILDDIR)/%.o,$(SRC))
tools/arch/x86/pmtctl/include/cmd_stat.h new file +75 -0
75 lines not on this page · raw message
tools/arch/x86/pmtctl/include/cmd_stat_format.h new file +11 -0
@@ -0,0 +1,11 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#ifndef PMTCTL_CMD_STAT_FORMAT_H +#define PMTCTL_CMD_STAT_FORMAT_H + +struct stat_options ; +struct stat_item ; + +void stat_print_header (const struct stat_options *opts); +void stat_print_rows (const struct stat_options *opts,const struct stat_item *items,int nitems, +int num_devices,int sample_idx); +#endif
tools/arch/x86/pmtctl/include/pmtctl_cli.h +2 -0
@@ -11,4 +11,6 @@ void pmtctl_finish_pager(FILE *out);int cmd_list (int argc,char **argv,const struct pmt_global_opts *gopts); +int cmd_stat (int argc,char **argv,const struct pmt_global_opts *gopts); +#endif
tools/arch/x86/pmtctl/src/cmd_stat.c new file +501 -0
501 lines not on this page · raw message
tools/arch/x86/pmtctl/src/cmd_stat_format.c new file +205 -0
205 lines not on this page · raw message
tools/arch/x86/pmtctl/src/cmd_stat_run.c new file +528 -0
528 lines not on this page · raw message
tools/arch/x86/pmtctl/src/main.c +4 -0
@@ -45,6 +45,7 @@ static void print_usage(FILE *out)"\n" "Commands:\n" " list List available PMT devices and metrics\n" +" stat Sample metrics over time (perf stat-like)\n" "\n" "Run 'pmtctl <command> --help' for command-specific options.\n" );
@@ -116,6 +117,9 @@ static int cmd_dispatch(int argc, char **argv)if (!strcmp (cmd,"list" ))return cmd_list (cmd_argc, cmd_argv, &gopts); +if (!strcmp (cmd,"stat" )) +return cmd_stat (cmd_argc, cmd_argv, &gopts); +if (!strcmp (cmd,"--help" ) || !strcmp (cmd,"help" )) {print_usage (stdout);return 0 ;
Signature · 1 line
2.43.0
PATCH 15/17 tools/arch/x86/pmtctl: Add pmtxml2json conversion tool
In reply to David E. BoxAdd a Python converter that turns Intel PMT XML metric definitions into the pmtctl/perf-style JSON consumed by pmtctl and by the built-in metric definition generator.
The converter supports two input modes:
Local path: point it at an existing Intel-PMT xml tree (--by-path
/path/to/Intel-PMT/xml) and convert in place.
Fetch: --fetch-pmt-repo clones the upstream Intel-PMT repository
into a cache (default ~/.cache/pmtctl).
--refresh-pmt-repo updates the cache.
Output JSON files are written under --output-dir, one file per metric group, suitable for direct use with pmtctl -J or as input to gen_builtin_defs.py for compiled-in definitions.
The document pmtxml2json.md provages usage examples covering the different workflows.
--- tools/arch/x86/pmtctl/Makefile | 96 +- tools/arch/x86/pmtctl/scripts/pmtxml2json.md | 158 ++++ tools/arch/x86/pmtctl/scripts/pmtxml2json.py | 883 +++++++++++++++++++ 3 files changed, 1129 insertions(+), 8 deletions(-) create mode 100644 tools/arch/x86/pmtctl/scripts/pmtxml2json.md create mode 100755 tools/arch/x86/pmtctl/scripts/pmtxml2json.py
tools/arch/x86/pmtctl/Makefile +88 -8
@@ -1,6 +1,27 @@ # SPDX-License-Identifier: GPL-2.0-only +# Remove targets whose recipe exited non-zero so a failed codegen step +# does not leave a truncated $@ behind that fools the next build. +.DELETE_ON_ERROR: + CC ?= gcc +PYTHON ?= python3 + +# Directories for the XML -> JSON -> C codegen pipeline. +DEFS_DIR ?= defs +GENERATED_DIR ?= generated +PMT_CACHE_DIR ?= $(HOME)/.cache/pmtctl + +XML2JSON_SCRIPT := scripts/pmtxml2json.py +GEN_DEFS_SCRIPT := scripts/gen_builtin_defs.py + +# JSON sources that define built-in metrics. pmtxml2json.py writes +# one subdirectory per platform under $(DEFS_DIR)/, so recurse. +DEFS_JSON ?= $(shell find $(DEFS_DIR) -name '*.json' 2>/dev/null) + +# 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. +DEFS_JSON_STAMP := $(DEFS_DIR)/.stamp BUILD ?= release
@@ -35,7 +56,6 @@ TARGET := pmtctl LIBDIR := lib LIBPMTCTL_CORE := $(BUILDDIR)/lib/libpmtctl_core.a LIBPMTCTL_ARTIFACTS := $(LIBPMTCTL_CORE) -LIBPMTCTL_STAMP := $(BUILDDIR)/lib/.built SAMPLE_SRC := samples/libpmtctl_sample.c SAMPLE_TARGET := $(BUILDDIR)/samples/libpmtctl_sample
@@ -50,13 +70,21 @@ SRC := \ OBJ := $(patsubst $(SRCDIR)/%.c,$(BUILDDIR)/%.o,$(SRC)) CLEAN_BUILDS := release debug -.PHONY: all clean libpmtctl_core sample FORCE +.PHONY: all clean defs defs-json-fetch defs-json-pull defs-clean \ + libpmtctl_core sample FORCE all: $(TARGET) $(TARGET): $(OBJ) $(LIBPMTCTL_ARTIFACTS) $(CC) $(CFLAGS) -o $@ $(OBJ) $(LIBPMTCTL_ARTIFACTS) $(LDLIBS) +# If JSON definitions exist, ensure the generated built-in defs are up to +# date before the lib sub-make runs. Without this, edits under defs/ would +# not propagate into pmtctl until the user explicitly ran 'make defs'. +ifneq ($(DEFS_JSON),) +$(LIBPMTCTL_CORE): $(GENERATED_DIR)/builtin_defs.c +endif + libpmtctl_core: $(LIBPMTCTL_CORE) sample: $(SAMPLE_TARGET)
@@ -69,15 +97,58 @@ $(SAMPLE_TARGET): $(SAMPLE_SRC) $(LIBPMTCTL_ARTIFACTS) @mkdir -p $(dir $@) $(CC) $(CPPFLAGS) $(CFLAGS) -o $@ $< $(LIBPMTCTL_ARTIFACTS) $(LDLIBS) -$(LIBPMTCTL_ARTIFACTS): $(LIBPMTCTL_STAMP) - -$(LIBPMTCTL_STAMP): FORCE +# Recurse into lib/ on every invocation. The sub-make is incremental and +# does nothing when up to date. Because $(LIBPMTCTL_CORE) has its own +# recipe here, GNU make re-stats it afterwards, so any mtime advance from +# sub-make correctly propagates to $(TARGET) and triggers a relink. +$(LIBPMTCTL_CORE): FORCE $(MAKE) -C $(LIBDIR) BUILD=$(BUILD) - @mkdir -p $(dir $@) - @touch $@ FORCE: +# --- XML -> JSON step (network-bound; opt-in) --- +# +# Fetches the Intel-PMT git repo (cached under $(PMT_CACHE_DIR)) and +# converts every aggregator XML into perf-style JSON under $(DEFS_DIR)/. +# Not wired into 'all' on purpose: avoid surprise git clones. +defs-json-fetch: $(DEFS_JSON_STAMP) + +$(DEFS_JSON_STAMP): $(XML2JSON_SCRIPT) + @echo "defs-json-fetch: git cloning Intel-PMT into $(PMT_CACHE_DIR)" + @command -v $(PYTHON) >/dev/null 2>&1 || { \ + echo "$(PYTHON) is required for $(XML2JSON_SCRIPT)" >&2; exit 1; } + @mkdir -p $(DEFS_DIR) + $(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)" + @mkdir -p $(DEFS_DIR) + $(PYTHON) $(XML2JSON_SCRIPT) \ + --fetch-pmt-repo --refresh-pmt-repo \ + --pmt-cache-dir $(PMT_CACHE_DIR) \ + --output-dir $(DEFS_DIR) + @touch $(DEFS_JSON_STAMP) + +# --- JSON -> C step (does NOT build pmtctl) --- +# +# DEFS_JSON is expanded at parse time, so 'make defs-json-fetch' must be run +# in a separate invocation before 'make defs' the first time. +$(GENERATED_DIR)/builtin_defs.c: $(GEN_DEFS_SCRIPT) $(DEFS_JSON) + @mkdir -p $(GENERATED_DIR) + @if [ -z "$(DEFS_JSON)" ]; then \ + echo "No JSON files under $(DEFS_DIR)/. Run 'make defs-json-fetch' first," >&2; \ + echo "then re-run 'make defs'." >&2; \ + exit 1; \ + fi + @command -v $(PYTHON) >/dev/null 2>&1 || { \ + echo "$(PYTHON) is required for $(GEN_DEFS_SCRIPT)" >&2; exit 1; } + $(PYTHON) $(GEN_DEFS_SCRIPT) $(DEFS_JSON) > $@ + # Install settings PREFIX ?= /usr/local DESTDIR ?=
@@ -105,6 +176,15 @@ uninstall: $(MAKE) -C $(LIBDIR) BUILD=$(BUILD) PREFIX=$(PREFIX) DESTDIR=$(DESTDIR) uninstall-headers $(MAKE) -C $(LIBDIR) BUILD=$(BUILD) PREFIX=$(PREFIX) DESTDIR=$(DESTDIR) uninstall-pkgconfig @echo "Removed $(DESTDIR)$(PREFIX)/bin/$(TARGET) (if present)" +defs: $(GENERATED_DIR)/builtin_defs.c + @if [ -f $(GENERATED_DIR)/builtin_defs.c ]; then \ + echo "Generated defs in $(GENERATED_DIR)/builtin_defs.c"; \ + fi + +# Separate from 'clean' so a routine clean does not throw away the +# (potentially slow) fetched/converted JSON tree. +defs-clean: + rm -rf $(DEFS_DIR) $(GENERATED_DIR)/builtin_defs.c $(BUILDDIR)/%.o: $(SRCDIR)/%.c @mkdir -p $(BUILDDIR)
@@ -115,4 +195,4 @@ clean: $(MAKE) -C $(LIBDIR) BUILD=$$build_type clean; \ rm -rf build/$$build_type; \ done - rm -rf $(BUILDDIR) $(TARGET) + rm -rf $(BUILDDIR) $(TARGET) $(GENERATED_DIR)/builtin_defs.c
tools/arch/x86/pmtctl/scripts/pmtxml2json.md new file +158 -0
158 lines not on this page · raw message
tools/arch/x86/pmtctl/scripts/pmtxml2json.py new file +883 -0
883 lines not on this page · raw message
Signature · 1 line
2.43.0
PATCH 16/17 tools/arch/x86/pmtctl: Add README.md
In reply to David E. BoxAdd the user-facing README documenting pmtctl usage, supported metric sources, and command-line options.
--- tools/arch/x86/pmtctl/README.md | 276 ++++++++++++++++++++++++++++++++ 1 file changed, 276 insertions(+) create mode 100644 tools/arch/x86/pmtctl/README.md
tools/arch/x86/pmtctl/README.md new file +276 -0
@@ -0,0 +1,276 @@ +# pmtctl +Intel Platform Monitoring Technology (PMT) command-line tool for Linux + +## Overview + +pmtctl is a small command-line utility to query Intel Platform Monitoring +Technology (PMT) metrics via the telem telemetry interface. It can load +metric definitions from JSON files or use built-in definitions. + +The project is split into a CLI frontend and a reusable library: + +- `src/`: CLI frontend (`pmtctl`, commands, formatting, pager) +- `lib/`: reusable PMT library implementation (`libpmtctl_core.a`) + - transport/enumeration/binding core + - metric DB container operations + - built-in and runtime-JSON metric-definition providers + +Core ownership model: + +- Core library owns PMT source selection, device enumeration, telem reads, + metric DB container operations, and both metric-definition providers + (built-in compiled defs and runtime JSON parsing/loading). + +## Prerequisites + +- A C toolchain (gcc/clang) +- make +- python3 (for JSON metric generation) +- libjansson (JSON parsing library) +- Linux (dev/test on systems with `/sys/bus/auxiliary/drivers/pmt_telemetry` for telem) + +## Build Instructions + +The built-in metrics pipeline has two opt-in stages, then the build: + +```text +Intel-PMT repo (XML) --[pmtxml2json.py]--> defs/*.json + | + [gen_builtin_defs.py] + v + generated/builtin_defs.c --> make --> pmtctl +``` + +Each stage is a separate Make target so a routine `make` never hits the +network and never re-runs codegen unnecessarily. + +### Option 1: Build with built-in metrics (recommended) + +First-time setup (the `defs-json-fetch` step git clones the Intel-PMT repo into +`~/.cache/pmtctl` and converts every aggregator XML to perf-style JSON): + +```bash +make defs-json-fetch # git clone Intel-PMT (cached) and produce defs/*.json +make defs # JSON -> generated/builtin_defs.c +make # build pmtctl with built-in metric definitions +``` + +If you already have JSON files of your own, drop them under `defs/` +and skip straight to `make defs && make`. + +To update from upstream Intel-PMT later: + +```bash +make defs-json-pull # git pull the cache and regenerate JSON +make defs # regenerate generated/builtin_defs.c +make # rebuild +``` + +### Option 2: Build without built-in metrics + +If you don't have metric JSONs or prefer to load them at runtime: + +```bash +make +``` + +This uses the empty stub (`lib/builtin_defs_empty.c`); load metrics at +runtime with `-J/--json-file`. + +### Make targets (summary) + +| Target | Purpose | +|---------------------|----------------------------------------------------| +| `all` (default) | Build `pmtctl` and `libpmtctl_core.a` | +| `defs-json-fetch` | git clone Intel-PMT (cached) and emit `defs/*.json` | +| `defs-json-pull` | Same as above, but git pull the cache first | +| `defs` | Generate `generated/builtin_defs.c` from JSON | +| `defs-clean` | Remove `defs/` and `generated/builtin_defs.c` | +| `clean` | Remove build outputs (keeps `defs/` intact) | +| `install` / | Install or remove `pmtctl`, lib, headers, .pc | +| `uninstall` | | + +Useful variables (override on the make command line): + +- `PYTHON` — Python interpreter (default `python3`) +- `DEFS_DIR` — JSON output / input directory (default `defs`) +- `GENERATED_DIR` — codegen output directory (default `generated`) +- `PMT_CACHE_DIR` — Intel-PMT clone cache (default `~/.cache/pmtctl`) + +### Library artifacts produced + +Building `make` also builds the static library artifact under +`build/<build-type>/lib/`: + +- `libpmtctl_core.a` + +## Usage (examples) + +General form: + +```text +pmtctl [global options] <command> [command options] +``` + +Global options: + +- `-h, --help` Show help and exit +- `-V, --version` Show version and exit +- `-b, --source <mode>` Data source: `telem` (pmu support is pending upstream driver availability) +- `-J, --json-file <path>` Path to metrics JSON (file or directory) — loads metrics at runtime +- `-d, --device <selector>` Restrict to single endpoint (guid or ep name) + +Note: Metrics can be loaded in two ways: +1. **Built-in** (compiled during build) — see "Build with JSON metrics" above +2. **Runtime** (loaded via `-J` option) — useful for testing or using different metric sets + +Commands: + +- `list` — list known metrics and/or discovered devices +- `stat` — sample/stream metrics over time (similar to `perf stat`) + +Examples (basic): + +```bash +# list all metrics with built-in or runtime-loaded definitions +./pmtctl list + +# list with GUIDs (useful for debugging metric definitions) +./pmtctl list --guids + +# load metrics from a directory at runtime +./pmtctl -J /path/to/metrics/ list --guids + +# load metrics from a single JSON file at runtime +./pmtctl -J /path/to/metrics.json list --guids + +# list devices only +./pmtctl list --devices + +# keep the last pager screen on exit (useful before running stat) +./pmtctl list -X + +# sample a named metric at the default 1 s interval +sudo ./pmtctl stat -e temp_socket + +# sample at 500 ms intervals +sudo ./pmtctl stat -e socket_power --interval 500 + +# take a single snapshot and exit +sudo ./pmtctl stat -e fw_version_0 --once + +# sample multiple metrics (one line per metric per sample) +sudo ./pmtctl stat -e temp_socket -e socket_power --vertical + +# restrict to a specific device by GUID +sudo ./pmtctl -d guid=22806802 stat -e temp_core0 + +# read raw sample data by sample id (no metric definitions required) +sudo ./pmtctl stat --raw id=0,lsb=0,msb=31 --count 2 + +# read multiple raw samples with bit slicing +sudo ./pmtctl stat --raw id=2,msb=7 --raw id=3,lsb=8,msb=15 + +# output values in hex +sudo ./pmtctl stat -e fw_version_0 --once --hex +``` + +See `pmtctl_cli_spec.txt` in the repository root for the full CLI +specification and additional example usage. + +## Developer Notes + +### Adding new C source files + +If you add new `.c` files: + +- CLI/frontend code goes in `src/` and is added to top-level `Makefile` `SRC`. +- Reusable library core code goes in `lib/` and is added to `lib/Makefile` + `CORE_SRC`. +- Built-in provider code goes in `lib/` and is added to `lib/Makefile` + `BUILTIN_OBJ` inputs. +- JSON provider code goes in `lib/` and is added to `lib/Makefile` `JSON_OBJ` + inputs. + +This keeps transport and provider policy boundaries explicit. + +### Regenerating metrics from JSON + +The Makefile recursively tracks `*.json` under `defs/` (so per-platform +subdirectories produced by `pmtxml2json.py` are picked up automatically): + +```bash +# Re-generate after editing or adding JSON under defs/ +make defs + +# Throw away converted JSON + codegen output (does NOT touch the +# Intel-PMT cache under ~/.cache/pmtctl) +make defs-clean +``` + +`make clean` intentionally does *not* remove `defs/` — the XML->JSON step +can be slow, so use `make defs-clean` when you really want to start over. + +The `scripts/gen_builtin_defs.py` script also runs standalone and accepts +both files and directories: + +```bash +python3 scripts/gen_builtin_defs.py defs/ > generated/builtin_defs.c +``` + +## PMTXML2JSON Conversion + +`scripts/pmtxml2json.py` turns Intel PMT XML definitions into pmtctl / +perf-style JSON. The `make defs-json-fetch` target wraps the common case; +invoke the script directly for one-off workflows: + +```bash +# convert all XML groups under a local Intel-PMT xml tree +python3 scripts/pmtxml2json.py --by-path /path/to/Intel-PMT/xml --output-dir defs + +# auto-fetch Intel-PMT into cache, then convert from the fetched xml directory +python3 scripts/pmtxml2json.py --fetch-pmt-repo --output-dir defs + +# refresh the cached Intel-PMT repository before converting +python3 scripts/pmtxml2json.py --fetch-pmt-repo --refresh-pmt-repo --output-dir defs +``` + +Fetch/cache behavior: + +- `--fetch-pmt-repo` is opt-in and preserves existing local-path workflows. +- Default cache location is `~/.cache/pmtctl` (override with `--pmt-cache-dir`). +- `--refresh-pmt-repo` only works with `--fetch-pmt-repo` and updates the cache explicitly. + +If `--fetch-pmt-repo` is used without a positional XML file and without +`--by-path`, the converter automatically uses the fetched Intel-PMT `xml/` +directory as the discovery root. + +## Install and Export + +Minimal install/export support is available for the CLI and static libraries: + +```bash +# Stage install output +make DESTDIR=$PWD/stage install +``` + +Installs: + +- `bin/pmtctl` +- `lib/libpmtctl_core.a` +- `include/pmtctl/{pmtctl.h,metrics_db.h,device.h}` +- `lib/pkgconfig/libpmtctl-core.pc` + +Uninstall: + +```bash +make DESTDIR=$PWD/stage uninstall +``` + +## Testing + +Stat commands require elevated privileges to read telemetry files: + +```bash +sudo ./pmtctl stat -e <metric_name> +```
Signature · 1 line
2.43.0
PATCH 17/17 tools/arch/x86/pmtctl: Add man page
In reply to David E. BoxAdd a man page for pmtctl describing the command-line interface, the list and stat subcommands, common options, and output formats.
--- tools/arch/x86/pmtctl/Makefile | 6 + tools/arch/x86/pmtctl/README.md | 3 + tools/arch/x86/pmtctl/pmtctl.8 | 317 ++++++++++++++++++++++++++++++++ 3 files changed, 326 insertions(+) create mode 100644 tools/arch/x86/pmtctl/pmtctl.8
tools/arch/x86/pmtctl/Makefile +6 -0
@@ -152,6 +152,7 @@ $(GENERATED_DIR)/builtin_defs.c: $(GEN_DEFS_SCRIPT) $(DEFS_JSON) # Install settings PREFIX ?= /usr/local DESTDIR ?= +MANDIR ?= $(PREFIX)/share/man .PHONY: install uninstall install-lib install-headers install-pkgconfig uninstall-lib uninstall-headers uninstall-pkgconfig
@@ -159,7 +160,10 @@ DESTDIR ?= install: $(TARGET) install-lib install-headers install-pkgconfig install -d $(DESTDIR)$(PREFIX)/bin install -m 0755 $(TARGET) $(DESTDIR)$(PREFIX)/bin + install -d $(DESTDIR)$(MANDIR)/man8 + install -m 0644 pmtctl.8 $(DESTDIR)$(MANDIR)/man8/pmtctl.8 @echo "Installed $(TARGET) to $(DESTDIR)$(PREFIX)/bin/" + @echo "Installed pmtctl.8 to $(DESTDIR)$(MANDIR)/man8/" install-lib: $(MAKE) -C $(LIBDIR) BUILD=$(BUILD) PREFIX=$(PREFIX) DESTDIR=$(DESTDIR) install-lib
@@ -172,10 +176,12 @@ install-pkgconfig: uninstall: rm -f $(DESTDIR)$(PREFIX)/bin/$(TARGET) + rm -f $(DESTDIR)$(MANDIR)/man8/pmtctl.8 $(MAKE) -C $(LIBDIR) BUILD=$(BUILD) PREFIX=$(PREFIX) DESTDIR=$(DESTDIR) uninstall-lib $(MAKE) -C $(LIBDIR) BUILD=$(BUILD) PREFIX=$(PREFIX) DESTDIR=$(DESTDIR) uninstall-headers $(MAKE) -C $(LIBDIR) BUILD=$(BUILD) PREFIX=$(PREFIX) DESTDIR=$(DESTDIR) uninstall-pkgconfig @echo "Removed $(DESTDIR)$(PREFIX)/bin/$(TARGET) (if present)" + @echo "Removed $(DESTDIR)$(MANDIR)/man8/pmtctl.8 (if present)" defs: $(GENERATED_DIR)/builtin_defs.c @if [ -f $(GENERATED_DIR)/builtin_defs.c ]; then \ echo "Generated defs in $(GENERATED_DIR)/builtin_defs.c"; \
tools/arch/x86/pmtctl/README.md +3 -0
@@ -260,6 +260,9 @@ Installs: - `lib/libpmtctl_core.a` - `include/pmtctl/{pmtctl.h,metrics_db.h,device.h}` - `lib/pkgconfig/libpmtctl-core.pc` +- `share/man/man8/pmtctl.8` + +Override `MANDIR` (default `$(PREFIX)/share/man`) to relocate the man page. Uninstall:
tools/arch/x86/pmtctl/pmtctl.8 new file +317 -0
317 lines not on this page · raw message
Signature · 1 line
2.43.0
Ilpo Järvinen
maintainerRe: [PATCH 02/17] tools/arch/x86/pmtctl: Add libpmtctl shared type enumerations
In reply to David E. BoxQuoted 20 lines · David E. Box
Add
pmtctl_types.hto centralize shared libpmtctl type definitions used across both the public and internal library interfaces.This provides a common definition point for core library-facing types, including device backend classification and logging verbosity levels, avoiding duplication across API boundaries.
Assisted-by GitHub-Copilot:claude-sonnet-4.6Signed-off-by David E. Box <[email protected]>--- tools/arch/x86/pmtctl/include/lib/pmtctl_types.h | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 tools/arch/x86/pmtctl/include/lib/pmtctl_types.htools/arch/x86/pmtctl/include/lib/pmtctl_types.h new file +0
-0
tools/arch/x86/pmtctl/include/lib/pmtctl_types.h line 6
Quoted 6 lines
tools/arch/x86/pmtctl/include/lib/pmtctl_types.h new file +6
-0@@ -0,0 +1,16 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#ifndef PMTCTL_TYPES_H +#define PMTCTL_TYPES_H + +enum pmt_device_type { + PMT_DEVICE_TELEM
Missing comma.
Quoted 11 lines
tools/arch/x86/pmtctl/include/lib/pmtctl_types.h new file +10
-0+}; + +enum pmtctl_log_level { +PMTCTL_LOG_ERROR =0 , +PMTCTL_LOG_WARN , +PMTCTL_LOG_INFO , +PMTCTL_LOG_DEBUG , +}; + +#endif
Signature · 1 line
i.
Ilpo Järvinen
maintainerRe: [PATCH 03/17] tools/arch/x86/pmtctl: Add libpmtctl internal logging and utility functions
In reply to David E. BoxQuoted 264 lines · David E. Box
Add the internal logging infrastructure and shared utility helpers used by
libpmtctl_core.The logging layer provides consistent level-filtered diagnostics across the library, while the utility helpers centralize common sysfs access, string handling, and scoped resource cleanup functionality used across backend implementations.
Logging levels mirror the public
pmtctl_log_levelenum and can be used to control library verbosity.Assisted-by GitHub-Copilot:claude-sonnet-4.6Signed-off-by David E. Box <[email protected]>--- tools/arch/x86/pmtctl/include/lib/common.h | 34 ++++ tools/arch/x86/pmtctl/include/lib/log.h | 80 ++++++++ tools/arch/x86/pmtctl/include/lib/pmt_guid.h | 63 ++++++ tools/arch/x86/pmtctl/lib/common.c | 178 +++++++++++++++++ tools/arch/x86/pmtctl/lib/log.c | 80 ++++++++ tools/arch/x86/pmtctl/lib/pmt_guid.c | 200 +++++++++++++++++++ 6 files changed, 635 insertions(+) create mode 100644 tools/arch/x86/pmtctl/include/lib/common.h create mode 100644 tools/arch/x86/pmtctl/include/lib/log.h create mode 100644 tools/arch/x86/pmtctl/include/lib/pmt_guid.h create mode 100644 tools/arch/x86/pmtctl/lib/common.c create mode 100644 tools/arch/x86/pmtctl/lib/log.c create mode 100644 tools/arch/x86/pmtctl/lib/pmt_guid.ctools/arch/x86/pmtctl/include/lib/common.h new file +34
-0@@ -0,0 +1,34 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#ifndef PMTCTL_COMMON_H +#define PMTCTL_COMMON_H + +#include <stdlib.h> +#include <stdio.h> +#include <stdint.h> + +#ifndef __GNUC__ +#error "pmtctl: cleanup helpers require GCC/Clang (__GNUC__)." +#endif + +static inline void freep (void *p) +{ +void **ptr = (void **)p; + +if (*ptr) { +free (*ptr); + *ptr =NULL ; + } +} + +#define auto_free __attribute__((cleanup(freep))) + +#ifndef ARRAY_SIZE +#define ARRAY_SIZE (arr) (sizeof(arr) / sizeof((arr)[0])) +#endif + +char *xstrdup (const char *s); +int read_attr_text (const char *dir,const char *name,char *buf,size_t buflen); +int read_optional_int_attr (const char *devpath,const char *attr,int *out_id); +int read_int_attr (const char *devpath,const char *attr,int *out_id); +int read_u32_hex_attr (const char *devpath,const char *attr,uint32_t *out,int err_invalid); +#endif tools/arch/x86/pmtctl/include/lib/log.h new file +80
-0@@ -0,0 +1,80 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#ifndef PMTCTL_LOG_H +#define PMTCTL_LOG_H + +#include <linux/compiler.h> +#include "pmtctl_types.h" + +#define PMTCTL_EXIT_USER 1 +#define PMTCTL_EXIT_SYSTEM 2 +#define PMTCTL_EXIT_BUG 3 + +enum { +PMTCTL_ERR_PARSE =1 ,/* malformed JSON, invalid numbers, missing fields */ +PMTCTL_ERR_NOTFOUND ,/* metric/device/group not found */ +PMTCTL_ERR_BAD_ARG , +PMTCTL_ERR_CMD_PARSE , +PMTCTL_ERR_CMD_LIST , +PMTCTL_ERR_CMD_STAT , +PMTCTL_ERR_NOMETRICS , +PMTCTL_ERR_METRICS , +PMTCTL_ERR_INVALID ,/* bad selector, bad arguments, bad config */ +PMTCTL_ERR_DEVICE ,/* device mismatch or device internal failure */ +PMTCTL_ERR_BINDING ,/* binding table construction failed */ +PMTCTL_ERR_UNSUPPORTED ,/* metric/feature not supported on this system */ +}; + +#ifdef LOG_PREFIX +#define _LOG_PREFIXED (fmt) LOG_PREFIX ": " fmt +#else +#define _LOG_PREFIXED (fmt) fmt +#endif + +#define LOG_ERROR PMTCTL_LOG_ERROR +#define LOG_WARN PMTCTL_LOG_WARN +#define LOG_INFO PMTCTL_LOG_INFO +#define LOG_DEBUG PMTCTL_LOG_DEBUG + +void log_impl(enum pmtctl_log_level lvl, int err, const char *fmt, ...) + __printf(3, 4); +void log_set_level (enum pmtctl_log_level lvl); + +#define log_bug_and_exit (fmt, ...) \ + log_bug_impl(__FILE__, __LINE__, fmt, ##__VA_ARGS__) + +#define log_err (err, fmt, ...) \ + log_impl(LOG_ERROR, (err), _LOG_PREFIXED(fmt), ##__VA_ARGS__) + +#define log_warn (fmt, ...) \ + log_impl(LOG_WARN, 0, _LOG_PREFIXED(fmt), ##__VA_ARGS__) + +#define log_info (fmt, ...) \ + log_impl(LOG_INFO, 0, _LOG_PREFIXED(fmt), ##__VA_ARGS__) + +#ifdef DEBUG +#define log_debug (fmt, ...) \ + log_impl(LOG_DEBUG, 0, _LOG_PREFIXED(fmt), ##__VA_ARGS__) +#else +#define log_debug (fmt, ...) \ + ((void)(0 ? log_info(fmt, ##__VA_ARGS__) : 0)) +#endif + +int log_ret (int ret,const char *fmt, ...); + +__noreturn +void log_bug_impl (const char *file,int line,const char *fmt, ...); + +#define LOG_ONCE (level, fmt, ...) \ + do { \ + static int __done_##__LINE__; \ + if (!__done_##__LINE__) { \ + level(fmt, ##__VA_ARGS__); \ + __done_##__LINE__ = 1; \ + } \ + } while (0) + +#define log_err_once (fmt, ...) LOG_ONCE(log_err, fmt, ##__VA_ARGS__) +#define log_warn_once (fmt, ...) LOG_ONCE(log_warn, fmt, ##__VA_ARGS__) +#define log_info_once (fmt, ...) LOG_ONCE(log_info, fmt, ##__VA_ARGS__) + +#endif tools/arch/x86/pmtctl/include/lib/pmt_guid.h new file +63
-0@@ -0,0 +1,63 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#ifndef PMTCTL_PMT_GUID_H +#define PMTCTL_PMT_GUID_H + +#include <stdbool.h> +#include <stdint.h> + +/* +* Per-GUID metadata derived from the Intel-PMT pmt.xml top-level mapping +* table. The compiled-in built-in table (builtin_guids[]) is generated by +* scripts/gen_builtin_defs.py. Runtime-loaded providers may register +* additional entries via pmt_guid_register(). +* +* A global intern registry ensures pointer-equality across pmt_device and +* pmt_metric_def: two references to the same GUID always yield the same +* struct pmt_guid pointer. +*/ +struct pmt_guid { +uint32_t guid; +const char *name;/* basedir lowercased with '/' -> '_'; may be NULL */ +const char *description;/* may be NULL */ +}; + +/* +* Register an array of pmt_guid entries with the global registry. The +* pointer must remain valid for the registry's lifetime. Entries with a +* GUID already present in the registry are skipped (first wins). +* +* Returns 0 on success, negative errno on failure. +*/ +int pmt_guid_register (const struct pmt_guid *entries,int count); + +/* +* Same as pmt_guid_register(), but the registry takes ownership of `block` +* (typically the heap allocation that backs `entries` and any pooled +* strings the entries point into). The block is freed by pmt_guid_cleanup(). +* +* `block` may equal `entries` when the array sits at the head of the +* allocation. Passing a NULL block degrades to pmt_guid_register(). +* +* Returns 0 on success, negative errno on failure. On failure the caller +* retains ownership of `block` and must free it. +*/ +int pmt_guid_register_owned (void *block,const struct pmt_guid *entries,int count); + +/* +* Lookup the registered pmt_guid for the given numeric GUID. Returns NULL +* if no entry has been registered or interned for that GUID. +*/ +const struct pmt_guid *pmt_guid_lookup (uint32_t guid); + +/* +* Resolve numeric GUID to a stable struct pmt_guid pointer. If no entry is +* registered, a synthetic entry (name = NULL, description = NULL) is +* allocated and returned; subsequent calls with the same GUID return the +* same pointer. Returns NULL only on allocation failure. +*/ +const struct pmt_guid *pmt_guid_intern (uint32_t guid); + +/* Free all synthetic (interned) entries and clear registrations. */ +void pmt_guid_cleanup (void ); + +#endif tools/arch/x86/pmtctl/lib/common.c new file +35
-0@@ -0,0 +1,178 @@ +// SPDX-License-Identifier: GPL-2.0-only +#include <errno.h> +#include <fcntl.h> +#include <limits.h> +#include <stdlib.h> +#include <stdint.h> +#include <stdio.h> +#include <string.h> +#include <sys/types.h> +#include <unistd.h> + +#include "lib/common.h" +#include "lib/log.h" + +char *xstrdup (const char *s) +{ +char *p; + +if (!s) +return NULL ; + + p =strdup (s); +if (!p) { +log_err (errno,"out of memory" ); +exit (EXIT_FAILURE ); + } + +return p; +} + +static void trim_newline (char *s) +{ +size_t len; +char *end; +
tools/arch/x86/pmtctl/lib/common.c line 45
Quoted 10 lines
tools/arch/x86/pmtctl/lib/common.c new file +10
-0+if (!s) +return ; + + len =strlen (s); +if (!len) +return ; + + end = s + len -1 ; + +while (end >= s && (*end =='\n' || *end =='\r' )) {
Is it beneficial to trim just newlines or would it be better to trim anything for which isspace() is true?
Quoted 8 lines
tools/arch/x86/pmtctl/lib/common.c new file +8
-0+ *end ='\0' ; + end--; + } +} + +int read_attr_text (const char *dir,const char *name,char *buf,size_t buflen) +{ +char path[PATH_MAX ];
tools/arch/x86/pmtctl/lib/common.c line 63
Quoted 10 lines
tools/arch/x86/pmtctl/lib/common.c new file +10
-0+int fd; +ssize_t n; + +if (!dir || !name || !buf || buflen ==0 ) +return -EINVAL ; + +if (snprintf (path,sizeof (path),"%s/%s" , dir, name) >= (int )sizeof (path)) +return -ENAMETOOLONG ; + + fd =open (path,O_RDONLY |O_CLOEXEC );
Why is O_CLOEXEC required? (The is closed just a few lines down.)
Quoted 28 lines
tools/arch/x86/pmtctl/lib/common.c new file +28
-0+if (fd ==-1 ) +return -errno; + + n =read (fd, buf, buflen -1 ); +close (fd); + +if (n ==-1 ) +return -errno; + + buf[n] ='\0' ; +trim_newline (buf); + +return 0 ; +} + +int read_optional_int_attr (const char *devpath,const char *attr,int *out_id) +{ +char buf[64 ]; +char *end; +long v; +int ret; + +if (!out_id || !devpath || !attr) +return -EINVAL ; + + ret =read_attr_text (devpath, attr, buf,sizeof (buf)); +if (ret !=0 ) { +if (ret == -ENOENT ) {
tools/arch/x86/pmtctl/lib/common.c line 101
Quoted 10 lines
tools/arch/x86/pmtctl/lib/common.c new file +10
-0+/* file not found */ + *out_id =-1 ; +return 0 ; + } + +return ret; + } + + errno =0 ; +
This belongs tightly together with strtol() so I don't know why there's empty in between.
Quoted 37 lines
tools/arch/x86/pmtctl/lib/common.c new file +37
-0+/* accept decimal or 0x-prefixed hex */ + v =strtol (buf, &end,0 ); +if (errno) +return -errno; + +if (end == buf || *end !='\0' ) +return -EINVAL ; + +if (v <INT_MIN || v >INT_MAX ) +return -ERANGE ; + + *out_id = (int )v; + +return 0 ; +} + +int read_int_attr (const char *devpath,const char *attr,int *out_id) +{ +char buf[64 ]; +char *end; +long v; +int ret; + +if (!out_id || !devpath || !attr) +return -EINVAL ; + + ret =read_attr_text (devpath, attr, buf,sizeof (buf)); +if (ret !=0 ) +return ret; + + errno =0 ; + +/* accept decimal or 0x-prefixed hex */ + v =strtol (buf, &end,0 ); +if (errno) +return -errno; +
tools/arch/x86/pmtctl/lib/common.c line 148
Quoted 10 lines
tools/arch/x86/pmtctl/lib/common.c new file +10
-0+if (end == buf || *end !='\0' ) +return -EINVAL ; + +if (v <INT_MIN || v >INT_MAX ) +return -ERANGE ; + + *out_id = (int )v; + +return 0 ; +}
Lots of code duplication.
Quoted 55 lines
tools/arch/x86/pmtctl/lib/common.c new file +30
-0+ +int read_u32_hex_attr (const char *devpath,const char *attr,uint32_t *out,int err_invalid) +{ +char buf[64 ]; +char *end; +unsigned long v; +int ret; + +if (!out || !devpath || !attr) +return -EINVAL ; + + ret =read_attr_text (devpath, attr, buf,sizeof (buf)); +if (ret !=0 ) +return ret; + + errno =0 ; + v =strtoul (buf, &end,16 ); +if (errno) +return -errno; + +if (end == buf || *end !='\0' ) +return err_invalid; + +if (v >UINT32_MAX ) +return err_invalid; + + *out = (uint32_t )v; + +return 0 ; +}tools/arch/x86/pmtctl/lib/log.c new file +19
-0@@ -0,0 +1,80 @@ +// SPDX-License-Identifier: GPL-2.0-only +#include <stdarg.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <errno.h> + +#include "lib/log.h" + +static enum pmtctl_log_level g_log_level =LOG_INFO ; + +void log_set_level (enum pmtctl_log_level lvl) +{ +if (lvl <LOG_ERROR || lvl >LOG_DEBUG ) + g_log_level =LOG_INFO ; +else + g_log_level = lvl; +} +
tools/arch/x86/pmtctl/lib/log.c line 29
Quoted 10 lines
tools/arch/x86/pmtctl/lib/log.c new file +10
-0+static void log_vmsg (enum pmtctl_log_level lvl,int err,const char *fmt, +va_list ap) +{ +if (lvl > g_log_level) +return ; + +const char *tag = + (lvl ==LOG_ERROR ) ?"error" : + (lvl ==LOG_WARN ) ?"warning" : + (lvl == LOG_INFO) ? "info" :
Aligning is off.
tools/arch/x86/pmtctl/lib/log.c line 36
Quoted 7 lines
tools/arch/x86/pmtctl/lib/log.c new file +7
-0+"debug" ; + +fprintf (stderr,"%s: " , tag); +vfprintf (stderr, fmt, ap); + +if (err !=0 ) { +int e = (err <0 ) ? -err : err;
???
tools/arch/x86/pmtctl/lib/log.c line 38
Quoted 2 lines
tools/arch/x86/pmtctl/lib/log.c new file +2
-0+ +if (err <0 )
???
Quoted 62 lines
tools/arch/x86/pmtctl/lib/log.c new file +42
-0+fprintf (stderr,": %s" ,strerror (e)); + } + +fputc ('\n' , stderr); +} + +void log_impl (enum pmtctl_log_level lvl,int err,const char *fmt, ...) +{ +va_list ap; + +va_start (ap, fmt); +log_vmsg (lvl, err, fmt, ap); +va_end (ap); +} + +int log_ret (int ret,const char *fmt, ...) +{ +if (ret ==0 ) +return 0 ; + +va_list ap; + +va_start (ap, fmt); +log_vmsg (LOG_ERROR , ret, fmt, ap); +va_end (ap); + +return ret; +} + +__noreturn +void log_bug_impl (const char *file,int line,const char *fmt, ...) +{ +va_list ap; + +fprintf (stderr,"pmtctl: BUG at %s:%d: " , file, line); +va_start (ap, fmt); +vfprintf (stderr, fmt, ap); +va_end (ap); +fputc ('\n' , stderr); + +exit (PMTCTL_EXIT_BUG ); +}tools/arch/x86/pmtctl/lib/pmt_guid.c new file +14
-0@@ -0,0 +1,200 @@ +// SPDX-License-Identifier: GPL-2.0-only +#include <errno.h> +#include <stdbool.h> +#include <stdint.h> +#include <stdlib.h> +#include <string.h> + +#include "lib/pmt_guid.h" + +/* +* Global intern registry for struct pmt_guid. +* +* Two sources feed this table: +* 1. Pre-registered blocks (e.g. builtin_guids[] from generated code,
tools/arch/x86/pmtctl/lib/pmt_guid.c line 24
Quoted 10 lines
tools/arch/x86/pmtctl/lib/pmt_guid.c new file +10
-0+* or JSON-loaded pmt_guids.json from the runtime provider). Pointers +* to those entries are stored verbatim and assumed to outlive the +* registry's use. +* 2. Synthetic entries allocated on demand by pmt_guid_intern() for +* GUIDs that no provider knows about. These have name = NULL and +* description = NULL. +* +* A simple linear-scan array is used; the registry holds at most a few +* hundred entries on any realistic system. +*/
This seems largely irrelevant to what it comments about (struct guid_slot is definitely not a "global intern registry" nor a "table").
Quoted 18 lines
tools/arch/x86/pmtctl/lib/pmt_guid.c new file +18
-0+struct guid_slot { +const struct pmt_guid *entry;/* points into registered block or synth_storage */ +struct pmt_guid *synth;/* non-NULL iff this slot owns the entry */ +}; + +static struct guid_slot *g_slots; +static int g_nslots; +static int g_cap; + +/* +* Heap blocks handed to pmt_guid_register_owned(). The registry frees +* them in pmt_guid_cleanup() after disposing of the slot array, so any +* pointers the slots held into these blocks are gone by then. +*/ +static void **g_owned_blocks; +static int g_nowned; +static int g_owned_cap; +
tools/arch/x86/pmtctl/lib/pmt_guid.c line 52
Quoted 10 lines
tools/arch/x86/pmtctl/lib/pmt_guid.c new file +10
-0+static int reserve_one (void ) +{ +struct guid_slot *tmp; +int new_cap; + +if (g_nslots < g_cap) +return 0 ; + + new_cap = g_cap ? g_cap *2 :32 ; + tmp =realloc (g_slots, (size_t )new_cap *sizeof (*tmp));
Why is new_cap int if it is needed as size_t ??
And a follow up from that, why are g_cap and g_nslots signed if only positive values are acceptable?
Quoted 50 lines
tools/arch/x86/pmtctl/lib/pmt_guid.c new file +50
-0+if (!tmp) +return -ENOMEM ; + + g_slots = tmp; + g_cap = new_cap; +return 0 ; +} + +const struct pmt_guid *pmt_guid_lookup (uint32_t guid) +{ +for (int i =0 ; i < g_nslots; i++) { +if (g_slots[i].entry && g_slots[i].entry->guid == guid) +return g_slots[i].entry; + } +return NULL ; +} + +int pmt_guid_register (const struct pmt_guid *entries,int count) +{ +if (!entries || count <=0 ) +return -EINVAL ; + +for (int i =0 ; i < count; i++) { +const struct pmt_guid *e = &entries[i]; +bool already_known = false; +int ret; + +/* +* If a slot already exists for this GUID, upgrade it when the +* existing entry is a synthetic placeholder (created earlier +* by pmt_guid_intern() before any provider was loaded) and the +* new entry carries real metadata. The synthetic struct must +* be kept alive because earlier callers (e.g. devices) hold +* pointers to it; patch its fields in place instead of +* swapping the slot entry. +*/ +for (int s =0 ; s < g_nslots; s++) { +struct guid_slot *slot = &g_slots[s]; + +if (!slot->entry || slot->entry->guid != e->guid) +continue ; + +if (slot->synth && e->name && *e->name) { + slot->synth->name = e->name; + slot->synth->description = e->description; + } + already_known = true; +break ; + } +
tools/arch/x86/pmtctl/lib/pmt_guid.c line 112
Quoted 10 lines
tools/arch/x86/pmtctl/lib/pmt_guid.c new file +10
-0+if (already_known) +continue ; + + ret =reserve_one (); +if (ret <0 ) +return ret; + + g_slots[g_nslots].entry = e; + g_slots[g_nslots].synth =NULL ; + g_nslots++;
So does reserve_one() and this function, instead of returning the index, communicate using g_nslots variable???
Quoted 10 lines
tools/arch/x86/pmtctl/lib/pmt_guid.c new file +10
-0+ } + +return 0 ; +} + +int pmt_guid_register_owned (void *block,const struct pmt_guid *entries,int count) +{ +void **tmp; +int ret; +
tools/arch/x86/pmtctl/lib/pmt_guid.c line 132
Quoted 10 lines
tools/arch/x86/pmtctl/lib/pmt_guid.c new file +10
-0+/* +* Grow g_owned_blocks first, before registering anything. If this +* fails, no entries have been added to g_slots yet, so the caller +* can safely free(block) on error without leaving dangling slot +* pointers behind. +*/ +if (block && g_nowned == g_owned_cap) { +int new_cap = g_owned_cap ? g_owned_cap *2 :8 ; + + tmp =realloc (g_owned_blocks, (size_t )new_cap *sizeof (*tmp));
Same typing problem as above but it also implies this duplicating code.
Quoted 69 lines
tools/arch/x86/pmtctl/lib/pmt_guid.c new file +68
-0+if (!tmp) +return -ENOMEM ; + + g_owned_blocks = tmp; + g_owned_cap = new_cap; + } + + ret =pmt_guid_register (entries, count); +if (ret <0 ) +return ret; + +if (block) + g_owned_blocks[g_nowned++] = block; + +return 0 ; +} + +const struct pmt_guid *pmt_guid_intern (uint32_t guid) +{ +const struct pmt_guid *existing; +struct pmt_guid *synth; +int ret; + + existing =pmt_guid_lookup (guid); +if (existing) +return existing; + + ret =reserve_one (); +if (ret <0 ) +return NULL ; + + synth =calloc (1 ,sizeof (*synth)); +if (!synth) +return NULL ; + + synth->guid = guid; + synth->name =NULL ; + synth->description =NULL ; + + g_slots[g_nslots].entry = synth; + g_slots[g_nslots].synth = synth; + g_nslots++; + +return synth; +} + +void pmt_guid_cleanup (void ) +{ +for (int i =0 ; i < g_nslots; i++) +free (g_slots[i].synth); + +free (g_slots); + g_slots =NULL ; + g_nslots =0 ; + g_cap =0 ; + +/* +* Owned blocks are freed last: slot entries may have pointed into +* them, but those pointers are gone now that g_slots is released. +*/ +for (int i =0 ; i < g_nowned; i++) +free (g_owned_blocks[i]); + +free (g_owned_blocks); + g_owned_blocks =NULL ; + g_nowned =0 ; + g_owned_cap =0 ; +}
Signature · 1 line
i.
Ilpo Järvinen
maintainerRe: [PATCH 04/17] tools/arch/x86/pmtctl: Add libpmtctl metric definition database
In reply to David E. BoxQuoted 50 lines · David E. Box
Add a growable container for PMT metric definitions to support loading and querying hardware metric descriptors at runtime.
PMT metrics vary by platform and are discovered dynamically from sysfs. A block-based database allows metric definitions to be appended as they are parsed, without requiring the final size to be known in advance, while bounding individual memory allocations.
Assisted-by GitHub-Copilot:claude-sonnet-4.6Signed-off-by David E. Box <[email protected]>--- .../arch/x86/pmtctl/include/lib/metrics_db.h | 69 +++++++++++++++++++ tools/arch/x86/pmtctl/lib/metrics_db.c | 62 +++++++++++++++++ 2 files changed, 131 insertions(+) create mode 100644 tools/arch/x86/pmtctl/include/lib/metrics_db.h create mode 100644 tools/arch/x86/pmtctl/lib/metrics_db.ctools/arch/x86/pmtctl/include/lib/metrics_db.h new file +27
-0@@ -0,0 +1,69 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#ifndef PMTCTL_METRICS_DB_H +#define PMTCTL_METRICS_DB_H + +#include <stdbool.h> +#include <stddef.h> +#include <stdint.h> + +#include "lib/pmt_guid.h" + +/* Metric definition from builtin or JSON */ +struct pmt_metric_def { + const char *event_name; + const char *description; + const char *group; + const char *platform_group; + + const struct pmt_guid *guid; + uint32_t sample_id; + uint8_t lsb; + uint8_t msb; +}; + +struct pmt_metrics_block { + const struct pmt_metric_def *defs; + int count; + bool is_builtin;
tools/arch/x86/pmtctl/include/lib/metrics_db.h line 37
Quoted 10 lines
tools/arch/x86/pmtctl/include/lib/metrics_db.h new file +10
-0+}; + +struct pmt_metrics_db { +struct pmt_metrics_block *blocks; +int nblocks; +int total;/* sum of all block->count */ +}; + +/* Treat DB as a flat array [0..total-1] */ +static inline const struct pmt_metric_def *pmt_metrics_at (const struct pmt_metrics_db *db,int idx)
inline???
Quoted 16 lines
tools/arch/x86/pmtctl/include/lib/metrics_db.h new file +16
-0+{ +if (!db || idx <0 || idx >= db->total) +return NULL ; + +for (int i =0 ; i < db->nblocks; i++) { +if (idx < db->blocks[i].count) +return &db->blocks[i].defs[idx]; + idx -= db->blocks[i].count; + } +return NULL ; +} + +static inline const struct pmt_metrics_block * +pmt_metrics_block_for (const struct pmt_metrics_db *db,int idx) +{ +if (!db || idx <0 || idx >= db->total)
tools/arch/x86/pmtctl/include/lib/metrics_db.h line 63
Quoted 10 lines
tools/arch/x86/pmtctl/include/lib/metrics_db.h new file +10
-0+return NULL ; + +for (int i =0 ; i < db->nblocks; i++) { +if (idx < db->blocks[i].count) +return &db->blocks[i]; + idx -= db->blocks[i].count; + } + +return NULL ; +}
Code duplication.
Quoted 29 lines
tools/arch/x86/pmtctl/include/lib/metrics_db.h new file +6
-0+ +int pmt_metrics_add_block (struct pmt_metrics_db *db,const struct pmt_metric_def *defs, +int count,bool is_builtin); +void pmt_metrics_free (struct pmt_metrics_db *db); + +#endif tools/arch/x86/pmtctl/lib/metrics_db.c new file +17
-0@@ -0,0 +1,62 @@ +// SPDX-License-Identifier: GPL-2.0-only +#include <errno.h> +#include <limits.h> +#include <stdlib.h> +#include <string.h> + +#include "lib/metrics_db.h" + +int pmt_metrics_add_block (struct pmt_metrics_db *db,const struct pmt_metric_def *defs, +int count,bool is_builtin) +{ +struct pmt_metrics_block *blocks; +size_t alloc_size; +int new_cap; + +if (!db || !defs || count <=0 ) +return -EINVAL ;
tools/arch/x86/pmtctl/lib/metrics_db.c line 27
Quoted 10 lines
tools/arch/x86/pmtctl/lib/metrics_db.c new file +10
-0+ +if (db->nblocks >INT_MAX -1 ) +return -EOVERFLOW ; + +if (db->total >INT_MAX - count) +return -EOVERFLOW ; + + new_cap = db->nblocks +1 ; + +if ((size_t )new_cap >SIZE_MAX /sizeof (*blocks))
Casts like this likely indicates some typing issue in your code.
tools/arch/x86/pmtctl/lib/metrics_db.c line 32
Quoted 5 lines
tools/arch/x86/pmtctl/lib/metrics_db.c new file +5
-0+return -EOVERFLOW ; + + alloc_size = (size_t )new_cap *sizeof (*blocks); + + blocks =realloc (db->blocks, alloc_size);
So this reallocs + 1 every time??
Quoted 29 lines
tools/arch/x86/pmtctl/lib/metrics_db.c new file +29
-0+if (!blocks) +return -ENOMEM ; + + db->blocks = blocks; + + db->blocks[db->nblocks].defs = defs; + db->blocks[db->nblocks].count = count; + db->blocks[db->nblocks].is_builtin = is_builtin; + + db->nblocks++; + db->total += count; + +return 0 ; +} + +void pmt_metrics_free (struct pmt_metrics_db *db) +{ +if (!db) +return ; + +if (db->blocks) { +for (int i =0 ; i < db->nblocks; i++) { +if (!db->blocks[i].is_builtin && db->blocks[i].defs) +free ((void *)db->blocks[i].defs); + } +free (db->blocks); + } + +memset (db,0 ,sizeof (*db));
Signature · 1 line
i.
Ilpo Järvinen
maintainerRe: [PATCH 05/17] tools/arch/x86/pmtctl: Add libpmtctl device enumeration backend
In reply to David E. BoxQuoted 38 lines · David E. Box
Add a sysfs-based backend for enumerating Intel PMT telemetry devices, enabling libpmtctl to discover and access hardware telemetry data at runtime without hardcoded device paths.
Intel PMT telemetry devices are exposed under
/sys/bus/auxiliary/drivers/pmt_telemetry. This backend walks those sysfs entries to discover device metadata and data paths, populating per-device descriptors used by the metric access layer.Introduce a
pmt_device_opsvtable to allow additional enumeration backends or PMT transport types to be added without changing the calling code.Assisted-by GitHub-Copilot:claude-sonnet-4.6Signed-off-by David E. Box <[email protected]>--- tools/arch/x86/pmtctl/include/lib/device.h | 53 +++ tools/arch/x86/pmtctl/lib/device_telem.c | 371 +++++++++++++++++++++ 2 files changed, 424 insertions(+) create mode 100644 tools/arch/x86/pmtctl/include/lib/device.h create mode 100644 tools/arch/x86/pmtctl/lib/device_telem.ctools/arch/x86/pmtctl/include/lib/device.h new file +11
-0@@ -0,0 +1,53 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#ifndef PMTCTL_DEVICES_H +#define PMTCTL_DEVICES_H + +#include <stdint.h> + +#include "metrics_db.h" +#include "pmtctl_types.h" + +#define PMT_SAMPLE_SIZE 8 +
tools/arch/x86/pmtctl/include/lib/device.h line 21
Quoted 10 lines
tools/arch/x86/pmtctl/include/lib/device.h new file +10
-0+/* --- Device representation returned by any device --- */ +struct pmt_device { +const struct pmt_guid *guid;/* per-GUID metadata (interned) */ +int guid_inst;/* global guid instance */ +int dev_inst;/* local device instance */ + +char *name;/* e.g. "pmt_ep_27971628_0" or "telem0" */ +char *path;/* e.g. "/sys/class/intel_pmt/telem0" */ +char *data_path;/* readable metric data path for this device */ +int instance;/* 0, 1, etc. */
Inconsistent alignment.
These are using spaces to align.
Quoted 7 lines
tools/arch/x86/pmtctl/include/lib/device.h new file +7
-0+int pkg_id;/* Package/Socket ID if known, else -1 */ +int die_id;/* Die ID if known, else -1 */ + +int fd;/* telem file fd */ +}; + +struct pmt_metric_desc {
tools/arch/x86/pmtctl/include/lib/device.h line 39
Quoted 10 lines
tools/arch/x86/pmtctl/include/lib/device.h new file +10
-0+const struct pmt_metric_def *def; +struct pmt_device *dev; + +const char *name;/* JSON name */ +int guid_inst;/* global GUID instance (matches pmt_device.guid_inst) */ + +/* raw mode fields */ +uint32_t raw_sample_id; +uint8_t raw_lsb; +uint8_t raw_msb;
Extra spaces.
tools/arch/x86/pmtctl/include/lib/device.h line 47
Quoted 8 lines
tools/arch/x86/pmtctl/include/lib/device.h new file +8
-0+ +}; + +struct pmt_device_ops { +enum pmt_device_type dev_type; +int (*init)(void ); +void (*cleanup)(void ); +int (*read)(struct pmt_metric_desc *m,uint64_t *val);
It seems pretty random when things are aligned with extra spaces and when not.
Quoted 37 lines
tools/arch/x86/pmtctl/include/lib/device.h new file +6
-0+ struct pmt_device *(*device_list)(int *count); +}; + +extern struct pmt_device_ops device_telem_ops; + +#endif tools/arch/x86/pmtctl/lib/device_telem.c new file +25
-0@@ -0,0 +1,371 @@ +// SPDX-License-Identifier: GPL-2.0-only +#define LOG_PREFIX "telem" +#include <dirent.h> +#include <errno.h> +#include <fcntl.h> +#include <limits.h> +#include <stdio.h> +#include <stdint.h> +#include <stdlib.h> +#include <string.h> +#include <sys/stat.h> +#include <sys/types.h> +#include <unistd.h> + +#include "lib/common.h" +#include "lib/device.h" +#include "lib/log.h" + +#define PMT_TELEM_AUX_DIR "/sys/bus/auxiliary/drivers/pmt_telemetry" +#define PMT_TELEM_PMT_DIR "intel_pmt" +#define PMT_TELEM_DATA_FILE "telem" + +static struct pmt_device *devices; +static int device_count; +static int device_initialized;
tools/arch/x86/pmtctl/lib/device_telem.c line 35
Quoted 10 lines
tools/arch/x86/pmtctl/lib/device_telem.c new file +10
-0+ +static int telem_read (struct pmt_metric_desc *m,uint64_t *val) +{ +uint64_t raw; +uint64_t mask; +uint8_t width; +ssize_t n; +off_t off; +uint32_t sample_id; +uint8_t lsb, msb;
Extra space.
tools/arch/x86/pmtctl/lib/device_telem.c line 47
Quoted 12 lines
tools/arch/x86/pmtctl/lib/device_telem.c new file +12
-0+ +if (!m || !val || !m->dev) +log_bug_and_exit ("unexpected NULL parameters" ); + +/* Open the telem file on first read */ +if (m->dev->fd <0 ) { +int fd; + +if (!m->dev->data_path) +return log_ret (-EINVAL ,"missing data path for %s" , m->dev->name); + + fd =open (m->dev->data_path,O_RDONLY |O_CLOEXEC );
Is CLOEXEC required? (I don't know the general structure of this program.)
Quoted 7 lines
tools/arch/x86/pmtctl/lib/device_telem.c new file +7
-0+if (fd ==-1 ) +return log_ret (-errno,"could not open telem file %s" , m->dev->data_path); + + m->dev->fd = fd; + } + +if (m->def) {
tools/arch/x86/pmtctl/lib/device_telem.c line 64
Quoted 10 lines
tools/arch/x86/pmtctl/lib/device_telem.c new file +10
-0+ sample_id = m->def->sample_id; + lsb = m->def->lsb; + msb = m->def->msb; + }else { + sample_id = m->raw_sample_id; + lsb = m->raw_lsb; + msb = m->raw_msb; + } + +if (msb >63 || lsb > msb)
Isn't that 63 a bit index? It should be written without literals.
tools/arch/x86/pmtctl/lib/device_telem.c line 75
Quoted 11 lines
tools/arch/x86/pmtctl/lib/device_telem.c new file +11
-0+return PMTCTL_ERR_DEVICE ; + + off = (off_t )sample_id *PMT_SAMPLE_SIZE ; + + n =pread (m->dev->fd, &raw,sizeof (raw), off); +if (n ==-1 ) { +log_err_once (-errno,"unable to read telem %s" , m->dev->name); +return -errno; + } + +if (n != (ssize_t )sizeof (raw)) {
If casting after error n checking, shouldn't the case be other way around?
tools/arch/x86/pmtctl/lib/device_telem.c line 84
Quoted 9 lines
tools/arch/x86/pmtctl/lib/device_telem.c new file +9
-0+log_err_once (-EIO ,"read expected %zu bytes, got %zd (dev=%s)" , +sizeof (raw), n, m->dev->name); +return -EIO ; + } + +if (lsb ==0 && msb ==63 ) { + *val = raw; +return 0 ; + }
Is this optimization useful?
tools/arch/x86/pmtctl/lib/device_telem.c line 87
Quoted 2 lines
tools/arch/x86/pmtctl/lib/device_telem.c new file +2
-0+ width = msb - lsb +1 ; +if (width >=64 )
How can this happen?
tools/arch/x86/pmtctl/lib/device_telem.c line 90
Quoted 3 lines
tools/arch/x86/pmtctl/lib/device_telem.c new file +3
-0+ mask = ~0ULL ; + else + mask = (1ULL << width) -1ULL ;
Is shifting by 64 undefined behavior? If it's not, then it looks to me that this is all you need?
Quoted 41 lines
tools/arch/x86/pmtctl/lib/device_telem.c new file +41
-0+ + *val = (raw >> lsb) & mask; + +return 0 ; +} + +static struct pmt_device *telem_device_list (int *count) +{ +if (!count || !device_initialized) +return NULL ; + + *count = device_count; + +return devices; +} + +/* ----------------- per-GUID instance tracking ----------------- */ +struct guid_counter { +uint32_t guid; +int next_guid_inst; +}; + +struct dev_guid_counter { +int dev_index; +uint32_t guid; +int next_dev_inst; +}; + +static struct guid_counter *guid_counters; +static int guid_counter_cnt; + +static struct dev_guid_counter *dev_guid_counters; +static int dev_guid_counter_cnt; +/* -------------------------------------------------------------- */ + +static int next_guid_instance_global (uint32_t guid) +{ +struct guid_counter *tmp; +int inst =0 ; +int i; +
tools/arch/x86/pmtctl/lib/device_telem.c line 141
Quoted 10 lines
tools/arch/x86/pmtctl/lib/device_telem.c new file +10
-0+for (i =0 ; i < guid_counter_cnt; i++) { +if (guid_counters[i].guid == guid) { + inst = guid_counters[i].next_guid_inst; + guid_counters[i].next_guid_inst++; +return inst; + } + } + +/* new guid, start at 0 */ + tmp =realloc (guid_counters, (guid_counter_cnt +1 ) *sizeof (*guid_counters));
This realloc by +1 seems really endemic and I'm not convinced its good way to handle things.
Quoted 33 lines
tools/arch/x86/pmtctl/lib/device_telem.c new file +33
-0+if (!tmp) +return -ENOMEM ; + + guid_counters = tmp; + guid_counters[guid_counter_cnt].guid = guid; + guid_counters[guid_counter_cnt].next_guid_inst =1 ; + guid_counter_cnt++; + +return inst; +} + +static int next_guid_instance_device (int dev_index,uint32_t guid) +{ +struct dev_guid_counter *tmp; +int inst =0 ; +int i; + +for (i =0 ; i < dev_guid_counter_cnt; i++) { +if (dev_guid_counters[i].dev_index == dev_index && + dev_guid_counters[i].guid == guid) { + inst = dev_guid_counters[i].next_dev_inst; + dev_guid_counters[i].next_dev_inst++; +return inst; + } + } + +/* new (dev_index, guid) pair */ + tmp =realloc (dev_guid_counters, (dev_guid_counter_cnt +1 ) *sizeof (*dev_guid_counters)); +if (!tmp) +return -ENOMEM ; + + dev_guid_counters = tmp; + dev_guid_counters[dev_guid_counter_cnt].dev_index = dev_index;
tools/arch/x86/pmtctl/lib/device_telem.c line 184
Quoted 10 lines
tools/arch/x86/pmtctl/lib/device_telem.c new file +10
-0+ dev_guid_counters[dev_guid_counter_cnt].guid = guid; + dev_guid_counters[dev_guid_counter_cnt].next_dev_inst =1 ; + dev_guid_counter_cnt++; + +return inst; +} + +static int telem_add_device (const char *devpath,const char *devname,int dev_index) +{ +struct pmt_device dev = {0 };
= {} is enough to initialize.
Quoted 10 lines
tools/arch/x86/pmtctl/lib/device_telem.c new file +10
-0+ + auto_free char *temp_name = NULL; + auto_free char *temp_path = NULL; + auto_free char *temp_data_path = NULL; +char data_path[PATH_MAX ]; +uint32_t raw_guid; +int len; +int ret; + +if (!devpath || !devname)
tools/arch/x86/pmtctl/lib/device_telem.c line 204
Quoted 10 lines
tools/arch/x86/pmtctl/lib/device_telem.c new file +10
-0+return -EINVAL ; + + temp_name =xstrdup (devname); + temp_path =xstrdup (devpath); + + len =snprintf (data_path,sizeof (data_path),"%s/" PMT_TELEM_DATA_FILE , devpath); +if (len <0 || (size_t )len >=sizeof (data_path)) +return log_ret (-EINVAL ,"path too long for %s" , devname); + + temp_data_path =xstrdup (data_path);
Why you first write to stack and then strdup() instead of doing it directly?
Quoted 67 lines
tools/arch/x86/pmtctl/lib/device_telem.c new file +67
-0+ +/* Defaults */ + dev.pkg_id =-1 ;// not availeble in /sys/class/intel_pmt + dev.die_id =-1 ;// not available in /sys/class/intel_pmt + +/* Get guid */ + ret =read_u32_hex_attr (devpath,"guid" , &raw_guid,PMTCTL_ERR_DEVICE ); +if (ret) +return log_ret (ret,"unable to read guid for %s" , devpath); + + dev.guid =pmt_guid_intern (raw_guid); +if (!dev.guid) +return log_ret (-ENOMEM ,"could not intern guid 0x%08x" , raw_guid); + +/* Compute instances */ + ret =next_guid_instance_global (raw_guid); +if (ret <0 ) +return ret; + + dev.guid_inst = ret; + + ret =next_guid_instance_device (dev_index, raw_guid); +if (ret <0 ) +return ret; + + dev.dev_inst = ret; + +/* Don't open telem file yet - defer until first read */ + dev.fd =-1 ; + +/* Append to global array */ +struct pmt_device *tmp; + + tmp =realloc (devices, (device_count +1 ) *sizeof (*devices)); +if (!tmp) +return log_ret (-ENOMEM ,"could not add telem device %s" , devpath); + + dev.name = temp_name; + dev.path = temp_path; + dev.data_path = temp_data_path; + + temp_name =NULL ; + temp_path =NULL ; + temp_data_path =NULL ; + + devices = tmp; + devices[device_count++] = dev; + +return 0 ; +} + +static int telem_scan_intel_pmt (void ) +{ +DIR *aux_dir =opendir (PMT_TELEM_AUX_DIR ); +struct dirent *aux_de; +int dev_index =0 ; + +if (!aux_dir) { +log_debug ("error opening %s: %s" ,PMT_TELEM_AUX_DIR ,strerror (errno)); +return -errno; + } + +while ((aux_de =readdir (aux_dir))) { +char intel_pmt_path[PATH_MAX ]; +struct dirent *pmt_de; +DIR *pmt_dir; +ssize_t len;
tools/arch/x86/pmtctl/lib/device_telem.c line 281
Quoted 10 lines
tools/arch/x86/pmtctl/lib/device_telem.c new file +10
-0+ +/* skip . and .. */ +if (aux_de->d_name[0 ] =='.' ) +continue ; + + len =snprintf (intel_pmt_path,sizeof (intel_pmt_path), +"%s/%s/" PMT_TELEM_PMT_DIR , +PMT_TELEM_AUX_DIR , aux_de->d_name); + +if (len <0 || (size_t )len >=sizeof (intel_pmt_path))
No emptylines between call and its error handling.
tools/arch/x86/pmtctl/lib/device_telem.c line 294
Quoted 13 lines
tools/arch/x86/pmtctl/lib/device_telem.c new file +13
-0+continue ; + + pmt_dir =opendir (intel_pmt_path); +if (!pmt_dir) +continue ; + +while ((pmt_de =readdir (pmt_dir)) !=NULL ) { +char telem_path[PATH_MAX ]; +int ret; + +/* only telem* directories */ +if (strncmp (pmt_de->d_name,PMT_TELEM_DATA_FILE , +strlen (PMT_TELEM_DATA_FILE )) !=0 )
I tried to figure out if strncmp() can be replaced with strcmp() but I was left unsure. It seems telem_add_device() adds '/' to it which would indicate n variant is not required (and the comment is misleadingly lacking that /).
Quoted 78 lines
tools/arch/x86/pmtctl/lib/device_telem.c new file +77
-0+continue ; + + len =snprintf (telem_path,sizeof (telem_path), +"%s/%s" , intel_pmt_path, pmt_de->d_name); +if (len <0 || (size_t )len >=sizeof (telem_path)) +continue ; + + ret =telem_add_device (telem_path, pmt_de->d_name, dev_index); +if (ret) +log_warn ("unable to add telem device %s (ret=%d)" , + telem_path, ret); + } + +closedir (pmt_dir); + dev_index++; + } +closedir (aux_dir); + +if (device_count ==0 ) +return PMTCTL_ERR_NOTFOUND ; + +return 0 ; +} + +static int telem_init (void ) +{ +int ret; + +if (device_initialized) +return 0 ; + + ret =telem_scan_intel_pmt (); +if (ret) +return ret; + + device_initialized =1 ; + +return 0 ; +} + +static void telem_cleanup (void ) +{ +int i; + +if (!device_initialized) +return ; + +for (i =0 ; i < device_count; i++) { +if (devices[i].fd >=0 ) +close (devices[i].fd); + +free (devices[i].name); +free (devices[i].path); +free (devices[i].data_path); + } + +free (guid_counters); + guid_counters =NULL ; + guid_counter_cnt =0 ; + +free (dev_guid_counters); + dev_guid_counters =NULL ; + dev_guid_counter_cnt =0 ; + +free (devices); + devices =NULL ; + device_count =0 ; + device_initialized =0 ; +} + +struct pmt_device_ops device_telem_ops = { + .dev_type =PMT_DEVICE_TELEM , + .init = telem_init, + .cleanup = telem_cleanup, + .read = telem_read, + .device_list = telem_device_list, +};
Signature · 1 line
i.
Ilpo Järvinen
maintainerRe: [PATCH 07/17] tools/arch/x86/pmtctl: Add libpmtctl JSON metric provider
In reply to David E. BoxQuoted 28 lines · David E. Box
Add an optional JSON-based metric definition provider to
libpmtctl_core, allowing PMT metric definitions to be supplied at runtime from external files rather than compiled into the library.This allows platform-specific metric definitions to be maintained separately from the kernel tree and updated without rebuilding the library. The provider accepts either a single JSON file or a directory of JSON files, loading discovered definitions into the metric database.
When built with
HAVE_JANSSON,pmt_metrics_load()dispatches non-NULL path arguments to the JSON provider. Otherwise,PMTCTL_ERR_UNSUPPORTEDis returned so callers can detect that JSON-backed loading is unavailable.Build-system wiring is added in a later patch of the series.
Assisted-by GitHub-Copilot:claude-sonnet-4.6Signed-off-by David E. Box <[email protected]>--- .../x86/pmtctl/lib/metrics_provider_json.c | 459 ++++++++++++++++++ 1 file changed, 459 insertions(+) create mode 100644 tools/arch/x86/pmtctl/lib/metrics_provider_json.ctools/arch/x86/pmtctl/lib/metrics_provider_json.c new file +0
-0
tools/arch/x86/pmtctl/lib/metrics_provider_json.c line 2
Quoted 2 lines
tools/arch/x86/pmtctl/lib/metrics_provider_json.c new file +2
-0@@ -0,0 +1,459 @@ +// SPDX-License-Identifier: GPL-2.0-only +#define LOG_PREFIX "metrics_provider_json"
Empty lines missing, but shouldn't this be after includes?
Quoted 11 lines
tools/arch/x86/pmtctl/lib/metrics_provider_json.c new file +11
-0+#include <dirent.h> +#include <errno.h> +#include <jansson.h> +#include <limits.h> +#include <stdbool.h> +#include <stdlib.h> +#include <string.h> +#include <sys/stat.h> + +#include "lib/log.h" +#include "lib/metrics_db.h"
tools/arch/x86/pmtctl/lib/metrics_provider_json.c line 23
Quoted 10 lines
tools/arch/x86/pmtctl/lib/metrics_provider_json.c new file +10
-0+#include "lib/metrics_provider.h" + +static bool is_regular (const char *path) +{ +struct stat st; + +if (stat (path, &st) <0 ) +return false; + +return !!S_ISREG (st.st_mode);
Unnecessary !!
Quoted 14 lines
tools/arch/x86/pmtctl/lib/metrics_provider_json.c new file +14
-0+} + +static bool is_dir (const char *path) +{ +struct stat st; + +if (stat (path, &st) <0 ) +return false; + +return !!S_ISDIR (st.st_mode); +} + +static const char *pool_copy (char **pool,const char *s) +{
tools/arch/x86/pmtctl/lib/metrics_provider_json.c line 47
Quoted 10 lines
tools/arch/x86/pmtctl/lib/metrics_provider_json.c new file +10
-0+char *dst; +size_t len; + +if (!pool || !s) +return NULL ; + + len =strlen (s) +1 ; + dst = *pool; + +memcpy (dst, s, len);
This is generally a dangerous pattern: length is taken from that of source, whereas we'd want to check that dst space does not overflow.
tools/arch/x86/pmtctl/lib/metrics_provider_json.c line 48
Quoted 1 line
tools/arch/x86/pmtctl/lib/metrics_provider_json.c new file +1
-0+ *pool += len;
This looks some adhoc string heap management to me, and it honestly doesn't impress me.
Quoted 14 lines
tools/arch/x86/pmtctl/lib/metrics_provider_json.c new file +14
-0+return dst; +} + +/* +* Example PMU name: "pmt_ep_3d4bb41a" +* Extract GUID = 0x3d4bb41a +*/ +static uint32_t parse_guid_from_pmu (const char *pmu) +{ +unsigned long val; +const char *last; +const char *p; +char *end; +
tools/arch/x86/pmtctl/lib/metrics_provider_json.c line 73
Quoted 10 lines
tools/arch/x86/pmtctl/lib/metrics_provider_json.c new file +10
-0+if (!pmu) +return 0 ; + + last =strrchr (pmu,'_' ); + p = last ? last +1 : pmu; + + end =NULL ; + val =strtoul (p, &end,16 ); + +if (end == p || val >0xffffffffUL )
Some _MAX?
Quoted 27 lines
tools/arch/x86/pmtctl/lib/metrics_provider_json.c new file +27
-0+return 0 ; + +return (uint32_t )val; +} + +/* +* Decode a perf-style ConfigCode string into (sample_id, lsb, msb). +* +* Bit layout (matches scripts/gen_builtin_defs.py::decode_config_code() +* and scripts/pmtxml2json.py::pack_config()): +* +* bits[15:0] sample_id +* bits[23:16] lsb +* bits[31:24] msb +* +* Returns 0 on success, or -EINVAL if the string is malformed or the +* decoded range is out of bounds. A missing ConfigCode (NULL) decodes +* to (0, 0, 0) successfully so callers don't need to special-case it. +*/ +static int parse_config_code (const char *s,uint32_t *sample_id, +uint8_t *lsb,uint8_t *msb) +{ +unsigned long val; +char *end; +uint8_t l, m; + + *sample_id =0 ;
tools/arch/x86/pmtctl/lib/metrics_provider_json.c line 110
Quoted 10 lines
tools/arch/x86/pmtctl/lib/metrics_provider_json.c new file +10
-0+ *lsb =0 ; + *msb =0 ; + +if (!s) +return 0 ; + + end =NULL ; + val =strtoul (s, &end,0 ); + +if (end == s || *end !='\0' || val >0xffffffffUL )
*_MAX?
tools/arch/x86/pmtctl/lib/metrics_provider_json.c line 116
Quoted 6 lines
tools/arch/x86/pmtctl/lib/metrics_provider_json.c new file +6
-0+return -EINVAL ; + + l = (val >>16 ) &0xff ; + m = (val >>24 ) &0xff ; + +if (m >63 || l > m)
63 relates to bit index so don't write it as a literal)
Quoted 14 lines
tools/arch/x86/pmtctl/lib/metrics_provider_json.c new file +14
-0+return -EINVAL ; + + *sample_id = val &0xffff ; + *lsb = l; + *msb = m; +return 0 ; +} + +static int json_count_root (json_t *root,size_t *metric_count,size_t *string_bytes) +{ +size_t n; + +if (!json_is_array (root)) +return -EINVAL ;
tools/arch/x86/pmtctl/lib/metrics_provider_json.c line 140
Quoted 10 lines
tools/arch/x86/pmtctl/lib/metrics_provider_json.c new file +10
-0+ + n =json_array_size (root); + +for (size_t i =0 ; i < n; i++) { +const char *name, *brief, *group, *platform_group; +json_t *ev; + + ev =json_array_get (root, i); + +if (!json_is_object (ev))
No empty lines between call and its error handling.
Quoted 5 lines
tools/arch/x86/pmtctl/lib/metrics_provider_json.c new file +5
-0+continue ; + + name =json_string_value (json_object_get (ev,"EventName" )); + brief =json_string_value (json_object_get (ev,"BriefDescription" )); + group =json_string_value (json_object_get (ev,"MetricGroup" ));
tools/arch/x86/pmtctl/lib/metrics_provider_json.c line 155
Quoted 10 lines
tools/arch/x86/pmtctl/lib/metrics_provider_json.c new file +10
-0+ platform_group =json_string_value (json_object_get (ev,"PlatformGroup" )); + +if (name) + *string_bytes +=strlen (name) +1 ; +if (brief) + *string_bytes +=strlen (brief) +1 ; +if (group) + *string_bytes +=strlen (group) +1 ; +if (platform_group) + *string_bytes +=strlen (platform_group) +1 ;
Another part of the adhoc heap management? Please don't do this.
Quoted 149 lines
tools/arch/x86/pmtctl/lib/metrics_provider_json.c new file +149
-0+ + (*metric_count)++; + } + +if (*metric_count ==0 ) +return PMTCTL_ERR_NOMETRICS ; + +return 0 ; +} + +static int json_fill_root (json_t *root,struct pmt_metric_def *defs,char **pool) +{ +int idx =0 ; +size_t n; + +if (!json_is_array (root)) +return -EINVAL ; + + n =json_array_size (root); + +for (size_t i =0 ; i < n; i++) { +const char *pmu, *name, *brief, *group, *platform_group, *cfg; +json_t *ev; +struct pmt_metric_def *m; +int ret; + + ev =json_array_get (root, i); + +if (!json_is_object (ev)) +continue ; + + m = &defs[idx++]; + + pmu =json_string_value (json_object_get (ev,"PMU" )); + name =json_string_value (json_object_get (ev,"EventName" )); + brief =json_string_value (json_object_get (ev,"BriefDescription" )); + group =json_string_value (json_object_get (ev,"MetricGroup" )); + platform_group =json_string_value (json_object_get (ev,"PlatformGroup" )); + cfg =json_string_value (json_object_get (ev,"ConfigCode" )); + + m->event_name =pool_copy (pool, name); + m->description =pool_copy (pool, brief); + m->group =pool_copy (pool, group); + m->platform_group =pool_copy (pool, platform_group); + m->guid =pmt_guid_intern (parse_guid_from_pmu (pmu)); +if (!m->guid) +return -ENOMEM ; + + ret =parse_config_code (cfg, &m->sample_id, &m->lsb, &m->msb); +if (ret) +return log_ret (ret,"metric \"%s\" (PMU %s): invalid ConfigCode \"%s\"" , + name ? name :"(null)" , + pmu ? pmu :"(null)" , + cfg ? cfg :"(null)" ); + } + +return 0 ; +} + +static struct pmt_metric_def *load_metrics_from_json_single (const char *path,int *count) +{ +json_error_t error; +json_t *root; +struct pmt_metric_def *defs; +void *block; +char *pool; +size_t metric_count =0 ; +size_t string_bytes =0 ; +size_t def_bytes; +size_t total_bytes; +int ret; + +if (!count) +return NULL ; + + *count =0 ; + + root =json_load_file (path,0 , &error); +if (!root) { +log_err (PMTCTL_ERR_METRICS ,"JSON parse error in %s: %s\n" , path, error.text); +return NULL ; + } + + ret =json_count_root (root, &metric_count, &string_bytes); +if (ret <0 ) { +json_decref (root); +return NULL ; + } + + def_bytes = metric_count *sizeof (struct pmt_metric_def ); + total_bytes = def_bytes + string_bytes; + + block =malloc (total_bytes); +if (!block) { +json_decref (root); +return NULL ; + } + + defs = block; +memset (defs,0 , def_bytes); + pool = (char *)block + def_bytes; + + ret =json_fill_root (root, defs, &pool); +json_decref (root); +if (ret <0 ) { +free (block); +return NULL ; + } + + *count = (int )metric_count; + +return defs; +} + +static int load_pmt_guids_sidecar (const char *path) +{ +json_error_t error; +json_t *root; +struct pmt_guid *table; +char *pool; +size_t string_bytes =0 ; +size_t n; +int ret = -EINVAL ; + + root =json_load_file (path,0 , &error); +if (!root) { +log_warn ("pmt_guids JSON parse error in %s: %s\n" , path, error.text); +return -EINVAL ; + } + +if (!json_is_array (root)) { +json_decref (root); +return -EINVAL ; + } + + n =json_array_size (root); +if (n ==0 ) { +json_decref (root); +return 0 ; + } + +for (size_t i =0 ; i < n; i++) { +json_t *e =json_array_get (root, i); +const char *s; + +if (!json_is_object (e)) +continue ; + s =json_string_value (json_object_get (e,"name" )); +if (s)
tools/arch/x86/pmtctl/lib/metrics_provider_json.c line 314
Quoted 10 lines
tools/arch/x86/pmtctl/lib/metrics_provider_json.c new file +10
-0+ string_bytes +=strlen (s) +1 ; + s =json_string_value (json_object_get (e,"description" )); +if (s) + string_bytes +=strlen (s) +1 ; + } + + table =calloc (1 , n *sizeof (*table) + string_bytes); +if (!table) { +json_decref (root); +return -ENOMEM ;
Instead of duplication root decref, add a label and goto to the end.
tools/arch/x86/pmtctl/lib/metrics_provider_json.c line 317
Quoted 3 lines
tools/arch/x86/pmtctl/lib/metrics_provider_json.c new file +3
-0+ } + + pool = (char *)table + n *sizeof (*table);
Can this be written without casting to an alien type???
Quoted 15 lines
tools/arch/x86/pmtctl/lib/metrics_provider_json.c new file +15
-0+ +for (size_t i =0 ; i < n; i++) { +json_t *e =json_array_get (root, i); +const char *guid_s, *name, *desc; +unsigned long guid_val; +char *end; + +if (!json_is_object (e)) +continue ; + + guid_s =json_string_value (json_object_get (e,"guid" )); +if (!guid_s) +continue ; + + errno =0 ;
tools/arch/x86/pmtctl/lib/metrics_provider_json.c line 342
Quoted 10 lines
tools/arch/x86/pmtctl/lib/metrics_provider_json.c new file +10
-0+ guid_val =strtoul (guid_s, &end,0 ); +if (errno || end == guid_s || *end !='\0' || guid_val >UINT32_MAX ) +continue ; + + name =json_string_value (json_object_get (e,"name" )); + desc =json_string_value (json_object_get (e,"description" )); + + table[i].guid = (uint32_t )guid_val; + table[i].name = name ?pool_copy (&pool, name) :NULL ; + table[i].description = desc ?pool_copy (&pool, desc) :NULL ;
pool_copy() handles NULL inputs so why is the check duplicated here?
tools/arch/x86/pmtctl/lib/metrics_provider_json.c line 345
Quoted 3 lines
tools/arch/x86/pmtctl/lib/metrics_provider_json.c new file +3
-0+ } + + ret =pmt_guid_register_owned (table, table, (int )n);
A typing issue?
tools/arch/x86/pmtctl/lib/metrics_provider_json.c line 349
Quoted 4 lines
tools/arch/x86/pmtctl/lib/metrics_provider_json.c new file +4
-0+ +json_decref (root); +if (ret <0 ) +free (table);
Error handling should be first.
Quoted 22 lines
tools/arch/x86/pmtctl/lib/metrics_provider_json.c new file +22
-0+ +return ret; +} + +static int load_metrics_from_json_dir (const char *dir_path,struct pmt_metrics_db *db) +{ +DIR *d =opendir (dir_path); +struct dirent *de; +char guids_path[PATH_MAX ]; +int len; +int ret =0 ; + +if (!d) +return log_ret (-errno,"could not open %s" , dir_path); + +/* +* Load the optional pmt_guids.json sidecar first so any subsequent +* intern calls in json_fill_root() resolve to the registered +* struct pmt_guid entries (with name/description populated). +*/ + len =snprintf (guids_path,sizeof (guids_path),"%s/%s" , dir_path,"pmt_guids.json" ); +if (len >0 && (size_t )len <sizeof (guids_path) &&is_regular (guids_path))
tools/arch/x86/pmtctl/lib/metrics_provider_json.c line 381
Quoted 10 lines
tools/arch/x86/pmtctl/lib/metrics_provider_json.c new file +10
-0+ (void )load_pmt_guids_sidecar (guids_path); + +while ((de =readdir (d)) !=NULL ) { +struct pmt_metric_def *defs; +const char *name = de->d_name; +const char *dot =strrchr (name,'.' ); +char pathbuf[PATH_MAX ]; +int count =0 ; + +if (name[0 ] =='.' )
dot == name ?
tools/arch/x86/pmtctl/lib/metrics_provider_json.c line 392
Quoted 11 lines
tools/arch/x86/pmtctl/lib/metrics_provider_json.c new file +11
-0+continue ; + +if (!dot ||strcmp (dot,".json" )) +continue ; + +/* Sidecar already handled above. */ +if (!strcmp (name,"pmt_guids.json" )) +continue ; + +if (snprintf (pathbuf,sizeof (pathbuf),"%s/%s" , dir_path, name) >= + (int )sizeof (pathbuf))
No! Do the error check separately.
Quoted 68 lines
tools/arch/x86/pmtctl/lib/metrics_provider_json.c new file +67
-0+continue ; +if (!is_regular (pathbuf)) +continue ; + + defs =load_metrics_from_json_single (pathbuf, &count); +if (!defs) { +log_warn ("unable to load JSON %s\n" , pathbuf); + ret = -EINVAL ; +continue ; + } + + ret =pmt_metrics_add_block (db, defs, count, false); +if (ret <0 ) { +free (defs); +log_ret (ret,"unable to add json %s" , pathbuf); +break ; + } + } +closedir (d); + +if (ret <0 ) { +pmt_metrics_free (db); +return ret; + } + +/* +* Successfully scanned the directory. A zero count is reported via +* db->total == 0 to the caller; the dir itself was not broken, so +* do not invent an error rc here. pmtctl_init() distinguishes +* "broken source" (negative rc) from "empty source" (rc == 0 with +* db->total == 0) and only fails the init in the former case. +*/ +return 0 ; +} + +int pmt_metrics_load_json (const char *json_path,struct pmt_metrics_db *db) +{ +int ret; + +if (!db) +log_bug_and_exit ("invalid metric db pointer" ); + +if (!json_path) +return PMTCTL_ERR_METRICS ; + +if (is_regular (json_path)) { +struct pmt_metric_def *defs; +int count =0 ; + + defs =load_metrics_from_json_single (json_path, &count); +if (!defs) +return log_ret (PMTCTL_ERR_METRICS ,"unable to load json %s" , json_path); + + ret =pmt_metrics_add_block (db, defs, count, false); +if (ret <0 ) { +free (defs); +return log_ret (ret,"unable to add json %s" , json_path); + } + +return 0 ; + } + +if (is_dir (json_path)) +return load_metrics_from_json_dir (json_path, db); + +return PMTCTL_ERR_METRICS ; +}
Signature · 1 line
i.
Ilpo Järvinen
maintainerRe: [PATCH 08/17] tools/arch/x86/pmtctl: Add libpmtctl public API and context
In reply to David E. BoxQuoted 234 lines · David E. Box
Add the public API for
libpmtctl_coreand the context object that backs it, providing callers with a stable, opaque interface for discovering Intel PMT telemetry devices and querying their metrics without depending on internal library structures.This patch adds the primary lifecycle and query interfaces used by library consumers.
pmtctl_init()performs device enumeration and metric database loading once during initialization so subsequent queries operate on cached state rather than re-scanning sysfs.pmtctl_cleanup()releases associated resources.The library context (struct
pmtctl_context) remains opaque to callers.pmtctl_get_ctx()provides controlled access for consumers that need to pass library context across translation units.Add
PMTCTL_SCOPE_GUARD()as a convenience macro for deterministic cleanup of library-managed resources in single-exit C code paths.Build-system wiring is added a later patch of the series.
Assisted-by GitHub-Copilot:claude-sonnet-4.6Signed-off-by David E. Box <[email protected]>--- tools/arch/x86/pmtctl/include/lib/pmtctl.h | 90 +++++ .../x86/pmtctl/include/lib/pmtctl_context.h | 21 ++ tools/arch/x86/pmtctl/lib/pmtctl.c | 327 ++++++++++++++++++ 3 files changed, 438 insertions(+) create mode 100644 tools/arch/x86/pmtctl/include/lib/pmtctl.h create mode 100644 tools/arch/x86/pmtctl/include/lib/pmtctl_context.h create mode 100644 tools/arch/x86/pmtctl/lib/pmtctl.ctools/arch/x86/pmtctl/include/lib/pmtctl.h new file +90
-0@@ -0,0 +1,90 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#ifndef PMTCTL_H +#define PMTCTL_H + +#include <stdbool.h> +#include <stdint.h> + +#include <linux/compiler.h> +#include "pmtctl_types.h" + +enum pmt_selector_kind { +PMT_SEL_ANY =0 ,/* no selector provided */ +PMT_SEL_GUID ,/* guid=27971628 */ +PMT_SEL_EP_NAME ,/* ep=pmt_ep_27971628_0 OR ep=telem1 */ +}; + +struct pmt_ep_selector { +enum pmt_selector_kind kind; + +uint32_t guid; + +/* For SEL_EP_NAME */ +const char *str; +}; + +struct pmt_binding { +int metric_idx;/* index into defs[] */ +int device_idx;/* index into devices[] */ +}; + +struct pmtctl_context ; + +struct pmt_global_opts { +const char *json_path;/* -J / --json-file */ +const char *device_selector;/* -d / --device (raw) */ +bool quiet;/* -q / --quiet */ +bool debug;/* --debug */ +}; + +/* +* Initialize library-global PMT state. +* +* This may return success even if no metric definitions are available. +* In that case, device enumeration is still usable and raw mode remains +* supported (raw reads do not require metric definitions). +*/ +int pmtctl_init (const struct pmt_global_opts *gopts); +const struct pmtctl_context *pmtctl_get_ctx (void ); +enum pmt_device_type pmtctl_get_device_type (void ); +int pmtctl_get_num_devices (void ); +int pmtctl_get_num_metrics (void ); +int pmtctl_get_num_bindings (void ); + +/* +* Set process-global library logging verbosity. +* +* Invalid values are clamped to PMTCTL_LOG_INFO. +*/ +void pmtctl_set_log_level (enum pmtctl_log_level level); + +/* +* Thread-safety note: +* +* libpmtctl_core is generally not thread-safe. Callers should serialize +* pmtctl_init()/pmtctl_cleanup() and API usage around shared library state. +*/ +void pmtctl_cleanup (void ); + +static inline __always_unused void pmtctl_scope_cleanup (int *unused) +{ + (void )unused; +pmtctl_cleanup (); +} + +#define PMTCTL_SCOPE_GUARD \ + __attribute__((cleanup(pmtctl_scope_cleanup))) \ + int _pmtctl_scope_guard __always_unused \ + +int pmt_select_devices (const struct pmtctl_context *ctx,const struct pmt_ep_selector *sel, +int *out_idx,int max_out); + +/* +* Parse an ep selector string like "guid=27971628" or "ep=pmt_ep_...". +* For selectors that set a string (ep/name) the implementation will +* allocate a copy into sel->str; the caller is responsible for freeing +* sel->str if non-NULL. +*/ +int pmtctl_parse_ep_selector (const char *s,struct pmt_ep_selector *out); + +#endif tools/arch/x86/pmtctl/include/lib/pmtctl_context.h new file +21
-0@@ -0,0 +1,21 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#ifndef PMTCTL_CONTEXT_H +#define PMTCTL_CONTEXT_H + +#include "lib/device.h" +#include "lib/metrics_db.h" +#include "lib/pmtctl.h" + +struct pmtctl_context { +const struct pmt_device_ops *ops; + +struct pmt_device *devices; +int num_devices; + +struct pmt_metrics_db metrics; + +struct pmt_binding *bindings; +int num_bindings; +}; + +#endif tools/arch/x86/pmtctl/lib/pmtctl.c new file +74
-0@@ -0,0 +1,327 @@ +// SPDX-License-Identifier: GPL-2.0-only +#include <errno.h> +#include <string.h> +#include <stdio.h> +#include <stdlib.h> + +#include "lib/common.h" +#include "lib/device.h" +#include "lib/log.h" +#include "lib/metrics_db.h" +#include "lib/metrics_provider.h" +#include "lib/pmtctl.h" +#include "lib/pmtctl_context.h" + +static struct pmtctl_context g_pmtctl_ctx; + +const struct pmtctl_context *pmtctl_get_ctx (void ) +{ +return &g_pmtctl_ctx; +} + +enum pmt_device_type pmtctl_get_device_type (void ) +{ +const struct pmt_device_ops *ops = g_pmtctl_ctx.ops; + +return ops ? ops->dev_type :PMT_DEVICE_TELEM ; +} + +int pmtctl_get_num_devices (void ) +{ +return g_pmtctl_ctx.num_devices; +} + +int pmtctl_get_num_metrics (void ) +{ +return g_pmtctl_ctx.metrics.total; +} + +int pmtctl_get_num_bindings (void ) +{ +return g_pmtctl_ctx.num_bindings; +} + +void pmtctl_set_log_level (enum pmtctl_log_level level) +{ +log_set_level (level); +} + +int pmt_select_devices (const struct pmtctl_context *ctx, +const struct pmt_ep_selector *sel, +int *out_idx,int max_out) +{ +int i, n =0 ; + +if (!ctx || !sel || !out_idx || max_out <=0 ) +return log_ret (PMTCTL_ERR_INVALID ,"bad argument" ); + +if (!ctx->devices || ctx->num_devices <=0 ) +return log_ret (PMTCTL_ERR_INVALID ,"no devices" ); + +switch (sel->kind) { +case PMT_SEL_ANY : +/* No filter: return all devices */ +for (i =0 ; i < ctx->num_devices && n < max_out; i++) + out_idx[n++] = i; +break ; + +case PMT_SEL_GUID : +for (i =0 ; i < ctx->num_devices && n < max_out; i++) { +const struct pmt_device *dev = &ctx->devices[i]; + +if (dev->guid && dev->guid->guid == sel->guid) + out_idx[n++] = i; + }
tools/arch/x86/pmtctl/lib/pmtctl.c line 84
Quoted 10 lines
tools/arch/x86/pmtctl/lib/pmtctl.c new file +10
-0+break ; + +case PMT_SEL_EP_NAME : +if (!sel->str || !sel->str[0 ]) +return log_ret (PMTCTL_ERR_CMD_PARSE ,"empty ep selector" ); + +for (i =0 ; i < ctx->num_devices && n < max_out; i++) { +const struct pmt_device *dev = &ctx->devices[i]; + +if (dev->name &&strcmp (dev->name, sel->str) ==0 )
!strcmp()
tools/arch/x86/pmtctl/lib/pmtctl.c line 86
Quoted 2 lines
tools/arch/x86/pmtctl/lib/pmtctl.c new file +2
-0+ out_idx[n++] = i; + }
Move the code to helper with parameter(s) to filter variations.
Quoted 23 lines
tools/arch/x86/pmtctl/lib/pmtctl.c new file +23
-0+break ; + +default : +return log_ret (PMTCTL_ERR_CMD_PARSE ,"unknown selector kind %d" , sel->kind); + } + +/* n == 0 is "no matches", not an API error. Caller decides what to do. */ +return n; +} + +int pmtctl_parse_ep_selector (const char *s,struct pmt_ep_selector *out) +{ + auto_free char *copy = NULL; +char *end; +char *eq; +char *key =NULL ; +const char *val =NULL ; + +if (!out) +return -EINVAL ; + +if (!s || !*s) { + out->kind =PMT_SEL_ANY ;
tools/arch/x86/pmtctl/lib/pmtctl.c line 119
Quoted 10 lines
tools/arch/x86/pmtctl/lib/pmtctl.c new file +10
-0+ out->str =NULL ; + out->guid =0 ; +return 0 ; + } + +/* Expect a single key=value selector: guid=..., ep=..., name=... */ + copy =strdup (s); + +if (!copy) +return -ENOMEM ;
Hmm, so for some reason this can survive without invoking exit() right away. I wonder if exit() is really necessary with the other xstrdup() callers either...
tools/arch/x86/pmtctl/lib/pmtctl.c line 132
Quoted 13 lines
tools/arch/x86/pmtctl/lib/pmtctl.c new file +13
-0+ + eq =strchr (copy,'=' ); +if (!eq) +return -EINVAL ; + + *eq ='\0' ; + key = copy; + val = eq +1 ; + +if (!strcmp (key,"guid" )) { + errno =0 ; +unsigned long v =strtoul (val, &end,16 ); +
Please fix this.
I think I've read enough of AI thrown curveballs. Please review _all_ the patches yourself before sending them again and don't let AI slipping from usual style or using unusual construct through but fix them all before submitting.
Given the size of this patch series, the next round, I'll just be passing the ball back to ypu on the spot where I see the usual style is blatantly violated or some odd constructs are found.
I think I was quite generous to look this far.
tools/arch/x86/pmtctl/lib/pmtctl.c line 134
Quoted 2 lines
tools/arch/x86/pmtctl/lib/pmtctl.c new file +2
-0+if (errno || end == val || *end !='\0' || v >UINT32_MAX ) +return errno ? -errno : -EINVAL ;
Please split if you have to do elvis like this.
--
i.
Quoted 194 lines
tools/arch/x86/pmtctl/lib/pmtctl.c new file +193
-0+ out->kind =PMT_SEL_GUID ; + out->guid = (uint32_t )v; + out->str =NULL ; + }else if (!strcmp (key,"ep" ) || !strcmp (key,"name" )) { + out->kind =PMT_SEL_EP_NAME ; + out->str =strdup (val); +if (!out->str) +return -ENOMEM ; + out->guid =0 ; + }else { +log_err (PMTCTL_ERR_CMD_PARSE ,"unknown device selector %s" , key); +return -EINVAL ; + } +return 0 ; +} + +static bool +metric_matches_device (const struct pmt_metric_def *def,const struct pmt_device *dev) +{ +/* +* Compare the underlying numeric GUID rather than the pmt_guid pointer: +* builtin metric defs reference &builtin_guids[idx] directly, while +* devices intern through the registry. These may resolve to different +* pmt_guid entries for the same GUID depending on init order. +*/ +return def->guid->guid == dev->guid->guid; +} + +static int pmt_bind_build (struct pmtctl_context *ctx) +{ +struct pmt_binding *bindings; +size_t count =0 ; +int i, j, k; + +/* +* ----------------------------- +* Pass 1: count bindings +* ----------------------------- +*/ +for (i =0 ; i < ctx->metrics.total; i++) { +const struct pmt_metric_def *def =pmt_metrics_at (&ctx->metrics, i); + +if (!def) +continue ; + +for (j =0 ; j < ctx->num_devices; j++) { +const struct pmt_device *dev = &ctx->devices[j]; + +if (!metric_matches_device (def, dev)) +continue ; + + count++; + } + } + +if (count ==0 ) { +log_warn ("no metric/device bindings found" ); +return 0 ; + } + + bindings =calloc (count,sizeof (*bindings)); +if (!bindings) +return log_ret (-ENOMEM ,"count not allocate bindings" ); + +/* +* ----------------------------- +* Pass 2: fill bindings +* ----------------------------- +*/ + k =0 ; +for (i =0 ; i < ctx->metrics.total; i++) { +const struct pmt_metric_def *def =pmt_metrics_at (&ctx->metrics, i); + +if (!def) +continue ; + +for (j =0 ; j < ctx->num_devices; j++) { +const struct pmt_device *dev = &ctx->devices[j]; + +if (!metric_matches_device (def, dev)) +continue ; + + bindings[k].metric_idx = i; + bindings[k].device_idx = j; + k++; + } + } + + ctx->bindings = bindings; + ctx->num_bindings = k; + +return 0 ; +} + +int pmtctl_init (const struct pmt_global_opts *gopts) +{ +const struct pmt_device_ops *ops =NULL ; +int num_devices; +int ret; + +if (!gopts) +return log_ret (PMTCTL_ERR_INVALID ,"bad argument" ); + +memset (&g_pmtctl_ctx,0 ,sizeof (g_pmtctl_ctx)); + +/* +* 1) Initialize device backend. +* Only the telem backend is currently supported; PMU support is +* pending upstream driver availability. +*/ + ret = device_telem_ops.init (); +if (ret !=0 ) +return log_ret (ret,"failed to find PMT source" ); + ops = &device_telem_ops; +log_debug ("Selecting from /sys/class/intel_pmt" ); + g_pmtctl_ctx.ops = ops; + +/* +* 2) Enumerate devices from the chosen device +*/ + g_pmtctl_ctx.devices = ops->device_list (&num_devices); +if (!g_pmtctl_ctx.devices) { +pmtctl_cleanup (); +log_bug_and_exit ("unexpected NULL device context" ); + } + +if (num_devices <=0 ) { +pmtctl_cleanup (); +log_bug_and_exit ("unexpected zero device count" ); + } + g_pmtctl_ctx.num_devices = num_devices; + +/* +* 3) Load metric definitions from JSON or built-in +* +* If metric load fails or returns zero metrics, we intentionally keep init as a +* degraded success (return 0) with a warning. This allows raw mode operation, +* which does not require metric definitions. +*/ + ret =pmt_metrics_load (gopts->json_path, &g_pmtctl_ctx.metrics); +/* +* Any nonzero rc here means the metric source itself was broken +* (e.g. -J pointed at a nonexistent path, or a JSON file failed to +* parse). Treat that as a hard init failure so the CLI exits with +* PMTCTL_EXIT_SYSTEM instead of silently degrading to a metric-less +* session. Empty source (ret == 0 but metrics.total == 0) stays a +* degraded success -- raw mode and `list --devices` are still usable. +* +* Some provider paths return positive PMTCTL_ERR_* codes; normalize +* those to -EIO so main()'s mapping selects EXIT_SYSTEM. +*/ +if (ret !=0 ) { +pmtctl_cleanup (); +if (ret >0 ) + ret = -EIO ; +return log_ret (ret,"failed to load metrics from %s" , + gopts->json_path ? gopts->json_path :"<built-in>" ); + } +if (g_pmtctl_ctx.metrics.total ==0 ) { +log_warn ("no metrics from %s" , gopts->json_path ? gopts->json_path :"<built-in>" ); +return 0 ; + } + +/* +* 4) Build metric ↔ device bindings +*/ + ret =pmt_bind_build (&g_pmtctl_ctx); +if (ret !=0 ) { +pmtctl_cleanup (); +return ret; + } + +return 0 ; +} + +void pmtctl_cleanup (void ) +{ +if (g_pmtctl_ctx.bindings) { +free (g_pmtctl_ctx.bindings); + g_pmtctl_ctx.bindings =NULL ; + g_pmtctl_ctx.num_bindings =0 ; + } + +if (g_pmtctl_ctx.ops && g_pmtctl_ctx.ops->cleanup) + g_pmtctl_ctx.ops->cleanup (); + +pmt_metrics_free (&g_pmtctl_ctx.metrics); +pmt_guid_cleanup (); + + g_pmtctl_ctx.ops =NULL ; + g_pmtctl_ctx.devices =NULL ; + g_pmtctl_ctx.num_devices =0 ; +}
Re: [PATCH 08/17] tools/arch/x86/pmtctl: Add libpmtctl public API and context
Quoted 314 lines · Ilpo Järvinen
Quoted 234 lines · David E. Box
Add the public API for
libpmtctl_coreand the context object that backs it, providing callers with a stable, opaque interface for discovering Intel PMT telemetry devices and querying their metrics without depending on internal library structures.This patch adds the primary lifecycle and query interfaces used by library consumers.
pmtctl_init()performs device enumeration and metric database loading once during initialization so subsequent queries operate on cached state rather than re-scanning sysfs.pmtctl_cleanup()releases associated resources.The library context (struct
pmtctl_context) remains opaque to callers.pmtctl_get_ctx()provides controlled access for consumers that need to pass library context across translation units.Add
PMTCTL_SCOPE_GUARD()as a convenience macro for deterministic cleanup of library-managed resources in single-exit C code paths.Build-system wiring is added a later patch of the series.
Assisted-by GitHub-Copilot:claude-sonnet-4.6Signed-off-by David E. Box <[email protected]>--- tools/arch/x86/pmtctl/include/lib/pmtctl.h | 90 +++++ .../x86/pmtctl/include/lib/pmtctl_context.h | 21 ++ tools/arch/x86/pmtctl/lib/pmtctl.c | 327 ++++++++++++++++++ 3 files changed, 438 insertions(+) create mode 100644 tools/arch/x86/pmtctl/include/lib/pmtctl.h create mode 100644 tools/arch/x86/pmtctl/include/lib/pmtctl_context.h create mode 100644 tools/arch/x86/pmtctl/lib/pmtctl.ctools/arch/x86/pmtctl/include/lib/pmtctl.h new file +90
-0@@ -0,0 +1,90 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#ifndef PMTCTL_H +#define PMTCTL_H + +#include <stdbool.h> +#include <stdint.h> + +#include <linux/compiler.h> +#include "pmtctl_types.h" + +enum pmt_selector_kind { +PMT_SEL_ANY =0 ,/* no selector provided */ +PMT_SEL_GUID ,/* guid=27971628 */ +PMT_SEL_EP_NAME ,/* ep=pmt_ep_27971628_0 OR ep=telem1 */ +}; + +struct pmt_ep_selector { +enum pmt_selector_kind kind; + +uint32_t guid; + +/* For SEL_EP_NAME */ +const char *str; +}; + +struct pmt_binding { +int metric_idx;/* index into defs[] */ +int device_idx;/* index into devices[] */ +}; + +struct pmtctl_context ; + +struct pmt_global_opts { +const char *json_path;/* -J / --json-file */ +const char *device_selector;/* -d / --device (raw) */ +bool quiet;/* -q / --quiet */ +bool debug;/* --debug */ +}; + +/* +* Initialize library-global PMT state. +* +* This may return success even if no metric definitions are available. +* In that case, device enumeration is still usable and raw mode remains +* supported (raw reads do not require metric definitions). +*/ +int pmtctl_init (const struct pmt_global_opts *gopts); +const struct pmtctl_context *pmtctl_get_ctx (void ); +enum pmt_device_type pmtctl_get_device_type (void ); +int pmtctl_get_num_devices (void ); +int pmtctl_get_num_metrics (void ); +int pmtctl_get_num_bindings (void ); + +/* +* Set process-global library logging verbosity. +* +* Invalid values are clamped to PMTCTL_LOG_INFO. +*/ +void pmtctl_set_log_level (enum pmtctl_log_level level); + +/* +* Thread-safety note: +* +* libpmtctl_core is generally not thread-safe. Callers should serialize +* pmtctl_init()/pmtctl_cleanup() and API usage around shared library state. +*/ +void pmtctl_cleanup (void ); + +static inline __always_unused void pmtctl_scope_cleanup (int *unused) +{ + (void )unused; +pmtctl_cleanup (); +} + +#define PMTCTL_SCOPE_GUARD \ + __attribute__((cleanup(pmtctl_scope_cleanup))) \ + int _pmtctl_scope_guard __always_unused \ + +int pmt_select_devices (const struct pmtctl_context *ctx,const struct pmt_ep_selector *sel, +int *out_idx,int max_out); + +/* +* Parse an ep selector string like "guid=27971628" or "ep=pmt_ep_...". +* For selectors that set a string (ep/name) the implementation will +* allocate a copy into sel->str; the caller is responsible for freeing +* sel->str if non-NULL. +*/ +int pmtctl_parse_ep_selector (const char *s,struct pmt_ep_selector *out); + +#endif tools/arch/x86/pmtctl/include/lib/pmtctl_context.h new file +21
-0@@ -0,0 +1,21 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#ifndef PMTCTL_CONTEXT_H +#define PMTCTL_CONTEXT_H + +#include "lib/device.h" +#include "lib/metrics_db.h" +#include "lib/pmtctl.h" + +struct pmtctl_context { +const struct pmt_device_ops *ops; + +struct pmt_device *devices; +int num_devices; + +struct pmt_metrics_db metrics; + +struct pmt_binding *bindings; +int num_bindings; +}; + +#endif tools/arch/x86/pmtctl/lib/pmtctl.c new file +74
-0@@ -0,0 +1,327 @@ +// SPDX-License-Identifier: GPL-2.0-only +#include <errno.h> +#include <string.h> +#include <stdio.h> +#include <stdlib.h> + +#include "lib/common.h" +#include "lib/device.h" +#include "lib/log.h" +#include "lib/metrics_db.h" +#include "lib/metrics_provider.h" +#include "lib/pmtctl.h" +#include "lib/pmtctl_context.h" + +static struct pmtctl_context g_pmtctl_ctx; + +const struct pmtctl_context *pmtctl_get_ctx (void ) +{ +return &g_pmtctl_ctx; +} + +enum pmt_device_type pmtctl_get_device_type (void ) +{ +const struct pmt_device_ops *ops = g_pmtctl_ctx.ops; + +return ops ? ops->dev_type :PMT_DEVICE_TELEM ; +} + +int pmtctl_get_num_devices (void ) +{ +return g_pmtctl_ctx.num_devices; +} + +int pmtctl_get_num_metrics (void ) +{ +return g_pmtctl_ctx.metrics.total; +} + +int pmtctl_get_num_bindings (void ) +{ +return g_pmtctl_ctx.num_bindings; +} + +void pmtctl_set_log_level (enum pmtctl_log_level level) +{ +log_set_level (level); +} + +int pmt_select_devices (const struct pmtctl_context *ctx, +const struct pmt_ep_selector *sel, +int *out_idx,int max_out) +{ +int i, n =0 ; + +if (!ctx || !sel || !out_idx || max_out <=0 ) +return log_ret (PMTCTL_ERR_INVALID ,"bad argument" ); + +if (!ctx->devices || ctx->num_devices <=0 ) +return log_ret (PMTCTL_ERR_INVALID ,"no devices" ); + +switch (sel->kind) { +case PMT_SEL_ANY : +/* No filter: return all devices */ +for (i =0 ; i < ctx->num_devices && n < max_out; i++) + out_idx[n++] = i; +break ; + +case PMT_SEL_GUID : +for (i =0 ; i < ctx->num_devices && n < max_out; i++) { +const struct pmt_device *dev = &ctx->devices[i]; + +if (dev->guid && dev->guid->guid == sel->guid) + out_idx[n++] = i; + }tools/arch/x86/pmtctl/lib/pmtctl.c line 84
Quoted 10 lines
tools/arch/x86/pmtctl/lib/pmtctl.c new file +10
-0+break ; + +case PMT_SEL_EP_NAME : +if (!sel->str || !sel->str[0 ]) +return log_ret (PMTCTL_ERR_CMD_PARSE ,"empty ep selector" ); + +for (i =0 ; i < ctx->num_devices && n < max_out; i++) { +const struct pmt_device *dev = &ctx->devices[i]; + +if (dev->name &&strcmp (dev->name, sel->str) ==0 )!strcmp()
tools/arch/x86/pmtctl/lib/pmtctl.c line 86
Quoted 2 lines
tools/arch/x86/pmtctl/lib/pmtctl.c new file +2
-0+ out_idx[n++] = i; + }Move the code to helper with parameter(s) to filter variations.
Quoted 23 lines
tools/arch/x86/pmtctl/lib/pmtctl.c new file +23
-0+break ; + +default : +return log_ret (PMTCTL_ERR_CMD_PARSE ,"unknown selector kind %d" , sel->kind); + } + +/* n == 0 is "no matches", not an API error. Caller decides what to do. */ +return n; +} + +int pmtctl_parse_ep_selector (const char *s,struct pmt_ep_selector *out) +{ + auto_free char *copy = NULL; +char *end; +char *eq; +char *key =NULL ; +const char *val =NULL ; + +if (!out) +return -EINVAL ; + +if (!s || !*s) { + out->kind =PMT_SEL_ANY ;tools/arch/x86/pmtctl/lib/pmtctl.c line 119
Quoted 10 lines
tools/arch/x86/pmtctl/lib/pmtctl.c new file +10
-0+ out->str =NULL ; + out->guid =0 ; +return 0 ; + } + +/* Expect a single key=value selector: guid=..., ep=..., name=... */ + copy =strdup (s); + +if (!copy) +return -ENOMEM ;Hmm, so for some reason this can survive without invoking
exit()right away. I wonder ifexit()is really necessary with the otherxstrdup()callers either...tools/arch/x86/pmtctl/lib/pmtctl.c line 132
Quoted 13 lines
tools/arch/x86/pmtctl/lib/pmtctl.c new file +13
-0+ + eq =strchr (copy,'=' ); +if (!eq) +return -EINVAL ; + + *eq ='\0' ; + key = copy; + val = eq +1 ; + +if (!strcmp (key,"guid" )) { + errno =0 ; +unsigned long v =strtoul (val, &end,16 ); +Please fix this.
I think I've read enough of AI thrown curveballs. Please review _all_ the patches yourself before sending them again and don't let AI slipping from usual style or using unusual construct through but fix them all before submitting.
Quoted 5 lines
Given the size of this patch series, the next round, I'll just be passing the ball back to ypu on the spot where I see the usual style is blatantly violated or some odd constructs are found.
I think I was quite generous to look this far.
Yes you were.
I agree with the feedback. I started leaning too much on generated code toward the end of development and did not give the final result the full line-by-line review it needed before posting.
Rather than respond to each comment, I'll do a full pass over the series for v2, addressing the issues you mentioned along with any other inconsistencies.
Thanks for taking the time to review it this far.
David
Quoted 203 lines
tools/arch/x86/pmtctl/lib/pmtctl.c line 134
Quoted 3 lines
tools/arch/x86/pmtctl/lib/pmtctl.c new file +2
-0+if (errno || end == val || *end !='\0' || v >UINT32_MAX ) +return errno ? -errno : -EINVAL ;Please split if you have to do elvis like this.
--
i.Quoted 194 lines
tools/arch/x86/pmtctl/lib/pmtctl.c new file +193
-0+ out->kind =PMT_SEL_GUID ; + out->guid = (uint32_t )v; + out->str =NULL ; + }else if (!strcmp (key,"ep" ) || !strcmp (key,"name" )) { + out->kind =PMT_SEL_EP_NAME ; + out->str =strdup (val); +if (!out->str) +return -ENOMEM ; + out->guid =0 ; + }else { +log_err (PMTCTL_ERR_CMD_PARSE ,"unknown device selector %s" , key); +return -EINVAL ; + } +return 0 ; +} + +static bool +metric_matches_device (const struct pmt_metric_def *def,const struct pmt_device *dev) +{ +/* +* Compare the underlying numeric GUID rather than the pmt_guid pointer: +* builtin metric defs reference &builtin_guids[idx] directly, while +* devices intern through the registry. These may resolve to different +* pmt_guid entries for the same GUID depending on init order. +*/ +return def->guid->guid == dev->guid->guid; +} + +static int pmt_bind_build (struct pmtctl_context *ctx) +{ +struct pmt_binding *bindings; +size_t count =0 ; +int i, j, k; + +/* +* ----------------------------- +* Pass 1: count bindings +* ----------------------------- +*/ +for (i =0 ; i < ctx->metrics.total; i++) { +const struct pmt_metric_def *def =pmt_metrics_at (&ctx->metrics, i); + +if (!def) +continue ; + +for (j =0 ; j < ctx->num_devices; j++) { +const struct pmt_device *dev = &ctx->devices[j]; + +if (!metric_matches_device (def, dev)) +continue ; + + count++; + } + } + +if (count ==0 ) { +log_warn ("no metric/device bindings found" ); +return 0 ; + } + + bindings =calloc (count,sizeof (*bindings)); +if (!bindings) +return log_ret (-ENOMEM ,"count not allocate bindings" ); + +/* +* ----------------------------- +* Pass 2: fill bindings +* ----------------------------- +*/ + k =0 ; +for (i =0 ; i < ctx->metrics.total; i++) { +const struct pmt_metric_def *def =pmt_metrics_at (&ctx->metrics, i); + +if (!def) +continue ; + +for (j =0 ; j < ctx->num_devices; j++) { +const struct pmt_device *dev = &ctx->devices[j]; + +if (!metric_matches_device (def, dev)) +continue ; + + bindings[k].metric_idx = i; + bindings[k].device_idx = j; + k++; + } + } + + ctx->bindings = bindings; + ctx->num_bindings = k; + +return 0 ; +} + +int pmtctl_init (const struct pmt_global_opts *gopts) +{ +const struct pmt_device_ops *ops =NULL ; +int num_devices; +int ret; + +if (!gopts) +return log_ret (PMTCTL_ERR_INVALID ,"bad argument" ); + +memset (&g_pmtctl_ctx,0 ,sizeof (g_pmtctl_ctx)); + +/* +* 1) Initialize device backend. +* Only the telem backend is currently supported; PMU support is +* pending upstream driver availability. +*/ + ret = device_telem_ops.init (); +if (ret !=0 ) +return log_ret (ret,"failed to find PMT source" ); + ops = &device_telem_ops; +log_debug ("Selecting from /sys/class/intel_pmt" ); + g_pmtctl_ctx.ops = ops; + +/* +* 2) Enumerate devices from the chosen device +*/ + g_pmtctl_ctx.devices = ops->device_list (&num_devices); +if (!g_pmtctl_ctx.devices) { +pmtctl_cleanup (); +log_bug_and_exit ("unexpected NULL device context" ); + } + +if (num_devices <=0 ) { +pmtctl_cleanup (); +log_bug_and_exit ("unexpected zero device count" ); + } + g_pmtctl_ctx.num_devices = num_devices; + +/* +* 3) Load metric definitions from JSON or built-in +* +* If metric load fails or returns zero metrics, we intentionally keep init as a +* degraded success (return 0) with a warning. This allows raw mode operation, +* which does not require metric definitions. +*/ + ret =pmt_metrics_load (gopts->json_path, &g_pmtctl_ctx.metrics); +/* +* Any nonzero rc here means the metric source itself was broken +* (e.g. -J pointed at a nonexistent path, or a JSON file failed to +* parse). Treat that as a hard init failure so the CLI exits with +* PMTCTL_EXIT_SYSTEM instead of silently degrading to a metric-less +* session. Empty source (ret == 0 but metrics.total == 0) stays a +* degraded success -- raw mode and `list --devices` are still usable. +* +* Some provider paths return positive PMTCTL_ERR_* codes; normalize +* those to -EIO so main()'s mapping selects EXIT_SYSTEM. +*/ +if (ret !=0 ) { +pmtctl_cleanup (); +if (ret >0 ) + ret = -EIO ; +return log_ret (ret,"failed to load metrics from %s" , + gopts->json_path ? gopts->json_path :"<built-in>" ); + } +if (g_pmtctl_ctx.metrics.total ==0 ) { +log_warn ("no metrics from %s" , gopts->json_path ? gopts->json_path :"<built-in>" ); +return 0 ; + } + +/* +* 4) Build metric ↔ device bindings +*/ + ret =pmt_bind_build (&g_pmtctl_ctx); +if (ret !=0 ) { +pmtctl_cleanup (); +return ret; + } + +return 0 ; +} + +void pmtctl_cleanup (void ) +{ +if (g_pmtctl_ctx.bindings) { +free (g_pmtctl_ctx.bindings); + g_pmtctl_ctx.bindings =NULL ; + g_pmtctl_ctx.num_bindings =0 ; + } + +if (g_pmtctl_ctx.ops && g_pmtctl_ctx.ops->cleanup) + g_pmtctl_ctx.ops->cleanup (); + +pmt_metrics_free (&g_pmtctl_ctx.metrics); +pmt_guid_cleanup (); + + g_pmtctl_ctx.ops =NULL ; + g_pmtctl_ctx.devices =NULL ; + g_pmtctl_ctx.num_devices =0 ; +}