Skip to contentSkip to conversation

perf tools: Fix thread cache race, stat per-pkg delta bug, and memory leaks

PATCH New Ian Rogers 2 participants 6 messages Nov 30 perf events

lore
Share & tools
lore

Ian Rogers

author reviewer
#0 lore raw

v2 cover perf tools: Fix thread cache race, stat per-pkg delta bug, and memory leaks

Four standalone bug fixes for pre-existing issues in perf tools uncovered during Sashiko review:

1. util/threads.c: Fix a race between threads__find() and threads__remove() where dropping table->lock between lookup and updating table->last_match could resurrect a removed thread in last_match (and avoid taking down_write(&table->lock) on last_match cache hits).
2. util/stat.c: Fix process_counter_values() on skipped per-pkg secondary
CPUs: compute interval deltas before check_per_pkg() so prev_raw_counts and interval ena/run are accurate, remove the static zero struct, and return 0 when skip is true so non-global aggregation modes (such as --per-socket and --per-die) do not mark ps_aggr failed (<not counted>) or inflate ps_aggr->nr.
3. util/metricgroup.c: Fix realloc() failure memory leaks of pending in resolve_metric() and root_metric->metric_refs in __add_metric().
4. util/pmu.c: Free alias on parse_double() and io__getline() error returns in perf_pmu__new_alias().

Changes in v2:
- Rebase onto perf-tools-next (419442c00c66).
- Patch 2: Return 0 immediately from process_counter_values() when skip is true (after computing interval deltas before check_per_pkg()) instead of falling through with a zeroed count struct, which caused evsel__count_has_error() in non-global aggregation modes (e.g. --per-socket, --per-die) to wipe out the primary CPU's package count, mark ps_aggr->failed, and increment ps_aggr->nr (Sashiko).

v1: https://lore.kernel.org/linux-perf-users/[email protected]/

AI Assistance Disclosure (per Documentation/process/coding-assistants.rst and Documentation/process/generated-content.rst):
- Tools used: Sashiko automated patch review (sashiko.dev) for bug detection, and Google Antigravity / Jetski coding assistant for root cause verification and patch drafting.
- Summary of prompts and assistance: Verified pre-existing issues flagged by Sashiko during review of the perf generic hashmap series and prepared standalone fixes with Fixes tags against perf-tools-next.
- Testing performed: Built on perf-tools-next (419442c00c66) with GCC (-DREFCNT_CHECKING=1) and Clang (BUILD_NONDISTRO=1, including -Wthread-safety context analysis); verified per-pkg aggregation and interval deltas across AGGR_GLOBAL and AGGR_SOCKET; ran perf test and scripts/checkpatch.pl.

Ian Rogers (4):
perf threads: Don't resurrect removed threads in last_match perf stat: Skip per-pkg secondary CPUs after computing deltas perf metricgroup: Fix realloc() leaks in resolve_metric() and

    __add_metric()

perf pmu: Free alias on error paths in perf_pmu__new_alias()

 tools/perf/util/metricgroup.c | 19 +++++++++++++------
 tools/perf/util/pmu.c         |  5 ++++-
 tools/perf/util/stat.c        |  9 ++++-----
 tools/perf/util/threads.c     | 16 +++++++++++-----
 4 files changed, 32 insertions(+), 17 deletions(-)

base-commit: 419442c00c667d33e27db4fef9733fa966e6a149

Signature · 1 line
2.56.1.839.g22a8290db9-goog
author reviewer
#1 lore raw

PATCH v2 1/4 perf threads: Don't resurrect removed threads in last_match

threads__find() looks up the thread under down_read(&table->lock), drops the read lock, and then acquires down_write(&table->lock) inside threads_table_entry__set_last_match() to update table->last_match.

If threads__remove() (or threads__remove_all_threads()) runs in the window between up_read(&table->lock) and down_write(&table->lock), it clears table->last_match and deletes the thread from table->shard, only for threads__find() to overwrite table->last_match with the removed thread. Subsequent lookups for that tid then return the removed thread from table->last_match, causing stale event attribution and keeping a cached reference until another lookup evicts it. In addition, threads__find() unnecessarily took down_write(&table->lock) to re-set table->last_match even when last_match already hit.

Only update table->last_match on a cache miss, and recheck under down_write(&table->lock) that tid still maps to the same struct thread in table->shard before updating table->last_match.

Fixes d436f90a64f3 ("perf machine: Move machine's threads into its own abstraction")
---
 tools/perf/util/threads.c | 16 +++++++++++-----
 1 file changed, 11 insertions(+), 5 deletions(-)
tools/perf/util/threads.c +11 -5
index 7cf951cbc963..9f5f186c7072 100644
@@ -89,10 +89,13 @@ static void __threads_table_entry__set_last_match(struct threads_table_entry *ta
 }
 
 static void threads_table_entry__set_last_match(struct threads_table_entry *table,
-						struct thread *th)
+						pid_t tid, struct thread *th)
 {
+	struct thread *cur;
+
 	down_write(&table->lock);
-	__threads_table_entry__set_last_match(table, th);
+	if (hashmap__find(&table->shard, tid, &cur) && RC_CHK_EQUAL(cur, th))
+		__threads_table_entry__set_last_match(table, th);
 	up_write(&table->lock);
 }
 
@@ -100,16 +103,19 @@ struct thread *threads__find(struct threads *threads, pid_t tid)
 {
 	struct threads_table_entry *table  = threads__table(threads, tid);
 	struct thread *res;
+	bool update_last_match = false;
 
 	down_read(&table->lock);
 	res = __threads_table_entry__get_last_match(table, tid);
 	if (!res) {
-		if (hashmap__find(&table->shard, tid, &res))
+		if (hashmap__find(&table->shard, tid, &res)) {
 			res = thread__get(res);
+			update_last_match = true;
+		}
 	}
 	up_read(&table->lock);
-	if (res)
-		threads_table_entry__set_last_match(table, res);
+	if (update_last_match)
+		threads_table_entry__set_last_match(table, tid, res);
 	return res;
 }
 
Signature · 1 line
2.56.1.839.g22a8290db9-goog
author reviewer
#2 lore raw

PATCH v2 2/4 perf stat: Skip per-pkg secondary CPUs after computing deltas

In reply to Ian Rogers

In process_counter_values(), when check_per_pkg() sets skip = true for a secondary CPU in an already-counted package/die, count was pointed at a local 'static struct perf_counts_values zero' before calling evsel__compute_deltas() and falling through into ps->aggr aggregation.

This caused multiple bugs:
1. evsel__compute_deltas() saves *count into evsel->prev_raw_counts and subtracts the previous interval's raw counts from *count in place. If a CPU had non-zero counts in an earlier interval and is later skipped, subtracting tmp from zero underflows the static zero struct in place (corrupting all subsequent skipped CPUs for the remainder of the perf stat run) and overwrites prev_raw_counts for that CPU with zeros.
2. In non-global aggregation modes (such as --per-socket or --per-die), falling through with zero (ena == 0 and run == 0) into ps->aggr makes evsel__count_has_error() return true for non-cgroup events, wiping out the package count accumulated from the first CPU, marking ps_aggr as failed (<not counted>), and inflating ps_aggr->nr with skipped CPUs.
3. Calling check_per_pkg() before evsel__compute_deltas() checked cumulative rather than per-interval ena/run, so in interval mode a CPU that ran in an earlier interval could mark the package used even when idle during the current interval.

Remove the static zero struct, compute interval deltas on the real CPU counter values before calling check_per_pkg(), and return 0 immediately when skip is true.

Fixes 779d0b997e07 ("perf stat: Add support for per-pkg counters")
Fixes f976bc6b6bfc ("perf stat: Aggregate events using evsel->stats->aggr")
---
 tools/perf/util/stat.c | 9 ++++-----
 1 file changed, 4 insertions(+), 5 deletions(-)
tools/perf/util/stat.c +4 -5
index 6da3dbbde0e2..2f3dce698d1f 100644
@@ -398,19 +398,18 @@ process_counter_values(struct perf_stat_config *config, struct evsel *evsel,
 		       struct perf_counts_values *count)
 {
 	struct perf_stat_evsel *ps = evsel->stats;
-	static struct perf_counts_values zero;
 	bool skip = false;
 
+	if (!evsel->snapshot)
+		evsel__compute_deltas(evsel, cpu_map_idx, thread, count);
+
 	if (check_per_pkg(evsel, count, cpu_map_idx, &skip)) {
 		pr_err("failed to read per-pkg counter\n");
 		return -1;
 	}
-
 	if (skip)
-		count = &zero;
+		return 0;
 
-	if (!evsel->snapshot)
-		evsel__compute_deltas(evsel, cpu_map_idx, thread, count);
 	perf_counts_values__scale(count, config->scale, NULL);
 
 	if (config->aggr_mode == AGGR_THREAD) {
Signature · 1 line
2.56.1.839.g22a8290db9-goog
author reviewer
#3 lore raw

PATCH v2 3/4 perf metricgroup: Fix realloc() leaks in resolve_metric() and __add_metric()

In reply to Ian Rogers

In resolve_metric(), growing the pending array assigns the result of realloc() directly back to pending; if realloc() fails after earlier iterations succeeded, the existing pending allocation is overwritten with NULL and leaked.

Similarly, in __add_metric(), assigning realloc() directly to root_metric->metric_refs overwrites the existing pointer with NULL on failure, preventing metric__free(root_metric) in the root caller from freeing the prior metric_refs array.

Use temporary pointers for both realloc() calls, freeing pending before returning -ENOMEM in resolve_metric() and preserving root_metric->metric_refs for metric__free() in __add_metric().

Fixes 80be6434c36f ("perf metric: Modify resolution and recursion check")
Fixes 46bdc0bf8d21 ("perf metric: Simplify metric_refs calculation")
---
 tools/perf/util/metricgroup.c | 19 +++++++++++++------
 1 file changed, 13 insertions(+), 6 deletions(-)
tools/perf/util/metricgroup.c +13 -6
index 779fe56fe8d0..489f13b34361 100644
@@ -771,10 +771,15 @@ static int resolve_metric(struct list_head *metric_list,
 		if (pmu_metrics_table__find_metric(table, pmu, cur->pkey,
 						   metricgroup__find_metric_callback,
 						   &pm) != PMU_METRICS__NOT_FOUND) {
-			pending = realloc(pending,
-					(pending_cnt + 1) * sizeof(struct to_resolve));
-			if (!pending)
+			struct to_resolve *new_pending;
+
+			new_pending = realloc(pending,
+					      (pending_cnt + 1) * sizeof(struct to_resolve));
+			if (!new_pending) {
+				free(pending);
 				return -ENOMEM;
+			}
+			pending = new_pending;
 
 			memcpy(&pending[pending_cnt].pm, &pm, sizeof(pm));
 			pending[pending_cnt].key = cur->pkey;
@@ -863,6 +868,7 @@ static int __add_metric(struct list_head *metric_list,
 			return -ENOMEM;
 
 	} else {
+		struct metric_ref *new_refs;
 		int cnt = 0;
 
 		/*
@@ -879,10 +885,11 @@ static int __add_metric(struct list_head *metric_list,
 		}
 
 		/* Create reference. Need space for the entry and the terminator. */
-		root_metric->metric_refs = realloc(root_metric->metric_refs,
-						(cnt + 2) * sizeof(struct metric_ref));
-		if (!root_metric->metric_refs)
+		new_refs = realloc(root_metric->metric_refs,
+				   (cnt + 2) * sizeof(struct metric_ref));
+		if (!new_refs)
 			return -ENOMEM;
+		root_metric->metric_refs = new_refs;
 
 		/*
 		 * Intentionally passing just const char pointers,
Signature · 1 line
2.56.1.839.g22a8290db9-goog
author reviewer
#4 lore raw

PATCH v2 4/4 perf pmu: Free alias on error paths in perf_pmu__new_alias()

In reply to Ian Rogers

In perf_pmu__new_alias(), alias is allocated with zalloc(), but if parse_double() fails on any of the retirement latency fields or io__getline() fails when reading sysfs alias terms, the function returns ret directly without freeing alias.

Call perf_pmu_free_alias(alias) on both error paths, matching the existing perf_pmu__convert_scale() failure path.

Fixes 84bae3af20d0 ("perf pmu: Don't eagerly parse event terms")
Fixes fc807b6bde6a ("perf pmu-events: Add retirement latency to JSON events inside of perf")
---
 tools/perf/util/pmu.c | 5 ++++-
 1 file changed, 4 insertions(+), 1 deletion(-)
tools/perf/util/pmu.c +4 -1
index 1ae8bcf71c68..adf85d0c26c2 100644
@@ -607,8 +607,10 @@ static int perf_pmu__new_alias(struct perf_pmu *pmu, const char *name,
 		ret = parse_double(pe->retirement_latency_max, NULL,
 				   &alias->retirement_latency_max);
 	}
-	if (ret)
+	if (ret) {
+		perf_pmu_free_alias(alias);
 		return ret;
+	}
 
 	if (val_fd < 0) {
 		alias->terms = strdup(val);
@@ -621,6 +623,7 @@ static int perf_pmu__new_alias(struct perf_pmu *pmu, const char *name,
 		ret = io__getline(&io, &alias->terms, &line_len) < 0 ? -errno : 0;
 		if (ret) {
 			pr_err("Failed to read alias %s\n", name);
+			perf_pmu_free_alias(alias);
 			return ret;
 		}
 		if (line_len >= 1 && alias->terms[line_len - 1] == '\n')
Signature · 1 line
2.56.1.839.g22a8290db9-goog