From nobody Tue Nov 24 11:51:44 2026 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=74.125.82.72 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1795323856; b=IgsT4c/PNv+njtQlCYZH5nm6VbctLLcKtDwYJruhznlmAXJVzJuiS/dCFfdajc7tDG0p Gu0km5bNSEorScPdUpw9NLtTCwF334hWggszD8Cee6Q1necuIHd/dvjQ+6X8APdfuVzVn NE+DG0txbIx1JJsm9yIiCi+tWAr1A5MVbEWc72vLdLIevrPmDLRbU2rrfojyTFv9JUXmr wB+QngP5rQndQCsH3dplsoDFcUm/Y1sLHW7ouQjL9nLa9QR7kdLubUrKQe7SjwDGdyhhi 58iObW5lTqSq8olSl4jhvXxlh83qHNmkNZpglOcVbjE0kG1K/IVIMBoJPXRD/nYXBng== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1795323856; h=DMARC-Filter:Received:DKIM-Signature:X-Google-DKIM-Signature: X-Forwarded-Encrypted:X-Gm-Message-State:X-Received:Date:In-Reply-To: Mime-Version:References:X-Mailer:Message-ID:Subject:From:To:Cc: Content-Type; bh=pH2BPzLxsd8NvvUmkGMcSjMobCCeF4ip9zrDbmpxIGM=; b=a6TO08fAZIynSoV1sXGdD0OroZREIscYEAiAnW9lYc1kvhURonRU5yFNxjaSMKf9BRAV 7dLH3E+Zz60whwfY6NS1xwo84mVL3eUW/0ZMnh02FuQuFHoH4eTVBgUZTyYD8xNVtH4DQ 8TKyOIlzjDZeta6gKnnH1rRZ7mSVpYXxLdnkayp0FIQv9Uw08B7aZOvJcs3QQ0y2TADxW Jo/LO3iZhmYLmbYBEWZcVGhXMszLyv9+WM9IXW7YRWqvnGq2u0rKU183KMwsyor1UyVw9 g5awlftCfKePHH1fxn71qcxJKeEa72fliL2VA/a2axgY1mRU332WD5ExzU6rupsxg4g== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass header.from=google.com; spf=pass smtp.mailfrom=flex--irogers.bounces.google.com; dkim=pass header.d=google.com header.i=@google.com header.a=rsa-sha256 header.s=20260707 header.b=nLQ0PXQ7; arc=none smtp.remote-ip=74.125.82.72 Received: from mail-dl1-f72.google.com (mail-dl1-f72.google.com [74.125.82.72]) (using TLSv1.3 with cipher TLS_AES_128_GCM_SHA256 (128/128 bits) key-exchange X25519 server-signature ECDSA (prime256v1) server-digest SHA256) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id C4615606A32A for ; Sun, 22 Nov 2026 05:04:15 +0000 (UTC) DMARC-Filter: OpenDMARC Filter v1.4.2 smtp.subspace.kernel.org C4615606A32A Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=flex--irogers.bounces.google.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.a=rsa-sha256 header.s=20260707 header.b=nLQ0PXQ7 Received: by mail-dl1-f72.google.com with SMTP id a92af1059eb24-16bc6f3fdb1so1416692c88.0 for ; Sat, 21 Nov 2026 21:04:15 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20260707; t=1795323855; x=1795928655; darn=vger.kernel.org; h=content-type:cc:to:from:subject:message-id:references:mime-version :in-reply-to:date:from:to:cc:subject:date:message-id:reply-to :content-type; bh=pH2BPzLxsd8NvvUmkGMcSjMobCCeF4ip9zrDbmpxIGM=; b=nLQ0PXQ7VRoh6j8O1l2lTKM+Mz25ztUwDpe2kiROjNruKcbNSKU9EKsMjX22EvwqL9 S31tRt1aPR/FVNkn5+joY9QOtq/2KH4ZmkUSDaBZZvG32nRzap0XESdf86Kx6JBuohvq gcUHl0hU9k7eyRH5tE6xoDw2KW0q9xmVS36GxYEZAAVUwpVTv+ctpgdUFYaxYlfnapLM y7E6rVo8LllAPUVeeQWF59zYZZThH9v7YTYMpDSI+HGtiZcREr+SpHIA4aR9/R6Uhtpv Lv3EE9C24llnyBfKNuAwd79+ARYnP/v9rKq2Fd0YtpCDJmRUM/p6k+qUUw31GoIpBpTp ujSA== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20260707; t=1795323855; x=1795928655; h=content-type:cc:to:from:subject:message-id:references:mime-version :in-reply-to:date:x-gm-message-state:from:to:cc:subject:date :message-id:reply-to:content-type; bh=pH2BPzLxsd8NvvUmkGMcSjMobCCeF4ip9zrDbmpxIGM=; b=Kq9XbnLrCRVHbKrjwxspewsZcmqGFfxvj4nfrDpDDIdTtzs16KF43lKdW2Mdkk80Gg x5PdAH9JiBXKoz9RbPNSoYcK4jAi/extcjmxQBnM1zmX95Tebdq9in6KXnGqaZHafS8n nl7iPW1711JhcfDs9QtdhcxVGS+yM+xwR13aaEi06cy8youwQGUnAT+IqCbs1ZtJl9Da hUSX5jQe0Z+3YF2TXpmGOHT4PvP6hWY39JGHMhWDFLRNemTVjTbqSqJgbIhMGLj7Ham7 OYNO2nhp8YJyxlZaHTYXr/9sX5ziVggLNpCoXX+zeJzEQ9LG/nfJlJCfSmW91DL8FeqJ L7Nw== X-Forwarded-Encrypted: i=1; AL+hErGxM/uViE+X38JIvRS87LPDb1+FdpTKjXfTMn3zf8eASfgras4wXXimjrE7biY6GGAF8dnriXHc3e1neX8=@vger.kernel.org X-Gm-Message-State: APuU4Z9p60HclaLQSAmkaWMmZf8bh7KFxSZ27wskS/ztgGuIEZPML1gn fNDIudx/dGM+T+UWr82rJ2fNgvIpxKfRmg/4QUNCxWEA+2Ku13lJ7iF1ZkrQjFPKkSRLSqGyuRE mmEkDy4ICKw== X-Received: from dlam5-n1.prod.google.com ([2002:a05:701b:2085:10b0:15d:6b8d:2adc]) (user=irogers job=prod-delivery.src-stubby-dispatcher) by 2002:a05:701b:2088:10b0:1b3:a22c:7f68 with SMTP id a92af1059eb24-1b5568d349fmr8253316c88.29.1795323854566; Sat, 21 Nov 2026 21:04:14 -0800 (PST) Date: Sat, 21 Nov 2026 21:03:56 -0800 In-Reply-To: <20261122050405.80335-1-irogers@google.com> X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Post: List-Help: List-Subscribe: List-Unsubscribe: List-Owner: Precedence: list Mime-Version: 1.0 References: <20261122050405.80335-1-irogers@google.com> X-Mailer: git-send-email 2.56.1.750.gf70dc682cf-goog Message-ID: <20261122050405.80335-2-irogers@google.com> Subject: [PATCH v8 01/10] perf kmem: Fix alloc_func_regex leak on error in build_alloc_func_list() From: Ian Rogers To: Namhyung Kim , Arnaldo Carvalho de Melo , Alireza Haghdoost , Ian Rogers Cc: Peter Zijlstra , Ingo Molnar , Jiri Olsa , Adrian Hunter , James Clark , linux-perf-users@vger.kernel.org, linux-kernel@vger.kernel.org Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" In build_alloc_func_list(), after regcomp(&alloc_func_regex, ...) succeeds, the early error returns on map__load() failure and realloc() failure return without calling regfree(&alloc_func_regex), leaking the compiled regular expression buffer. Call regfree(&alloc_func_regex) on both error paths before returning. Fixes: c9758cc45699 ("perf kmem: Implement stat --page --caller") Signed-off-by: Ian Rogers --- tools/perf/builtin-kmem.c | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/tools/perf/builtin-kmem.c b/tools/perf/builtin-kmem.c index 8693c6b135ca..1404b523a785 100644 --- a/tools/perf/builtin-kmem.c +++ b/tools/perf/builtin-kmem.c @@ -364,6 +364,7 @@ static int build_alloc_func_list(void) kernel_map =3D machine__kernel_map(machine); if (map__load(kernel_map) < 0) { pr_err("cannot load kernel map\n"); + regfree(&alloc_func_regex); return -ENOENT; } =20 @@ -373,8 +374,10 @@ static int build_alloc_func_list(void) =20 func =3D realloc(alloc_func_list, (nr_alloc_funcs + 1) * sizeof(*func)); - if (func =3D=3D NULL) + if (func =3D=3D NULL) { + regfree(&alloc_func_regex); return -ENOMEM; + } =20 pr_debug("alloc func: %s\n", sym->name); func[nr_alloc_funcs].start =3D sym->start; --=20 2.56.1.750.gf70dc682cf-goog From nobody Tue Nov 24 11:51:44 2026 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=74.125.82.199 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1795323862; b=185sK89/IXHN99AEq68z4ZvbvE1dBsofbH2D8IMxb2YGduUKtvAN331NlQo0bMXmKbsd oIz8+b8Zi8Ltla5mnSX5V2gBMQTCEKwcoKkYihmoGfEvqWHrAlRxE6GCG5t214AScnS+0 XOQinXlSlEkolQZ63BDBzswmfphspnfqL57t8jtecpK2IRCG9nXZPS51rzdPLQ/0JN86b wxmLCkp7mMKGrdPL4bML59qeP4O5+oiO1ItOtuH6ATmGpVKo4iKAlxd3rYNz5yJXoNp6z HhFMB+EyZq1/2RP7j7h1uNNBrJVWqvMe+yGwGVl/P3UwZqilKmt2CMstOfBlooDklXg== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1795323862; h=DMARC-Filter:Received:DKIM-Signature:X-Google-DKIM-Signature: X-Forwarded-Encrypted:X-Gm-Message-State:X-Received:Date:In-Reply-To: Mime-Version:References:X-Mailer:Message-ID:Subject:From:To:Cc: Content-Type; bh=3+RVnA1KvRuho7W5JEL26qwdJaS2/5G8Cho/yb352Tg=; b=qUd6kNivumVLvV8RIY3QY6yQpR57R9PnRa5N7RMt4SbECA0ioawO3zPdsWlRSgrGF8Ds NgbY9gcBCnSb5Vc2YbmhmZSdsQ7cx+ZCoUYbEIsNVOQhlqN0LawgQuaLDXo0THPd9gIRh EH1u7+m1nC62H4iDllxbS5g6vGIXXp+qVtJwQAHj1hEL2fTEjwqhZQsuqmSGXJy7z5GUR gtVFom+22RN01ovO45Q9H5he00F3yRAlxV2srx32qjSWsDfZ03kkrwbLGY5xDqwCrwjsh 3oH3Vy2hI2RoT57ihHBCC1Btm1hV8JT8RxfZTjama+h8uwdahQ43bPdPjC9shy1xENA== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass header.from=google.com; spf=pass smtp.mailfrom=flex--irogers.bounces.google.com; dkim=pass header.d=google.com header.i=@google.com header.a=rsa-sha256 header.s=20260707 header.b=pYIb4A2Y; arc=none smtp.remote-ip=74.125.82.199 Received: from mail-dy1-f199.google.com (mail-dy1-f199.google.com [74.125.82.199]) (using TLSv1.3 with cipher TLS_AES_128_GCM_SHA256 (128/128 bits) key-exchange X25519 server-signature ECDSA (prime256v1) server-digest SHA256) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 9CDE8606A330 for ; Sun, 22 Nov 2026 05:04:21 +0000 (UTC) DMARC-Filter: OpenDMARC Filter v1.4.2 smtp.subspace.kernel.org 9CDE8606A330 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=flex--irogers.bounces.google.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.a=rsa-sha256 header.s=20260707 header.b=pYIb4A2Y Received: by mail-dy1-f199.google.com with SMTP id 5a478bee46e88-33c35f5ca6cso3137856eec.1 for ; Sat, 21 Nov 2026 21:04:21 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20260707; t=1795323861; x=1795928661; darn=vger.kernel.org; h=content-type:cc:to:from:subject:message-id:references:mime-version :in-reply-to:date:from:to:cc:subject:date:message-id:reply-to :content-type; bh=3+RVnA1KvRuho7W5JEL26qwdJaS2/5G8Cho/yb352Tg=; b=pYIb4A2YDUgJW3/cv/didT2UkN8udEvUHytxfzEl1B31hB+GgmwXH8wJj0m6xuDi7J QqjMDwaqmJHnt8WG9tOMlnmIjy/9oSSL6mceZlFXp7ohjcVh4PXq3T168T4fTQvKEfcL Qy4mSVn/jYIB9ivzPzZX3t4rFPr6jIVP3CCug3whPKI6fFVWX7gTW9WMZOTtza2xqr0q vx0rPnzFum3cbzD2Q33o96As3JqNQtMLmI0vdRoePYEs3efQxhHju8imvklYLS8OAQy/ UkLoTXH0yHWkOJTa1DZFhCeJW6TiO+1Eizxj/g8/xbOLnlciLL9LQwrRb91Xkt5R103i RitQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20260707; t=1795323861; x=1795928661; h=content-type:cc:to:from:subject:message-id:references:mime-version :in-reply-to:date:x-gm-message-state:from:to:cc:subject:date :message-id:reply-to:content-type; bh=3+RVnA1KvRuho7W5JEL26qwdJaS2/5G8Cho/yb352Tg=; b=T1rdq0QOtNY3qf1XLyl8oo1fBzLF+TTdGzfslyXmFnawtHWMEseCtBES0no+RbaTDw mMyeWmCFzsLuDRQidBwkfDaw12X1nR5hnL/gnonYo9QbEVjvWA7HdLof1VdkNQwLM2NR 515N1fKElqeLAUsynP3ANn4p0coOWc/ulySwEPVdCzKszkfzBoY/KECR3Jga2UcXRX3b jdCjGOCCWJCuhSkuOTLwnMXHKCEFh4ytFMpvygwXgCd7dbdwETK4YjgkXKIAwp+2wnRN OaT1Xc/PV+BbXRV28PATSYhHolC5sWSkf55CYM5jHiscy7965NbBpmWF9H9oPityWlpv 5fuA== X-Forwarded-Encrypted: i=1; AL+hErFgaHdrayp5j37ymN8VyeSFHFMTfpkZma6QROTTVzetayArwWEhuHYaA1L+E6TOPnEhBf0BBt4zsq9wkrQ=@vger.kernel.org X-Gm-Message-State: APuU4Z/lTofYDpsCU9hzzKnpTZXoV16evVhibfusK2+HakEzicggwyzi LVfvu/jEtXBn+wrw5hBb/r5jCdZIo2z2Gfup/IF9S7mxPt+6As2fEKN2aLdFlrGJvf6mViFwH5k xC4iaUY5Qxg== X-Received: from dycpv11.prod.google.com ([2002:a05:7300:de0b:b0:383:7418:1e01]) (user=irogers job=prod-delivery.src-stubby-dispatcher) by 2002:a05:7301:1884:b0:374:ba43:ae2e with SMTP id 5a478bee46e88-3856f65eccamr7554250eec.14.1795323860261; Sat, 21 Nov 2026 21:04:20 -0800 (PST) Date: Sat, 21 Nov 2026 21:03:57 -0800 In-Reply-To: <20261122050405.80335-1-irogers@google.com> X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Post: List-Help: List-Subscribe: List-Unsubscribe: List-Owner: Precedence: list Mime-Version: 1.0 References: <20261122050405.80335-1-irogers@google.com> X-Mailer: git-send-email 2.56.1.750.gf70dc682cf-goog Message-ID: <20261122050405.80335-3-irogers@google.com> Subject: [PATCH v8 02/10] perf maps: Add tail fast-path check in first_ending_after() From: Ian Rogers To: Namhyung Kim , Arnaldo Carvalho de Melo , Alireza Haghdoost , Ian Rogers Cc: Peter Zijlstra , Ingo Molnar , Jiri Olsa , Adrian Hunter , James Clark , linux-perf-users@vger.kernel.org, linux-kernel@vger.kernel.org Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" User-space map insertions (from /proc/pid/maps synthesis, runtime PERF_RECORD_MMAP2, and jitdump) and BPF ksymbol registrations all flow through maps__fixup_overlap_and_insert() -> first_ending_after(). Currently first_ending_after() has a fast-path check for the first map (maps_by_address[0]), but no fast-path check for the last map (maps_by_address[high]). Because /proc/pid/maps entries are synthesized in ascending address order, every synthesized mapping starts at or after maps_by_address[high]'s end, yet currently executes the full O(log N) binary search loop. Add a tail check in first_ending_after() so non-overlapping ascending insertions complete in O(1), and add a unit test in tools/perf/tests/maps.c covering ascending tail insertions. Using 'perf bench internals maps': Before: Average ascending insert + lookup: 63.370 usec (+- 0.476 usec) After (-6.9%): Average ascending insert + lookup: 58.970 usec (+- 0.609 usec) Signed-off-by: Ian Rogers # Conflicts: # tools/perf/tests/maps.c --- tools/perf/tests/maps.c | 46 +++++++++++++++++++++++++++++++++++++++++ tools/perf/util/maps.c | 4 ++++ 2 files changed, 50 insertions(+) diff --git a/tools/perf/tests/maps.c b/tools/perf/tests/maps.c index 054e4fafef3f..7f48f944aa67 100644 --- a/tools/perf/tests/maps.c +++ b/tools/perf/tests/maps.c @@ -392,10 +392,56 @@ static int test__maps__remove(struct test_suite *t __= maybe_unused, int subtest _ return TEST_OK; } =20 +static int test__maps__tail_insert(struct test_suite *t __maybe_unused, + int subtest __maybe_unused) +{ + struct map_def ascending_maps[] =3D { + { "map_c", 1000, 2000 }, + { "map_a", 2000, 3000 }, + { "map_d", 4000, 5000 }, + }; + struct map *map, *found; + struct perf_env host_env; + struct machine *machine; + struct maps *maps; + int ret; + + perf_env__init(&host_env); + machine =3D machine__new_live(&host_env, /*kernel_maps=3D*/false, getpid(= )); + maps =3D maps__new(machine); + + TEST_ASSERT_VAL("failed to create machine", machine); + TEST_ASSERT_VAL("failed to create maps", maps); + + /* Exercise tail fast-path in maps__fixup_overlap_and_insert. */ + for (unsigned int i =3D 0; i < ARRAY_SIZE(ascending_maps); i++) { + map =3D dso__new_map(ascending_maps[i].name); + TEST_ASSERT_VAL("failed to create map", map); + map__set_start(map, ascending_maps[i].start); + map__set_end(map, ascending_maps[i].end); + TEST_ASSERT_VAL("failed to insert sorted map", + maps__fixup_overlap_and_insert(maps, map) =3D=3D 0); + map__put(map); + } + + ret =3D check_maps(ascending_maps, ARRAY_SIZE(ascending_maps), maps); + TEST_ASSERT_VAL("tail insert check_maps failed", !ret); + + found =3D maps__find(maps, 2500); + TEST_ASSERT_VAL("failed to find map_a by address", found && map__start(fo= und) =3D=3D 2000); + map__zput(found); + + maps__zput(maps); + machine__delete(machine); + perf_env__exit(&host_env); + return TEST_OK; +} + static struct test_case tests__maps[] =3D { TEST_CASE("Test merge_in interface", maps__merge_in), TEST_CASE("Test fix up overlap interface", maps__fixup_overlap_and_insert= ), TEST_CASE("Test remove interface", maps__remove), + TEST_CASE("Test tail insert fast-path", maps__tail_insert), { .name =3D NULL, } }; =20 diff --git a/tools/perf/util/maps.c b/tools/perf/util/maps.c index 672c0ace5a00..770ce43a4ce3 100644 --- a/tools/perf/util/maps.c +++ b/tools/perf/util/maps.c @@ -907,6 +907,10 @@ static unsigned int first_ending_after(struct maps *ma= ps, const struct map *map) assert(maps__maps_by_address_sorted(maps)); if (low <=3D high && map__end(maps_by_address[0]) > map__start(map)) return 0; + if (low <=3D high && !RC_CHK_ACCESS(maps)->ends_broken && + map__end(maps_by_address[high]) <=3D map__start(map)) { + return first; + } =20 while (low <=3D high) { int mid =3D (low + high) / 2; --=20 2.56.1.750.gf70dc682cf-goog From nobody Tue Nov 24 11:51:44 2026 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=74.125.82.72 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1795323868; b=cHVbxT2+vdgjD6rnHEnvI4gFQFmDBiQE0uDGlhOKaEh7lUW6on3OjNNIl3fjpIbofbPK wNA3ew0D3HX0qcTTnEndpigg0G1S0uF1+B48WV0EWXsTO28yjgqfnsTmMhFTvOeMMmUkM hAehYaUSDEh1KraTaEfkO4sDFXkEtnN4ITLpElEPJl8/AX+Ey2GZHGjfY0xw6vRDBIW3O wKrUpob9Sc7wGoNA56yFJIm1N5driVlEVCJhLPd3BzvaCPxqjpGyBgQoqw2Ry1SXtoj9u YtZqXZ/PnmgbatnCobnUTpZHtwa7LzIX/SD3pbnrTswQmcFl9d5ReHMD2r9nMvmfMBA== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1795323868; h=DMARC-Filter:Received:DKIM-Signature:X-Google-DKIM-Signature: X-Forwarded-Encrypted:X-Gm-Message-State:X-Received:Date:In-Reply-To: Mime-Version:References:X-Mailer:Message-ID:Subject:From:To:Cc: Content-Type; bh=MpPxIDsgRyyQm9jNwFMpA3OG+xyCq5lkVmLNHfH4dVs=; b=B3OJ7JYOh/jsJOzYnnjuShgQK9j1arvaeRSl5n7qQHKzXy5QAMuqIaczK/4dhJXmYRmy XqVETlo7PZVujx6YVBuUFsb+SI+5WTdDB8mwmjI0TCsvRsuSXorfNQ8Pw4n/oWDR6pbhl 7JR1t6iTuqUrAELHqb3tRN6UM5w6F86c3wEPvwfx7vmL0gZg9ycbLqBhZaDVoCGzRifch 8FmEbHSQGq/o6kTB1HYLhqisFCCPFFwIBb3N2rlqPG+uYh0rz4jrRQCtJpNiC29JoB2PO Q+I11PKocg3JJDwqNXTRzpoz+KkP5TQg8p7xI3H3AQCtmYriGMl/X2S2BLTNTFdAxjQ== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass header.from=google.com; spf=pass smtp.mailfrom=flex--irogers.bounces.google.com; dkim=pass header.d=google.com header.i=@google.com header.a=rsa-sha256 header.s=20260707 header.b=HEakuNrY; arc=none smtp.remote-ip=74.125.82.72 Received: from mail-dl1-f72.google.com (mail-dl1-f72.google.com [74.125.82.72]) (using TLSv1.3 with cipher TLS_AES_128_GCM_SHA256 (128/128 bits) key-exchange X25519 server-signature ECDSA (prime256v1) server-digest SHA256) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 17960606A32C for ; Sun, 22 Nov 2026 05:04:26 +0000 (UTC) DMARC-Filter: OpenDMARC Filter v1.4.2 smtp.subspace.kernel.org 17960606A32C Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=flex--irogers.bounces.google.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.a=rsa-sha256 header.s=20260707 header.b=HEakuNrY Received: by mail-dl1-f72.google.com with SMTP id a92af1059eb24-1b3b45597c7so1338767c88.1 for ; Sat, 21 Nov 2026 21:04:26 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20260707; t=1795323866; x=1795928666; darn=vger.kernel.org; h=content-type:cc:to:from:subject:message-id:references:mime-version :in-reply-to:date:from:to:cc:subject:date:message-id:reply-to :content-type; bh=MpPxIDsgRyyQm9jNwFMpA3OG+xyCq5lkVmLNHfH4dVs=; b=HEakuNrYo7Vd1ywlkiTsOKgOw+7NU4AOTtBhPfYvQJUYvk3f1hiGtHi08cW4NQu2cc uidWmQlsVmr5R0KtOgsmnHqPUKt7fRIkSKt5h6u00sc0pvizdfTXOq7c9c28jzpSd/O8 G1KOJMI66Hyu93hfR9MyJweWSGpvnVXSQUnLp7OflAg9obo3FBZuLJ3j7NIpi1Owh/jV IS3zGSUB2f5yailkCMEGh6fr0TYnDEMsT+YdGAeZ1iFDLZ2WpwJZ9z3RdhTILBAHEdo+ dgh6x+yNQebMbFDRN8hg2I91Op/gRQx3u5INdsYWw0nafhXjTfDsbnQHdv9iNU9xJF3R +a1Q== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20260707; t=1795323866; x=1795928666; h=content-type:cc:to:from:subject:message-id:references:mime-version :in-reply-to:date:x-gm-message-state:from:to:cc:subject:date :message-id:reply-to:content-type; bh=MpPxIDsgRyyQm9jNwFMpA3OG+xyCq5lkVmLNHfH4dVs=; b=XGcaCh2cogc2mccSmGnovn4ziJgAi0kqqOuPEZrzQVcoX9XiX693SiMPnA9EMWD0SL 9q0N1oC1ER081wh/Ks8/01cb5hbxrJF8zyyERjShSzXLUV37C/cJldQAD+vDmgpmO0cd je4gffQOMh98xaqBt6/tH7MMFOQ3eFXOiklPYg19YHy8GGoyTILeVnk1n07CzOHUWmf+ un0AObW+JEcjf1YKHDJ4NkJk4Xseytf5A8tiQBwLfUpPjiapDYJlpNGhbE3cA1CZMTKD CZJDWncD42Hf0JXWrSVSSYKL2YQn+eLHNaNla1bUORTDZAT15dhxzbga1wHhH/tnwGna zyQA== X-Forwarded-Encrypted: i=1; AL+hErGIXt1Ex1X0U/sSd0QYifxT2NAQrB0X/sVHs9OLrvtsFuzVXs43Fk9j++LbyZPeUL73vuJmC1fm+0Whyzc=@vger.kernel.org X-Gm-Message-State: APuU4Z+Su7C+6R2GT5QF5WsIQJtSP5BGmK4mR2leJskOP5tLWfcz/N3E WD9+sZyi3yCKaCWaU63FG4swVLY6SzpZqX/dNB+PZnMZFr0wEmZaT5n/kD77s1e7IP/IRif+HTi TOz6kazddvg== X-Received: from dlbuu1.prod.google.com ([2002:a05:7022:7e81:b0:1b3:ba1e:2c7]) (user=irogers job=prod-delivery.src-stubby-dispatcher) by 2002:a05:7022:1583:b0:1b3:a9c6:b293 with SMTP id a92af1059eb24-1b5568c0198mr8592915c88.25.1795323865533; Sat, 21 Nov 2026 21:04:25 -0800 (PST) Date: Sat, 21 Nov 2026 21:03:58 -0800 In-Reply-To: <20261122050405.80335-1-irogers@google.com> X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Post: List-Help: List-Subscribe: List-Unsubscribe: List-Owner: Precedence: list Mime-Version: 1.0 References: <20261122050405.80335-1-irogers@google.com> X-Mailer: git-send-email 2.56.1.750.gf70dc682cf-goog Message-ID: <20261122050405.80335-4-irogers@google.com> Subject: [PATCH v8 03/10] perf symbol: Convert map__for_each_symbol() to callback-based iteration From: Ian Rogers To: Namhyung Kim , Arnaldo Carvalho de Melo , Alireza Haghdoost , Ian Rogers Cc: Peter Zijlstra , Ingo Molnar , Jiri Olsa , Adrian Hunter , James Clark , linux-perf-users@vger.kernel.org, linux-kernel@vger.kernel.org Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" Currently symbols__for_each_entry(), dso__for_each_symbol(), and map__for_each_symbol() are macros that expose struct rb_node * cursors to callers and perform unlocked rb_first_cached() / rb_next() walks. To prepare for replacing the unprotected symbol rbtree with a locked symbol array, replace symbols__for_each_entry() with a callback-based symbols__visit() helper and convert dso__for_each_symbol() and map__for_each_symbol() to callback-based iteration matching dsos__for_each_dso() and maps__for_each_map(), updating the existing map__for_each_symbol() callers. Signed-off-by: Ian Rogers --- tools/perf/arch/powerpc/util/sym-handling.c | 34 ++-- tools/perf/builtin-kmem.c | 52 +++--- tools/perf/tests/vmlinux-kallsyms.c | 181 ++++++++++---------- tools/perf/util/dso.h | 8 +- tools/perf/util/map.h | 8 +- tools/perf/util/probe-event.c | 82 +++++---- tools/perf/util/symbol.c | 19 ++ tools/perf/util/symbol.h | 16 +- 8 files changed, 228 insertions(+), 172 deletions(-) diff --git a/tools/perf/arch/powerpc/util/sym-handling.c b/tools/perf/arch/= powerpc/util/sym-handling.c index 947bfad7aa59..f87d77262c00 100644 --- a/tools/perf/arch/powerpc/util/sym-handling.c +++ b/tools/perf/arch/powerpc/util/sym-handling.c @@ -115,13 +115,27 @@ void arch__fix_tev_from_maps(struct perf_probe_event = *pev, } =20 #ifdef HAVE_LIBELF_SUPPORT +struct post_process_probe_trace_events_args { + struct perf_probe_event *pev; + struct probe_trace_event *tev; + struct map *map; +}; + +static int post_process_probe_trace_events_cb(struct symbol *sym, void *da= ta) +{ + struct post_process_probe_trace_events_args *args =3D data; + + if (map__unmap_ip(args->map, sym->start) =3D=3D args->tev->point.address)= { + arch__fix_tev_from_maps(args->pev, args->tev, args->map, sym); + return 1; + } + return 0; +} + void arch__post_process_probe_trace_events(struct perf_probe_event *pev, int ntevs) { - struct probe_trace_event *tev; struct map *map; - struct symbol *sym =3D NULL; - struct rb_node *tmp; int i =3D 0; =20 map =3D get_target_map(pev->target, pev->nsi, pev->uprobes); @@ -129,13 +143,13 @@ void arch__post_process_probe_trace_events(struct per= f_probe_event *pev, return; =20 for (i =3D 0; i < ntevs; i++) { - tev =3D &pev->tevs[i]; - map__for_each_symbol(map, sym, tmp) { - if (map__unmap_ip(map, sym->start) =3D=3D tev->point.address) { - arch__fix_tev_from_maps(pev, tev, map, sym); - break; - } - } + struct post_process_probe_trace_events_args args =3D { + .pev =3D pev, + .tev =3D &pev->tevs[i], + .map =3D map, + }; + + map__for_each_symbol(map, post_process_probe_trace_events_cb, &args); } } #endif /* HAVE_LIBELF_SUPPORT */ diff --git a/tools/perf/builtin-kmem.c b/tools/perf/builtin-kmem.c index 1404b523a785..87869c717266 100644 --- a/tools/perf/builtin-kmem.c +++ b/tools/perf/builtin-kmem.c @@ -341,13 +341,33 @@ static int callcmp(const void *a, const void *b) return -1; } =20 +static int build_alloc_func_list_cb(struct symbol *sym, void *data) +{ + regex_t *alloc_func_regex =3D data; + struct alloc_func *func; + + if (regexec(alloc_func_regex, sym->name, 0, NULL, 0)) + return 0; + + func =3D realloc(alloc_func_list, + (nr_alloc_funcs + 1) * sizeof(*func)); + if (func =3D=3D NULL) + return -ENOMEM; + + pr_debug("alloc func: %s\n", sym->name); + func[nr_alloc_funcs].start =3D sym->start; + func[nr_alloc_funcs].end =3D sym->end; + func[nr_alloc_funcs].name =3D sym->name; + + alloc_func_list =3D func; + nr_alloc_funcs++; + return 0; +} + static int build_alloc_func_list(void) { int ret; struct map *kernel_map; - struct symbol *sym; - struct rb_node *node; - struct alloc_func *func; struct machine *machine =3D &kmem_session->machines.host; regex_t alloc_func_regex; static const char pattern[] =3D "^_?_?(alloc|get_free|get_zeroed)_pages?"; @@ -368,29 +388,13 @@ static int build_alloc_func_list(void) return -ENOENT; } =20 - map__for_each_symbol(kernel_map, sym, node) { - if (regexec(&alloc_func_regex, sym->name, 0, NULL, 0)) - continue; - - func =3D realloc(alloc_func_list, - (nr_alloc_funcs + 1) * sizeof(*func)); - if (func =3D=3D NULL) { - regfree(&alloc_func_regex); - return -ENOMEM; - } - - pr_debug("alloc func: %s\n", sym->name); - func[nr_alloc_funcs].start =3D sym->start; - func[nr_alloc_funcs].end =3D sym->end; - func[nr_alloc_funcs].name =3D sym->name; - - alloc_func_list =3D func; - nr_alloc_funcs++; - } + ret =3D map__for_each_symbol(kernel_map, build_alloc_func_list_cb, &alloc= _func_regex); + regfree(&alloc_func_regex); + if (ret) + return ret; =20 - qsort(alloc_func_list, nr_alloc_funcs, sizeof(*func), funcmp); + qsort(alloc_func_list, nr_alloc_funcs, sizeof(*alloc_func_list), funcmp); =20 - regfree(&alloc_func_regex); return 0; } =20 diff --git a/tools/perf/tests/vmlinux-kallsyms.c b/tools/perf/tests/vmlinux= -kallsyms.c index 9396c8a77c86..38f5c9584e15 100644 --- a/tools/perf/tests/vmlinux-kallsyms.c +++ b/tools/perf/tests/vmlinux-kallsyms.c @@ -113,6 +113,7 @@ static bool is_ignored_symbol(const char *name, char ty= pe) struct test__vmlinux_matches_kallsyms_cb_args { struct machine kallsyms; struct map *vmlinux_map; + int err; bool header_printed; }; =20 @@ -185,16 +186,101 @@ static int test__vmlinux_matches_kallsyms_cb3(struct= map *map, void *data) return 0; } =20 +static int test__vmlinux_matches_kallsyms_sym_cb(struct symbol *sym, void = *data) +{ + struct test__vmlinux_matches_kallsyms_cb_args *args =3D data; + /* + * Step 4: + * + * kallsyms will be internally on demand sorted by name so that we can + * find the reference relocation * symbol, i.e. the symbol we will use + * to see if the running kernel was relocated by checking if it has the + * same value in the vmlinux file we load. + */ + struct map *kallsyms_map =3D machine__kernel_map(&args->kallsyms); + struct symbol *pair, *first_pair; + u64 mem_start, mem_end; + + if (sym->start =3D=3D sym->end) + return 0; + + mem_start =3D map__unmap_ip(args->vmlinux_map, sym->start); + mem_end =3D map__unmap_ip(args->vmlinux_map, sym->end); + + first_pair =3D machine__find_kernel_symbol(&args->kallsyms, mem_start, NU= LL); + pair =3D first_pair; + + if (pair && UM(pair->start) =3D=3D mem_start) { +next_pair: + if (arch__compare_symbol_names(sym->name, pair->name) =3D=3D 0) { + /* + * kallsyms don't have the symbol end, so we + * set that by using the next symbol start - 1, + * in some cases we get this up to a page + * wrong, trace_kmalloc when I was developing + * this code was one such example, 2106 bytes + * off the real size. More than that and we + * _really_ have a problem. + */ + s64 skew =3D mem_end - UM(pair->end); + + if (llabs(skew) >=3D page_size) { + pr_debug("WARN: %#" PRIx64 ": diff end addr for %s v: %#" + PRIx64 " k: %#" PRIx64 "\n", + mem_start, sym->name, mem_end, + UM(pair->end)); + } + + /* + * Do not count this as a failure, because we + * could really find a case where it's not + * possible to get proper function end from + * kallsyms. + */ + return 0; + } + pair =3D machine__find_kernel_symbol_by_name(&args->kallsyms, + sym->name, NULL); + if (pair) { + if (UM(pair->start) =3D=3D mem_start) + goto next_pair; + + pr_debug("WARN: %#" PRIx64 ": diff name v: %s k: %s\n", + mem_start, sym->name, pair->name); + } else { + pr_debug("WARN: %#" PRIx64 ": diff name v: %s k: %s\n", + mem_start, sym->name, first_pair->name); + } + + return 0; + } + + if (mem_start =3D=3D map__end(args->kallsyms.vmlinux_map)) { + /* + * Ignore aliases to _etext, i.e. to the end of the kernel text area, + * such as __indirect_thunk_end. + */ + return 0; + } + if (is_ignored_symbol(sym->name, symbol__type(sym))) { + /* + * Ignore hidden symbols, see scripts/kallsyms.c for the details + */ + return 0; + } + pr_debug("ERR : %#" PRIx64 ": %s not on kallsyms\n", + mem_start, sym->name); + + args->err =3D -1; + return 0; +} + static int test__vmlinux_matches_kallsyms(struct test_suite *test __maybe_= unused, int subtest __maybe_unused) { int err =3D TEST_FAIL; - struct rb_node *nd; - struct symbol *sym; - struct map *kallsyms_map; struct machine vmlinux =3D { 0 }; struct maps *maps; - u64 mem_start, mem_end; struct test__vmlinux_matches_kallsyms_cb_args args; =20 /* @@ -240,16 +326,6 @@ static int test__vmlinux_matches_kallsyms(struct test_= suite *test __maybe_unused goto out; } =20 - /* - * Step 4: - * - * kallsyms will be internally on demand sorted by name so that we can - * find the reference relocation * symbol, i.e. the symbol we will use - * to see if the running kernel was relocated by checking if it has the - * same value in the vmlinux file we load. - */ - kallsyms_map =3D machine__kernel_map(&args.kallsyms); - /* * Step 5: * @@ -279,7 +355,7 @@ static int test__vmlinux_matches_kallsyms(struct test_s= uite *test __maybe_unused goto out; } =20 - err =3D 0; + args.err =3D 0; /* * Step 7: * @@ -287,79 +363,8 @@ static int test__vmlinux_matches_kallsyms(struct test_= suite *test __maybe_unused * in the kallsyms dso. For the ones that are in both, check its names and * end addresses too. */ - map__for_each_symbol(args.vmlinux_map, sym, nd) { - struct symbol *pair, *first_pair; - - sym =3D rb_entry(nd, struct symbol, rb_node); - - if (sym->start =3D=3D sym->end) - continue; - - mem_start =3D map__unmap_ip(args.vmlinux_map, sym->start); - mem_end =3D map__unmap_ip(args.vmlinux_map, sym->end); - - first_pair =3D machine__find_kernel_symbol(&args.kallsyms, mem_start, NU= LL); - pair =3D first_pair; - - if (pair && UM(pair->start) =3D=3D mem_start) { -next_pair: - if (arch__compare_symbol_names(sym->name, pair->name) =3D=3D 0) { - /* - * kallsyms don't have the symbol end, so we - * set that by using the next symbol start - 1, - * in some cases we get this up to a page - * wrong, trace_kmalloc when I was developing - * this code was one such example, 2106 bytes - * off the real size. More than that and we - * _really_ have a problem. - */ - s64 skew =3D mem_end - UM(pair->end); - if (llabs(skew) >=3D page_size) - pr_debug("WARN: %#" PRIx64 ": diff end addr for %s v: %#" PRIx64 " k:= %#" PRIx64 "\n", - mem_start, sym->name, mem_end, - UM(pair->end)); - - /* - * Do not count this as a failure, because we - * could really find a case where it's not - * possible to get proper function end from - * kallsyms. - */ - continue; - } else { - pair =3D machine__find_kernel_symbol_by_name(&args.kallsyms, - sym->name, NULL); - if (pair) { - if (UM(pair->start) =3D=3D mem_start) - goto next_pair; - - pr_debug("WARN: %#" PRIx64 ": diff name v: %s k: %s\n", - mem_start, sym->name, pair->name); - } else { - pr_debug("WARN: %#" PRIx64 ": diff name v: %s k: %s\n", - mem_start, sym->name, first_pair->name); - } - - continue; - } - } else if (mem_start =3D=3D map__end(args.kallsyms.vmlinux_map)) { - /* - * Ignore aliases to _etext, i.e. to the end of the kernel text area, - * such as __indirect_thunk_end. - */ - continue; - } else if (is_ignored_symbol(sym->name, symbol__type(sym))) { - /* - * Ignore hidden symbols, see scripts/kallsyms.c for the details - */ - continue; - } else { - pr_debug("ERR : %#" PRIx64 ": %s not on kallsyms\n", - mem_start, sym->name); - } - - err =3D -1; - } + map__for_each_symbol(args.vmlinux_map, test__vmlinux_matches_kallsyms_sym= _cb, &args); + err =3D args.err; =20 if (verbose <=3D 0) goto out; diff --git a/tools/perf/util/dso.h b/tools/perf/util/dso.h index bb887d10a9ee..dd859356ecd9 100644 --- a/tools/perf/util/dso.h +++ b/tools/perf/util/dso.h @@ -362,11 +362,11 @@ int dso_id__cmp(const struct dso_id *a, const struct = dso_id *b); /* dso__for_each_symbol - iterate over the symbols of given type * * @dso: the 'struct dso *' in which symbols are iterated - * @pos: the 'struct symbol *' to use as a loop cursor - * @n: the 'struct rb_node *' to use as a temporary storage + * @cb: callback function invoked for each symbol + * @data: opaque data pointer passed to @cb */ -#define dso__for_each_symbol(dso, pos, n) \ - symbols__for_each_entry(dso__symbols(dso), pos, n) +#define dso__for_each_symbol(dso, cb, data) \ + symbols__visit(dso__symbols(dso), cb, data) =20 static inline void *dso__a2l(const struct dso *dso) { diff --git a/tools/perf/util/map.h b/tools/perf/util/map.h index c2e31be232c8..32f1fd9a7404 100644 --- a/tools/perf/util/map.h +++ b/tools/perf/util/map.h @@ -146,12 +146,12 @@ struct thread; /* map__for_each_symbol - iterate over the symbols in the given map * * @map: the 'struct map *' in which symbols are iterated - * @pos: the 'struct symbol *' to use as a loop cursor - * @n: the 'struct rb_node *' to use as a temporary storage + * @cb: callback function invoked for each symbol + * @data: opaque data pointer passed to @cb * Note: caller must ensure map->dso is not NULL (map is loaded). */ -#define map__for_each_symbol(map, pos, n) \ - dso__for_each_symbol(map__dso(map), pos, n) +#define map__for_each_symbol(map, cb, data) \ + dso__for_each_symbol(map__dso(map), cb, data) =20 /* map__for_each_symbol_with_name - iterate over the symbols in the given = map * that have the given name diff --git a/tools/perf/util/probe-event.c b/tools/perf/util/probe-event.c index 1534280c0c1d..3d506c09b749 100644 --- a/tools/perf/util/probe-event.c +++ b/tools/perf/util/probe-event.c @@ -3047,49 +3047,63 @@ static int __add_probe_trace_events(struct perf_pro= be_event *pev, return ret; } =20 -static int find_probe_functions(struct map *map, char *name, - struct symbol **syms) +struct find_probe_functions_args { + const char *name; + struct symbol **syms; + int found; + bool cut_version; +}; + +static int find_probe_functions_cb(struct symbol *sym, void *data) { - int found =3D 0; - struct symbol *sym; - struct rb_node *tmp; + struct find_probe_functions_args *args =3D data; const char *norm, *ver; char *buf =3D NULL; - bool cut_version =3D true; - - if (map__load(map) < 0) - return -EACCES; /* Possible permission error to load symbols */ =20 - /* If user gives a version, don't cut off the version from symbols */ - if (strchr(name, '@')) - cut_version =3D false; - - map__for_each_symbol(map, sym, tmp) { - norm =3D arch__normalize_symbol_name(sym->name); - if (!norm) - continue; + norm =3D arch__normalize_symbol_name(sym->name); + if (!norm) + return 0; =20 - if (cut_version) { - /* We don't care about default symbol or not */ - ver =3D strchr(norm, '@'); - if (ver) { - buf =3D strndup(norm, ver - norm); - if (!buf) - return -ENOMEM; - norm =3D buf; - } + if (args->cut_version) { + /* We don't care about default symbol or not */ + ver =3D strchr(norm, '@'); + if (ver) { + buf =3D strndup(norm, ver - norm); + if (!buf) + return -ENOMEM; + norm =3D buf; } + } =20 - if (strglobmatch(norm, name)) { - found++; - if (syms && found < probe_conf.max_probes) - syms[found - 1] =3D sym; - } - if (buf) - zfree(&buf); + if (strglobmatch(norm, args->name)) { + args->found++; + if (args->syms && args->found < probe_conf.max_probes) + args->syms[args->found - 1] =3D sym; } + free(buf); + return 0; +} + +static int find_probe_functions(struct map *map, char *name, + struct symbol **syms) +{ + struct find_probe_functions_args args =3D { + .name =3D name, + .syms =3D syms, + /* If user gives a version, don't cut off the version from symbols */ + .cut_version =3D strchr(name, '@') =3D=3D NULL, + .found =3D 0, + }; + int ret; + + if (map__load(map) < 0) + return -EACCES; /* Possible permission error to load symbols */ + + ret =3D map__for_each_symbol(map, find_probe_functions_cb, &args); + if (ret < 0) + return ret; =20 - return found; + return args.found; } =20 void __weak arch__fix_tev_from_maps(struct perf_probe_event *pev __maybe_u= nused, diff --git a/tools/perf/util/symbol.c b/tools/perf/util/symbol.c index 8dded88c9763..2977457bfb48 100644 --- a/tools/perf/util/symbol.c +++ b/tools/perf/util/symbol.c @@ -613,6 +613,25 @@ struct symbol *dso__find_symbol(struct dso *dso, u64 a= ddr) return dso__last_find_result_symbol(dso); } =20 +int symbols__visit(struct rb_root_cached *symbols, + int (*cb)(struct symbol *sym, void *data), + void *data) +{ + struct rb_node *nd; + + if (!symbols) + return 0; + + for (nd =3D rb_first_cached(symbols); nd; nd =3D rb_next(nd)) { + struct symbol *sym =3D rb_entry(nd, struct symbol, rb_node); + int ret =3D cb(sym, data); + + if (ret) + return ret; + } + return 0; +} + struct symbol *dso__find_symbol_nocache(struct dso *dso, u64 addr) { return symbols__find(dso__symbols(dso), addr); diff --git a/tools/perf/util/symbol.h b/tools/perf/util/symbol.h index a6a2ab200f98..5a105b10a089 100644 --- a/tools/perf/util/symbol.h +++ b/tools/perf/util/symbol.h @@ -141,16 +141,16 @@ void symbol__set_annotate2(struct symbol *sym, bool a= nnotate2); void symbol__set_inlined(struct symbol *sym, bool inlined); void symbol__set_ifunc_alias(struct symbol *sym, bool ifunc_alias); =20 -/* symbols__for_each_entry - iterate over symbols (rb_root) +/* + * symbols__visit - iterate over symbols calling @cb for each entry * - * @symbols: the rb_root of symbols - * @pos: the 'struct symbol *' to use as a loop cursor - * @nd: the 'struct rb_node *' to use as a temporary storage + * @symbols: the rb_root_cached of symbols + * @cb: callback function invoked for each symbol + * @data: opaque data pointer passed to @cb */ -#define symbols__for_each_entry(symbols, pos, nd) \ - for (nd =3D rb_first_cached(symbols); \ - nd && (pos =3D rb_entry(nd, struct symbol, rb_node)); \ - nd =3D rb_next(nd)) +int symbols__visit(struct rb_root_cached *symbols, + int (*cb)(struct symbol *sym, void *data), + void *data); =20 static inline size_t symbol__size(const struct symbol *sym) { --=20 2.56.1.750.gf70dc682cf-goog From nobody Tue Nov 24 11:51:44 2026 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=209.85.210.200 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1795323874; b=067YS09vS/tGmsBraKnc9j0opraZBVm7zGGK6v+jTkSZ2Baqp8735uRzqqblcPx7hHXx wpkF79ScYPD4zmpQT7V+uUkanoJfNXgmtjuuXlZszBcqEAoLmx9cfwpejqL5TuKTy7oqq 5A/h94bwqoSN8JFR+3PghPxjSDKLOogbrq8GtNWP2BURkAnHkBU+oqvg9eN6GhUPjHHzi QfenE+GlrgDs2tUofk0rT/B/E/LnxL+WX/Jcvw7I4qSuzm7vdnvNg8UITd9JWNUUKT179 sDQrXNQbWpB93vTA+r603XhE20bxcrvVeF18aCMwtyZWZgFiyxJpnIr86ks38FtRezg== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1795323874; h=DMARC-Filter:Received:DKIM-Signature:X-Google-DKIM-Signature: X-Forwarded-Encrypted:X-Gm-Message-State:X-Received:Date:In-Reply-To: Mime-Version:References:X-Mailer:Message-ID:Subject:From:To:Cc: Content-Type; bh=Np5KXfe3NBZd587exl6mjQGpa7okg5fzQbM6YlrNB2w=; b=l1wNjowUOWXzUbCsPL9hYPzEvHfMUPTv4B85mpbhbGKUwm2GfY4sdxWMTIvlp0IPmKda TU6UHBPUlZNdOKXoOF4Yv3Xzsz9F1fQbmhLpNuRqsVVFa48lnc8rDfKn8Xrhcdczt85bu DVp4DJHroctAOPfxBVTxnLENId078D9vsDAqA7t5ZJjuaSWlFWBh3S+PdRRpI3hCtfwww 9BBFJgCVqwrUq3qbNCMUzhISjasdIoSJL3R8J+CS+UdPIAM2Zo14Woib7ty0KGIDfpoa+ i9HF3wTlFRaX1S9FIxOzqjyeVogSgQshtW7VmEiaV36eZAObq2aFr7Il5NNQLsBhuhg== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass header.from=google.com; spf=pass smtp.mailfrom=flex--irogers.bounces.google.com; dkim=pass header.d=google.com header.i=@google.com header.a=rsa-sha256 header.s=20260707 header.b=Dmkg0lmL; arc=none smtp.remote-ip=209.85.210.200 Received: from mail-pf1-f200.google.com (mail-pf1-f200.google.com [209.85.210.200]) (using TLSv1.3 with cipher TLS_AES_128_GCM_SHA256 (128/128 bits) key-exchange X25519 server-signature ECDSA (prime256v1) server-digest SHA256) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id A6F58606A332 for ; Sun, 22 Nov 2026 05:04:33 +0000 (UTC) DMARC-Filter: OpenDMARC Filter v1.4.2 smtp.subspace.kernel.org A6F58606A332 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=flex--irogers.bounces.google.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.a=rsa-sha256 header.s=20260707 header.b=Dmkg0lmL Received: by mail-pf1-f200.google.com with SMTP id d2e1a72fcca58-8b6463f95a4so1957048b3a.2 for ; Sat, 21 Nov 2026 21:04:33 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20260707; t=1795323873; x=1795928673; darn=vger.kernel.org; h=content-type:cc:to:from:subject:message-id:references:mime-version :in-reply-to:date:from:to:cc:subject:date:message-id:reply-to :content-type; bh=Np5KXfe3NBZd587exl6mjQGpa7okg5fzQbM6YlrNB2w=; b=Dmkg0lmLygDOqx1Q0mwH1MhUWa55rNbFiK+dWtFNWNsStkGMiUjHBk0OlGiZDIrGWg BB3rZakYEXR+iKO43FRqEraXbcPdESq61bcO9PtHD0nvFjJLYQts6chOx3buMb5FTxPE 1SRhjV5Ybhq3WjN8yp1Q2cTSUHqCeSW1DKsS0a6h3822eHuCYrCGCiNFSR2QvFHDn0sg 7K3A5mXBRiJrHw+uUyp0yFS3GWZoSvJBqHo1Ojls2qVKV0PDAwE+BrnTSjSSwQqr/6Y+ CUPPOQu6wv1Gx7RjZdYdy0BYI2oCCKoaBMQ5BapsWIVZ0MDUAQ6jjgZp32EHRSjmPhdY gS6A== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20260707; t=1795323873; x=1795928673; h=content-type:cc:to:from:subject:message-id:references:mime-version :in-reply-to:date:x-gm-message-state:from:to:cc:subject:date :message-id:reply-to:content-type; bh=Np5KXfe3NBZd587exl6mjQGpa7okg5fzQbM6YlrNB2w=; b=c34v2Zn7cFZGzJwti8gupInQ0OoG/sVvBW8U7iLQFjPcgJEzYcx7InRoiqqrBirC4G MoKQrxT3NdLoUCZ2eSOaff1+huSOX10fyKCiN8xTfHFUfUcZChm2pEtqfr3uBEmKer7R TAHe6pifYNWKTOBaw2z/tOz8E6GppzsXcU68H/1/jJbnvAdBLLKUouAtO5CY1ECfIueR 8WRfhjDkVsh7zYYJX743MAm2MX+KDJrHGVzC9RToQSWyWqFuHwrtKE8gmi06N4BRzubF k3oh59fMvKW0fa9y23IPix5nYXXMVxCbnq0jlGQSLi4+28kYC/SQLDZTvpI0ZJHuqx1t 7xMg== X-Forwarded-Encrypted: i=1; AL+hErH0sW3ildV2CCktmKHTNnL74NTiUvNh0SNMBGVdFcP7taP2dtjFl4+zRfg5ziFIL5WFz5lGT9mAKd3JPII=@vger.kernel.org X-Gm-Message-State: APuU4Z+Rrqstsbu4sHEbQ3lX+ssbXKhrsfK6DB6ajeuh7Q+zFqKW85F8 sGQZ9pdavFsKUFGVs44YAEVwakoKi36PYdi7vq5yXW6SZsn14d5UvDO0HqcBEgliIor7pGNVwMF UMmN3h6gFRQ== X-Received: from pgcv7.prod.google.com ([2002:a05:6a02:5307:b0:cdb:225e:d520]) (user=irogers job=prod-delivery.src-stubby-dispatcher) by 2002:a05:6300:670e:b0:3f9:9114:8038 with SMTP id adf61e73a8af0-4014d25fa0dmr6984533637.45.1795323872767; Sat, 21 Nov 2026 21:04:32 -0800 (PST) Date: Sat, 21 Nov 2026 21:03:59 -0800 In-Reply-To: <20261122050405.80335-1-irogers@google.com> X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Post: List-Help: List-Subscribe: List-Unsubscribe: List-Owner: Precedence: list Mime-Version: 1.0 References: <20261122050405.80335-1-irogers@google.com> X-Mailer: git-send-email 2.56.1.750.gf70dc682cf-goog Message-ID: <20261122050405.80335-5-irogers@google.com> Subject: [PATCH v8 04/10] perf symbol: Use callback iteration instead of open-coded symbol loops From: Ian Rogers To: Namhyung Kim , Arnaldo Carvalho de Melo , Alireza Haghdoost , Ian Rogers Cc: Peter Zijlstra , Ingo Molnar , Jiri Olsa , Adrian Hunter , James Clark , linux-perf-users@vger.kernel.org, linux-kernel@vger.kernel.org Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" Convert open-coded dso__first_symbol() / dso__next_symbol(), rb_first_cached() / rb_next(), and dso__symbol_names() loops across auxtrace, intel-pt, machine, dso, probe-event, symbol_fprintf, and tests/symbols.c to use dso__for_each_symbol(), map__for_each_symbol(), and a new dso__for_each_symbol_by_name() callback helper. With no remaining callers, remove dso__first_symbol(), dso__last_symbol(), and dso__next_symbol(). Signed-off-by: Ian Rogers --- tools/perf/tests/symbols.c | 61 ++++++++++------- tools/perf/util/auxtrace.c | 109 ++++++++++++++++++++----------- tools/perf/util/dso.c | 34 ++++++---- tools/perf/util/dso.h | 3 + tools/perf/util/intel-pt.c | 74 +++++++++++++-------- tools/perf/util/machine.c | 28 ++++---- tools/perf/util/probe-event.c | 16 +++-- tools/perf/util/symbol.c | 52 ++++----------- tools/perf/util/symbol.h | 7 +- tools/perf/util/symbol_fprintf.c | 25 +++++-- 10 files changed, 239 insertions(+), 170 deletions(-) diff --git a/tools/perf/tests/symbols.c b/tools/perf/tests/symbols.c index d3180db45ee6..b73da581f895 100644 --- a/tools/perf/tests/symbols.c +++ b/tools/perf/tests/symbols.c @@ -116,39 +116,50 @@ static int create_map(struct test_info *ti, char *fil= ename, struct map **map_p) return TEST_OK; } =20 +struct test_dso_args { + struct symbol *last_sym; + int ret; +}; + +static int test_dso_cb(struct symbol *sym, void *data) +{ + struct test_dso_args *args =3D data; + struct symbol *last_sym =3D args->last_sym; + + if (symbol__type(sym) !=3D STT_FUNC && symbol__type(sym) !=3D STT_GNU_IFU= NC) + return 0; + + /* Check for overlapping function symbols */ + if (last_sym && sym->start < last_sym->end) { + pr_debug("Overlapping symbols:\n"); + symbol__fprintf(last_sym, stderr); + symbol__fprintf(sym, stderr); + args->ret =3D TEST_FAIL; + } + /* Check for zero-length function symbol */ + if (sym->start =3D=3D sym->end) { + pr_debug("Zero-length symbol:\n"); + symbol__fprintf(sym, stderr); + args->ret =3D TEST_FAIL; + } + args->last_sym =3D sym; + return 0; +} + static int test_dso(struct dso *dso) { - struct symbol *last_sym =3D NULL; - struct rb_node *nd; - int ret =3D TEST_OK; + struct test_dso_args args =3D { + .last_sym =3D NULL, + .ret =3D TEST_OK, + }; =20 /* dso__fprintf() prints all the symbols */ if (verbose > 1) dso__fprintf(dso, stderr); =20 - for (nd =3D rb_first_cached(dso__symbols(dso)); nd; nd =3D rb_next(nd)) { - struct symbol *sym =3D rb_entry(nd, struct symbol, rb_node); + dso__for_each_symbol(dso, test_dso_cb, &args); =20 - if (symbol__type(sym) !=3D STT_FUNC && symbol__type(sym) !=3D STT_GNU_IF= UNC) - continue; - - /* Check for overlapping function symbols */ - if (last_sym && sym->start < last_sym->end) { - pr_debug("Overlapping symbols:\n"); - symbol__fprintf(last_sym, stderr); - symbol__fprintf(sym, stderr); - ret =3D TEST_FAIL; - } - /* Check for zero-length function symbol */ - if (sym->start =3D=3D sym->end) { - pr_debug("Zero-length symbol:\n"); - symbol__fprintf(sym, stderr); - ret =3D TEST_FAIL; - } - last_sym =3D sym; - } - - return ret; + return args.ret; } =20 static int subdivided_dso_cb(struct dso *dso, struct machine *machine __ma= ybe_unused, void *d) diff --git a/tools/perf/util/auxtrace.c b/tools/perf/util/auxtrace.c index 1451de019df0..e6916c2044c5 100644 --- a/tools/perf/util/auxtrace.c +++ b/tools/perf/util/auxtrace.c @@ -2719,61 +2719,96 @@ static bool dso_sym_match(struct symbol *sym, const= char *name, int *cnt, idx < 0); } =20 +struct print_duplicate_syms_args { + const char *sym_name; + bool near; + int cnt; +}; + +static int print_duplicate_syms_cb(struct symbol *sym, void *data) +{ + struct print_duplicate_syms_args *args =3D data; + + if (dso_sym_match(sym, args->sym_name, &args->cnt, -1)) { + pr_err("#%d\t0x%"PRIx64"\t%c\t%s\n", + ++args->cnt, sym->start, + symbol__binding(sym) =3D=3D STB_GLOBAL ? 'g' : + symbol__binding(sym) =3D=3D STB_LOCAL ? 'l' : 'w', + sym->name); + args->near =3D true; + } else if (args->near) { + args->near =3D false; + pr_err("\t\twhich is near\t\t%s\n", sym->name); + } + return 0; +} + static void print_duplicate_syms(struct dso *dso, const char *sym_name) { - struct symbol *sym; - bool near =3D false; - int cnt =3D 0; + struct print_duplicate_syms_args args =3D { + .sym_name =3D sym_name, + .near =3D false, + .cnt =3D 0, + }; =20 pr_err("Multiple symbols with name '%s'\n", sym_name); =20 - sym =3D dso__first_symbol(dso); - while (sym) { - if (dso_sym_match(sym, sym_name, &cnt, -1)) { - pr_err("#%d\t0x%"PRIx64"\t%c\t%s\n", - ++cnt, sym->start, - symbol__binding(sym) =3D=3D STB_GLOBAL ? 'g' : - symbol__binding(sym) =3D=3D STB_LOCAL ? 'l' : 'w', - sym->name); - near =3D true; - } else if (near) { - near =3D false; - pr_err("\t\twhich is near\t\t%s\n", sym->name); - } - sym =3D dso__next_symbol(sym); - } + dso__for_each_symbol(dso, print_duplicate_syms_cb, &args); =20 pr_err("Disambiguate symbol name by inserting #n after the name e.g. %s #= 2\n", sym_name); pr_err("Or select a global symbol by inserting #0 or #g or #G\n"); } =20 +struct find_dso_sym_args { + const char *sym_name; + u64 *start; + u64 *size; + int idx; + int cnt; + bool duplicate; +}; + +static int find_dso_sym_cb(struct symbol *sym, void *data) +{ + struct find_dso_sym_args *args =3D data; + + if (*args->start) { + if (!*args->size) + *args->size =3D sym->start - *args->start; + if (args->idx > 0) { + if (*args->size) + return 1; + } else if (dso_sym_match(sym, args->sym_name, &args->cnt, args->idx)) { + args->duplicate =3D true; + return 1; + } + } else if (dso_sym_match(sym, args->sym_name, &args->cnt, args->idx)) { + *args->start =3D sym->start; + *args->size =3D sym->end - sym->start; + } + return 0; +} + static int find_dso_sym(struct dso *dso, const char *sym_name, u64 *start, u64 *size, int idx) { - struct symbol *sym; - int cnt =3D 0; + struct find_dso_sym_args args =3D { + .sym_name =3D sym_name, + .start =3D start, + .size =3D size, + .idx =3D idx, + .cnt =3D 0, + .duplicate =3D false, + }; =20 *start =3D 0; *size =3D 0; =20 - sym =3D dso__first_symbol(dso); - while (sym) { - if (*start) { - if (!*size) - *size =3D sym->start - *start; - if (idx > 0) { - if (*size) - return 0; - } else if (dso_sym_match(sym, sym_name, &cnt, idx)) { - print_duplicate_syms(dso, sym_name); - return -EINVAL; - } - } else if (dso_sym_match(sym, sym_name, &cnt, idx)) { - *start =3D sym->start; - *size =3D sym->end - sym->start; - } - sym =3D dso__next_symbol(sym); + dso__for_each_symbol(dso, find_dso_sym_cb, &args); + if (args.duplicate) { + print_duplicate_syms(dso, sym_name); + return -EINVAL; } =20 if (!*start) diff --git a/tools/perf/util/dso.c b/tools/perf/util/dso.c index 49813424e4ee..e090a5bd12b6 100644 --- a/tools/perf/util/dso.c +++ b/tools/perf/util/dso.c @@ -1998,22 +1998,34 @@ static size_t dso__fprintf_buildid(struct dso *dso,= FILE *fp) return fprintf(fp, "%s", sbuild_id); } =20 +struct dso__fprintf_cb_args { + FILE *fp; + size_t ret; +}; + +static int dso__fprintf_cb(struct symbol *pos, void *data) +{ + struct dso__fprintf_cb_args *args =3D data; + + args->ret +=3D symbol__fprintf(pos, args->fp); + return 0; +} + size_t dso__fprintf(struct dso *dso, FILE *fp) { - struct rb_node *nd; - size_t ret =3D fprintf(fp, "dso: %s (", dso__short_name(dso)); + struct dso__fprintf_cb_args args =3D { + .fp =3D fp, + .ret =3D fprintf(fp, "dso: %s (", dso__short_name(dso)), + }; =20 if (dso__short_name(dso) !=3D dso__long_name(dso)) - ret +=3D fprintf(fp, "%s, ", dso__long_name(dso)); - ret +=3D fprintf(fp, "%sloaded, ", dso__loaded(dso) ? "" : "NOT "); - ret +=3D dso__fprintf_buildid(dso, fp); - ret +=3D fprintf(fp, ")\n"); - for (nd =3D rb_first_cached(dso__symbols(dso)); nd; nd =3D rb_next(nd)) { - struct symbol *pos =3D rb_entry(nd, struct symbol, rb_node); - ret +=3D symbol__fprintf(pos, fp); - } + args.ret +=3D fprintf(fp, "%s, ", dso__long_name(dso)); + args.ret +=3D fprintf(fp, "%sloaded, ", dso__loaded(dso) ? "" : "NOT "); + args.ret +=3D dso__fprintf_buildid(dso, fp); + args.ret +=3D fprintf(fp, ")\n"); + dso__for_each_symbol(dso, dso__fprintf_cb, &args); =20 - return ret; + return args.ret; } =20 enum dso_type dso__type(struct dso *dso, struct machine *machine) diff --git a/tools/perf/util/dso.h b/tools/perf/util/dso.h index dd859356ecd9..dddfcd3db0aa 100644 --- a/tools/perf/util/dso.h +++ b/tools/perf/util/dso.h @@ -368,6 +368,9 @@ int dso_id__cmp(const struct dso_id *a, const struct ds= o_id *b); #define dso__for_each_symbol(dso, cb, data) \ symbols__visit(dso__symbols(dso), cb, data) =20 +#define dso__for_each_symbol_by_name(dso, cb, data) \ + dso__visit_symbols_by_name(dso, cb, data) + static inline void *dso__a2l(const struct dso *dso) { return RC_CHK_ACCESS(dso)->a2l; diff --git a/tools/perf/util/intel-pt.c b/tools/perf/util/intel-pt.c index e8b9c8a67b0a..9b7d315ca391 100644 --- a/tools/perf/util/intel-pt.c +++ b/tools/perf/util/intel-pt.c @@ -2988,13 +2988,37 @@ static int intel_pt_sample(struct intel_pt_queue *p= tq) return 0; } =20 +struct intel_pt_switch_ip_args { + struct map *map; + const char *name; + bool check_global; + u64 ip; +}; + +static int intel_pt_switch_ip_cb(struct symbol *sym, void *data) +{ + struct intel_pt_switch_ip_args *args =3D data; + u64 ip; + + if (args->check_global && symbol__binding(sym) !=3D STB_GLOBAL) + return 0; + + if (!strcmp(sym->name, args->name)) { + ip =3D map__unmap_ip(args->map, sym->start); + if (ip >=3D map__start(args->map) && ip < map__end(args->map)) { + args->ip =3D ip; + return 1; + } + } + return 0; +} + static u64 intel_pt_switch_ip(struct intel_pt *pt, u64 *ptss_ip) { struct machine *machine =3D pt->machine; struct map *map; - struct symbol *sym, *start; - u64 ip, switch_ip =3D 0; - const char *ptss; + struct intel_pt_switch_ip_args args; + u64 switch_ip =3D 0; =20 if (ptss_ip) *ptss_ip =3D 0; @@ -3006,36 +3030,28 @@ static u64 intel_pt_switch_ip(struct intel_pt *pt, = u64 *ptss_ip) if (map__load(map)) return 0; =20 - start =3D dso__first_symbol(map__dso(map)); - - for (sym =3D start; sym; sym =3D dso__next_symbol(sym)) { - if (symbol__binding(sym) =3D=3D STB_GLOBAL && - !strcmp(sym->name, "__switch_to")) { - ip =3D map__unmap_ip(map, sym->start); - if (ip >=3D map__start(map) && ip < map__end(map)) { - switch_ip =3D ip; - break; - } - } - } + args =3D (struct intel_pt_switch_ip_args) { + .map =3D map, + .name =3D "__switch_to", + .check_global =3D true, + .ip =3D 0, + }; + map__for_each_symbol(map, intel_pt_switch_ip_cb, &args); + switch_ip =3D args.ip; =20 if (!switch_ip || !ptss_ip) return 0; =20 - if (pt->have_sched_switch =3D=3D 1) - ptss =3D "perf_trace_sched_switch"; - else - ptss =3D "__perf_event_task_sched_out"; - - for (sym =3D start; sym; sym =3D dso__next_symbol(sym)) { - if (!strcmp(sym->name, ptss)) { - ip =3D map__unmap_ip(map, sym->start); - if (ip >=3D map__start(map) && ip < map__end(map)) { - *ptss_ip =3D ip; - break; - } - } - } + args =3D (struct intel_pt_switch_ip_args) { + .map =3D map, + .name =3D pt->have_sched_switch =3D=3D 1 ? + "perf_trace_sched_switch" : + "__perf_event_task_sched_out", + .check_global =3D false, + .ip =3D 0, + }; + map__for_each_symbol(map, intel_pt_switch_ip_cb, &args); + *ptss_ip =3D args.ip; =20 return switch_ip; } diff --git a/tools/perf/util/machine.c b/tools/perf/util/machine.c index 70870baa157e..6dd05ec1bbaf 100644 --- a/tools/perf/util/machine.c +++ b/tools/perf/util/machine.c @@ -1125,29 +1125,35 @@ int machine__create_extra_kernel_map(struct machine= *machine, return err; } =20 -static u64 find_entry_trampoline(struct dso *dso) +static int find_entry_trampoline_cb(struct symbol *sym, void *data) { /* Duplicates are removed so lookup all aliases */ - const char *syms[] =3D { + static const char * const syms[] =3D { "_entry_trampoline", "__entry_trampoline_start", "entry_SYSCALL_64_trampoline", }; - struct symbol *sym =3D dso__first_symbol(dso); - unsigned int i; + u64 *addr =3D data; =20 - for (; sym; sym =3D dso__next_symbol(sym)) { - if (symbol__binding(sym) !=3D STB_GLOBAL) - continue; - for (i =3D 0; i < ARRAY_SIZE(syms); i++) { - if (!strcmp(sym->name, syms[i])) - return sym->start; + if (symbol__binding(sym) !=3D STB_GLOBAL) + return 0; + for (unsigned int i =3D 0; i < ARRAY_SIZE(syms); i++) { + if (!strcmp(sym->name, syms[i])) { + *addr =3D sym->start; + return 1; } } - return 0; } =20 +static u64 find_entry_trampoline(struct dso *dso) +{ + u64 addr =3D 0; + + dso__for_each_symbol(dso, find_entry_trampoline_cb, &addr); + return addr; +} + /* * These values can be used for kernels that do not have symbols for the e= ntry * trampolines in kallsyms. diff --git a/tools/perf/util/probe-event.c b/tools/perf/util/probe-event.c index 3d506c09b749..e3f8e3cd68c0 100644 --- a/tools/perf/util/probe-event.c +++ b/tools/perf/util/probe-event.c @@ -3788,6 +3788,15 @@ void cleanup_perf_probe_events(struct perf_probe_eve= nt *pevs, int npevs) } } =20 +static int show_available_funcs_cb(struct symbol *pos, void *data) +{ + struct strfilter *_filter =3D data; + + if (strfilter__compare(_filter, pos->name)) + printf("%s\n", pos->name); + return 0; +} + int show_available_funcs(const char *target, struct nsinfo *nsi, struct strfilter *_filter, bool user) { @@ -3824,12 +3833,7 @@ int show_available_funcs(const char *target, struct = nsinfo *nsi, /* Show all (filtered) symbols */ setup_pager(); =20 - for (size_t i =3D 0; i < dso__symbol_names_len(dso); i++) { - struct symbol *pos =3D dso__symbol_names(dso)[i]; - - if (strfilter__compare(_filter, pos->name)) - printf("%s\n", pos->name); - } + dso__for_each_symbol_by_name(dso, show_available_funcs_cb, _filter); end: map__put(map); exit_probe_symbol_maps(); diff --git a/tools/perf/util/symbol.c b/tools/perf/util/symbol.c index 2977457bfb48..710b80d86d07 100644 --- a/tools/perf/util/symbol.c +++ b/tools/perf/util/symbol.c @@ -451,36 +451,6 @@ static struct symbol *symbols__find(struct rb_root_cac= hed *symbols, u64 ip) return NULL; } =20 -static struct symbol *symbols__first(struct rb_root_cached *symbols) -{ - struct rb_node *n =3D rb_first_cached(symbols); - - if (n) - return rb_entry(n, struct symbol, rb_node); - - return NULL; -} - -static struct symbol *symbols__last(struct rb_root_cached *symbols) -{ - struct rb_node *n =3D rb_last(&symbols->rb_root); - - if (n) - return rb_entry(n, struct symbol, rb_node); - - return NULL; -} - -static struct symbol *symbols__next(struct symbol *sym) -{ - struct rb_node *n =3D rb_next(&sym->rb_node); - - if (n) - return rb_entry(n, struct symbol, rb_node); - - return NULL; -} - static int symbols__sort_name_cmp(const void *vlhs, const void *vrhs) { const struct symbol *lhs =3D *((const struct symbol **)vlhs); @@ -637,19 +607,21 @@ struct symbol *dso__find_symbol_nocache(struct dso *d= so, u64 addr) return symbols__find(dso__symbols(dso), addr); } =20 -struct symbol *dso__first_symbol(struct dso *dso) +int dso__visit_symbols_by_name(struct dso *dso, + int (*cb)(struct symbol *sym, void *data), + void *data) { - return symbols__first(dso__symbols(dso)); -} + if (!dso) + return 0; =20 -struct symbol *dso__last_symbol(struct dso *dso) -{ - return symbols__last(dso__symbols(dso)); -} + dso__sort_by_name(dso); + for (size_t i =3D 0; i < dso__symbol_names_len(dso); i++) { + int ret =3D cb(dso__symbol_names(dso)[i], data); =20 -struct symbol *dso__next_symbol(struct symbol *sym) -{ - return symbols__next(sym); + if (ret) + return ret; + } + return 0; } =20 struct symbol *dso__next_symbol_by_name(struct dso *dso, size_t *idx) diff --git a/tools/perf/util/symbol.h b/tools/perf/util/symbol.h index 5a105b10a089..784c87b72f38 100644 --- a/tools/perf/util/symbol.h +++ b/tools/perf/util/symbol.h @@ -197,10 +197,9 @@ struct symbol *dso__find_symbol_nocache(struct dso *ds= o, u64 addr); =20 struct symbol *dso__next_symbol_by_name(struct dso *dso, size_t *idx); struct symbol *dso__find_symbol_by_name(struct dso *dso, const char *name,= size_t *idx); - -struct symbol *dso__first_symbol(struct dso *dso); -struct symbol *dso__last_symbol(struct dso *dso); -struct symbol *dso__next_symbol(struct symbol *sym); +int dso__visit_symbols_by_name(struct dso *dso, + int (*cb)(struct symbol *sym, void *data), + void *data); =20 enum dso_type dso__type_fd(int fd); =20 diff --git a/tools/perf/util/symbol_fprintf.c b/tools/perf/util/symbol_fpri= ntf.c index 4dc8d5761f52..f818e7ad1519 100644 --- a/tools/perf/util/symbol_fprintf.c +++ b/tools/perf/util/symbol_fprintf.c @@ -59,15 +59,26 @@ size_t symbol__fprintf_symname(const struct symbol *sym= , FILE *fp) return __symbol__fprintf_symname_offs(sym, NULL, false, false, fp); } =20 +struct fprintf_symbols_by_name_args { + FILE *fp; + size_t ret; +}; + +static int fprintf_symbols_by_name_cb(struct symbol *pos, void *data) +{ + struct fprintf_symbols_by_name_args *args =3D data; + + args->ret +=3D fprintf(args->fp, "%s\n", pos->name); + return 0; +} + size_t dso__fprintf_symbols_by_name(struct dso *dso, FILE *fp) { - size_t ret =3D 0; - - for (size_t i =3D 0; i < dso__symbol_names_len(dso); i++) { - struct symbol *pos =3D dso__symbol_names(dso)[i]; + struct fprintf_symbols_by_name_args args =3D { + .fp =3D fp, + }; =20 - ret +=3D fprintf(fp, "%s\n", pos->name); - } - return ret; + dso__for_each_symbol_by_name(dso, fprintf_symbols_by_name_cb, &args); + return args.ret; } --=20 2.56.1.750.gf70dc682cf-goog From nobody Tue Nov 24 11:51:44 2026 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=74.125.82.200 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1795323880; b=oiRfaQMyTTo6x4mbCunUm6zQ3rj99XOFuO7zct+N4Uh9fXcEkjTUbEihw/GDrG5updpt PQBjjRYvngl0YdVBpHGG6m0YvjhPFlqjDqgE5XuYFG7Q6ybArYz6EWYHnCtfiG4+PYIIH rOed60Jy+E5NLZcKxhWPCK7os5aC8ltHLfEYctIqpGxzQY1tixef7kadN9MczACnHrNN8 LPHx15pzAHSfcDhTuUtlZSpgKmLc+2mK/4oFlJ4FEsZV/M4Rdu8+zCD56l48RVPw1i9q2 4aVp9pPd/4Q5NOL67mO/Agn4H5FRunfg85lKpvWNg4NV8nzI5lETvrVkhkAKzRag6dw== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1795323880; h=DMARC-Filter:Received:DKIM-Signature:X-Google-DKIM-Signature: X-Forwarded-Encrypted:X-Gm-Message-State:X-Received:Date:In-Reply-To: Mime-Version:References:X-Mailer:Message-ID:Subject:From:To:Cc: Content-Type; bh=eioM0PC7l/LAaBEflaadXqSxpvWv6IaP6K49lqa7SY8=; b=Q3kwTGSmq3tTS5k5rvB0+zbgbUB+EwKo/F8yiJXh4/TfbzedHrdU3MsUcediV5vDPSHq MY9khKQ3lOZNpqla/5j+O+2yr5aCAwpjvjr2/ouNZ9KC+oOYdlfXhH0fF1VdNrVx/PPBb 5LJnOQ9pL2AIz5QgzpwNx3Ze56ABMu3Qz3JMJDoPWxjrLwNU4K133Y4/iH8IhjaKvU9ic DfMvX1FvE/KLBynX/crOssE32FEojJm+vlogc7hzF0QXKow3AuyForTE+a1MOI0rFUCTn Q/orFDfJlNkEI0WnsCQfPcTax885ruXSfxM7IPgc2KzDbBIURGTbYzKwpM+Buaj6WgQ== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass header.from=google.com; spf=pass smtp.mailfrom=flex--irogers.bounces.google.com; dkim=pass header.d=google.com header.i=@google.com header.a=rsa-sha256 header.s=20260707 header.b=U8mXUuDh; arc=none smtp.remote-ip=74.125.82.200 Received: from mail-dy1-f200.google.com (mail-dy1-f200.google.com [74.125.82.200]) (using TLSv1.3 with cipher TLS_AES_128_GCM_SHA256 (128/128 bits) key-exchange X25519 server-signature ECDSA (prime256v1) server-digest SHA256) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 9588F606A330 for ; Sun, 22 Nov 2026 05:04:38 +0000 (UTC) DMARC-Filter: OpenDMARC Filter v1.4.2 smtp.subspace.kernel.org 9588F606A330 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=flex--irogers.bounces.google.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.a=rsa-sha256 header.s=20260707 header.b=U8mXUuDh Received: by mail-dy1-f200.google.com with SMTP id 5a478bee46e88-38531c1a566so5935456eec.1 for ; Sat, 21 Nov 2026 21:04:38 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20260707; t=1795323878; x=1795928678; darn=vger.kernel.org; h=content-type:cc:to:from:subject:message-id:references:mime-version :in-reply-to:date:from:to:cc:subject:date:message-id:reply-to :content-type; bh=eioM0PC7l/LAaBEflaadXqSxpvWv6IaP6K49lqa7SY8=; b=U8mXUuDh5tih+/icUpKNHjWrETxW/pLbiz4Fa7g50tBW9sBaiRYc8zJY6B7mzarsvH yhWQ+AZ5Uo56nFYrwdPIPYCseoeL7+ELrS8K7H7wof/nNzjYXdRiMoQZ0eN83YeDkZNx U6ue7m9AW+ylVruoh+KmnFB6lBSVyqfCa4Gr8jzT6HZG7rZMckTUG0FGqrQmprghax+m jesC2f4crZt4+ETujx2+OXyna10xZ8nSS+QXRd1H/eM2TMfRGMIYKJ6OSlNDW4xwfvbP P1MrDOLQahUVGn0MIH1TbZnanqpV8D8RuHpA8EG0vM7wx8tOANE73354/Ct6dp0Ko4e3 fM7w== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20260707; t=1795323878; x=1795928678; h=content-type:cc:to:from:subject:message-id:references:mime-version :in-reply-to:date:x-gm-message-state:from:to:cc:subject:date :message-id:reply-to:content-type; bh=eioM0PC7l/LAaBEflaadXqSxpvWv6IaP6K49lqa7SY8=; b=x5m+xh6FbrdfXxdkVQeC5093L8ruqpMgxcQlLWDx/aM0y51tzsXkdsgvwU3RT/J8HQ jCUXwQhA8LtSqHgdyo6TCibt0W2xTw7Qs31cw8gNtBMUhXlmLPArFig0HHujCg+yHaWN YN66sHqKUbklh7o+gy7HfVtwtElugNAzbksl8cSPB6VeNSJ7VI9NXoCmqQ30Gu1Bpu00 D/9jXzXrQTpfL5X8b8veR0noVeQA9Bxvegn5unlqlupf0T+/276UFTQmYwBswWbXLMB7 QSAzi4m7tX/OTX18DIYp2haVWNUBLt1mOydTob2/ZbHOWF8T2uTlRNdmFBB0+xAoE58i rEDQ== X-Forwarded-Encrypted: i=1; AL+hErGiKGP/4pHi8C0jrifE/jRFA8hAxjiYgcTVY6g7e/c+xIxdBRRDkZTO7dvpLW+rXcPNzp35pqP66OIQf3o=@vger.kernel.org X-Gm-Message-State: APuU4Z+ahozqfZTO+giP+QnGtg9sOr+iTS4XOLJqojV4DO6tUc7xmg8Z hASmHrus5l5THkh73evk94cvo/0SamjtOOFil6EUJXQT7eFPX+ymtheORvxuVNRi1Kd0rudDFRL TPHk1R2lbNg== X-Received: from dleb16-n2.prod.google.com ([2002:a05:701b:4250:20b0:1ac:2245:a27b]) (user=irogers job=prod-delivery.src-stubby-dispatcher) by 2002:a05:701b:2706:b0:154:e9d2:d741 with SMTP id a92af1059eb24-1b5568a12f4mr7639797c88.8.1795323877213; Sat, 21 Nov 2026 21:04:37 -0800 (PST) Date: Sat, 21 Nov 2026 21:04:00 -0800 In-Reply-To: <20261122050405.80335-1-irogers@google.com> X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Post: List-Help: List-Subscribe: List-Unsubscribe: List-Owner: Precedence: list Mime-Version: 1.0 References: <20261122050405.80335-1-irogers@google.com> X-Mailer: git-send-email 2.56.1.750.gf70dc682cf-goog Message-ID: <20261122050405.80335-6-irogers@google.com> Subject: [PATCH v8 05/10] perf symbol: Switch backing storage from rbtree to struct symbols array From: Ian Rogers To: Namhyung Kim , Arnaldo Carvalho de Melo , Alireza Haghdoost , Ian Rogers Cc: Peter Zijlstra , Ingo Molnar , Jiri Olsa , Adrian Hunter , James Clark , linux-perf-users@vger.kernel.org, linux-kernel@vger.kernel.org Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" Previously, DSO symbols were stored in an unprotected rb_root_cached with a 24-byte struct rb_node embedded inside every struct symbol. That design had three drawbacks: 1. Embedding struct rb_node (3 pointers, 24 bytes on 64-bit) accounted for nearly 40% of struct symbol's fixed header size and scattered symbol lookups across non-contiguous heap nodes. 2. Unlike struct dsos and struct maps, the symbol rbtree had no lock protecting concurrent lookups, sorting, and insertions. 3. Deduplicating symbols, splitting kallsyms, and trimming excess symbol container capacity under memory pressure benefit from operating on a compact array under a lock. Replace struct rb_node in struct symbol with a locked, lazily-sorted pointer array in struct symbols, matching the design of struct dsos and struct maps: - Introduce struct symbols containing a rw_semaphore lock, primary address-sorted symbols array, secondary name-sorted symbols_by_name array, counts, capacity, and sorted state flags. - Lazily sort symbols by start address using qsort (symbols__sort_locked) and use binary search in symbols__find(). - Update symbols__fixup_duplicate(), symbols__fixup_end(), maps__split_kallsyms_for_kcore(), and maps__split_kallsyms() to operate on the sorted array and compact entries in place. - Update symbols__visit() and symbols__visit_by_name() to iterate the sorted arrays under symbols->lock. - Remove the unsynchronized single-entry dso->last_find_result cache and dso__reset_find_symbol_cache() since binary search over a contiguous array is cache-friendly. - Remove the direct rb_erase_cached() workaround in builtin-annotate.c's add_sample(). - Update the TUI map browser (ui/browsers/map.c) to snapshot the sorted symbol array into an entries array and use ui_browser__argv_refresh and ui_browser__argv_seek instead of ui_browser__rb_tree_refresh. Using 'perf bench internals symbols': Before (perf binary): Average DSO load + sort: 7.041 msec (+- 0.051 msec) Average DSO memory usage: 1401 KB (+- 4 KB) Average bulk insert + lookup: 1453.950 usec (+- 10.895 usec) After (perf binary, -13.5% load, -14.6% memory, -7.7% bulk): Average DSO load + sort: 6.089 msec (+- 0.039 msec) Average DSO memory usage: 1197 KB (+- 3 KB) Average bulk insert + lookup: 1341.500 usec (+- 21.564 usec) Before (libLLVM.so.21.1): Average DSO load + sort: 78.599 msec (+- 0.857 msec) Average DSO memory usage: 9530 KB (+- 5 KB) After (libLLVM.so.21.1, -22.3% load, -8.1% memory): Average DSO load + sort: 61.074 msec (+- 0.236 msec) Average DSO memory usage: 8755 KB (+- 1 KB) Signed-off-by: Ian Rogers --- tools/perf/builtin-annotate.c | 11 - tools/perf/tests/hists_common.c | 5 +- tools/perf/ui/browser.c | 3 + tools/perf/ui/browsers/hists.c | 3 +- tools/perf/ui/browsers/map.c | 62 ++- tools/perf/util/db-export.c | 4 +- tools/perf/util/dso.c | 20 +- tools/perf/util/dso.h | 65 +--- tools/perf/util/libbfd.c | 3 +- tools/perf/util/machine.c | 2 +- tools/perf/util/map.c | 36 +- tools/perf/util/symbol-elf.c | 12 +- tools/perf/util/symbol.c | 656 ++++++++++++++++++++++---------- tools/perf/util/symbol.h | 61 ++- 14 files changed, 604 insertions(+), 339 deletions(-) diff --git a/tools/perf/builtin-annotate.c b/tools/perf/builtin-annotate.c index 7cb7e03d9a21..65846110c309 100644 --- a/tools/perf/builtin-annotate.c +++ b/tools/perf/builtin-annotate.c @@ -258,17 +258,6 @@ static int add_sample(struct perf_sample *sample, (al->sym =3D=3D NULL || strcmp(ann->sym_hist_filter, al->sym->name) !=3D 0)) { /* We're only interested in a symbol named sym_hist_filter */ - /* - * FIXME: why isn't this done in the symbol_filter when loading - * the DSO? - */ - if (al->sym !=3D NULL) { - struct dso *dso =3D map__dso(al->map); - - rb_erase_cached(&al->sym->rb_node, dso__symbols(dso)); - symbol__delete(al->sym); - dso__reset_find_symbol_cache(dso); - } return 0; } =20 diff --git a/tools/perf/tests/hists_common.c b/tools/perf/tests/hists_commo= n.c index 187f12f5bc21..0d3acb03e02c 100644 --- a/tools/perf/tests/hists_common.c +++ b/tools/perf/tests/hists_common.c @@ -146,7 +146,10 @@ struct machine *setup_fake_machine(struct machines *ma= chines) goto out; } =20 - symbols__insert(dso__symbols(dso), sym); + if (symbols__insert(dso__symbols(dso), sym)) { + dso__put(dso); + goto out; + } } =20 dso__put(dso); diff --git a/tools/perf/ui/browser.c b/tools/perf/ui/browser.c index 321187b204d3..c7451f640d1d 100644 --- a/tools/perf/ui/browser.c +++ b/tools/perf/ui/browser.c @@ -622,6 +622,9 @@ static int ui_browser__color_config(const char *var, co= nst char *value, =20 void ui_browser__argv_seek(struct ui_browser *browser, off_t offset, int w= hence) { + if (browser->nr_entries =3D=3D 0) + return; + switch (whence) { case SEEK_SET: browser->top =3D browser->entries; diff --git a/tools/perf/ui/browsers/hists.c b/tools/perf/ui/browsers/hists.c index 6f9d9f7aec91..ad6882744eba 100644 --- a/tools/perf/ui/browsers/hists.c +++ b/tools/perf/ui/browsers/hists.c @@ -2532,7 +2532,8 @@ static struct symbol *symbol__new_unresolved(u64 addr= , struct map *map) return NULL; } =20 - dso__insert_symbol(map__dso(map), sym); + if (dso__insert_symbol(map__dso(map), sym)) + return NULL; } =20 return sym; diff --git a/tools/perf/ui/browsers/map.c b/tools/perf/ui/browsers/map.c index be7390156edd..51a71b20947f 100644 --- a/tools/perf/ui/browsers/map.c +++ b/tools/perf/ui/browsers/map.c @@ -24,7 +24,7 @@ struct map_browser { =20 static void map_browser__write(struct ui_browser *browser, void *nd, int r= ow) { - struct symbol *sym =3D rb_entry(nd, struct symbol, rb_node); + struct symbol *sym =3D *(struct symbol **)nd; struct map_browser *mb =3D container_of(browser, struct map_browser, b); bool current_entry =3D ui_browser__is_current_entry(browser, row); int width; @@ -56,17 +56,16 @@ static int map_browser__search(struct map_browser *brow= ser) sym =3D map__find_symbol_by_name(browser->map, target); =20 if (sym !=3D NULL) { - struct rb_node *nd; - u32 idx =3D 0; + struct symbol **entries =3D browser->b.entries; =20 /* - * Walk the map browser's symbol entries to find the matching - * symbol node and its display row index, then position the - * browser cursor at that entry. + * Scan the map browser's symbol entries to find the matching + * symbol and its display row index, then position the browser + * cursor at that entry. */ - for (nd =3D rb_first(browser->b.entries); nd; nd =3D rb_next(nd), ++idx)= { - if (&sym->rb_node =3D=3D nd) { - browser->b.top =3D nd; + for (u32 idx =3D 0; idx < browser->b.nr_entries; ++idx) { + if (entries[idx] =3D=3D sym) { + browser->b.top =3D &entries[idx]; browser->b.index =3D browser->b.top_idx =3D idx; break; } @@ -109,27 +108,48 @@ static int map_browser__run(struct map_browser *brows= er) =20 int map__browse(struct map *map) { + struct symbols *symbols =3D dso__symbols(map__dso(map)); struct map_browser mb =3D { .b =3D { - .entries =3D dso__symbols(map__dso(map)), - .refresh =3D ui_browser__rb_tree_refresh, - .seek =3D ui_browser__rb_tree_seek, + .refresh =3D ui_browser__argv_refresh, + .seek =3D ui_browser__argv_seek, .write =3D map_browser__write, }, .map =3D map, }; - struct rb_node *nd; + struct symbol **entries =3D NULL; + unsigned int nr_entries =3D 0; char tmp[BITS_PER_LONG / 4]; u64 maxaddr =3D 0; - - for (nd =3D rb_first(mb.b.entries); nd; nd =3D rb_next(nd)) { - struct symbol *pos =3D rb_entry(nd, struct symbol, rb_node); - - if (maxaddr < pos->end) - maxaddr =3D pos->end; - ++mb.b.nr_entries; + int ret; + + /* + * Snapshot the DSO's sorted symbol array under symbols->lock for use + * with ui_browser__argv_refresh and ui_browser__argv_seek. + */ + symbols__sort_read_lock(symbols); + nr_entries =3D symbols->cnt; + if (nr_entries > 0) { + entries =3D malloc(nr_entries * sizeof(*entries)); + if (entries) { + for (unsigned int idx =3D 0; idx < nr_entries; idx++) { + struct symbol *pos =3D symbols->symbols[idx]; + + entries[idx] =3D pos; + if (maxaddr < pos->end) + maxaddr =3D pos->end; + } + } else { + nr_entries =3D 0; + } } + up_read(&symbols->lock); + + mb.b.entries =3D entries; + mb.b.nr_entries =3D nr_entries; =20 mb.addrlen =3D snprintf(tmp, sizeof(tmp), "%" PRIx64, maxaddr); - return map_browser__run(&mb); + ret =3D map_browser__run(&mb); + free(entries); + return ret; } diff --git a/tools/perf/util/db-export.c b/tools/perf/util/db-export.c index e7b807e968cf..b3790383237f 100644 --- a/tools/perf/util/db-export.c +++ b/tools/perf/util/db-export.c @@ -289,8 +289,8 @@ static int db_ids_from_al(struct db_export *dbe, struct= addr_location *al, =20 if (!al->sym) { al->sym =3D symbol__new(al->addr, 0, 0, 0, "unknown"); - if (al->sym) - dso__insert_symbol(dso, al->sym); + if (al->sym && dso__insert_symbol(dso, al->sym)) + al->sym =3D NULL; } =20 if (al->sym) { diff --git a/tools/perf/util/dso.c b/tools/perf/util/dso.c index e090a5bd12b6..d1668c986e8d 100644 --- a/tools/perf/util/dso.c +++ b/tools/perf/util/dso.c @@ -1802,12 +1802,13 @@ bool dso__loaded(const struct dso *dso) =20 bool dso__sorted_by_name(const struct dso *dso) { - return RC_CHK_ACCESS(dso)->sorted_by_name; -} + struct symbols *symbols =3D (struct symbols *)&RC_CHK_ACCESS(dso)->symbol= s; + bool res; =20 -void dso__set_sorted_by_name(struct dso *dso) -{ - RC_CHK_ACCESS(dso)->sorted_by_name =3D true; + down_read(&symbols->lock); + res =3D symbols->sorted_by_name; + up_read(&symbols->lock); + return res; } =20 struct dso *dso__new_id(const char *name, const struct dso_id *id) @@ -1825,9 +1826,7 @@ struct dso *dso__new_id(const char *name, const struc= t dso_id *id) dso->id =3D *id; dso__set_long_name_id(res, dso->name, false); dso__set_short_name(res, dso->name, false); - dso->symbols =3D RB_ROOT_CACHED; - dso->symbol_names =3D NULL; - dso->symbol_names_len =3D 0; + symbols__init(&dso->symbols); dso->inlined_nodes =3D RB_ROOT_CACHED; dso->srclines =3D RB_ROOT_CACHED; dso->data_types =3D RB_ROOT; @@ -1838,7 +1837,6 @@ struct dso *dso__new_id(const char *name, const struc= t dso_id *id) dso->is_64_bit =3D (sizeof(void *) =3D=3D 8); dso->loaded =3D 0; dso->rel =3D 0; - dso->sorted_by_name =3D 0; dso->has_srcline =3D 1; dso->a2l_fails =3D 1; dso->kernel =3D DSO_SPACE__USER; @@ -1869,9 +1867,7 @@ void dso__delete(struct dso *dso) /* free inlines first, as they reference symbols */ inlines__tree_delete(&RC_CHK_ACCESS(dso)->inlined_nodes); srcline__tree_delete(&RC_CHK_ACCESS(dso)->srclines); - symbols__delete(&RC_CHK_ACCESS(dso)->symbols); - RC_CHK_ACCESS(dso)->symbol_names_len =3D 0; - zfree(&RC_CHK_ACCESS(dso)->symbol_names); + symbols__exit(&RC_CHK_ACCESS(dso)->symbols); annotated_data_type__tree_delete(dso__data_types(dso)); global_var_type__tree_delete(dso__global_vars(dso)); =20 diff --git a/tools/perf/util/dso.h b/tools/perf/util/dso.h index dddfcd3db0aa..63c1b7d6f6f8 100644 --- a/tools/perf/util/dso.h +++ b/tools/perf/util/dso.h @@ -13,6 +13,7 @@ #include "build-id.h" #include "debuginfo.h" #include "mutex.h" +#include "symbol.h" #include =20 struct machine; @@ -284,18 +285,12 @@ struct auxtrace_cache; DECLARE_RC_STRUCT(dso) { struct mutex lock; struct dsos *dsos; - struct rb_root_cached symbols; - struct symbol **symbol_names; - size_t symbol_names_len; + struct symbols symbols; struct rb_root_cached inlined_nodes; struct rb_root_cached srclines; struct rb_root data_types; struct rb_root global_vars; =20 - struct { - u64 addr; - struct symbol *symbol; - } last_find_result; u64 text_offset; u64 text_end; const char *short_name; @@ -348,7 +343,6 @@ DECLARE_RC_STRUCT(dso) { u8 is_64_bit:1; u8 bintype_searched:1; u8 debuginfo_searched:1; - bool sorted_by_name; bool loaded; u8 rel; char name[]; @@ -369,7 +363,7 @@ int dso_id__cmp(const struct dso_id *a, const struct ds= o_id *b); symbols__visit(dso__symbols(dso), cb, data) =20 #define dso__for_each_symbol_by_name(dso, cb, data) \ - dso__visit_symbols_by_name(dso, cb, data) + symbols__visit_by_name(dso__symbols(dso), cb, data) =20 static inline void *dso__a2l(const struct dso *dso) { @@ -598,26 +592,6 @@ static inline void dso__set_kernel(struct dso *dso, en= um dso_space_type kernel) RC_CHK_ACCESS(dso)->kernel =3D kernel; } =20 -static inline u64 dso__last_find_result_addr(const struct dso *dso) -{ - return RC_CHK_ACCESS(dso)->last_find_result.addr; -} - -static inline void dso__set_last_find_result_addr(struct dso *dso, u64 add= r) -{ - RC_CHK_ACCESS(dso)->last_find_result.addr =3D addr; -} - -static inline struct symbol *dso__last_find_result_symbol(const struct dso= *dso) -{ - return RC_CHK_ACCESS(dso)->last_find_result.symbol; -} - -static inline void dso__set_last_find_result_symbol(struct dso *dso, struc= t symbol *symbol) -{ - RC_CHK_ACCESS(dso)->last_find_result.symbol =3D symbol; -} - static inline enum dso_load_errno *dso__load_errno(struct dso *dso) { return &RC_CHK_ACCESS(dso)->load_errno; @@ -731,31 +705,11 @@ static inline struct rb_root *dso__global_vars(struct= dso *dso) return &RC_CHK_ACCESS(dso)->global_vars; } =20 -static inline struct rb_root_cached *dso__symbols(struct dso *dso) +static inline struct symbols *dso__symbols(struct dso *dso) { return &RC_CHK_ACCESS(dso)->symbols; } =20 -static inline struct symbol **dso__symbol_names(struct dso *dso) -{ - return RC_CHK_ACCESS(dso)->symbol_names; -} - -static inline void dso__set_symbol_names(struct dso *dso, struct symbol **= names) -{ - RC_CHK_ACCESS(dso)->symbol_names =3D names; -} - -static inline size_t dso__symbol_names_len(struct dso *dso) -{ - return RC_CHK_ACCESS(dso)->symbol_names_len; -} - -static inline void dso__set_symbol_names_len(struct dso *dso, size_t len) -{ - RC_CHK_ACCESS(dso)->symbol_names_len =3D len; -} - static inline const char *dso__symsrc_filename(const struct dso *dso) { return RC_CHK_ACCESS(dso)->symsrc_filename; @@ -825,13 +779,18 @@ bool dso__loaded(const struct dso *dso); =20 static inline bool dso__has_symbols(const struct dso *dso) { - return !RB_EMPTY_ROOT(&RC_CHK_ACCESS(dso)->symbols.rb_root); + struct symbols *symbols =3D (struct symbols *)&RC_CHK_ACCESS(dso)->symbol= s; + bool res; + + down_read(&symbols->lock); + res =3D symbols->cnt > 0; + up_read(&symbols->lock); + return res; } =20 char *dso__filename_with_chroot(const struct dso *dso, const char *filenam= e); =20 bool dso__sorted_by_name(const struct dso *dso); -void dso__set_sorted_by_name(struct dso *dso); void dso__sort_by_name(struct dso *dso); =20 int dso__swap_init(struct dso *dso, unsigned char eidata); @@ -955,8 +914,6 @@ struct map *dso__new_map(const char *name); struct dso *machine__findnew_kernel(struct machine *machine, const char *n= ame, const char *short_name, int dso_type); =20 -void dso__reset_find_symbol_cache(struct dso *dso); - size_t dso__fprintf_symbols_by_name(struct dso *dso, FILE *fp); size_t dso__fprintf(struct dso *dso, FILE *fp); =20 diff --git a/tools/perf/util/libbfd.c b/tools/perf/util/libbfd.c index 61bd4f49afba..9728e2509d4a 100644 --- a/tools/perf/util/libbfd.c +++ b/tools/perf/util/libbfd.c @@ -453,7 +453,8 @@ int dso__load_bfd_symbols(struct dso *dso, const char *= debugfile) if (!symbol) goto out_free; =20 - symbols__insert(dso__symbols(dso), symbol); + if (symbols__insert(dso__symbols(dso), symbol)) + goto out_free; } #ifdef bfd_get_section #undef bfd_asymbol_section diff --git a/tools/perf/util/machine.c b/tools/perf/util/machine.c index 6dd05ec1bbaf..3c206c26bd62 100644 --- a/tools/perf/util/machine.c +++ b/tools/perf/util/machine.c @@ -822,7 +822,7 @@ static int machine__process_ksymbol_register(struct mac= hine *machine, err =3D -ENOMEM; goto out; } - dso__insert_symbol(dso, sym); + err =3D dso__insert_symbol(dso, sym); out: map__put(map); dso__put(dso); diff --git a/tools/perf/util/map.c b/tools/perf/util/map.c index 5155c95df85d..38b116d230d0 100644 --- a/tools/perf/util/map.c +++ b/tools/perf/util/map.c @@ -304,27 +304,35 @@ void map__put(struct map *map) =20 void map__fixup_start(struct map *map) { - struct dso *dso =3D map__dso(map); - struct rb_root_cached *symbols =3D dso__symbols(dso); - struct rb_node *nd =3D rb_first_cached(symbols); - - if (nd !=3D NULL) { - struct symbol *sym =3D rb_entry(nd, struct symbol, rb_node); + struct symbols *symbols =3D dso__symbols(map__dso(map)); =20 - map__set_start(map, sym->start); - } + symbols__sort_read_lock(symbols); + if (symbols->cnt > 0) + map__set_start(map, symbols->symbols[0]->start); + up_read(&symbols->lock); } =20 void map__fixup_end(struct map *map) { - struct dso *dso =3D map__dso(map); - struct rb_root_cached *symbols =3D dso__symbols(dso); - struct rb_node *nd =3D rb_last(&symbols->rb_root); + struct symbols *symbols =3D dso__symbols(map__dso(map)); =20 - if (nd !=3D NULL) { - struct symbol *sym =3D rb_entry(nd, struct symbol, rb_node); - map__set_end(map, sym->end); + symbols__sort_read_lock(symbols); + if (symbols->cnt > 0) { + u64 last_start =3D symbols->symbols[symbols->cnt - 1]->start; + u64 end =3D symbols->symbols[symbols->cnt - 1]->end; + + for (unsigned int i =3D symbols->cnt - 1; i > 0; i--) { + u64 sym_end; + + if (symbols->symbols[i - 1]->start !=3D last_start) + break; + sym_end =3D symbols->symbols[i - 1]->end; + if (sym_end > end) + end =3D sym_end; + } + map__set_end(map, end); } + up_read(&symbols->lock); } =20 #define DSO__DELETED "(deleted)" diff --git a/tools/perf/util/symbol-elf.c b/tools/perf/util/symbol-elf.c index 2b7f9e30916d..bda0b92ada24 100644 --- a/tools/perf/util/symbol-elf.c +++ b/tools/perf/util/symbol-elf.c @@ -698,7 +698,8 @@ static int dso__synthesize_plt_got_symbols(struct dso *= dso, Elf *elf, sym =3D symbol__new(shdr.sh_offset + i, shdr.sh_entsize, STB_GLOBAL, STT= _FUNC, buf); if (!sym) goto out; - symbols__insert(dso__symbols(dso), sym); + if (symbols__insert(dso__symbols(dso), sym)) + goto out; } err =3D 0; out: @@ -752,7 +753,8 @@ int dso__synthesize_plt_symbols(struct dso *dso, struct= symsrc *ss) plt_sym =3D symbol__new(shdr_plt.sh_offset, plt_header_size, STB_GLOBAL, = STT_FUNC, ".plt"); if (!plt_sym) goto out_elf_end; - symbols__insert(dso__symbols(dso), plt_sym); + if (symbols__insert(dso__symbols(dso), plt_sym)) + goto out_elf_end; =20 /* Only x86 has .plt.got */ if (machine_is_x86(ehdr.e_machine) && @@ -874,7 +876,8 @@ int dso__synthesize_plt_symbols(struct dso *dso, struct= symsrc *ss) goto out_elf_end; =20 plt_offset +=3D plt_entry_size; - symbols__insert(dso__symbols(dso), f); + if (symbols__insert(dso__symbols(dso), f)) + goto out_elf_end; ++nr; } =20 @@ -1938,7 +1941,8 @@ dso__load_sym_internal(struct dso *dso, struct map *m= ap, struct symsrc *syms_ss, =20 arch__sym_update(f, &sym); =20 - __symbols__insert(dso__symbols(curr_dso), f); + if (symbols__insert(dso__symbols(curr_dso), f)) + goto out_elf_end; nr++; } dso__put(curr_dso); diff --git a/tools/perf/util/symbol.c b/tools/perf/util/symbol.c index 710b80d86d07..43347c9a3a0c 100644 --- a/tools/perf/util/symbol.c +++ b/tools/perf/util/symbol.c @@ -213,57 +213,169 @@ static int choose_best_symbol(struct symbol *syma, s= truct symbol *symb) return arch__choose_best_symbol(syma, symb); } =20 -void symbols__fixup_duplicate(struct rb_root_cached *symbols) +void symbols__init(struct symbols *symbols) + __context_unsafe(/* initialization */) { - struct rb_node *nd; - struct symbol *curr, *next; + init_rwsem(&symbols->lock); + symbols->symbols =3D NULL; + symbols->symbols_by_name =3D NULL; + symbols->cnt =3D 0; + symbols->allocated =3D 0; + symbols->num_by_name =3D 0; + symbols->sorted =3D true; + symbols->sorted_by_name =3D false; +} + +static void symbols__delete_locked(struct symbols *symbols) + __must_hold(&symbols->lock) +{ + for (unsigned int i =3D 0; i < symbols->cnt; i++) + symbol__delete(symbols->symbols[i]); + + zfree(&symbols->symbols); + zfree(&symbols->symbols_by_name); + symbols->cnt =3D 0; + symbols->allocated =3D 0; + symbols->num_by_name =3D 0; + symbols->sorted =3D true; + symbols->sorted_by_name =3D false; +} + +void symbols__delete(struct symbols *symbols) +{ + down_write(&symbols->lock); + symbols__delete_locked(symbols); + up_write(&symbols->lock); +} + +void symbols__exit(struct symbols *symbols) +{ + symbols__delete(symbols); + exit_rwsem(&symbols->lock); +} + +/* + * Order symbols by start address only, preserving insertion order among + * symbols sharing the same start address (matching the previous rbtree + * __symbols__insert() behavior so alias deduplication and IFUNC resolution + * remain unchanged). + */ +static inline bool symbol__less_or_equal(const struct symbol *a, const str= uct symbol *b) +{ + return a->start <=3D b->start; +} + +static int symbols__sort_cmp(const void *vlhs, const void *vrhs) +{ + const struct symbol *lhs =3D *((const struct symbol **)vlhs); + const struct symbol *rhs =3D *((const struct symbol **)vrhs); + + if (lhs->start !=3D rhs->start) + return lhs->start < rhs->start ? -1 : 1; + return 0; +} + +static void symbols__sort_locked(struct symbols *symbols) + __must_hold(&symbols->lock) +{ + if (symbols->sorted) + return; + + if (symbols->cnt > 1) { + qsort(symbols->symbols, symbols->cnt, sizeof(struct symbol *), + symbols__sort_cmp); + } + symbols->sorted =3D true; +} + +/* + * Acquire @symbols->lock for reading after ensuring @symbols->symbols is + * sorted. + */ +void symbols__sort_read_lock(struct symbols *symbols) +{ + down_read(&symbols->lock); + while (!symbols->sorted) { + up_read(&symbols->lock); + down_write(&symbols->lock); + symbols__sort_locked(symbols); + up_write(&symbols->lock); + down_read(&symbols->lock); + } +} + +/* + * Deduplicate symbols sharing the same start address by sorting @symbols = and + * compacting the array in place, keeping the best symbol at each address = as + * chosen by choose_best_symbol(). + */ +void symbols__fixup_duplicate(struct symbols *symbols) +{ + unsigned int write_idx =3D 0; =20 if (symbol_conf.allow_aliases) return; =20 - nd =3D rb_first_cached(symbols); + down_write(&symbols->lock); + symbols__sort_locked(symbols); + if (symbols->cnt <=3D 1) { + up_write(&symbols->lock); + return; + } =20 - while (nd) { - curr =3D rb_entry(nd, struct symbol, rb_node); -again: - nd =3D rb_next(&curr->rb_node); - if (!nd) - break; + for (unsigned int read_idx =3D 1; read_idx < symbols->cnt; read_idx++) { + struct symbol *curr =3D symbols->symbols[write_idx]; + struct symbol *next =3D symbols->symbols[read_idx]; =20 - next =3D rb_entry(nd, struct symbol, rb_node); - if (curr->start !=3D next->start) + if (curr->start !=3D next->start) { + symbols->symbols[++write_idx] =3D next; continue; + } =20 if (choose_best_symbol(curr, next) =3D=3D SYMBOL_A) { if (symbol__type(next) =3D=3D STT_GNU_IFUNC) symbol__set_ifunc_alias(curr, true); - rb_erase_cached(&next->rb_node, symbols); symbol__delete(next); - goto again; } else { if (symbol__type(curr) =3D=3D STT_GNU_IFUNC) symbol__set_ifunc_alias(next, true); - nd =3D rb_next(&curr->rb_node); - rb_erase_cached(&curr->rb_node, symbols); symbol__delete(curr); + symbols->symbols[write_idx] =3D next; } } + symbols->cnt =3D write_idx + 1; + zfree(&symbols->symbols_by_name); + symbols->num_by_name =3D 0; + symbols->sorted_by_name =3D false; + up_write(&symbols->lock); } =20 /* Update zero-sized symbols using the address of the next symbol */ -void symbols__fixup_end(struct rb_root_cached *symbols, bool is_kallsyms) +void symbols__fixup_end(struct symbols *symbols, bool is_kallsyms) { - struct rb_node *nd, *prevnd =3D rb_first_cached(symbols); struct symbol *curr, *prev; + bool addr_has_sized; =20 - if (prevnd =3D=3D NULL) + down_write(&symbols->lock); + symbols__sort_locked(symbols); + + if (symbols->cnt =3D=3D 0) { + up_write(&symbols->lock); return; + } =20 - curr =3D rb_entry(prevnd, struct symbol, rb_node); + curr =3D symbols->symbols[0]; + addr_has_sized =3D curr->end > curr->start; =20 - for (nd =3D rb_next(prevnd); nd; nd =3D rb_next(nd)) { + for (unsigned int i =3D 1; i < symbols->cnt; i++) { prev =3D curr; - curr =3D rb_entry(nd, struct symbol, rb_node); + curr =3D symbols->symbols[i]; + + if (curr->start =3D=3D prev->start) { + if (curr->end > curr->start) + addr_has_sized =3D true; + continue; + } =20 /* * On some architecture kernel text segment start is located at @@ -281,39 +393,42 @@ void symbols__fixup_end(struct rb_root_cached *symbol= s, bool is_kallsyms) * like in: * ffffffffc1937000 T hdmi_driver_init [snd_hda_codec_hdmi] */ - if (prev->end =3D=3D prev->start) { + if (!addr_has_sized && prev->end =3D=3D prev->start) { const char *prev_mod; const char *curr_mod; =20 if (!is_kallsyms) { prev->end =3D curr->start; - continue; - } - - prev_mod =3D strchr(prev->name, '['); - curr_mod =3D strchr(curr->name, '['); - - /* Last kernel/module symbol mapped to end of page */ - if (!prev_mod !=3D !curr_mod) - prev->end =3D roundup(prev->end + 4096, 4096); - /* Last symbol in the previous module */ - else if (prev_mod && strcmp(prev_mod, curr_mod)) - prev->end =3D roundup(prev->end + 4096, 4096); - else - prev->end =3D curr->start; + } else { + prev_mod =3D strchr(prev->name, '['); + curr_mod =3D strchr(curr->name, '['); + + /* Last kernel/module symbol mapped to end of page */ + if (!prev_mod !=3D !curr_mod) { + prev->end =3D roundup(prev->end + 4096, 4096); + /* Last symbol in the previous module */ + } else if (prev_mod && strcmp(prev_mod, curr_mod)) { + prev->end =3D roundup(prev->end + 4096, 4096); + } else { + prev->end =3D curr->start; + } =20 - /* The next module can start within that page */ - if (prev->end > curr->start) - prev->end =3D curr->start; + /* The next module can start within that page */ + if (prev->end > curr->start) + prev->end =3D curr->start; =20 - pr_debug4("%s sym:%s end:%#" PRIx64 "\n", - __func__, prev->name, prev->end); + pr_debug4("%s sym:%s end:%#" PRIx64 "\n", + __func__, prev->name, prev->end); + } } + addr_has_sized =3D curr->end > curr->start; } =20 /* Last entry */ - if (curr->end =3D=3D curr->start) + if (!addr_has_sized && curr->end =3D=3D curr->start) curr->end =3D roundup(curr->start, 4096) + 4096; + + up_write(&symbols->lock); } =20 struct symbol *symbol__new(u64 start, u64 len, u8 binding, u8 type, const = char *name) @@ -388,67 +503,117 @@ static void symbol__set_idle(struct symbol *sym, boo= l idle) new_flags |=3D (idle_val << SYMBOL_FLAG_IDLE_SHIFT); } while (!atomic_compare_exchange_weak(&sym->flags, &old_flags, new_flags= )); } -void symbols__delete(struct rb_root_cached *symbols) + +static int __symbols__insert(struct symbols *symbols, struct symbol *sym) + __must_hold(&symbols->lock) { - struct symbol *pos; - struct rb_node *next =3D rb_first_cached(symbols); + if (symbols->cnt =3D=3D symbols->allocated) { + unsigned int to_allocate =3D symbols->allocated ? symbols->allocated * 2= : 32; + struct symbol **temp =3D realloc(symbols->symbols, + sizeof(struct symbol *) * to_allocate); =20 - while (next) { - pos =3D rb_entry(next, struct symbol, rb_node); - next =3D rb_next(&pos->rb_node); - rb_erase_cached(&pos->rb_node, symbols); - symbol__delete(pos); + if (!temp) { + symbol__delete(sym); + return -ENOMEM; + } + symbols->symbols =3D temp; + symbols->allocated =3D to_allocate; } + + if (symbols->sorted && symbols->cnt > 0 && + !symbol__less_or_equal(symbols->symbols[symbols->cnt - 1], sym)) + symbols->sorted =3D false; + + symbols->symbols[symbols->cnt++] =3D sym; + zfree(&symbols->symbols_by_name); + symbols->num_by_name =3D 0; + symbols->sorted_by_name =3D false; + return 0; } =20 -void __symbols__insert(struct rb_root_cached *symbols, struct symbol *sym) +int symbols__insert(struct symbols *symbols, struct symbol *sym) { - struct rb_node **p =3D &symbols->rb_root.rb_node; - struct rb_node *parent =3D NULL; - const u64 ip =3D sym->start; - struct symbol *s; - bool leftmost =3D true; + int ret; =20 - while (*p !=3D NULL) { - parent =3D *p; - s =3D rb_entry(parent, struct symbol, rb_node); - if (ip < s->start) - p =3D &(*p)->rb_left; - else { - p =3D &(*p)->rb_right; - leftmost =3D false; - } - } - rb_link_node(&sym->rb_node, parent, p); - rb_insert_color_cached(&sym->rb_node, symbols, leftmost); + down_write(&symbols->lock); + ret =3D __symbols__insert(symbols, sym); + up_write(&symbols->lock); + return ret; +} + +static inline bool symbol__covers(const struct symbol *s, u64 ip) +{ + u64 start =3D s->start; + u64 end =3D s->end; + + return ip >=3D start && (ip < end || (ip =3D=3D end && ip =3D=3D start)); } =20 -void symbols__insert(struct rb_root_cached *symbols, struct symbol *sym) +static struct symbol *symbols__find_range(struct symbol **arr, unsigned in= t cnt, u64 ip) { - __symbols__insert(symbols, sym); + unsigned int low =3D 0, high =3D cnt, idx; + u64 start; + + while (low < high) { + unsigned int mid =3D low + (high - low) / 2; + + if (arr[mid]->start <=3D ip) + low =3D mid + 1; + else + high =3D mid; + } + if (low =3D=3D 0) + return NULL; + + /* + * Rewind across any equal-start group so a trailing zero-length or + * shorter alias at the same start address cannot mask an earlier + * covering symbol. + */ + idx =3D low - 1; + start =3D arr[idx]->start; + while (idx > 0 && arr[idx - 1]->start =3D=3D start) + idx--; + for (; idx < low; idx++) { + if (symbol__covers(arr[idx], ip)) + return arr[idx]; + } + return NULL; } =20 -static struct symbol *symbols__find(struct rb_root_cached *symbols, u64 ip) +/* + * Binary search @symbols->symbols for a symbol covering @ip. Lazily sorts + * @symbols under @symbols->lock if unsorted. + */ +static struct symbol *symbols__find(struct symbols *symbols, u64 ip) { - struct rb_node *n; + struct symbol *res; =20 if (symbols =3D=3D NULL) return NULL; =20 - n =3D symbols->rb_root.rb_node; + symbols__sort_read_lock(symbols); + res =3D symbols__find_range(symbols->symbols, symbols->cnt, ip); + up_read(&symbols->lock); =20 - while (n) { - struct symbol *s =3D rb_entry(n, struct symbol, rb_node); + return res; +} =20 - if (ip < s->start) - n =3D n->rb_left; - else if (ip > s->end || (ip =3D=3D s->end && ip !=3D s->start)) - n =3D n->rb_right; - else - return s; +int symbols__visit(struct symbols *symbols, + int (*cb)(struct symbol *sym, void *data), + void *data) +{ + int err =3D 0; + + symbols__sort_read_lock(symbols); + for (unsigned int i =3D 0; i < symbols->cnt; i++) { + err =3D cb(symbols->symbols[i], data); + if (err) + break; } + up_read(&symbols->lock); =20 - return NULL; + return err; } =20 static int symbols__sort_name_cmp(const void *vlhs, const void *vrhs) @@ -459,27 +624,51 @@ static int symbols__sort_name_cmp(const void *vlhs, c= onst void *vrhs) return strcmp(lhs->name, rhs->name); } =20 -static struct symbol **symbols__sort_by_name(struct rb_root_cached *source= , size_t *len) +static int symbols__sort_by_name_locked(struct symbols *symbols) + __must_hold(&symbols->lock) { - struct rb_node *nd; struct symbol **result; - size_t i =3D 0, size =3D 0; + unsigned int size =3D symbols->cnt; + + if (symbols->sorted_by_name) + return 0; =20 - for (nd =3D rb_first_cached(source); nd; nd =3D rb_next(nd)) - size++; + zfree(&symbols->symbols_by_name); + symbols->num_by_name =3D 0; + + if (size =3D=3D 0) { + symbols->sorted_by_name =3D true; + return 0; + } =20 result =3D malloc(sizeof(*result) * size); if (!result) - return NULL; + return -ENOMEM; + + memcpy(result, symbols->symbols, sizeof(*result) * size); + qsort(result, size, sizeof(*result), symbols__sort_name_cmp); + symbols->symbols_by_name =3D result; + symbols->num_by_name =3D size; + symbols->sorted_by_name =3D true; + return 0; +} =20 - for (nd =3D rb_first_cached(source); nd; nd =3D rb_next(nd)) { - struct symbol *pos =3D rb_entry(nd, struct symbol, rb_node); +static int symbols__sort_by_name_read_lock(struct symbols *symbols) + __acquires_shared(&symbols->lock) +{ + int err =3D 0; =20 - result[i++] =3D pos; + down_read(&symbols->lock); + while (!symbols->sorted_by_name) { + up_read(&symbols->lock); + down_write(&symbols->lock); + err =3D symbols__sort_by_name_locked(symbols); + up_write(&symbols->lock); + down_read(&symbols->lock); + if (err) + break; } - qsort(result, size, sizeof(*result), symbols__sort_name_cmp); - *len =3D size; - return result; + return symbols->sorted_by_name ? 0 : err; } =20 int symbol__match_symbol_name(const char *name, const char *str, @@ -548,58 +737,34 @@ static struct symbol *symbols__find_by_name(struct sy= mbol *symbols[], return s; } =20 -void dso__reset_find_symbol_cache(struct dso *dso) -{ - dso__set_last_find_result_addr(dso, 0); - dso__set_last_find_result_symbol(dso, NULL); -} - -void dso__insert_symbol(struct dso *dso, struct symbol *sym) +int dso__insert_symbol(struct dso *dso, struct symbol *sym) { - __symbols__insert(dso__symbols(dso), sym); - - /* update the symbol cache if necessary */ - if (dso__last_find_result_addr(dso) >=3D sym->start && - (dso__last_find_result_addr(dso) < sym->end || - sym->start =3D=3D sym->end)) { - dso__set_last_find_result_symbol(dso, sym); - } + return symbols__insert(dso__symbols(dso), sym); } =20 void dso__delete_symbol(struct dso *dso, struct symbol *sym) { - rb_erase_cached(&sym->rb_node, dso__symbols(dso)); - symbol__delete(sym); - dso__reset_find_symbol_cache(dso); -} - -struct symbol *dso__find_symbol(struct dso *dso, u64 addr) -{ - if (dso__last_find_result_addr(dso) !=3D addr || dso__last_find_result_sy= mbol(dso) =3D=3D NULL) { - dso__set_last_find_result_addr(dso, addr); - dso__set_last_find_result_symbol(dso, symbols__find(dso__symbols(dso), a= ddr)); + struct symbols *symbols =3D dso__symbols(dso); + + down_write(&symbols->lock); + for (unsigned int i =3D 0; i < symbols->cnt; i++) { + if (symbols->symbols[i] =3D=3D sym) { + memmove(&symbols->symbols[i], &symbols->symbols[i + 1], + (symbols->cnt - i - 1) * sizeof(struct symbol *)); + symbols->cnt--; + zfree(&symbols->symbols_by_name); + symbols->num_by_name =3D 0; + symbols->sorted_by_name =3D false; + symbol__delete(sym); + break; + } } - - return dso__last_find_result_symbol(dso); + up_write(&symbols->lock); } =20 -int symbols__visit(struct rb_root_cached *symbols, - int (*cb)(struct symbol *sym, void *data), - void *data) +struct symbol *dso__find_symbol(struct dso *dso, u64 addr) { - struct rb_node *nd; - - if (!symbols) - return 0; - - for (nd =3D rb_first_cached(symbols); nd; nd =3D rb_next(nd)) { - struct symbol *sym =3D rb_entry(nd, struct symbol, rb_node); - int ret =3D cb(sym, data); - - if (ret) - return ret; - } - return 0; + return symbols__find(dso__symbols(dso), addr); } =20 struct symbol *dso__find_symbol_nocache(struct dso *dso, u64 addr) @@ -607,30 +772,23 @@ struct symbol *dso__find_symbol_nocache(struct dso *d= so, u64 addr) return symbols__find(dso__symbols(dso), addr); } =20 -int dso__visit_symbols_by_name(struct dso *dso, - int (*cb)(struct symbol *sym, void *data), - void *data) +struct symbol *dso__next_symbol_by_name(struct dso *dso, size_t *idx) { - if (!dso) - return 0; + struct symbols *symbols; + struct symbol *res =3D NULL; =20 - dso__sort_by_name(dso); - for (size_t i =3D 0; i < dso__symbol_names_len(dso); i++) { - int ret =3D cb(dso__symbol_names(dso)[i], data); + if (!dso) + return NULL; =20 - if (ret) - return ret; + symbols =3D dso__symbols(dso); + if (!symbols__sort_by_name_read_lock(symbols) && + *idx + 1 < symbols->num_by_name) { + ++*idx; + res =3D symbols->symbols_by_name[*idx]; } - return 0; -} + up_read(&symbols->lock); =20 -struct symbol *dso__next_symbol_by_name(struct dso *dso, size_t *idx) -{ - if (*idx + 1 >=3D dso__symbol_names_len(dso)) - return NULL; - - ++*idx; - return dso__symbol_names(dso)[*idx]; + return res; } =20 /* @@ -638,29 +796,58 @@ struct symbol *dso__next_symbol_by_name(struct dso *d= so, size_t *idx) */ struct symbol *dso__find_symbol_by_name(struct dso *dso, const char *name,= size_t *idx) { - struct symbol *s =3D symbols__find_by_name(dso__symbol_names(dso), - dso__symbol_names_len(dso), - name, SYMBOL_TAG_INCLUDE__NONE, idx); - if (!s) { - s =3D symbols__find_by_name(dso__symbol_names(dso), dso__symbol_names_le= n(dso), - name, SYMBOL_TAG_INCLUDE__DEFAULT_ONLY, idx); + struct symbols *symbols; + struct symbol *s =3D NULL; + + if (idx) + *idx =3D SIZE_MAX; + if (!dso) + return NULL; + symbols =3D dso__symbols(dso); + if (!symbols__sort_by_name_read_lock(symbols)) { + s =3D symbols__find_by_name(symbols->symbols_by_name, + symbols->num_by_name, + name, SYMBOL_TAG_INCLUDE__NONE, idx); + if (!s) { + s =3D symbols__find_by_name(symbols->symbols_by_name, symbols->num_by_n= ame, + name, SYMBOL_TAG_INCLUDE__DEFAULT_ONLY, idx); + } } + up_read(&symbols->lock); return s; } =20 void dso__sort_by_name(struct dso *dso) { - mutex_lock(dso__lock(dso)); - if (!dso__sorted_by_name(dso)) { - size_t len =3D 0; + struct symbols *symbols =3D dso__symbols(dso); + + down_read(&symbols->lock); + if (!symbols->sorted_by_name) { + up_read(&symbols->lock); + down_write(&symbols->lock); + symbols__sort_by_name_locked(symbols); + up_write(&symbols->lock); + return; + } + up_read(&symbols->lock); +} + +int symbols__visit_by_name(struct symbols *symbols, + int (*cb)(struct symbol *sym, void *data), + void *data) +{ + int err =3D symbols__sort_by_name_read_lock(symbols); =20 - dso__set_symbol_names(dso, symbols__sort_by_name(dso__symbols(dso), &len= )); - if (dso__symbol_names(dso)) { - dso__set_symbol_names_len(dso, len); - dso__set_sorted_by_name(dso); + if (!err) { + for (size_t i =3D 0; i < symbols->num_by_name; i++) { + err =3D cb(symbols->symbols_by_name[i], data); + if (err) + break; } } - mutex_unlock(dso__lock(dso)); + up_read(&symbols->lock); + + return err; } =20 /* @@ -860,7 +1047,7 @@ static int map__process_kallsym_symbol(void *arg, cons= t char *name, { struct symbol *sym; struct dso *dso =3D arg; - struct rb_root_cached *root =3D dso__symbols(dso); + struct symbols *root =3D dso__symbols(dso); =20 if (!symbol_type__filter(type)) return 0; @@ -881,9 +1068,7 @@ static int map__process_kallsym_symbol(void *arg, cons= t char *name, * We will pass the symbols to the filter later, in * map__split_kallsyms, when we have split the maps per module */ - __symbols__insert(root, sym); - - return 0; + return symbols__insert(root, sym); } =20 /* @@ -900,25 +1085,32 @@ static int maps__split_kallsyms_for_kcore(struct map= s *kmaps, struct dso *dso) { struct symbol *pos; int count =3D 0; - struct rb_root_cached *root =3D dso__symbols(dso); - struct rb_root_cached old_root =3D *root; - struct rb_node *next =3D rb_first_cached(root); + struct symbols *root =3D dso__symbols(dso); + struct symbol **old_symbols; + unsigned int old_cnt; =20 if (!kmaps) return -1; =20 - *root =3D RB_ROOT_CACHED; - - while (next) { + down_write(&root->lock); + symbols__sort_locked(root); + old_symbols =3D root->symbols; + old_cnt =3D root->cnt; + root->symbols =3D NULL; + root->cnt =3D 0; + root->allocated =3D 0; + root->sorted =3D true; + zfree(&root->symbols_by_name); + root->num_by_name =3D 0; + root->sorted_by_name =3D false; + up_write(&root->lock); + + for (unsigned int i =3D 0; i < old_cnt; i++) { struct map *curr_map; struct dso *curr_map_dso; char *module; =20 - pos =3D rb_entry(next, struct symbol, rb_node); - next =3D rb_next(&pos->rb_node); - - rb_erase_cached(&pos->rb_node, &old_root); - RB_CLEAR_NODE(&pos->rb_node); + pos =3D old_symbols[i]; module =3D strchr(pos->name, '\t'); if (module) *module =3D '\0'; @@ -935,11 +1127,13 @@ static int maps__split_kallsyms_for_kcore(struct map= s *kmaps, struct dso *dso) pos->end =3D map__end(curr_map); if (pos->end) pos->end -=3D map__start(curr_map) - map__pgoff(curr_map); - symbols__insert(dso__symbols(curr_map_dso), pos); - ++count; + if (symbols__insert(dso__symbols(curr_map_dso), pos) =3D=3D 0) + ++count; map__put(curr_map); } =20 + free(old_symbols); + /* Symbols have been adjusted */ dso__set_adjust_symbols(dso, true); =20 @@ -958,8 +1152,10 @@ static int maps__split_kallsyms(struct maps *kmaps, s= truct dso *dso, u64 delta, struct map *curr_map =3D map__get(initial_map); struct symbol *pos; int count =3D 0, moved =3D 0; - struct rb_root_cached *root =3D dso__symbols(dso); - struct rb_node *next =3D rb_first_cached(root); + struct symbols *root =3D dso__symbols(dso); + struct symbol **old_symbols; + unsigned int old_cnt, old_allocated; + unsigned int i, write_idx =3D 0; int kernel_range =3D 0; uint16_t e_machine =3D EM_NONE; =20 @@ -969,11 +1165,24 @@ static int maps__split_kallsyms(struct maps *kmaps, = struct dso *dso, u64 delta, machine =3D maps__machine(kmaps); e_machine =3D perf_env__e_machine(machine->env, /*e_flags=3D*/NULL); =20 - while (next) { + down_write(&root->lock); + symbols__sort_locked(root); + old_symbols =3D root->symbols; + old_cnt =3D root->cnt; + old_allocated =3D root->allocated; + root->symbols =3D NULL; + root->cnt =3D 0; + root->allocated =3D 0; + root->sorted =3D true; + zfree(&root->symbols_by_name); + root->num_by_name =3D 0; + root->sorted_by_name =3D false; + up_write(&root->lock); + + for (i =3D 0; i < old_cnt; i++) { char *module; =20 - pos =3D rb_entry(next, struct symbol, rb_node); - next =3D rb_next(&pos->rb_node); + pos =3D old_symbols[i]; =20 module =3D strchr(pos->name, '\t'); if (module) { @@ -1058,7 +1267,7 @@ static int maps__split_kallsyms(struct maps *kmaps, s= truct dso *dso, u64 delta, ndso =3D dso__new(dso_name); map__zput(curr_map); if (ndso =3D=3D NULL) - return -1; + goto out_err; =20 dso__set_kernel(ndso, dso__kernel(dso)); if (dso__kernel(dso) =3D=3D DSO_SPACE__KERNEL_GUEST) { @@ -1071,20 +1280,20 @@ static int maps__split_kallsyms(struct maps *kmaps,= struct dso *dso, u64 delta, dso__set_loaded(ndso); if (dsos__add(&machine->dsos, ndso)) { dso__put(ndso); - return -1; + goto out_err; } =20 curr_map =3D map__new2(pos->start, ndso); if (curr_map =3D=3D NULL) { dso__put(ndso); - return -1; + goto out_err; } =20 map__set_mapping_type(curr_map, MAPPING_TYPE__IDENTITY); if (maps__insert(kmaps, curr_map)) { map__zput(curr_map); dso__put(ndso); - return -1; + goto out_err; } dso__put(ndso); ++kernel_range; @@ -1097,18 +1306,35 @@ static int maps__split_kallsyms(struct maps *kmaps,= struct dso *dso, u64 delta, if (!RC_CHK_EQUAL(curr_map, initial_map)) { struct dso *curr_map_dso =3D map__dso(curr_map); =20 - rb_erase_cached(&pos->rb_node, root); - symbols__insert(dso__symbols(curr_map_dso), pos); - ++moved; - } else + if (symbols__insert(dso__symbols(curr_map_dso), pos) =3D=3D 0) + ++moved; + } else { + old_symbols[write_idx++] =3D pos; ++count; + } =20 continue; discard_symbol: - rb_erase_cached(&pos->rb_node, root); symbol__delete(pos); } =20 + down_write(&root->lock); + if (root->cnt =3D=3D 0) { + root->symbols =3D old_symbols; + root->cnt =3D write_idx; + root->allocated =3D old_allocated; + root->sorted =3D true; + old_symbols =3D NULL; + } else { + for (unsigned int j =3D 0; j < write_idx; j++) + __symbols__insert(root, old_symbols[j]); + } + zfree(&root->symbols_by_name); + root->num_by_name =3D 0; + root->sorted_by_name =3D false; + up_write(&root->lock); + free(old_symbols); + if (!RC_CHK_EQUAL(curr_map, initial_map) && dso__kernel(dso) =3D=3D DSO_SPACE__KERNEL_GUEST && machine__is_default_guest(maps__machine(kmaps))) { @@ -1116,6 +1342,29 @@ static int maps__split_kallsyms(struct maps *kmaps, = struct dso *dso, u64 delta, } map__put(curr_map); return count + moved; + +out_err: + memmove(&old_symbols[write_idx], &old_symbols[i], + (old_cnt - i) * sizeof(struct symbol *)); + write_idx +=3D old_cnt - i; + down_write(&root->lock); + if (root->cnt =3D=3D 0) { + root->symbols =3D old_symbols; + root->cnt =3D write_idx; + root->allocated =3D old_allocated; + root->sorted =3D (delta =3D=3D 0); + old_symbols =3D NULL; + } else { + for (unsigned int j =3D 0; j < write_idx; j++) + __symbols__insert(root, old_symbols[j]); + root->sorted =3D false; + } + zfree(&root->symbols_by_name); + root->num_by_name =3D 0; + root->sorted_by_name =3D false; + up_write(&root->lock); + free(old_symbols); + return -1; } =20 bool symbol__restricted_filename(const char *filename, @@ -1676,7 +1925,8 @@ static int dso__load_perf_map(const char *map_path, s= truct dso *dso) if (sym =3D=3D NULL) goto out_delete_line; =20 - symbols__insert(dso__symbols(dso), sym); + if (symbols__insert(dso__symbols(dso), sym)) + goto out_delete_line; nr_syms++; } =20 diff --git a/tools/perf/util/symbol.h b/tools/perf/util/symbol.h index 784c87b72f38..8b8ab7e1e148 100644 --- a/tools/perf/util/symbol.h +++ b/tools/perf/util/symbol.h @@ -15,6 +15,7 @@ #include #include "addr_location.h" #include "path.h" +#include "rwsem.h" #include "symbol_conf.h" #include "spark.h" #include "util.h" @@ -82,7 +83,6 @@ enum symbol_idle_kind { * A symtab entry. */ struct symbol { - struct rb_node rb_node; /** Range of symbol [start, end). */ u64 start; u64 end; @@ -95,8 +95,42 @@ struct symbol { char name[]; }; =20 +/** + * struct symbols - A locked collection of symbols stored in a sorted arra= y. + */ +struct symbols { + /** @lock: Read/write semaphore synchronizing access to the arrays. */ + struct rw_semaphore lock; + /** + * @symbols: Dynamically allocated array of symbol pointers, sorted by + * address range [start, end) when @sorted is true. + */ + struct symbol **symbols __guarded_by(&lock); + /** + * @symbols_by_name: Optional dynamically allocated array of symbol + * pointers sorted lexicographically by sym->name. + */ + struct symbol **symbols_by_name __guarded_by(&lock); + /** @cnt: Number of valid entries in @symbols. */ + unsigned int cnt __guarded_by(&lock); + /** @allocated: Capacity (in entries) of the @symbols allocation. */ + unsigned int allocated __guarded_by(&lock); + /** @num_by_name: Number of valid entries in @symbols_by_name. */ + unsigned int num_by_name __guarded_by(&lock); + /** + * @sorted_by_name: True when @symbols_by_name is populated and sorted + * by name. + */ + bool sorted_by_name __guarded_by(&lock); + /** @sorted: True when @symbols is sorted by address range. */ + bool sorted __guarded_by(&lock); +}; + void symbol__delete(struct symbol *sym); -void symbols__delete(struct rb_root_cached *symbols); +void symbols__init(struct symbols *symbols); +void symbols__exit(struct symbols *symbols); +void symbols__delete(struct symbols *symbols); +void symbols__sort_read_lock(struct symbols *symbols) __acquires_shared(&s= ymbols->lock); =20 static inline u8 symbol__type(const struct symbol *sym) { @@ -144,13 +178,16 @@ void symbol__set_ifunc_alias(struct symbol *sym, bool= ifunc_alias); /* * symbols__visit - iterate over symbols calling @cb for each entry * - * @symbols: the rb_root_cached of symbols - * @cb: callback function invoked for each symbol + * @symbols: the 'struct symbols *' of symbols + * @cb: callback function invoked under @symbols->lock * @data: opaque data pointer passed to @cb */ -int symbols__visit(struct rb_root_cached *symbols, +int symbols__visit(struct symbols *symbols, int (*cb)(struct symbol *sym, void *data), void *data); +int symbols__visit_by_name(struct symbols *symbols, + int (*cb)(struct symbol *sym, void *data), + void *data); =20 static inline size_t symbol__size(const struct symbol *sym) { @@ -187,8 +224,8 @@ int __dso__load_kallsyms(struct dso *dso, const char *f= ilename, struct map *map, bool no_kcore); int dso__load_kallsyms(struct dso *dso, const char *filename, struct map *= map); =20 -void dso__insert_symbol(struct dso *dso, - struct symbol *sym); +int dso__insert_symbol(struct dso *dso, + struct symbol *sym); void dso__delete_symbol(struct dso *dso, struct symbol *sym); =20 @@ -197,9 +234,6 @@ struct symbol *dso__find_symbol_nocache(struct dso *dso= , u64 addr); =20 struct symbol *dso__next_symbol_by_name(struct dso *dso, size_t *idx); struct symbol *dso__find_symbol_by_name(struct dso *dso, const char *name,= size_t *idx); -int dso__visit_symbols_by_name(struct dso *dso, - int (*cb)(struct symbol *sym, void *data), - void *data); =20 enum dso_type dso__type_fd(int fd); =20 @@ -251,10 +285,9 @@ int dso__synthesize_plt_symbols(struct dso *dso, struc= t symsrc *ss); =20 char *dso__demangle_sym(struct dso *dso, int kmodule, const char *elf_name= ); =20 -void __symbols__insert(struct rb_root_cached *symbols, struct symbol *sym); -void symbols__insert(struct rb_root_cached *symbols, struct symbol *sym); -void symbols__fixup_duplicate(struct rb_root_cached *symbols); -void symbols__fixup_end(struct rb_root_cached *symbols, bool is_kallsyms); +int symbols__insert(struct symbols *symbols, struct symbol *sym); +void symbols__fixup_duplicate(struct symbols *symbols); +void symbols__fixup_end(struct symbols *symbols, bool is_kallsyms); =20 typedef int (*mapfn_t)(u64 start, u64 len, u64 pgoff, void *data); int file__read_maps(int fd, bool exe, mapfn_t mapfn, void *data, --=20 2.56.1.750.gf70dc682cf-goog From nobody Tue Nov 24 11:51:44 2026 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=74.125.82.199 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1795323881; b=pLnTLjoeZeaypZtBjWd5Uz/XdixlXx0Vcv8ZxiBaGFTiRwBUHBQuI1RqyxXimU4c3LXh ePJJ9d+sOp/ahBIObKlTW7lnb5ZTMX0GhwaZBZGs2AgBW0Xmb/yqz+QsEABgzUyEjJkxr V6ZMEwMAkDXSoss2XOdwf2/DGpr80C3b4uh9EEjwEBclKtHvtr7vf4SL865Kx0gbsE1v7 DiwDhqzP730pc/qAF5IfoojR6cUFUSi7kgRB3oC0LoF2q1fwyKoyxiRmX2GvhO6kaANcD 1ouHBPjK/gWL10Bbv4B8GPlvMFDKqDoKDloFb2jA++VQD7Pug0qWxJhdz4oy8GoA5Eg== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1795323881; h=DMARC-Filter:Received:DKIM-Signature:X-Google-DKIM-Signature: X-Forwarded-Encrypted:X-Gm-Message-State:X-Received:Date:In-Reply-To: Mime-Version:References:X-Mailer:Message-ID:Subject:From:To:Cc: Content-Type; bh=YA/OERqmNLnTYyBBgkFLaJldkLHIN3L3qyA39CDis04=; b=N5gDa6Kry9mKkvdW1k5gTuFE+y1pQv1UY4fLtSG23K569BV0ViT96+YHwB11MoWJd3vC uRJqH7XmCqbqGoY6uFr3trx9++8Zl3QhJoxylFXrpsdyu4v/HgaLiqAP8/1V4PodIwfjp Hi+1E9EhqX4OfE0MM8yn8jkFdjGSIf9LlRiRYwtjlMRcvIRzRmqGjY3eJf8m/iHe380Hc wIxUnX9iMORiO2tbXS1PEh6G7i7XxAUKEGGWTLJUnjkvTSWdE/4d6JDDc/8pJZvrDUuyu ioDAB9vlDhv5lUCF+zHsJLIjGpe3HQ2hvs3mNRSJJDcesEi3RfmWbyDi+CYfXh3gxjg== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass header.from=google.com; spf=pass smtp.mailfrom=flex--irogers.bounces.google.com; dkim=pass header.d=google.com header.i=@google.com header.a=rsa-sha256 header.s=20260707 header.b=bmNCjR9P; arc=none smtp.remote-ip=74.125.82.199 Received: from mail-dy1-f199.google.com (mail-dy1-f199.google.com [74.125.82.199]) (using TLSv1.3 with cipher TLS_AES_128_GCM_SHA256 (128/128 bits) key-exchange X25519 server-signature ECDSA (prime256v1) server-digest SHA256) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id F2F90606A335 for ; Sun, 22 Nov 2026 05:04:40 +0000 (UTC) DMARC-Filter: OpenDMARC Filter v1.4.2 smtp.subspace.kernel.org F2F90606A335 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=flex--irogers.bounces.google.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.a=rsa-sha256 header.s=20260707 header.b=bmNCjR9P Received: by mail-dy1-f199.google.com with SMTP id 5a478bee46e88-3854627c1c8so3537496eec.1 for ; Sat, 21 Nov 2026 21:04:40 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20260707; t=1795323880; x=1795928680; darn=vger.kernel.org; h=content-type:cc:to:from:subject:message-id:references:mime-version :in-reply-to:date:from:to:cc:subject:date:message-id:reply-to :content-type; bh=YA/OERqmNLnTYyBBgkFLaJldkLHIN3L3qyA39CDis04=; b=bmNCjR9P7eFLYmbijQuAtpzMbIdQPEygRKZsHolwxoMpBhIXLytQCR3X9gkRBzo5Ws 3zpzLS96aevVMmUTGklNHAd7c+fQfmmW+6AYVKrF9wpjDr5DUqJennsVi7CRquUEoE0T 9L/+NzXgoVKjnuDXLSPPN4KjB96mlN5/aY/L3DI6OOGAqEVPgay10fq0YSHIPz0Md38S IAH4/fmhgygUo5WTEi2AhaRgPvFDkPOc6yYNZQzGGK3YCqk40DJRt2fnG0STEHMcyia3 PRycrTFzz+XUKOE9Keab3mojRv8M38eITfuAoUCOroeIKK3NjrCocHgmDrH6XRXF98II r6PQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20260707; t=1795323880; x=1795928680; h=content-type:cc:to:from:subject:message-id:references:mime-version :in-reply-to:date:x-gm-message-state:from:to:cc:subject:date :message-id:reply-to:content-type; bh=YA/OERqmNLnTYyBBgkFLaJldkLHIN3L3qyA39CDis04=; b=F64lGJVovqfFej9PVIuP4l/nW+TEK9XZburXiCUMiNOgPQRVQ5VGav42RzHdOxVt9U TfSuIazlIpCuI3etuo4JojZhmtCDbip9JyEvps21hZY6bBhpT4yyy4HPmMRATWrDLShx p7XxQQFvtRP7p818yzjvCin6aLOCDlLmAGY9HuomWyuXOBYSq7e6Vu8n6SI5Giw9o0oC B1yBt9LojkhDeun8HJisgBPLgPt6AbiBDnOWznOOSsMdPmcBPR/lkj/nTd45WaUKZ2z4 defZl5gi2OlN1bjp1rlUQCjunn0QTHZprmsEp2/4n28IxUWhOPDmcfXzOArFdSAKCOz8 v2yA== X-Forwarded-Encrypted: i=1; AL+hErHGDu31RWYpRn0jK1Wb548Nwi9rvSDO7Ve3EXDhiXUIzQQ7TdYsQjn80WB13qEcx6eiLNAY88Jez5gfGtE=@vger.kernel.org X-Gm-Message-State: APuU4Z83XI0srPqML+TUDHI/1ZxP4ORJZ6yZJIjwSkvPRINfH0s3KaZG 6Z54+FOrE/wENUdteWMKepXosMvUHrF3T18NTgDm6gpIWcUxKijYnL3J2XaFNr92yYbii847o1U 2Jpd4BZqQGw== X-Received: from dlag8.prod.google.com ([2002:a05:701b:2508:b0:1b5:33c5:1c03]) (user=irogers job=prod-delivery.src-stubby-dispatcher) by 2002:a05:7022:3b8e:b0:1b5:10cf:c402 with SMTP id a92af1059eb24-1b5568a17d9mr8661709c88.10.1795323879580; Sat, 21 Nov 2026 21:04:39 -0800 (PST) Date: Sat, 21 Nov 2026 21:04:01 -0800 In-Reply-To: <20261122050405.80335-1-irogers@google.com> X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Post: List-Help: List-Subscribe: List-Unsubscribe: List-Owner: Precedence: list Mime-Version: 1.0 References: <20261122050405.80335-1-irogers@google.com> X-Mailer: git-send-email 2.56.1.750.gf70dc682cf-goog Message-ID: <20261122050405.80335-7-irogers@google.com> Subject: [PATCH v8 06/10] perf symbol: Replace qsort() with natural-run merge sort From: Ian Rogers To: Namhyung Kim , Arnaldo Carvalho de Melo , Alireza Haghdoost , Ian Rogers Cc: Peter Zijlstra , Ingo Molnar , Jiri Olsa , Adrian Hunter , James Clark , linux-perf-users@vger.kernel.org, linux-kernel@vger.kernel.org Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" ELF .symtab and .dynsym sections are typically already mostly ordered by address in ascending runs. Invoking full-array qsort() across pre-ordered ELF runs spends avoidable CPU time in symbol comparisons and does not guarantee relative order preservation for equal-start symbol aliases across C library implementations. Replace qsort() in symbols__sort_locked() with a stable natural-run merge sort (symbols__sort_range_with_tmp() and symbols__merge_runs()), falling back to in-place binary insertion sort (symbols__insertion_sort_range()) for small arrays (cnt <=3D 64) or on scratch-buffer allocation failure. Using 'perf bench internals symbols': Before: Average DSO load + sort: 6.242 msec (+- 0.057 msec) Average bulk insert + lookup: 1404.150 usec (+- 18.752 usec) After (-7.0% load, -13.9% bulk): Average DSO load + sort: 5.808 msec (+- 0.047 msec) Average bulk insert + lookup: 1209.250 usec (+- 18.446 usec) Signed-off-by: Ian Rogers --- tools/perf/util/symbol.c | 183 +++++++++++++++++++++++++++++++++++++-- 1 file changed, 174 insertions(+), 9 deletions(-) diff --git a/tools/perf/util/symbol.c b/tools/perf/util/symbol.c index 43347c9a3a0c..35b08c05a2fd 100644 --- a/tools/perf/util/symbol.c +++ b/tools/perf/util/symbol.c @@ -265,14 +265,171 @@ static inline bool symbol__less_or_equal(const struc= t symbol *a, const struct sy return a->start <=3D b->start; } =20 -static int symbols__sort_cmp(const void *vlhs, const void *vrhs) +static unsigned int symbols__upper_bound(struct symbol **arr, unsigned int= len, + const struct symbol *sym) { - const struct symbol *lhs =3D *((const struct symbol **)vlhs); - const struct symbol *rhs =3D *((const struct symbol **)vrhs); + unsigned int low =3D 0, high =3D len; =20 - if (lhs->start !=3D rhs->start) - return lhs->start < rhs->start ? -1 : 1; - return 0; + while (low < high) { + unsigned int mid =3D low + (high - low) / 2; + + if (symbol__less_or_equal(arr[mid], sym)) + low =3D mid + 1; + else + high =3D mid; + } + return low; +} + +static void symbols__insertion_sort_range(struct symbol **arr, + unsigned int start, + unsigned int end) +{ + for (unsigned int i =3D start + 1; i < end; i++) { + struct symbol *sym =3D arr[i]; + + if (!symbol__less_or_equal(arr[i - 1], sym)) { + unsigned int pos =3D start + + symbols__upper_bound(&arr[start], i - start, sym); + + memmove(&arr[pos + 1], &arr[pos], + (i - pos) * sizeof(struct symbol *)); + arr[pos] =3D sym; + } + } +} + +static void symbols__merge_runs(struct symbol **arr, + unsigned int left, + unsigned int mid, + unsigned int right, + struct symbol **tmp) +{ + unsigned int first_left, left_len, right_len; + unsigned int i, j, dst; + + if (left >=3D mid || mid >=3D right) + return; + if (symbol__less_or_equal(arr[mid - 1], arr[mid])) + return; + + first_left =3D left + symbols__upper_bound(&arr[left], mid - left, arr[mi= d]); + left_len =3D mid - first_left; + right_len =3D right - mid; + + if (left_len <=3D right_len) { + memcpy(tmp, &arr[first_left], left_len * sizeof(struct symbol *)); + i =3D 0; + j =3D mid; + dst =3D first_left; + while (i < left_len && j < right) { + if (symbol__less_or_equal(tmp[i], arr[j])) + arr[dst++] =3D tmp[i++]; + else + arr[dst++] =3D arr[j++]; + } + if (i < left_len) + memcpy(&arr[dst], &tmp[i], (left_len - i) * sizeof(struct symbol *)); + } else { + memcpy(tmp, &arr[mid], right_len * sizeof(struct symbol *)); + i =3D mid; + j =3D right_len; + dst =3D right; + while (i > first_left && j > 0) { + if (symbol__less_or_equal(arr[i - 1], tmp[j - 1])) + arr[--dst] =3D tmp[--j]; + else + arr[--dst] =3D arr[--i]; + } + if (j > 0) + memcpy(&arr[first_left], tmp, j * sizeof(struct symbol *)); + } +} + +struct symbol_run { + unsigned int start; + unsigned int len; +}; + +static void symbols__sort_range_with_tmp(struct symbol **arr, unsigned int= n, + struct symbol **tmp) +{ + struct symbol_run runs[64]; + unsigned int nr_runs =3D 0; + unsigned int i =3D 0; + + if (n <=3D 32) { + symbols__insertion_sort_range(arr, 0, n); + return; + } + + while (i < n) { + unsigned int start =3D i++; + + if (i < n) { + if (symbol__less_or_equal(arr[i - 1], arr[i])) { + while (i < n && symbol__less_or_equal(arr[i - 1], arr[i])) + i++; + } else { + while (i < n && !symbol__less_or_equal(arr[i - 1], arr[i])) + i++; + for (unsigned int lo =3D start, hi =3D i - 1; lo < hi; lo++, hi--) { + struct symbol *swap =3D arr[lo]; + + arr[lo] =3D arr[hi]; + arr[hi] =3D swap; + } + } + } + + if (i - start < 32 && i < n) { + i =3D min(start + 32U, n); + symbols__insertion_sort_range(arr, start, i); + } + + runs[nr_runs++] =3D (struct symbol_run){ + .start =3D start, + .len =3D i - start, + }; + + while (nr_runs > 1) { + unsigned int r =3D nr_runs - 2; + + if (nr_runs >=3D 3 && + runs[nr_runs - 3].len <=3D + runs[nr_runs - 2].len + runs[nr_runs - 1].len) { + if (runs[nr_runs - 3].len < runs[nr_runs - 1].len) + r =3D nr_runs - 3; + } else if (runs[nr_runs - 2].len > runs[nr_runs - 1].len && + nr_runs < ARRAY_SIZE(runs)) { + break; + } + + symbols__merge_runs(arr, runs[r].start, + runs[r + 1].start, + runs[r + 1].start + runs[r + 1].len, + tmp); + runs[r].len +=3D runs[r + 1].len; + if (r + 2 < nr_runs) + runs[r + 1] =3D runs[r + 2]; + nr_runs--; + } + } + + while (nr_runs > 1) { + unsigned int r =3D nr_runs - 2; + + if (nr_runs >=3D 3 && runs[nr_runs - 3].len < runs[nr_runs - 1].len) + r =3D nr_runs - 3; + symbols__merge_runs(arr, runs[r].start, + runs[r + 1].start, + runs[r + 1].start + runs[r + 1].len, + tmp); + runs[r].len +=3D runs[r + 1].len; + if (r + 2 < nr_runs) + runs[r + 1] =3D runs[r + 2]; + nr_runs--; + } } =20 static void symbols__sort_locked(struct symbols *symbols) @@ -281,9 +438,17 @@ static void symbols__sort_locked(struct symbols *symbo= ls) if (symbols->sorted) return; =20 - if (symbols->cnt > 1) { - qsort(symbols->symbols, symbols->cnt, sizeof(struct symbol *), - symbols__sort_cmp); + if (symbols->cnt <=3D 64) { + symbols__insertion_sort_range(symbols->symbols, 0, symbols->cnt); + } else { + struct symbol **tmp =3D malloc(((symbols->cnt + 1) / 2) * sizeof(struct = symbol *)); + + if (tmp) { + symbols__sort_range_with_tmp(symbols->symbols, symbols->cnt, tmp); + free(tmp); + } else { + symbols__insertion_sort_range(symbols->symbols, 0, symbols->cnt); + } } symbols->sorted =3D true; } --=20 2.56.1.750.gf70dc682cf-goog From nobody Tue Nov 24 11:51:44 2026 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=74.125.82.70 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1795323886; b=kVJdLN49QEJeeALFH9la/yaJXQECf0ltL4JFuBoFj2XTaQAn+fzUzR6mba4qSq6Dh0WC lXrBmD/wch7LDKDNwIUdUzmVnhy9DORyjK8FJJjKnnL+A5h8a8HcTpE/HbKjIWGxmW5Mc OdYBFl/u02HrmRly3g7Ru0YmGt4X7b9IRcBAr74GXyv6n34F5PoUNv8SbQnRw8rMkSLez +tWiG/gK0FoBZbTinySf/JAjKnMv8r0cbvsNuUP0GKycLc1Qk+ieYELam5Xl1TsxLJtoK UVMQS0IaacG6t9ZEY2BIaiwELVb3Jx4+PxEgc9F67LuvKUuZMhTVWH8RORjCh7dJH6g== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1795323886; h=DMARC-Filter:Received:DKIM-Signature:X-Google-DKIM-Signature: X-Forwarded-Encrypted:X-Gm-Message-State:X-Received:Date:In-Reply-To: Mime-Version:References:X-Mailer:Message-ID:Subject:From:To:Cc: Content-Type; bh=CWnAV6tVqdMDcZJwj0hP4WWO5uyvqyeRK1R20QMTbqA=; b=YWjlsEv9QC+kQdRTd9juUbYjD5OoiBiwukyqHCfraPUHRrkzAc6+qBXKBnzfmMUi7Uxk w6R4NepNRh9TGS8kD/3k9E41rGzSZEAwZrO2QVMtjNVn0IzqjxJNUy6fz5dF+xOtkNRVm I0HB0n5uPmhzatAFYgr/t93pW3Vy8u000j8KFhXwRgxdA0rphUe3l3SjmLoXkRQbLwMS0 TChG1RUqvMX+ESKdjNvushzPYST8WBv2aWdcLW9iAmS3Ynqr/zEzDfWdHufmCI8bDis5P lH2YPePogi4F9F5gP3dhCtYoqEE9VBsz2Qa83ymNMVewN5gvT7dN1FTI7unJKQ6ivLg== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass header.from=google.com; spf=pass smtp.mailfrom=flex--irogers.bounces.google.com; dkim=pass header.d=google.com header.i=@google.com header.a=rsa-sha256 header.s=20260707 header.b="b4/EfRDN"; arc=none smtp.remote-ip=74.125.82.70 Received: from mail-dl1-f70.google.com (mail-dl1-f70.google.com [74.125.82.70]) (using TLSv1.3 with cipher TLS_AES_128_GCM_SHA256 (128/128 bits) key-exchange X25519 server-signature ECDSA (prime256v1) server-digest SHA256) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 81360606A32C for ; Sun, 22 Nov 2026 05:04:45 +0000 (UTC) DMARC-Filter: OpenDMARC Filter v1.4.2 smtp.subspace.kernel.org 81360606A32C Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=flex--irogers.bounces.google.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.a=rsa-sha256 header.s=20260707 header.b=b4/EfRDN Received: by mail-dl1-f70.google.com with SMTP id a92af1059eb24-154e9d2d94fso1456947c88.0 for ; Sat, 21 Nov 2026 21:04:45 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20260707; t=1795323885; x=1795928685; darn=vger.kernel.org; h=content-type:cc:to:from:subject:message-id:references:mime-version :in-reply-to:date:from:to:cc:subject:date:message-id:reply-to :content-type; bh=CWnAV6tVqdMDcZJwj0hP4WWO5uyvqyeRK1R20QMTbqA=; b=b4/EfRDNn7VK2NV3rUwB7T8alIllnYy/mvx1HI9xHyYApYCCjK0O2KdOaJQmChGmcg SjuPfmxZWuXsY/7MK98QV6kMKl+moPXj2I3mUdc9G6yNJE3AzDW0jX7vDelZUYe1mznf eqoWO1EbFOeEgsH4FqCQaSVbwfHpDRSI32QmVpm7SWfOnPw55P8vi39VA80kVOXzm0dm JoWcimPQJb8wmDdUhKKHoD3jzZgNqrTkTLYRyE/KwulchJCrHLG0y4tm9/puetVuIiCx +3X26AYNYmVMq8knckOURtgAMI6CdqUnjZ7UQZwXTEI4+Dy0U+sFu8mqka9rGhp5JZGA V67A== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20260707; t=1795323885; x=1795928685; h=content-type:cc:to:from:subject:message-id:references:mime-version :in-reply-to:date:x-gm-message-state:from:to:cc:subject:date :message-id:reply-to:content-type; bh=CWnAV6tVqdMDcZJwj0hP4WWO5uyvqyeRK1R20QMTbqA=; b=lheCCP/l3prdV56yRhdVOwdMXsJ7j+yKeE3qhS6bce0fF+JnSUxM12ec+qJ1wKJw35 +lIk80BoNdlpZHOtkzhrBpPOd2z1vOcGrfN4+ZAaWFqNDemyTPOciA2DZ3QYK4aUxgOQ Wz9hEX2DlDvB8LGmp6g2wp+QPVAi9x+yOrzNmV3yxRqcmCuPLCBU14MNN+6+SpL0wNV6 CHWww7gkftmCXw9CRRk+LTUZYpzSmA2oEp95JgRx44TR4Rvybxn4dK2+Q4+Z4+JU7y0f H2qMenvft/p8rLjft7xtuXqPShNRhXZtWtt+u0RolvKk5lJNJ0rUohTeAHgScRns9d1Q Ic5A== X-Forwarded-Encrypted: i=1; AL+hErEygWU9l8V+fdWPemw5oCtIXSLyv1OiHzkCAxcPqTzU0VALtl8nJxes9r3qotePD8KHqRY0I0JQnbqoWU0=@vger.kernel.org X-Gm-Message-State: APuU4Z+AOZb7rleS5Z9uHtQKAEwiScYCsAH05hVSgzIy+vAZxvzsWLjD YHPGgLuGN4gf4r+1+00OXQaUvP816dWkI/O/ycw4OQhnjOcAy1G8ey1cGyUO3zHRy5nqNV9D6Vp LPW3MvW92sg== X-Received: from dlbuu1.prod.google.com ([2002:a05:7022:7e81:b0:1b3:ba1e:2c7]) (user=irogers job=prod-delivery.src-stubby-dispatcher) by 2002:a05:701b:4308:b0:1b5:1a6e:1bec with SMTP id a92af1059eb24-1b5568779e3mr7790764c88.10.1795323884202; Sat, 21 Nov 2026 21:04:44 -0800 (PST) Date: Sat, 21 Nov 2026 21:04:02 -0800 In-Reply-To: <20261122050405.80335-1-irogers@google.com> X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Post: List-Help: List-Subscribe: List-Unsubscribe: List-Owner: Precedence: list Mime-Version: 1.0 References: <20261122050405.80335-1-irogers@google.com> X-Mailer: git-send-email 2.56.1.750.gf70dc682cf-goog Message-ID: <20261122050405.80335-8-irogers@google.com> Subject: [PATCH v8 07/10] perf symbol: Optimize incremental symbol insertion with sorted tail From: Ian Rogers To: Namhyung Kim , Arnaldo Carvalho de Melo , Alireza Haghdoost , Ian Rogers Cc: Peter Zijlstra , Ingo Molnar , Jiri Olsa , Adrian Hunter , James Clark , linux-perf-users@vger.kernel.org, linux-kernel@vger.kernel.org Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" Dynamic symbol resolution (dso__insert_symbol()) frequently inserts one or a few symbols into an already-sorted DSO symbol table, and small batches of symbols may also be appended after an initial sort. Re-running full-array merge sort on every incremental insertion or memmoving the entire sorted array on every out-of-order dynamic insertion spends avoidable CPU time. Speed up incremental symbol insertions and small-append sorting: - Track the sorted prefix length (@sorted_cnt) in struct symbols and use an O(N) in-place binary insertion fast path in symbols__sort_locked() when <=3D 8 symbols have been appended. - Add __symbols__insert_sorted() for dso__insert_symbol() so that when symbols->sorted is true, ascending symbols append in O(1), small tables (cnt < 64) binary-insert in place, and larger out-of-order insertions maintain a sorted tail buffer at symbols[sorted_cnt .. cnt) with an amortized sqrt(N) merge threshold. - Search both the sorted prefix and any unmerged sorted tail in symbols__find() while preserving the single-array highest start <=3D ip semantics. Using 'perf bench internals symbols': Before: Average append + lookup: 40429.750 usec (+- 507.578 usec) After (-99.6%): Average append + lookup: 152.900 usec (+- 0.736 usec) Signed-off-by: Ian Rogers # Conflicts: # tools/perf/util/symbol.h --- tools/perf/util/symbol.c | 206 +++++++++++++++++++++++++++++++++++---- tools/perf/util/symbol.h | 11 ++- 2 files changed, 198 insertions(+), 19 deletions(-) diff --git a/tools/perf/util/symbol.c b/tools/perf/util/symbol.c index 35b08c05a2fd..22b84e9a40fd 100644 --- a/tools/perf/util/symbol.c +++ b/tools/perf/util/symbol.c @@ -220,6 +220,7 @@ void symbols__init(struct symbols *symbols) symbols->symbols =3D NULL; symbols->symbols_by_name =3D NULL; symbols->cnt =3D 0; + symbols->sorted_cnt =3D 0; symbols->allocated =3D 0; symbols->num_by_name =3D 0; symbols->sorted =3D true; @@ -235,6 +236,7 @@ static void symbols__delete_locked(struct symbols *symb= ols) zfree(&symbols->symbols); zfree(&symbols->symbols_by_name); symbols->cnt =3D 0; + symbols->sorted_cnt =3D 0; symbols->allocated =3D 0; symbols->num_by_name =3D 0; symbols->sorted =3D true; @@ -283,9 +285,10 @@ static unsigned int symbols__upper_bound(struct symbol= **arr, unsigned int len, =20 static void symbols__insertion_sort_range(struct symbol **arr, unsigned int start, + unsigned int first_unsorted, unsigned int end) { - for (unsigned int i =3D start + 1; i < end; i++) { + for (unsigned int i =3D max(first_unsorted, start + 1); i < end; i++) { struct symbol *sym =3D arr[i]; =20 if (!symbol__less_or_equal(arr[i - 1], sym)) { @@ -359,7 +362,7 @@ static void symbols__sort_range_with_tmp(struct symbol = **arr, unsigned int n, unsigned int i =3D 0; =20 if (n <=3D 32) { - symbols__insertion_sort_range(arr, 0, n); + symbols__insertion_sort_range(arr, 0, 1, n); return; } =20 @@ -383,8 +386,10 @@ static void symbols__sort_range_with_tmp(struct symbol= **arr, unsigned int n, } =20 if (i - start < 32 && i < n) { + unsigned int run_end =3D i; + i =3D min(start + 32U, n); - symbols__insertion_sort_range(arr, start, i); + symbols__insertion_sort_range(arr, start, run_end, i); } =20 runs[nr_runs++] =3D (struct symbol_run){ @@ -435,32 +440,79 @@ static void symbols__sort_range_with_tmp(struct symbo= l **arr, unsigned int n, static void symbols__sort_locked(struct symbols *symbols) __must_hold(&symbols->lock) { - if (symbols->sorted) + unsigned int m =3D symbols->sorted_cnt; + unsigned int k; + + if (symbols->sorted && symbols->sorted_cnt =3D=3D symbols->cnt) return; =20 - if (symbols->cnt <=3D 64) { - symbols__insertion_sort_range(symbols->symbols, 0, symbols->cnt); - } else { + if (m > symbols->cnt) + m =3D 0; + k =3D symbols->cnt - m; + + if (k =3D=3D 0) { + symbols->sorted =3D true; + return; + } + + /* + * When only a few symbols have been appended since the last sort + * (including single-symbol insertions), insert them directly at + * their binary-searched sorted positions in O(N) without allocating. + */ + if (k <=3D 8 || symbols->cnt <=3D 64) { + symbols__insertion_sort_range(symbols->symbols, 0, m, symbols->cnt); + symbols->sorted_cnt =3D symbols->cnt; + symbols->sorted =3D true; + return; + } + + if (symbols->sorted) { + /* + * Both [0 .. m) and the sorted tail [m .. cnt) are already + * sorted; merge them into a single sorted run. + */ + struct symbol **tmp =3D malloc(min(m, k) * sizeof(struct symbol *)); + + if (tmp) { + symbols__merge_runs(symbols->symbols, 0, m, symbols->cnt, tmp); + free(tmp); + } else { + symbols__insertion_sort_range(symbols->symbols, 0, m, symbols->cnt); + } + } else if (m <=3D 1) { struct symbol **tmp =3D malloc(((symbols->cnt + 1) / 2) * sizeof(struct = symbol *)); =20 if (tmp) { symbols__sort_range_with_tmp(symbols->symbols, symbols->cnt, tmp); free(tmp); } else { - symbols__insertion_sort_range(symbols->symbols, 0, symbols->cnt); + symbols__insertion_sort_range(symbols->symbols, 0, m, symbols->cnt); + } + } else { + struct symbol **tmp =3D malloc(k * sizeof(struct symbol *)); + + if (tmp) { + symbols__sort_range_with_tmp(&symbols->symbols[m], k, tmp); + symbols__merge_runs(symbols->symbols, 0, m, symbols->cnt, tmp); + free(tmp); + } else { + symbols__insertion_sort_range(symbols->symbols, 0, m, symbols->cnt); } } + + symbols->sorted_cnt =3D symbols->cnt; symbols->sorted =3D true; } =20 /* * Acquire @symbols->lock for reading after ensuring @symbols->symbols is - * sorted. + * fully sorted into a single contiguous run. */ void symbols__sort_read_lock(struct symbols *symbols) { down_read(&symbols->lock); - while (!symbols->sorted) { + while (!symbols->sorted || symbols->sorted_cnt < symbols->cnt) { up_read(&symbols->lock); down_write(&symbols->lock); symbols__sort_locked(symbols); @@ -509,6 +561,7 @@ void symbols__fixup_duplicate(struct symbols *symbols) } } symbols->cnt =3D write_idx + 1; + symbols->sorted_cnt =3D symbols->cnt; zfree(&symbols->symbols_by_name); symbols->num_by_name =3D 0; symbols->sorted_by_name =3D false; @@ -685,9 +738,15 @@ static int __symbols__insert(struct symbols *symbols, = struct symbol *sym) symbols->allocated =3D to_allocate; } =20 - if (symbols->sorted && symbols->cnt > 0 && - !symbol__less_or_equal(symbols->symbols[symbols->cnt - 1], sym)) + if (symbols->sorted && symbols->sorted_cnt =3D=3D symbols->cnt) { + if (symbols->cnt =3D=3D 0 || + symbol__less_or_equal(symbols->symbols[symbols->cnt - 1], sym)) + symbols->sorted_cnt =3D symbols->cnt + 1; + else + symbols->sorted =3D false; + } else { symbols->sorted =3D false; + } =20 symbols->symbols[symbols->cnt++] =3D sym; zfree(&symbols->symbols_by_name); @@ -696,6 +755,70 @@ static int __symbols__insert(struct symbols *symbols, = struct symbol *sym) return 0; } =20 +static int __symbols__insert_sorted(struct symbols *symbols, struct symbol= *sym) + __must_hold(&symbols->lock) +{ + unsigned int idx; + + if (!symbols->sorted) + return __symbols__insert(symbols, sym); + + if (symbols->cnt =3D=3D symbols->allocated) { + unsigned int to_allocate =3D symbols->allocated ? symbols->allocated * 2= : 32; + struct symbol **temp =3D realloc(symbols->symbols, + sizeof(struct symbol *) * to_allocate); + + if (!temp) { + symbol__delete(sym); + return -ENOMEM; + } + symbols->symbols =3D temp; + symbols->allocated =3D to_allocate; + } + + if (symbols->sorted_cnt =3D=3D symbols->cnt) { + if (symbols->cnt =3D=3D 0 || + symbol__less_or_equal(symbols->symbols[symbols->cnt - 1], sym)) { + symbols->symbols[symbols->cnt++] =3D sym; + symbols->sorted_cnt =3D symbols->cnt; + } else if (symbols->cnt < 64) { + idx =3D symbols__upper_bound(symbols->symbols, symbols->cnt, sym); + memmove(&symbols->symbols[idx + 1], &symbols->symbols[idx], + (symbols->cnt - idx) * sizeof(struct symbol *)); + symbols->symbols[idx] =3D sym; + symbols->cnt++; + symbols->sorted_cnt =3D symbols->cnt; + } else { + /* + * Start a sorted tail buffer at symbols[sorted_cnt .. cnt) + * so out-of-order insertions do not memmove the entire + * primary sorted prefix on every call. + */ + symbols->symbols[symbols->cnt++] =3D sym; + } + } else { + unsigned int tail_cnt =3D symbols->cnt - symbols->sorted_cnt; + + idx =3D symbols->sorted_cnt + + symbols__upper_bound(&symbols->symbols[symbols->sorted_cnt], + tail_cnt, sym); + memmove(&symbols->symbols[idx + 1], &symbols->symbols[idx], + (symbols->cnt - idx) * sizeof(struct symbol *)); + symbols->symbols[idx] =3D sym; + symbols->cnt++; + tail_cnt++; + + if (tail_cnt >=3D 256 && + (size_t)tail_cnt * tail_cnt >=3D symbols->sorted_cnt) + symbols__sort_locked(symbols); + } + + zfree(&symbols->symbols_by_name); + symbols->num_by_name =3D 0; + symbols->sorted_by_name =3D false; + return 0; +} + int symbols__insert(struct symbols *symbols, struct symbol *sym) { int ret; @@ -714,7 +837,9 @@ static inline bool symbol__covers(const struct symbol *= s, u64 ip) return ip >=3D start && (ip < end || (ip =3D=3D end && ip =3D=3D start)); } =20 -static struct symbol *symbols__find_range(struct symbol **arr, unsigned in= t cnt, u64 ip) +static struct symbol *symbols__find_range(struct symbol **arr, unsigned in= t cnt, + u64 ip, bool *has_candidate, + u64 *candidate_start) { unsigned int low =3D 0, high =3D cnt, idx; u64 start; @@ -727,8 +852,10 @@ static struct symbol *symbols__find_range(struct symbo= l **arr, unsigned int cnt, else high =3D mid; } - if (low =3D=3D 0) + if (low =3D=3D 0) { + *has_candidate =3D false; return NULL; + } =20 /* * Rewind across any equal-start group so a trailing zero-length or @@ -737,6 +864,8 @@ static struct symbol *symbols__find_range(struct symbol= **arr, unsigned int cnt, */ idx =3D low - 1; start =3D arr[idx]->start; + *has_candidate =3D true; + *candidate_start =3D start; while (idx > 0 && arr[idx - 1]->start =3D=3D start) idx--; for (; idx < low; idx++) { @@ -753,12 +882,38 @@ static struct symbol *symbols__find_range(struct symb= ol **arr, unsigned int cnt, static struct symbol *symbols__find(struct symbols *symbols, u64 ip) { struct symbol *res; + bool has_prefix; + u64 prefix_start =3D 0; =20 if (symbols =3D=3D NULL) return NULL; =20 - symbols__sort_read_lock(symbols); - res =3D symbols__find_range(symbols->symbols, symbols->cnt, ip); + down_read(&symbols->lock); + while (!symbols->sorted) { + up_read(&symbols->lock); + down_write(&symbols->lock); + symbols__sort_locked(symbols); + up_write(&symbols->lock); + down_read(&symbols->lock); + } + + res =3D symbols__find_range(symbols->symbols, symbols->sorted_cnt, ip, + &has_prefix, &prefix_start); + if (symbols->sorted_cnt < symbols->cnt) { + struct symbol *tail_res; + bool has_tail; + u64 tail_start =3D 0; + + tail_res =3D symbols__find_range(&symbols->symbols[symbols->sorted_cnt], + symbols->cnt - symbols->sorted_cnt, ip, + &has_tail, &tail_start); + if (has_tail) { + if (!has_prefix || tail_start > prefix_start) + res =3D tail_res; + else if (tail_start =3D=3D prefix_start && !res) + res =3D tail_res; + } + } up_read(&symbols->lock); =20 return res; @@ -904,7 +1059,13 @@ static struct symbol *symbols__find_by_name(struct sy= mbol *symbols[], =20 int dso__insert_symbol(struct dso *dso, struct symbol *sym) { - return symbols__insert(dso__symbols(dso), sym); + struct symbols *symbols =3D dso__symbols(dso); + int ret; + + down_write(&symbols->lock); + ret =3D __symbols__insert_sorted(symbols, sym); + up_write(&symbols->lock); + return ret; } =20 void dso__delete_symbol(struct dso *dso, struct symbol *sym) @@ -912,11 +1073,15 @@ void dso__delete_symbol(struct dso *dso, struct symb= ol *sym) struct symbols *symbols =3D dso__symbols(dso); =20 down_write(&symbols->lock); - for (unsigned int i =3D 0; i < symbols->cnt; i++) { + for (unsigned int i =3D symbols->cnt; i-- > 0; ) { if (symbols->symbols[i] =3D=3D sym) { memmove(&symbols->symbols[i], &symbols->symbols[i + 1], (symbols->cnt - i - 1) * sizeof(struct symbol *)); symbols->cnt--; + if (i < symbols->sorted_cnt) + symbols->sorted_cnt--; + if (symbols->sorted_cnt =3D=3D symbols->cnt) + symbols->sorted =3D true; zfree(&symbols->symbols_by_name); symbols->num_by_name =3D 0; symbols->sorted_by_name =3D false; @@ -1263,6 +1428,7 @@ static int maps__split_kallsyms_for_kcore(struct maps= *kmaps, struct dso *dso) old_cnt =3D root->cnt; root->symbols =3D NULL; root->cnt =3D 0; + root->sorted_cnt =3D 0; root->allocated =3D 0; root->sorted =3D true; zfree(&root->symbols_by_name); @@ -1337,6 +1503,7 @@ static int maps__split_kallsyms(struct maps *kmaps, s= truct dso *dso, u64 delta, old_allocated =3D root->allocated; root->symbols =3D NULL; root->cnt =3D 0; + root->sorted_cnt =3D 0; root->allocated =3D 0; root->sorted =3D true; zfree(&root->symbols_by_name); @@ -1487,6 +1654,7 @@ static int maps__split_kallsyms(struct maps *kmaps, s= truct dso *dso, u64 delta, if (root->cnt =3D=3D 0) { root->symbols =3D old_symbols; root->cnt =3D write_idx; + root->sorted_cnt =3D write_idx; root->allocated =3D old_allocated; root->sorted =3D true; old_symbols =3D NULL; @@ -1516,12 +1684,14 @@ static int maps__split_kallsyms(struct maps *kmaps,= struct dso *dso, u64 delta, if (root->cnt =3D=3D 0) { root->symbols =3D old_symbols; root->cnt =3D write_idx; + root->sorted_cnt =3D (delta =3D=3D 0) ? write_idx : 0; root->allocated =3D old_allocated; root->sorted =3D (delta =3D=3D 0); old_symbols =3D NULL; } else { for (unsigned int j =3D 0; j < write_idx; j++) __symbols__insert(root, old_symbols[j]); + root->sorted_cnt =3D 0; root->sorted =3D false; } zfree(&root->symbols_by_name); diff --git a/tools/perf/util/symbol.h b/tools/perf/util/symbol.h index 8b8ab7e1e148..541ab9321d99 100644 --- a/tools/perf/util/symbol.h +++ b/tools/perf/util/symbol.h @@ -113,6 +113,12 @@ struct symbols { struct symbol **symbols_by_name __guarded_by(&lock); /** @cnt: Number of valid entries in @symbols. */ unsigned int cnt __guarded_by(&lock); + /** + * @sorted_cnt: Number of leading entries in @symbols that form the + * primary sorted prefix. When @sorted is true and @sorted_cnt < @cnt, + * the remaining tail @symbols[@sorted_cnt .. @cnt - 1] is also sorted. + */ + unsigned int sorted_cnt __guarded_by(&lock); /** @allocated: Capacity (in entries) of the @symbols allocation. */ unsigned int allocated __guarded_by(&lock); /** @num_by_name: Number of valid entries in @symbols_by_name. */ @@ -122,7 +128,10 @@ struct symbols { * by name. */ bool sorted_by_name __guarded_by(&lock); - /** @sorted: True when @symbols is sorted by address range. */ + /** + * @sorted: True when @symbols[0 .. @sorted_cnt - 1] and any tail + * @symbols[@sorted_cnt .. @cnt - 1] are sorted by start address. + */ bool sorted __guarded_by(&lock); }; =20 --=20 2.56.1.750.gf70dc682cf-goog From nobody Tue Nov 24 11:51:44 2026 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=74.125.82.197 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1795323891; b=QS2bx29hUTsu1VG9XPHxxwPh0SHn99Ps54w5Qt14YOhHKEBVk59y0WQxJM6IqyeEjXBy XqcxcgEY0V26iXNCDuvrnYSAhoHB/42dZqOFG8MmZuEh7BA/RKe0PdrN9KB4lgP0lcqyg IyMbM2Mplle8QW2X2FYhKn2q67ntWAfSW8Mb+zMqb9bNuakVjCnalcR4O1kHFrdZg4gzi taL9Cbk+B1/tt8n6u+huqbSViU7+bW/hnWDiy02XXXTk87AGO8utE4+TDwjH0ekSbT8vt 0NHAPxqPzwKly3SWOIpqnUbaBJD1ZiuLE+CmOTk9gS3xjoyPD8yooeBYwLBWvLeTRLg== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1795323891; h=DMARC-Filter:Received:DKIM-Signature:X-Google-DKIM-Signature: X-Forwarded-Encrypted:X-Gm-Message-State:X-Received:Date:In-Reply-To: Mime-Version:References:X-Mailer:Message-ID:Subject:From:To:Cc: Content-Type; bh=sKCN0xkGtD40xmw8BUtJsPQkTFtJI6AVG6guKPdcdV8=; b=3WhUxyKGr4mcxXUTkrnn9vL4PppLvZDxcKpnDoxJiBPH+EunTeAM1WcgE3CgKcOx1GRO FZHalQhOWr4jmRhVKJ/RhFAGrpPUXg9NGauWGcMYhcYrdIG5QF2fppTsi3AH5o4Nhhiae qau+DlNdiQFuug0V7VqADZp/76CbGsJr5tXb9XCxbn68TbRTajectOAZ9/qzez3iyBQT2 9tuzfnuSxHlKW3k6wAmiHy64ReagQaHm92zCNSFvLpP0HIKcDzA2t1Psk9jktCvNX+u5S tEXALRAPu66G4HJwovrDUzoqWu2xw27Kw5W2JkDbVeb0yo+ArGUwpbX+azrMZbsJq4A== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass header.from=google.com; spf=pass smtp.mailfrom=flex--irogers.bounces.google.com; dkim=pass header.d=google.com header.i=@google.com header.a=rsa-sha256 header.s=20260707 header.b=Ync8aA+r; arc=none smtp.remote-ip=74.125.82.197 Received: from mail-dy1-f197.google.com (mail-dy1-f197.google.com [74.125.82.197]) (using TLSv1.3 with cipher TLS_AES_128_GCM_SHA256 (128/128 bits) key-exchange X25519 server-signature ECDSA (prime256v1) server-digest SHA256) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id F078E606A330 for ; Sun, 22 Nov 2026 05:04:50 +0000 (UTC) DMARC-Filter: OpenDMARC Filter v1.4.2 smtp.subspace.kernel.org F078E606A330 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=flex--irogers.bounces.google.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.a=rsa-sha256 header.s=20260707 header.b=Ync8aA+r Received: by mail-dy1-f197.google.com with SMTP id 5a478bee46e88-3854627c1c8so3537674eec.1 for ; Sat, 21 Nov 2026 21:04:50 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20260707; t=1795323890; x=1795928690; darn=vger.kernel.org; h=content-type:cc:to:from:subject:message-id:references:mime-version :in-reply-to:date:from:to:cc:subject:date:message-id:reply-to :content-type; bh=sKCN0xkGtD40xmw8BUtJsPQkTFtJI6AVG6guKPdcdV8=; b=Ync8aA+rqrajW+8kHx8KMMIL5qRB2PQMPqJGzuZlEGGYL9c6Hby6aDbYDtYyn3Va9v cuB24VtdC1z1N1wypCKPxglwK2kzJ1ZeO0D0o6L31TPLeRF6azjKTdk2KIjpaJMxl/Zl ZMwscJuCMFJYViclvX19SiXkgEWx/l056c+jKeNBEqamzidJ9FCfF7VmIWQdpgCGiIsv imjeM+j0ROlK4c26B+TeVDROWcmE6sbirsallETJNDJ8b0eDpCb+B12sCvQu1iqNOsCi o6YmGobpfHrqX27n3JhYZICP4kcCBuDhERDGdSbfBBYD2wzTb/hEDT06UAsvAv8Q3ojW rl/Q== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20260707; t=1795323890; x=1795928690; h=content-type:cc:to:from:subject:message-id:references:mime-version :in-reply-to:date:x-gm-message-state:from:to:cc:subject:date :message-id:reply-to:content-type; bh=sKCN0xkGtD40xmw8BUtJsPQkTFtJI6AVG6guKPdcdV8=; b=BbDKGWcZ+ToseCxPxNKECMqsrz6PYAxbe82ZCa1DNgzFkkCYnOpXrI3HeXPw5mhf4k HlIY4jHSeFuQ5rSXVmEIv96xgIqSm+D3P9zIrEpebhjzSj7r1/5CO/0Ndml0fKml5B6T 5yz/hXEERmrxERnFeYJ+SNVkGhyoy1rbQrJnVUi6/FIzk0pUhIMOulQzheyOA+2usVc+ sGGYYORSjmUmHBcf9d5XBLnnRxmXEihKl0vXYrf1mxsPfN5nk5JKgAm3dn4rlrwzJPo0 83W4SKoXUbi6tVVVpDRLU61pykI7t3iYiR+d14jTGr0kQx/DmLgxcedxX2vnOAtSWNGd 1imQ== X-Forwarded-Encrypted: i=1; AL+hErGT1GLgFCmkkm+f31r791mztQvpQKTcYAx3uxLsSKXN3XmtAKyod1rQiGH70dVXtEwiZtr6+n5kITg/p9c=@vger.kernel.org X-Gm-Message-State: APuU4Z8UpMBgE96RHj9omG/WGo72FbszemotjGdnMzfAO6AMP9Q+xje3 148EVJl09q60GA9NqfivcrC3We40sQLkYWTiXmbhW/KedSwwXkuTCjQl21tGQrQtHEaTYQr31sX n6yuRlVkumw== X-Received: from dyev10.prod.google.com ([2002:a05:7300:430a:b0:343:520f:7a80]) (user=irogers job=prod-delivery.src-stubby-dispatcher) by 2002:a05:7300:ce11:b0:381:6b5:56e6 with SMTP id 5a478bee46e88-3856f65aed4mr7827105eec.16.1795323889616; Sat, 21 Nov 2026 21:04:49 -0800 (PST) Date: Sat, 21 Nov 2026 21:04:03 -0800 In-Reply-To: <20261122050405.80335-1-irogers@google.com> X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Post: List-Help: List-Subscribe: List-Unsubscribe: List-Owner: Precedence: list Mime-Version: 1.0 References: <20261122050405.80335-1-irogers@google.com> X-Mailer: git-send-email 2.56.1.750.gf70dc682cf-goog Message-ID: <20261122050405.80335-9-irogers@google.com> Subject: [PATCH v8 08/10] perf symbol: Add memory shrinking for symbols, DSOs, and machines From: Ian Rogers To: Namhyung Kim , Arnaldo Carvalho de Melo , Alireza Haghdoost , Ian Rogers Cc: Peter Zijlstra , Ingo Molnar , Jiri Olsa , Adrian Hunter , James Clark , linux-perf-users@vger.kernel.org, linux-kernel@vger.kernel.org Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" When profiling large workloads or systems with thousands of processes and shared libraries, perf can accumulate significant memory in loaded DSO symbol tables, secondary name-sorted symbol indices, cached DSO file data, and DWARF/addr2line state. Because the lifetime of struct symbol is controlled by its owning struct dso, symbols in a referenced DSO (refcnt > 1) must remain valid for the lifetime of the DSO reference. However, auxiliary per-DSO allocations and unreferenced DSOs can still be reclaimed under memory pressure: 1. symbols__shrink(): Reclaims the secondary name-sorted index (symbols_by_name, which is rebuilt on demand by dso__sort_by_name()) and trims unused over-allocated tail capacity in the symbols array. 2. dso__shrink(): Releases cached DSO resources (open file descriptor, cached 4KB data pages, addr2line handles, and libdw DWARF contexts). When a DSO in a dsos collection has no external references (refcnt =3D=3D 1), dso__shrink() also evicts its unannotated symbol table via symbols__try_delete_unannotated() and marks the DSO unloaded so it can be reloaded on demand if mapped again; otherwise it calls symbols__shrink() to reclaim auxiliary symbol arrays. 3. dsos__shrink(), machine__shrink(), machines__shrink(), and perf_session__shrink(): Walk the session's host and guest machines to shrink DSOs and evict unreferenced user DSOs (refcnt =3D=3D 1, not kerne= l, not vDSO, not hit, and not carrying header build-ids), followed by malloc_trim(0) on glibc to return freed heap pages to the OS. Signed-off-by: Ian Rogers --- tools/perf/util/dso.c | 263 +++++++++++++++++++++++++++++++++++--- tools/perf/util/dso.h | 14 +- tools/perf/util/dsos.c | 50 ++++++++ tools/perf/util/dsos.h | 2 + tools/perf/util/machine.c | 29 +++++ tools/perf/util/machine.h | 3 + tools/perf/util/session.c | 8 ++ tools/perf/util/session.h | 2 + tools/perf/util/symbol.c | 68 +++++++++- tools/perf/util/symbol.h | 3 + 10 files changed, 419 insertions(+), 23 deletions(-) diff --git a/tools/perf/util/dso.c b/tools/perf/util/dso.c index d1668c986e8d..dce9d8d7838c 100644 --- a/tools/perf/util/dso.c +++ b/tools/perf/util/dso.c @@ -3,6 +3,7 @@ =20 #include #include +#include #include =20 #include @@ -16,6 +17,7 @@ #include #include =20 +#include "annotate.h" #include "annotate-data.h" #include "auxtrace.h" #include "compress.h" @@ -1050,12 +1052,12 @@ static int bpf_size(struct dso *dso) #endif // HAVE_LIBBPF_SUPPORT =20 static void -dso_cache__free(struct dso *dso) +__dso_cache__free(struct dso *dso) + __must_hold(dso__lock(dso)) { struct rb_root *root =3D &dso__data(dso)->cache; struct rb_node *next =3D rb_first(root); =20 - mutex_lock(dso__lock(dso)); while (next) { struct dso_cache *cache; =20 @@ -1064,10 +1066,18 @@ dso_cache__free(struct dso *dso) rb_erase(&cache->rb_node, root); free(cache); } +} + +static void +dso_cache__free(struct dso *dso) +{ + mutex_lock(dso__lock(dso)); + __dso_cache__free(dso); mutex_unlock(dso__lock(dso)); } =20 static struct dso_cache *__dso_cache__find(struct dso *dso, u64 offset) + __must_hold(dso__lock(dso)) { const struct rb_root *root =3D &dso__data(dso)->cache; struct rb_node * const *p =3D &root->rb_node; @@ -1218,27 +1228,30 @@ static struct dso_cache *dso_cache__populate(struct= dso *dso, return cache; } =20 -static struct dso_cache *dso_cache__find(struct dso *dso, - struct machine *machine, - u64 offset, - ssize_t *ret) -{ - struct dso_cache *cache =3D __dso_cache__find(dso, offset); - - return cache ? cache : dso_cache__populate(dso, machine, offset, ret); -} - static ssize_t dso_cache_io(struct dso *dso, struct machine *machine, u64 offset, u8 *data, ssize_t size, bool out) { struct dso_cache *cache; ssize_t ret =3D 0; =20 - cache =3D dso_cache__find(dso, machine, offset, &ret); - if (!cache) - return ret; + mutex_lock(dso__lock(dso)); + cache =3D __dso_cache__find(dso, offset); + while (!cache) { + mutex_unlock(dso__lock(dso)); + cache =3D dso_cache__populate(dso, machine, offset, &ret); + if (!cache) + return ret; + mutex_lock(dso__lock(dso)); + /* + * Re-lookup under dso__lock(dso) in case dso__shrink() freed + * the cache while the lock was dropped. + */ + cache =3D __dso_cache__find(dso, offset); + } =20 - return dso_cache__memcpy(cache, offset, data, size, out); + ret =3D dso_cache__memcpy(cache, offset, data, size, out); + mutex_unlock(dso__lock(dso)); + return ret; } =20 /* @@ -1797,7 +1810,7 @@ int dso__name_len(const struct dso *dso) =20 bool dso__loaded(const struct dso *dso) { - return RC_CHK_ACCESS(dso)->loaded; + return atomic_load_explicit(&RC_CHK_ACCESS(dso)->loaded, memory_order_acq= uire); } =20 bool dso__sorted_by_name(const struct dso *dso) @@ -1835,7 +1848,7 @@ struct dso *dso__new_id(const char *name, const struc= t dso_id *id) dso->binary_type =3D DSO_BINARY_TYPE__NOT_FOUND; dso->dbginfo_type =3D DSO_BINARY_TYPE__NOT_FOUND; dso->is_64_bit =3D (sizeof(void *) =3D=3D 8); - dso->loaded =3D 0; + atomic_init(&dso->loaded, false); dso->rel =3D 0; dso->has_srcline =3D 1; dso->a2l_fails =3D 1; @@ -1859,7 +1872,7 @@ struct dso *dso__new(const char *name) return dso__new_id(name, NULL); } =20 -void dso__delete(struct dso *dso) +static void __dso__delete(struct dso *dso, bool close_data) { if (dso__dsos(dso)) pr_err("DSO %s is still in rbtree when being deleted!\n", dso__long_name= (dso)); @@ -1881,7 +1894,8 @@ void dso__delete(struct dso *dso) RC_CHK_ACCESS(dso)->long_name_allocated =3D false; } =20 - dso__data_close(dso); + if (close_data) + dso__data_close(dso); auxtrace_cache__free(RC_CHK_ACCESS(dso)->auxtrace_cache); dso_cache__free(dso); dso__free_a2l(dso); @@ -1893,6 +1907,215 @@ void dso__delete(struct dso *dso) RC_CHK_FREE(dso); } =20 +void dso__delete(struct dso *dso) +{ + __dso__delete(dso, /*close_data=3D*/true); +} + +bool dso__can_shrink_symbols(const struct dso *dso) +{ + const char *name; + + if (!dso || !dso__loaded(dso)) + return false; + + if (dso__kernel(dso) || dso__is_kmod(dso)) + return false; + + if (dso__is_vdso(dso)) + return false; + + switch (dso__binary_type(dso)) { + case DSO_BINARY_TYPE__KALLSYMS: + case DSO_BINARY_TYPE__GUEST_KALLSYMS: + case DSO_BINARY_TYPE__VMLINUX: + case DSO_BINARY_TYPE__GUEST_VMLINUX: + case DSO_BINARY_TYPE__KCORE: + case DSO_BINARY_TYPE__GUEST_KCORE: + case DSO_BINARY_TYPE__BPF_PROG_INFO: + case DSO_BINARY_TYPE__BPF_IMAGE: + case DSO_BINARY_TYPE__OOL: + case DSO_BINARY_TYPE__JAVA_JIT: + case DSO_BINARY_TYPE__GUEST_KMODULE: + case DSO_BINARY_TYPE__GUEST_KMODULE_COMP: + case DSO_BINARY_TYPE__SYSTEM_PATH_KMODULE: + case DSO_BINARY_TYPE__SYSTEM_PATH_KMODULE_COMP: + return false; + case DSO_BINARY_TYPE__DEBUGLINK: + case DSO_BINARY_TYPE__BUILD_ID_CACHE: + case DSO_BINARY_TYPE__BUILD_ID_CACHE_DEBUGINFO: + case DSO_BINARY_TYPE__FEDORA_DEBUGINFO: + case DSO_BINARY_TYPE__UBUNTU_DEBUGINFO: + case DSO_BINARY_TYPE__MIXEDUP_UBUNTU_DEBUGINFO: + case DSO_BINARY_TYPE__BUILDID_DEBUGINFO: + case DSO_BINARY_TYPE__GNU_DEBUGDATA: + case DSO_BINARY_TYPE__SYSTEM_PATH_DSO: + case DSO_BINARY_TYPE__OPENEMBEDDED_DEBUGINFO: + case DSO_BINARY_TYPE__NOT_FOUND: + default: + break; + } + + switch (dso__symtab_type(dso)) { + case DSO_BINARY_TYPE__KALLSYMS: + case DSO_BINARY_TYPE__GUEST_KALLSYMS: + case DSO_BINARY_TYPE__VMLINUX: + case DSO_BINARY_TYPE__GUEST_VMLINUX: + case DSO_BINARY_TYPE__KCORE: + case DSO_BINARY_TYPE__GUEST_KCORE: + case DSO_BINARY_TYPE__BPF_PROG_INFO: + case DSO_BINARY_TYPE__BPF_IMAGE: + case DSO_BINARY_TYPE__OOL: + case DSO_BINARY_TYPE__JAVA_JIT: + case DSO_BINARY_TYPE__GUEST_KMODULE: + case DSO_BINARY_TYPE__GUEST_KMODULE_COMP: + case DSO_BINARY_TYPE__SYSTEM_PATH_KMODULE: + case DSO_BINARY_TYPE__SYSTEM_PATH_KMODULE_COMP: + case DSO_BINARY_TYPE__NOT_FOUND: + return false; + case DSO_BINARY_TYPE__DEBUGLINK: + case DSO_BINARY_TYPE__BUILD_ID_CACHE: + case DSO_BINARY_TYPE__BUILD_ID_CACHE_DEBUGINFO: + case DSO_BINARY_TYPE__FEDORA_DEBUGINFO: + case DSO_BINARY_TYPE__UBUNTU_DEBUGINFO: + case DSO_BINARY_TYPE__MIXEDUP_UBUNTU_DEBUGINFO: + case DSO_BINARY_TYPE__BUILDID_DEBUGINFO: + case DSO_BINARY_TYPE__GNU_DEBUGDATA: + case DSO_BINARY_TYPE__SYSTEM_PATH_DSO: + case DSO_BINARY_TYPE__OPENEMBEDDED_DEBUGINFO: + default: + break; + } + + name =3D dso__long_name(dso); + if (!name || name[0] =3D=3D '[' || is_perf_pid_map_name(name) || + strstr(name, " (deleted)") !=3D NULL) + return false; + + return true; +} + +static bool dso__has_annotated_inlines(struct dso *dso) +{ + struct rb_root_cached *tree =3D dso__inlined_nodes(dso); + struct rb_node *nd; + + for (nd =3D rb_first_cached(tree); nd; nd =3D rb_next(nd)) { + struct inline_node *node =3D rb_entry(nd, struct inline_node, rb_node); + struct inline_list *ilist; + + list_for_each_entry(ilist, &node->val, list) { + if (ilist->symbol && symbol__annotated(ilist->symbol)) + return true; + } + } + return false; +} + +static void dso__delete_inlines_and_srclines(void *ctx) +{ + struct dso *dso =3D ctx; + + /* Free inlines before symbols, as inline frames reference symbols. */ + inlines__tree_delete(dso__inlined_nodes(dso)); + srcline__tree_delete(dso__srclines(dso)); +} + +size_t dso__shrink(struct dso *dso) +{ + size_t freed =3D 0; + + if (!dso) + return 0; + + if (mutex_trylock(&dso__data_open_lock)) { + if (dso__data(dso)->fd >=3D 0) { + close_dso(dso); + freed++; + } + mutex_unlock(&dso__data_open_lock); + } + + if (!mutex_trylock(dso__lock(dso))) + return freed; + + if (!dso__kernel(dso) && dso__binary_type(dso) !=3D DSO_BINARY_TYPE__OOL = && + !RB_EMPTY_ROOT(&dso__data(dso)->cache)) { + __dso_cache__free(dso); + freed++; + } + if (dso__a2l(dso)) { + dso__free_a2l(dso); + freed++; + } +#ifdef HAVE_LIBBFD_SUPPORT + if (dso__a2l_libbfd(dso)) { + dso__free_a2l_libbfd(dso); + freed++; + } +#endif +#ifdef HAVE_LIBDW_SUPPORT + if (dso__libdw(dso)) { + dso__free_libdw(dso); + freed++; + } +#endif + + if (dso__dsos(dso) && refcount_read(dso__refcnt(dso)) =3D=3D 1 && + dso__can_shrink_symbols(dso) && dso__has_symbols(dso) && + !dso__has_annotated_inlines(dso) && + symbols__try_delete_unannotated(dso__symbols(dso), + dso__delete_inlines_and_srclines, dso)) { + atomic_store_explicit(&RC_CHK_ACCESS(dso)->loaded, false, + memory_order_release); + freed++; + } else { + freed +=3D symbols__shrink(dso__symbols(dso)); + } + + mutex_unlock(dso__lock(dso)); + return freed; +} + +/* + * Try to evict an unreferenced @dso from its owning struct dsos (whose wr= ite + * lock must be held by the caller) without blocking on any lock. + */ +bool dso__try_evict(struct dso *dso) +{ + bool can_evict =3D false; + + if (!dso || + dso__has_symbols(dso) || + dso__header_build_id(dso) || + dso__hit(dso) || + dso__kernel(dso) || + dso__is_vdso(dso) || + refcount_read(dso__refcnt(dso)) !=3D 1) + return false; + + if (!mutex_trylock(&dso__data_open_lock)) + return false; + + if (dso__data(dso)->fd < 0 && + list_empty(&dso__data(dso)->open_entry) && + refcount_read(dso__refcnt(dso)) =3D=3D 1 && + mutex_trylock(dso__lock(dso))) { + can_evict =3D !dso__has_symbols(dso) && !dso__has_annotated_inlines(dso); + mutex_unlock(dso__lock(dso)); + } + mutex_unlock(&dso__data_open_lock); + if (!can_evict) + return false; + + dso__set_dsos(dso, NULL); + if (refcount_dec_and_test(&RC_CHK_ACCESS(dso)->refcnt)) + __dso__delete(dso, /*close_data=3D*/false); + else + RC_CHK_PUT(dso); + return true; +} + struct dso *dso__get(struct dso *dso) { struct dso *result; diff --git a/tools/perf/util/dso.h b/tools/perf/util/dso.h index 63c1b7d6f6f8..b0ee45a53f40 100644 --- a/tools/perf/util/dso.h +++ b/tools/perf/util/dso.h @@ -6,6 +6,7 @@ #include #include #include +#include #include #include #include @@ -343,7 +344,7 @@ DECLARE_RC_STRUCT(dso) { u8 is_64_bit:1; u8 bintype_searched:1; u8 debuginfo_searched:1; - bool loaded; + _Atomic bool loaded; u8 rel; char name[]; }; @@ -599,7 +600,7 @@ static inline enum dso_load_errno *dso__load_errno(stru= ct dso *dso) =20 static inline void dso__set_loaded(struct dso *dso) { - RC_CHK_ACCESS(dso)->loaded =3D true; + atomic_store_explicit(&RC_CHK_ACCESS(dso)->loaded, true, memory_order_rel= ease); } =20 static inline struct mutex *dso__lock(struct dso *dso) @@ -788,6 +789,15 @@ static inline bool dso__has_symbols(const struct dso *= dso) return res; } =20 +static inline refcount_t *dso__refcnt(struct dso *dso) +{ + return &RC_CHK_ACCESS(dso)->refcnt; +} + +bool dso__can_shrink_symbols(const struct dso *dso); +bool dso__try_evict(struct dso *dso); +size_t dso__shrink(struct dso *dso); + char *dso__filename_with_chroot(const struct dso *dso, const char *filenam= e); =20 bool dso__sorted_by_name(const struct dso *dso); diff --git a/tools/perf/util/dsos.c b/tools/perf/util/dsos.c index 7a56577f4ec8..77f668d7557c 100644 --- a/tools/perf/util/dsos.c +++ b/tools/perf/util/dsos.c @@ -6,6 +6,9 @@ #include "vdso.h" #include "namespaces.h" #include +#ifdef __GLIBC__ +#include +#endif #include #include #include // filename__read_build_id @@ -517,3 +520,50 @@ int dsos__for_each_dso(struct dsos *dsos, int (*cb)(st= ruct dso *dso, void *data) up_read(&dsos->lock); return err; } + +size_t dsos__shrink(struct dsos *dsos) +{ + unsigned int write_idx =3D 0; + size_t freed =3D 0; + bool any_removed =3D false; + + down_write(&dsos->lock); + + for (unsigned int read_idx =3D 0; read_idx < dsos->cnt; read_idx++) { + struct dso *dso =3D dsos->dsos[read_idx]; + + freed +=3D dso__shrink(dso); + + if (dso__try_evict(dso)) { + any_removed =3D true; + freed++; + continue; + } + dsos->dsos[write_idx++] =3D dso; + } + + dsos->cnt =3D write_idx; + if (any_removed) { + if (write_idx =3D=3D 0) { + zfree(&dsos->dsos); + dsos->allocated =3D 0; + dsos->sorted =3D true; + } else if (write_idx < dsos->allocated / 2) { + struct dso **shrunk =3D realloc(dsos->dsos, + write_idx * sizeof(struct dso *)); + if (shrunk) { + dsos->dsos =3D shrunk; + dsos->allocated =3D write_idx; + } + } + } + + up_write(&dsos->lock); + +#ifdef __GLIBC__ + if (freed > 0) + malloc_trim(0); +#endif + + return freed; +} diff --git a/tools/perf/util/dsos.h b/tools/perf/util/dsos.h index cc7e3a42f9cb..de10a10de777 100644 --- a/tools/perf/util/dsos.h +++ b/tools/perf/util/dsos.h @@ -51,4 +51,6 @@ struct dso *dsos__find_kernel_dso(struct dsos *dsos); =20 int dsos__for_each_dso(struct dsos *dsos, int (*cb)(struct dso *dso, void = *data), void *data); =20 +size_t dsos__shrink(struct dsos *dsos); + #endif /* __PERF_DSOS */ diff --git a/tools/perf/util/machine.c b/tools/perf/util/machine.c index 3c206c26bd62..f4108cc725fc 100644 --- a/tools/perf/util/machine.c +++ b/tools/perf/util/machine.c @@ -3438,3 +3438,32 @@ int machine__hit_all_dsos(struct machine *machine) { return dsos__hit_all(&machine->dsos); } + +size_t machine__shrink(struct machine *machine) +{ + if (!machine) + return 0; + + return dsos__shrink(&machine->dsos); +} + +size_t machines__shrink(struct machines *machines) +{ + struct rb_node *nd; + size_t freed; + + if (!machines) + return 0; + + freed =3D machine__shrink(&machines->host); + + down_read(&machines->lock); + for (nd =3D rb_first_cached(&machines->guests); nd; nd =3D rb_next(nd)) { + struct machine *pos =3D rb_entry(nd, struct machine, rb_node); + + freed +=3D machine__shrink(pos); + } + up_read(&machines->lock); + + return freed; +} diff --git a/tools/perf/util/machine.h b/tools/perf/util/machine.h index 67d517742fb6..b42c363723c9 100644 --- a/tools/perf/util/machine.h +++ b/tools/perf/util/machine.h @@ -339,4 +339,7 @@ int machine__resolve(struct machine *machine, struct ad= dr_location *al, =20 int machine__hit_all_dsos(struct machine *machine); =20 +size_t machine__shrink(struct machine *machine); +size_t machines__shrink(struct machines *machines); + #endif /* __PERF_MACHINE_H */ diff --git a/tools/perf/util/session.c b/tools/perf/util/session.c index 4e11eabbbe6f..9f16bff1b72f 100644 --- a/tools/perf/util/session.c +++ b/tools/perf/util/session.c @@ -4270,3 +4270,11 @@ uint16_t perf_session__e_machine(struct perf_session= *session, uint32_t *e_flags */ return perf_env__e_machine_nocache(env, e_flags); } + +size_t perf_session__shrink(struct perf_session *session) +{ + if (!session) + return 0; + + return machines__shrink(&session->machines); +} diff --git a/tools/perf/util/session.h b/tools/perf/util/session.h index 05ea2c1ee8c9..cbea6792a008 100644 --- a/tools/perf/util/session.h +++ b/tools/perf/util/session.h @@ -211,4 +211,6 @@ int perf_event__process_finished_round(const struct per= f_tool *tool, struct perf_env *perf_session__env(struct perf_session *session); uint16_t perf_session__e_machine(struct perf_session *session, uint32_t *e= _flags); =20 +size_t perf_session__shrink(struct perf_session *session); + #endif /* __PERF_SESSION_H */ diff --git a/tools/perf/util/symbol.c b/tools/perf/util/symbol.c index 22b84e9a40fd..eadaa5bfaa9e 100644 --- a/tools/perf/util/symbol.c +++ b/tools/perf/util/symbol.c @@ -1,6 +1,7 @@ // SPDX-License-Identifier: GPL-2.0 #include #include +#include #include #include #include @@ -256,6 +257,69 @@ void symbols__exit(struct symbols *symbols) exit_rwsem(&symbols->lock); } =20 +bool symbols__try_delete_unannotated(struct symbols *symbols, + void (*pre_delete)(void *ctx), void *ctx) +{ + down_write(&symbols->lock); + for (unsigned int i =3D 0; i < symbols->cnt; i++) { + if (symbol__annotated(symbols->symbols[i])) { + up_write(&symbols->lock); + return false; + } + } + + if (pre_delete) + pre_delete(ctx); + + symbols__delete_locked(symbols); + up_write(&symbols->lock); + return true; +} + +/* + * Reclaim auxiliary memory from @symbols without freeing live symbol + * entries (whose lifetimes are owned by the containing struct dso): + * - Free the secondary name-sorted index (@symbols_by_name), which is + * rebuilt on demand by dso__sort_by_name(). + * - Trim unused over-allocated tail capacity in @symbols->symbols. + * + * Returns the number of buffers reclaimed/shrunk. + */ +size_t symbols__shrink(struct symbols *symbols) +{ + size_t freed =3D 0; + + down_write(&symbols->lock); + + if (symbols->symbols_by_name) { + zfree(&symbols->symbols_by_name); + symbols->num_by_name =3D 0; + symbols->sorted_by_name =3D false; + freed++; + } + + if (symbols->cnt =3D=3D 0) { + if (symbols->allocated > 0) { + zfree(&symbols->symbols); + symbols->sorted_cnt =3D 0; + symbols->allocated =3D 0; + symbols->sorted =3D true; + freed++; + } + } else if (symbols->cnt < symbols->allocated) { + struct symbol **shrunk =3D realloc(symbols->symbols, + symbols->cnt * sizeof(struct symbol *)); + if (shrunk) { + symbols->symbols =3D shrunk; + symbols->allocated =3D symbols->cnt; + freed++; + } + } + + up_write(&symbols->lock); + return freed; +} + /* * Order symbols by start address only, preserving insertion order among * symbols sharing the same start address (matching the previous rbtree @@ -2394,8 +2458,9 @@ int dso__load(struct dso *dso, struct map *map) /* check again under the dso->lock */ if (dso__loaded(dso)) { ret =3D 1; - goto out; + goto out_unlock; } + atomic_store_explicit(&RC_CHK_ACCESS(dso)->loaded, false, memory_order_re= lease); =20 kmod =3D dso__is_kmod(dso); =20 @@ -2553,6 +2618,7 @@ int dso__load(struct dso *dso, struct map *map) ret =3D 0; out: dso__set_loaded(dso); +out_unlock: mutex_unlock(dso__lock(dso)); nsinfo__mountns_exit(&nsc); =20 diff --git a/tools/perf/util/symbol.h b/tools/perf/util/symbol.h index 541ab9321d99..ca0e201f1756 100644 --- a/tools/perf/util/symbol.h +++ b/tools/perf/util/symbol.h @@ -139,6 +139,9 @@ void symbol__delete(struct symbol *sym); void symbols__init(struct symbols *symbols); void symbols__exit(struct symbols *symbols); void symbols__delete(struct symbols *symbols); +bool symbols__try_delete_unannotated(struct symbols *symbols, + void (*pre_delete)(void *ctx), void *ctx); +size_t symbols__shrink(struct symbols *symbols); void symbols__sort_read_lock(struct symbols *symbols) __acquires_shared(&s= ymbols->lock); =20 static inline u8 symbol__type(const struct symbol *sym) --=20 2.56.1.750.gf70dc682cf-goog From nobody Tue Nov 24 11:51:44 2026 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=74.125.82.200 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1795323893; b=0vpLkLbTuqrtnb27GwL+KIlzbnYwPEk8mIzKHiKZV6K9o1+TP4Lzq78XfYNxW29MaMO7 UQ52EqWksWg9E+MqhkuVbw7J7Zy9FMIQg4Ullpj+L+VYVZ5ieShABRHcm4C3uC2munSM6 ZRB8gIKMDtA8mqrwqJNFYXx+iAme/O1Zr2Dmn+B8xWBfLie9cG9f0EjIYuGJZkY7Q4CMC W/yxqOn3U0dBusRHyorPlRDQho6HzA7iRSQgReMMsML62v4qKwoO8y8cSXt8+jOKXuVQK +w9sj1YMBZMkNk/jwg7VFLbTv0+37jPawFcbLdk+t4RU3T8yuqbEOtTmIUkBqM5oJ8A== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1795323893; h=DMARC-Filter:Received:DKIM-Signature:X-Google-DKIM-Signature: X-Forwarded-Encrypted:X-Gm-Message-State:X-Received:Date:In-Reply-To: Mime-Version:References:X-Mailer:Message-ID:Subject:From:To:Cc: Content-Type; bh=9+9nQInNjKHi9FhFczD5gPabpM6jI6Q6X78w4bQJNUk=; b=tKnL7rXt0Xz71wNv3gx/uAbHPrYAh/wWokEDASePyHyNPna4Y+7ODeXw8hACXLOs21kN e6wmDLC1JwMORwrKP3WIapxE1nportlAfnGSRa2CfnAi5rdbAclMlwaWDoFCdBNmCeyCS Bq73t6p6XqS2Tp3MkvEwwwMuEBk73nUYlLb8V5bRLzqPY8ZqyB+zoiMQeaUv/WvFh+Rka h/vD5wfizSXZs1YzEUds04qZ/nvAyn4bKROqWWd0OTj2ZCoSTsQHfGieU/1+RpaxkaPY3 Kl27/JYc2TbbIRglg5kWg8anre36B2TO+MY2IcYr/Jn3Y8S4FM8fpbHDphaQaKNwX3A== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass header.from=google.com; spf=pass smtp.mailfrom=flex--irogers.bounces.google.com; dkim=pass header.d=google.com header.i=@google.com header.a=rsa-sha256 header.s=20260707 header.b=aOuWn5uR; arc=none smtp.remote-ip=74.125.82.200 Received: from mail-dy1-f200.google.com (mail-dy1-f200.google.com [74.125.82.200]) (using TLSv1.3 with cipher TLS_AES_128_GCM_SHA256 (128/128 bits) key-exchange X25519 server-signature ECDSA (prime256v1) server-digest SHA256) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 27656606A33D for ; Sun, 22 Nov 2026 05:04:53 +0000 (UTC) DMARC-Filter: OpenDMARC Filter v1.4.2 smtp.subspace.kernel.org 27656606A33D Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=flex--irogers.bounces.google.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.a=rsa-sha256 header.s=20260707 header.b=aOuWn5uR Received: by mail-dy1-f200.google.com with SMTP id 5a478bee46e88-382af5cfc58so6723658eec.0 for ; Sat, 21 Nov 2026 21:04:53 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20260707; t=1795323892; x=1795928692; darn=vger.kernel.org; h=content-type:cc:to:from:subject:message-id:references:mime-version :in-reply-to:date:from:to:cc:subject:date:message-id:reply-to :content-type; bh=9+9nQInNjKHi9FhFczD5gPabpM6jI6Q6X78w4bQJNUk=; b=aOuWn5uRfTPBUqxtMY8qqNpZ/9Sez9AwzIxTMM4CEBb2A8bj1Zp29FHOoHwPTGG7W+ q+sTY0vyOg8q2j4niO5vMN2NbxvJ0Or7jZsyGXzH/BMDb0sW278PUDZW4eU/m6BRKC39 UZJofEfoahZCVXou7wwiu9kEOvkYT7q0YIzz8Klg+lJXAT2z9TkU/JTcNhrlgOTAIRoZ CmE5/0P4NnhtIrY1j0xgweR4g+pkU95QQMTuNplhaisJqjpG7J/9Vzv73l9EykKcigmY CyEF1TctuLLdoX4WU5e6dbeRgWs9aGXyESYVvWNc3TUMsWO6zzuangEraKyvcDEPPUuU PURA== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20260707; t=1795323892; x=1795928692; h=content-type:cc:to:from:subject:message-id:references:mime-version :in-reply-to:date:x-gm-message-state:from:to:cc:subject:date :message-id:reply-to:content-type; bh=9+9nQInNjKHi9FhFczD5gPabpM6jI6Q6X78w4bQJNUk=; b=g6Jbz60kbCMoNEQoT4qUJ7Eq3cAlMQkWfslEbUUSH1oylHQfEmACL0P/ByW7v9+AV1 DyZkwvrA6e1w4rKN0nay9U0vHpB7Qyk3+91q6i0PgBkxZds8lVfBWXZaOFva/nwx8t3W hDsa6s3ySP5xDi3im7CCzucf+pDo8+Kwppt8OD3cgTLZkj2w9xSzOI8FN/bhuy8C0Ffz EySIF9YcW/lGVKYGaJjPhJW731I7HAMZtd3vWrrA6PeXnCQe39AF4vqiJuMRI8QcLsV7 0vSFwQiSlqW2X9BEXzUatmzLOypHxvXzBYgiLSgUjBqIszB0552QmpalPzcKEPg6G5B/ i6Zw== X-Forwarded-Encrypted: i=1; AL+hErFmhX4B/ekUs23ypprZZawgIuo50Nxj1lohvIa33I9LSa2hYw9XXNWSncS8LHntxugfo0EDy5ZnJXvnQcg=@vger.kernel.org X-Gm-Message-State: APuU4Z+JdZPJHtuIngesueVJBLfdGs0spf8umARX8GcV5THc13EO2jJH 0aEQ00xajo8BOoYNT1nAuF0tSJctpQbJ1MZDSVNLsUG5ChvBX+MMw9kn4uZvFNrPDdZBze/7pnU +9dldfzceQg== X-Received: from dybfe10.prod.google.com ([2002:a05:7300:bf8a:b0:385:416a:7356]) (user=irogers job=prod-delivery.src-stubby-dispatcher) by 2002:a05:7301:f02:b0:384:ce59:5e21 with SMTP id 5a478bee46e88-3856f6503d8mr8265867eec.32.1795323892076; Sat, 21 Nov 2026 21:04:52 -0800 (PST) Date: Sat, 21 Nov 2026 21:04:04 -0800 In-Reply-To: <20261122050405.80335-1-irogers@google.com> X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Post: List-Help: List-Subscribe: List-Unsubscribe: List-Owner: Precedence: list Mime-Version: 1.0 References: <20261122050405.80335-1-irogers@google.com> X-Mailer: git-send-email 2.56.1.750.gf70dc682cf-goog Message-ID: <20261122050405.80335-10-irogers@google.com> Subject: [PATCH v8 09/10] perf session: Add dso__session() and session-scoped allocation wrappers From: Ian Rogers To: Namhyung Kim , Arnaldo Carvalho de Melo , Alireza Haghdoost , Ian Rogers Cc: Peter Zijlstra , Ingo Molnar , Jiri Olsa , Adrian Hunter , James Clark , linux-perf-users@vger.kernel.org, linux-kernel@vger.kernel.org Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" Add explicit session-scoped memory allocation wrappers: - perf_session__malloc(session, size) - perf_session__zalloc(session, size) - perf_session__calloc(session, nmemb, size) - perf_session__realloc(session, ptr, size) - perf_session__strdup(session, s) When an allocation fails and returns NULL, if a non-NULL struct perf_session is provided, the wrapper invokes perf_session__shrink() to evict unreferenced symbols, DSOs, and cached debuginfo across the session's machines and then retries the allocation once. This avoids the thrashing overhead of periodic heuristic shrinking while allowing perf to recover from memory exhaustion. Also plumb a back-pointer from struct dsos to its owning struct machine so machine__session(machine) and dso__session(dso) can resolve the active perf_session. Signed-off-by: Ian Rogers --- tools/perf/util/dso.c | 7 ++++ tools/perf/util/dso.h | 2 ++ tools/perf/util/dsos.c | 1 + tools/perf/util/dsos.h | 1 + tools/perf/util/machine.c | 1 + tools/perf/util/machine.h | 5 +++ tools/perf/util/session.c | 70 +++++++++++++++++++++++++++++++++++++++ tools/perf/util/session.h | 6 ++++ 8 files changed, 93 insertions(+) diff --git a/tools/perf/util/dso.c b/tools/perf/util/dso.c index dce9d8d7838c..5ee30964b3df 100644 --- a/tools/perf/util/dso.c +++ b/tools/perf/util/dso.c @@ -1912,6 +1912,13 @@ void dso__delete(struct dso *dso) __dso__delete(dso, /*close_data=3D*/true); } =20 +struct perf_session *dso__session(const struct dso *dso) +{ + struct dsos *dsos =3D dso ? RC_CHK_ACCESS(dso)->dsos : NULL; + + return dsos ? machine__session(dsos->machine) : NULL; +} + bool dso__can_shrink_symbols(const struct dso *dso) { const char *name; diff --git a/tools/perf/util/dso.h b/tools/perf/util/dso.h index b0ee45a53f40..eb56bf9fb4d1 100644 --- a/tools/perf/util/dso.h +++ b/tools/perf/util/dso.h @@ -20,6 +20,7 @@ struct machine; struct map; struct perf_env; +struct perf_session; =20 #define DSO__NAME_KALLSYMS "[kernel.kallsyms]" #define DSO__NAME_KCORE "[kernel.kcore]" @@ -797,6 +798,7 @@ static inline refcount_t *dso__refcnt(struct dso *dso) bool dso__can_shrink_symbols(const struct dso *dso); bool dso__try_evict(struct dso *dso); size_t dso__shrink(struct dso *dso); +struct perf_session *dso__session(const struct dso *dso); =20 char *dso__filename_with_chroot(const struct dso *dso, const char *filenam= e); =20 diff --git a/tools/perf/util/dsos.c b/tools/perf/util/dsos.c index 77f668d7557c..43605daedba6 100644 --- a/tools/perf/util/dsos.c +++ b/tools/perf/util/dsos.c @@ -19,6 +19,7 @@ void dsos__init(struct dsos *dsos) { init_rwsem(&dsos->lock); =20 + dsos->machine =3D NULL; dsos->cnt =3D 0; dsos->allocated =3D 0; dsos->dsos =3D NULL; diff --git a/tools/perf/util/dsos.h b/tools/perf/util/dsos.h index de10a10de777..87002b25a3bb 100644 --- a/tools/perf/util/dsos.h +++ b/tools/perf/util/dsos.h @@ -19,6 +19,7 @@ struct machine; */ struct dsos { struct rw_semaphore lock; + struct machine *machine; struct dso **dsos __pt_guarded_by(&lock) __guarded_by(&lock); unsigned int cnt __guarded_by(&lock); unsigned int allocated __guarded_by(&lock); diff --git a/tools/perf/util/machine.c b/tools/perf/util/machine.c index f4108cc725fc..20215c12819e 100644 --- a/tools/perf/util/machine.c +++ b/tools/perf/util/machine.c @@ -81,6 +81,7 @@ int machine__init(struct machine *machine, const char *ro= ot_dir, pid_t pid) memset(machine, 0, sizeof(*machine)); RB_CLEAR_NODE(&machine->rb_node); dsos__init(&machine->dsos); + machine->dsos.machine =3D machine; threads__init(&machine->threads); =20 machine->kmaps =3D maps__new(machine); diff --git a/tools/perf/util/machine.h b/tools/perf/util/machine.h index b42c363723c9..80ef16384aa5 100644 --- a/tools/perf/util/machine.h +++ b/tools/perf/util/machine.h @@ -165,6 +165,11 @@ static inline struct perf_session *machines__session(s= truct machines *machines) return machines->session; } =20 +static inline struct perf_session *machine__session(const struct machine *= machine) +{ + return machine && machine->machines ? machine->machines->session : NULL; +} + void machines__process_guests(struct machines *machines, machine__process_t process, void *data); =20 diff --git a/tools/perf/util/session.c b/tools/perf/util/session.c index 9f16bff1b72f..610bbc769ef7 100644 --- a/tools/perf/util/session.c +++ b/tools/perf/util/session.c @@ -4278,3 +4278,73 @@ size_t perf_session__shrink(struct perf_session *ses= sion) =20 return machines__shrink(&session->machines); } + +static __thread bool perf_session__in_shrink; + +static bool perf_session__try_shrink(struct perf_session *session) +{ + size_t freed; + + if (!session || perf_session__in_shrink) + return false; + + perf_session__in_shrink =3D true; + freed =3D perf_session__shrink(session); + perf_session__in_shrink =3D false; + + return freed > 0; +} + +void *perf_session__malloc(struct perf_session *session, size_t size) +{ + void *ptr =3D malloc(size); + + if (unlikely(!ptr && size !=3D 0) && perf_session__try_shrink(session)) + ptr =3D malloc(size); + + return ptr; +} + +void *perf_session__zalloc(struct perf_session *session, size_t size) +{ + void *ptr =3D zalloc(size); + + if (unlikely(!ptr && size !=3D 0) && perf_session__try_shrink(session)) + ptr =3D zalloc(size); + + return ptr; +} + +void *perf_session__calloc(struct perf_session *session, size_t nmemb, siz= e_t size) +{ + void *ptr =3D calloc(nmemb, size); + + if (unlikely(!ptr && nmemb !=3D 0 && size !=3D 0) && perf_session__try_sh= rink(session)) + ptr =3D calloc(nmemb, size); + + return ptr; +} + +void *perf_session__realloc(struct perf_session *session, void *ptr, size_= t size) +{ + void *new_ptr =3D realloc(ptr, size); + + if (unlikely(!new_ptr && size !=3D 0) && perf_session__try_shrink(session= )) + new_ptr =3D realloc(ptr, size); + + return new_ptr; +} + +char *perf_session__strdup(struct perf_session *session, const char *s) +{ + char *dup; + + if (!s) + return NULL; + + dup =3D strdup(s); + if (unlikely(!dup) && perf_session__try_shrink(session)) + dup =3D strdup(s); + + return dup; +} diff --git a/tools/perf/util/session.h b/tools/perf/util/session.h index cbea6792a008..c6157eddcc43 100644 --- a/tools/perf/util/session.h +++ b/tools/perf/util/session.h @@ -213,4 +213,10 @@ uint16_t perf_session__e_machine(struct perf_session *= session, uint32_t *e_flags =20 size_t perf_session__shrink(struct perf_session *session); =20 +void *perf_session__malloc(struct perf_session *session, size_t size); +void *perf_session__zalloc(struct perf_session *session, size_t size); +void *perf_session__calloc(struct perf_session *session, size_t nmemb, siz= e_t size); +void *perf_session__realloc(struct perf_session *session, void *ptr, size_= t size); +char *perf_session__strdup(struct perf_session *session, const char *s); + #endif /* __PERF_SESSION_H */ --=20 2.56.1.750.gf70dc682cf-goog From nobody Tue Nov 24 11:51:44 2026 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=74.125.82.198 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1795323897; b=OqQpuoU9DW6CiJsDJcMC4my8zm+tfBtp9EJ1DOiSi8Gfgk5xC3fOgFajBJzPh3gJjF9n cRdY603lcN/rk7eFT6PAaR5rFbOs+xWJ7yYL9MZyuwCbIURnVKv0OLQ+pfBnZtMfzaf/7 wWcslYdA9H1g8Db0XY9TpBRA3nU88SjG9AARiHMJ9ZMwhah8hhIiYDSdnIGh7ka5dz6RQ l9WRsKTxTYqoZGQdotXHfqomZWdXCkdsKFlg5BcFezZwCJZ88JavdYgX/0Hcam6Vqxs9v CiILFoae16b2kvrIRTbPeDovNcVO/QkIUPvUxiy6iAQ4BYYjU/jyD5D4r1ayL0matJQ== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1795323897; h=DMARC-Filter:Received:DKIM-Signature:X-Google-DKIM-Signature: X-Forwarded-Encrypted:X-Gm-Message-State:X-Received:Date:In-Reply-To: Mime-Version:References:X-Mailer:Message-ID:Subject:From:To:Cc: Content-Type; bh=Y0V6hs42Oq2WCY+WPtJ/DQRfa1JpTYT53+R+X7aXL7M=; b=2hgCkgLT6iLs6acu4AW86P/pMYiJSL5lK9UM7PdYIRw4JEvPXL2HB3r4uvIXDDq9T8DP CJ0dsrPmoiLwr21oLDgPKXKtibdB1z+BpXh8tH/rIo/h9NwoEjLGUrJdxNr7rJgwVnI8D hBQAiP+2bCulWNxTDe0XrQcvIfX64Z5RbdT0ALe3Dxu7BympYIeilrG5kB7miHGPqagHi MMHmgFALv5ueIMT+9NsUd7+cV43jgtcIzHdxa59SDkDydAK97khhaI1ls4ndiE46XB9QC zsJrqMMncAtbFnt1CPS4qyEGsICBOtAi5HuO4mSr8VJ55XvOjWER+4K/l0nqy1gVFyg== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass header.from=google.com; spf=pass smtp.mailfrom=flex--irogers.bounces.google.com; dkim=pass header.d=google.com header.i=@google.com header.a=rsa-sha256 header.s=20260707 header.b=kWnWbrUY; arc=none smtp.remote-ip=74.125.82.198 Received: from mail-dy1-f198.google.com (mail-dy1-f198.google.com [74.125.82.198]) (using TLSv1.3 with cipher TLS_AES_128_GCM_SHA256 (128/128 bits) key-exchange X25519 server-signature ECDSA (prime256v1) server-digest SHA256) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id B1F24606A32A for ; Sun, 22 Nov 2026 05:04:56 +0000 (UTC) DMARC-Filter: OpenDMARC Filter v1.4.2 smtp.subspace.kernel.org B1F24606A32A Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=flex--irogers.bounces.google.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.a=rsa-sha256 header.s=20260707 header.b=kWnWbrUY Received: by mail-dy1-f198.google.com with SMTP id 5a478bee46e88-386177b0516so6165087eec.1 for ; Sat, 21 Nov 2026 21:04:56 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20260707; t=1795323896; x=1795928696; darn=vger.kernel.org; h=content-type:cc:to:from:subject:message-id:references:mime-version :in-reply-to:date:from:to:cc:subject:date:message-id:reply-to :content-type; bh=Y0V6hs42Oq2WCY+WPtJ/DQRfa1JpTYT53+R+X7aXL7M=; b=kWnWbrUYpJdroHGGP9a3D9l3ZjpMDIDC6FJVPm4inMRuPJePQPDZTKejeDuhJAHmeT uGKuZ9bCRndx8v3e5WwpXc6QZseIPd+M2hFUfcBc3dDXq5vxnO/SwDF8gyS73q4FVojE rd9vYfYQQPeE5d1ukGNgh7dLWKt76R6C830XONF/eHHIb8st4iSCPssCZprrTI0IsTw6 IAQsWd7iC7qb4KFzBOv+x16DUILHA6vW/k6YMD+GuAxMPrvS/1CjlAtvUeZuXSVQsc10 akdKW60vXxHxc1QArzjqdJ+3kSSs0OjLPrT4U8fkmbV07E9KbYsRtY7tJQKsdt0p/Ceu sjtA== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20260707; t=1795323896; x=1795928696; h=content-type:cc:to:from:subject:message-id:references:mime-version :in-reply-to:date:x-gm-message-state:from:to:cc:subject:date :message-id:reply-to:content-type; bh=Y0V6hs42Oq2WCY+WPtJ/DQRfa1JpTYT53+R+X7aXL7M=; b=J/5p1D6RGIb5ogdTlCEY8o4Z5stvqKO/4WWe7ZNbxZYkrSVm9uJBCKMyr+PwPwElnX Fe4LUkjm/QFumeGG2pMWBIqLptlg/9u5iUfSf14kwIsTT+TY488KaWTp4tbK1vOk3bmz Wod6cBnQKPVjnTlKHL68PFnqqMd0xdQHq6N1fX3ufK6j0Fb3Lxzuta9J6cMSpclJLFKp hTkpqSkaIYcx1BTbNHCzsT2ors2B/EBQd65uKproCZ4sudBKM1MJXAiW8hApE3Bq7/9h u/7T3v/kAlyvLUzAnLr/tCMs7v4wlqFacAbPaosL2JPYHyKnlMA3QQHmOtkNiMcJKwJv qmuw== X-Forwarded-Encrypted: i=1; AL+hErHlbhXo6fWMorr68cXXUxcahll0U34ZyDVqrTDRwx39W52kXiLGpq+jbfk9wF4QO8TdPEIl/XMYqNYhOFA=@vger.kernel.org X-Gm-Message-State: APuU4Z/IBr2j2C9urnUKjmDb7AFuBjSaGiW4Qi7ioLR2+gLnyXBcWcOj 26fzhiVZK7AfjFnJsof5vABM00Hmfd14wsrFqDaZ59KkhuZGz9mEqWrzxIdNuM/VgOtsv7VOdHX PxbBEkb/HrQ== X-Received: from dybmx4.prod.google.com ([2002:a05:7300:d404:b0:368:2c6d:de10]) (user=irogers job=prod-delivery.src-stubby-dispatcher) by 2002:a05:7301:6407:b0:386:2300:db04 with SMTP id 5a478bee46e88-38623101ee2mr7610537eec.22.1795323895456; Sat, 21 Nov 2026 21:04:55 -0800 (PST) Date: Sat, 21 Nov 2026 21:04:05 -0800 In-Reply-To: <20261122050405.80335-1-irogers@google.com> X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Post: List-Help: List-Subscribe: List-Unsubscribe: List-Owner: Precedence: list Mime-Version: 1.0 References: <20261122050405.80335-1-irogers@google.com> X-Mailer: git-send-email 2.56.1.750.gf70dc682cf-goog Message-ID: <20261122050405.80335-11-irogers@google.com> Subject: [PATCH v8 10/10] perf test symbols: Add tests for symbol shrinking and session alloc wrappers From: Ian Rogers To: Namhyung Kim , Arnaldo Carvalho de Melo , Alireza Haghdoost , Ian Rogers Cc: Peter Zijlstra , Ingo Molnar , Jiri Olsa , Adrian Hunter , James Clark , linux-perf-users@vger.kernel.org, linux-kernel@vger.kernel.org Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" Ensure the new symbol sorting, DSO-lifetime symbol and DSO shrinking, dso_symbol reference pinning, on-demand DSO reload after unreferenced eviction, and session-scoped allocation wrappers are verified by 'perf test symbols' (including under REFCNT_CHECKING=3D1). Add unit tests to 'perf test symbols' covering: - test_symbols_sorted_insert(): Verify ascending symbols__insert(), out-of-order dso__insert_symbol() maintaining sorted order, and unsorted symbols__insert() followed by sort-on-lookup in dso__find_symbol(). - test_symbols_shrink(): Verify symbols__shrink() reclaims the secondary symbols_by_name index and trims unused capacity in symbols->symbols while keeping live symbols intact, and verify symbols__try_delete_unannotated() preserves annotated symbol tables. - test_dsos_shrink(): Verify dsos__shrink() evicts unreferenced user DSOs while retaining DSOs with active external references and vDSOs. - test_session_alloc_shrink(): Verify machine__session(), dso__session(), perf_session__malloc/zalloc/calloc/realloc/strdup(), and perf_session__shrink(). - test_dso_shrink_and_reload(): Verify dso__shrink() on a referenced ELF DSO reclaims auxiliary buffers while preserving symbol pointers, dso_symbol__copy() pins DSO symbols across dsos__shrink() until dso_symbol__exit(), and dsos__shrink() on an unreferenced hit DSO evicts its symbol table and transparently reloads it on a subsequent map__find_symbol(). Signed-off-by: Ian Rogers --- tools/perf/tests/symbols.c | 790 ++++++++++++++++++++++++++++++++++++- 1 file changed, 779 insertions(+), 11 deletions(-) diff --git a/tools/perf/tests/symbols.c b/tools/perf/tests/symbols.c index b73da581f895..85d7bfd897c3 100644 --- a/tools/perf/tests/symbols.c +++ b/tools/perf/tests/symbols.c @@ -1,20 +1,34 @@ // SPDX-License-Identifier: GPL-2.0 #include +#include #include +#include #include #include +#include #include #include +#include +#include +#include +#include +#include #include +#include #include +#include "annotate.h" #include "debug.h" #include "dso.h" #include "env.h" #include "machine.h" +#include "session.h" +#include "srcline.h" #include "thread.h" #include "symbol.h" #include "map.h" +#include "map_symbol.h" #include "util.h" +#include "vdso.h" #include "tests.h" =20 struct test_info { @@ -182,6 +196,496 @@ static int process_subdivided_dso(struct machine *mac= hine, struct dso *dso) return ret < 0 ? TEST_FAIL : TEST_OK; } =20 +static int noop_visit_cb(struct symbol *sym __maybe_unused, void *data __m= aybe_unused) +{ + return 0; +} + +static int test_symbols_shrink(void) + __context_unsafe(/* single-threaded white-box test */) +{ + struct symbols symbols; + struct symbol *sym1, *sym2, *sym3; + int ret =3D TEST_FAIL; + + symbols__init(&symbols); + + sym1 =3D symbol__new(0x100, 0x50, STB_GLOBAL, STT_FUNC, "sym1"); + sym2 =3D symbol__new(0x200, 0x50, STB_GLOBAL, STT_FUNC, "sym2"); + sym3 =3D symbol__new(0x300, 0x50, STB_GLOBAL, STT_FUNC, "sym3"); + if (!sym1 || !sym2 || !sym3) { + symbol__delete(sym1); + symbol__delete(sym2); + symbol__delete(sym3); + goto out; + } + + symbols__insert(&symbols, sym1); + symbols__insert(&symbols, sym2); + symbols__insert(&symbols, sym3); + symbols__visit_by_name(&symbols, noop_visit_cb, NULL); + if (!symbols.symbols_by_name || symbols.allocated <=3D symbols.cnt) { + pr_debug("Expected populated symbols_by_name and excess capacity!\n"); + goto out; + } + + /* + * First shrink: reclaims symbols_by_name and trims excess capacity in + * symbols.symbols while keeping all 3 symbols intact. + */ + if (symbols__shrink(&symbols) !=3D 2 || symbols.cnt !=3D 3 || + symbols.allocated !=3D 3 || symbols.symbols_by_name !=3D NULL) { + pr_debug("First symbols__shrink failed (cnt=3D%u, allocated=3D%u)!\n", + symbols.cnt, symbols.allocated); + goto out; + } + + /* + * Second shrink with no symbols_by_name and no excess capacity is a no-o= p. + */ + if (symbols__shrink(&symbols) !=3D 0 || symbols.cnt !=3D 3) { + pr_debug("Second symbols__shrink failed (cnt=3D%u)!\n", symbols.cnt); + goto out; + } + + /* + * Verify symbols__try_delete_unannotated() skips deletion when any + * symbol has an entry in the annotations hashmap and deletes all + * symbols once unannotated. + */ + if (!symbol__annotation(sym1) || !symbol__annotated(sym1)) { + pr_debug("symbol__annotation(sym1) failed!\n"); + goto out; + } + if (symbols__try_delete_unannotated(&symbols, NULL, NULL) || symbols.cnt = !=3D 3) { + pr_debug("symbols__try_delete_unannotated deleted annotated table!\n"); + goto out; + } + symbol__annotation_delete(sym1); + if (symbol__annotated(sym1) || + !symbols__try_delete_unannotated(&symbols, NULL, NULL) || + symbols.cnt !=3D 0) { + pr_debug("symbols__try_delete_unannotated failed after clearing annotati= on!\n"); + goto out; + } + + ret =3D TEST_OK; +out: + symbols__exit(&symbols); + return ret; +} + +static int test_dsos_shrink(void) + __context_unsafe(/* single-threaded white-box test */) +{ + struct dsos dsos; + struct dso *dso1, *dso2, *vdso; + int ret =3D TEST_FAIL; + + dsos__init(&dsos); + + dso1 =3D dsos__findnew_id(&dsos, "/tmp/perf_test_dso1", NULL); + dso2 =3D dsos__findnew_id(&dsos, "/tmp/perf_test_dso2", NULL); + vdso =3D dsos__findnew_id(&dsos, DSO__NAME_VDSO, NULL); + if (!dso1 || !dso2 || !vdso) { + dso__put(dso1); + dso__put(dso2); + dso__put(vdso); + goto out; + } + + /* + * Keep the caller's active reference on dso1; drop caller references on + * dso2 and vdso. + */ + dso__put(dso2); + dso__put(vdso); + + /* + * First shrink: dso2 has refcnt =3D=3D 1 and no symbols, so it is evicte= d; + * dso1 (refcnt =3D=3D 2) and vdso (dso__is_vdso() =3D=3D true) are retai= ned. + */ + if (dsos__shrink(&dsos) !=3D 1 || dsos.cnt !=3D 2) { + pr_debug("First dsos__shrink failed (cnt=3D%u)!\n", dsos.cnt); + dso__put(dso1); + goto out; + } + + dso__put(dso1); + if (dsos__shrink(&dsos) !=3D 1 || dsos.cnt !=3D 1 || !dso__is_vdso(dsos.d= sos[0])) { + pr_debug("Second dsos__shrink failed (cnt=3D%u)!\n", dsos.cnt); + goto out; + } + + ret =3D TEST_OK; +out: + dsos__exit(&dsos); + return ret; +} + +struct shrink_lock_race_args { + struct dso *dso; + atomic_bool stop; +}; + +static void *shrink_lock_race_worker(void *arg) +{ + struct shrink_lock_race_args *args =3D arg; + + while (!atomic_load_explicit(&args->stop, memory_order_relaxed)) + dso__find_binary_type(args->dso); + + return NULL; +} + +static int test_session_alloc_shrink(void) +{ + struct perf_session *session =3D zalloc(sizeof(*session)); + struct dso *dso; + struct thread *th; + pid_t pid =3D getpid(); + char *p1 =3D NULL, *p2 =3D NULL, *p3 =3D NULL, *s =3D NULL, *tmp; + int ret =3D TEST_FAIL; + + if (!session) + return TEST_FAIL; + + perf_env__init(&session->header.env); + if (machines__init(&session->machines, session)) + goto out; + session->machines.host.env =3D &session->header.env; + if (machine__session(&session->machines.host) !=3D session) { + pr_debug("machine__session did not return owning session!\n"); + goto out; + } + + dso =3D machine__findnew_dso(&session->machines.host, "/tmp/perf_test_ses= sion_dso"); + if (!dso) + goto out; + if (dso__session(dso) !=3D session) { + pr_debug("dso__session did not return owning session!\n"); + dso__put(dso); + goto out; + } + dso__put(dso); + + p1 =3D perf_session__malloc(session, 64); + p2 =3D perf_session__zalloc(session, 64); + p3 =3D perf_session__calloc(session, 4, 16); + s =3D perf_session__strdup(session, "perf_session_alloc_test"); + if (!p1 || !p2 || !p3 || !s || strcmp(s, "perf_session_alloc_test") !=3D = 0) { + pr_debug("perf_session allocation wrappers failed!\n"); + goto out; + } + + tmp =3D perf_session__realloc(session, p1, 128); + if (!tmp) { + pr_debug("perf_session__realloc failed!\n"); + goto out; + } + p1 =3D tmp; + + if (perf_session__shrink(session) =3D=3D 0) { + pr_debug("perf_session__shrink failed to evict unreferenced DSO!\n"); + goto out; + } + down_read(&session->machines.host.dsos.lock); + if (session->machines.host.dsos.cnt !=3D 0) { + up_read(&session->machines.host.dsos.lock); + pr_debug("perf_session__shrink failed to evict unreferenced DSO!\n"); + goto out; + } + up_read(&session->machines.host.dsos.lock); + + /* + * Regression test for AB-BA lock inversion between dso__lock(dso_A) + * (held by dso__load() when calling perf_session__shrink() to evict + * unreferenced dso_B) and dso__data_open_lock (acquired before + * dso__lock(dso_A) by dso__find_binary_type()). + */ + dso =3D machine__findnew_dso(&session->machines.host, "/tmp/perf_test_con= tended_dso"); + if (!dso) + goto out; + { + bool was_singlethreaded =3D perf_singlethreaded; + struct shrink_lock_race_args race_args =3D { + .dso =3D dso, + .stop =3D false, + }; + pthread_t worker; + + perf_set_multithreaded(); + if (pthread_create(&worker, NULL, shrink_lock_race_worker, &race_args) != =3D 0) { + if (was_singlethreaded) + perf_set_singlethreaded(); + dso__put(dso); + goto out; + } + for (int i =3D 0; i < 200; i++) { + struct dso *evict =3D machine__findnew_dso(&session->machines.host, + "/tmp/perf_test_evict_dso"); + + dso__put(evict); + mutex_lock(dso__lock(dso)); + RC_CHK_ACCESS(dso)->bintype_searched =3D 0; + perf_session__shrink(session); + mutex_unlock(dso__lock(dso)); + } + atomic_store_explicit(&race_args.stop, true, memory_order_relaxed); + pthread_join(worker, NULL); + if (was_singlethreaded) + perf_set_singlethreaded(); + } + dso__put(dso); + perf_session__shrink(session); + + /* + * Verify perf_session__e_machine() -> threads__for_each_thread() does + * not self-deadlock on table->lock when a non-leader thread looks up or + * creates its leader thread in the same shard. + */ + { + bool was_singlethreaded =3D perf_singlethreaded; + uint16_t e_machine; + + perf_set_multithreaded(); + th =3D machine__findnew_thread(&session->machines.host, pid, + pid + THREADS__TABLE_SIZE); + if (!th) { + if (was_singlethreaded) + perf_set_singlethreaded(); + goto out; + } + thread__put(th); + e_machine =3D perf_session__e_machine(session, NULL); + if (was_singlethreaded) + perf_set_singlethreaded(); + if (e_machine =3D=3D EM_NONE) { + pr_debug("perf_session__e_machine failed!\n"); + goto out; + } + } + + ret =3D TEST_OK; +out: + free(p1); + free(p2); + free(p3); + free(s); + machines__exit(&session->machines); + perf_env__exit(&session->header.env); + free(session); + return ret; +} + +struct shrink_reload_find_args { + struct symbol *kept; + u64 first_start; + u64 second_start; + char *second_name; + u64 max_end; +}; + +static int shrink_reload_find_cb(struct symbol *sym, void *data) +{ + struct shrink_reload_find_args *args =3D data; + + if (!args->kept) { + args->kept =3D sym; + args->first_start =3D sym->start; + args->max_end =3D sym->end; + return 0; + } + if (!args->second_name && sym->start >=3D args->max_end) { + args->second_start =3D sym->start; + args->second_name =3D strdup(sym->name); + if (!args->second_name) + return -ENOMEM; + } + if (sym->end > args->max_end) + args->max_end =3D sym->end; + return 0; +} + +static int test_dso_shrink_and_reload(struct test_info *ti, char *filename= , struct map **map_p) + __context_unsafe(/* single-threaded white-box test */) +{ + struct shrink_reload_find_args args =3D { + .kept =3D NULL, + .first_start =3D 0, + .second_start =3D 0, + .second_name =3D NULL, + .max_end =3D 0, + }; + struct map *map =3D *map_p; + struct dso *dso =3D map__dso(map); + struct symbols *syms =3D dso__symbols(dso); + struct symbol *sym, *reloaded; + unsigned int initial_cnt; + + if (!dso__can_shrink_symbols(dso) || dso__kernel(dso)) + return TEST_SKIP; + initial_cnt =3D syms->cnt; + if (dso__for_each_symbol(dso, shrink_reload_find_cb, &args) < 0) + return TEST_FAIL; + if (!args.second_name) + return TEST_SKIP; + + /* + * While dso is referenced by map (refcnt > 1), dso__shrink() reclaims + * auxiliary buffers (such as symbols_by_name) while keeping all symbols + * and their pointers valid. + */ + dso__sort_by_name(dso); + if (syms->num_by_name < 2) { + free(args.second_name); + return TEST_FAIL; + } + { + size_t idx =3D 0; + struct symbol *expected_next =3D syms->symbols_by_name[1]; + u8 hdr_byte =3D 0; + + /* Populate dso data fd and cache so dso__shrink() reclaims them too. */ + (void)dso__data_read_offset(dso, ti->machine, 0, &hdr_byte, 1); + + if (dso__shrink(dso) =3D=3D 0 || syms->cnt !=3D initial_cnt || + syms->symbols_by_name !=3D NULL || dso__data(dso)->fd >=3D 0) { + pr_debug("dso__shrink on referenced DSO failed!\n"); + free(args.second_name); + return TEST_FAIL; + } + if (dso__next_symbol_by_name(dso, &idx) !=3D expected_next || idx !=3D 1= ) { + pr_debug("dso__next_symbol_by_name failed to rebuild symbols_by_name!\n= "); + free(args.second_name); + return TEST_FAIL; + } + dso__shrink(dso); + } + + sym =3D dso__find_symbol(dso, args.first_start); + if (sym !=3D args.kept) { + pr_debug("Symbol pointer changed after dso__shrink on referenced DSO!\n"= ); + free(args.second_name); + return TEST_FAIL; + } + + /* + * Verify struct dso_symbol retains a reference on its owning DSO even + * after the map reference is dropped, preventing dsos__shrink() from + * evicting the DSO's symbol table until dso_symbol__exit() is called. + */ + dso__set_hit(dso); + { + struct dso_symbol src =3D { + .dso =3D dso, + .sym =3D args.kept, + }; + struct dso_symbol pinned; + struct inline_node *inode; + struct symbol *inlined_sym; + char *srcline; + + dso_symbol__copy(&pinned, &src); + map__zput(*map_p); + dsos__shrink(&ti->machine->dsos); + if (!dso__loaded(pinned.dso) || + dso__symbols(pinned.dso)->cnt !=3D initial_cnt || + dso__find_symbol(pinned.dso, args.first_start) !=3D pinned.sym) { + pr_debug("dso_symbol failed to pin DSO symbols across dsos__shrink!\n"); + dso_symbol__exit(&pinned); + free(args.second_name); + return TEST_FAIL; + } + + /* + * Populate dso->inlined_nodes (referencing both a base symbol + * from dso->symbols and an owned inlined symbol) and + * dso->srclines so dsos__shrink() exercises freeing inlines + * before freeing the underlying symbol table. + */ + inode =3D zalloc(sizeof(*inode)); + inlined_sym =3D new_inline_sym(pinned.dso, pinned.sym, "inlined_helper"); + srcline =3D strdup("test.c:1"); + if (!inode || !inlined_sym || !srcline) { + free(inode); + if (inlined_sym && symbol__inlined(inlined_sym)) + symbol__delete(inlined_sym); + free(srcline); + dso_symbol__exit(&pinned); + free(args.second_name); + return TEST_FAIL; + } + inode->addr =3D args.first_start; + INIT_LIST_HEAD(&inode->val); + if (inline_list__append(inlined_sym, SRCLINE_UNKNOWN, inode) < 0) { + if (symbol__inlined(inlined_sym)) + symbol__delete(inlined_sym); + inline_node__delete(inode); + free(srcline); + dso_symbol__exit(&pinned); + free(args.second_name); + return TEST_FAIL; + } + if (inline_list__append(pinned.sym, SRCLINE_UNKNOWN, inode) < 0) { + inline_node__delete(inode); + free(srcline); + dso_symbol__exit(&pinned); + free(args.second_name); + return TEST_FAIL; + } + inlines__tree_insert(dso__inlined_nodes(pinned.dso), inode); + srcline__tree_insert(dso__srclines(pinned.dso), args.first_start, srclin= e); + dso_symbol__exit(&pinned); + } + + if (dsos__shrink(&ti->machine->dsos) =3D=3D 0) { + pr_debug("dsos__shrink did not reclaim unreferenced DSO symbols!\n"); + free(args.second_name); + return TEST_FAIL; + } + + if (create_map(ti, filename, map_p) !=3D TEST_OK) { + free(args.second_name); + return TEST_FAIL; + } + map =3D *map_p; + dso =3D map__dso(map); + syms =3D dso__symbols(dso); + if (!dso__hit(dso) || syms->cnt !=3D 0 || dso__loaded(dso) || + inlines__tree_find(dso__inlined_nodes(dso), args.first_start) !=3D NU= LL || + srcline__tree_find(dso__srclines(dso), args.first_start) !=3D NULL) { + pr_debug("Unreferenced hit DSO state mismatch after dsos__shrink!\n"); + free(args.second_name); + return TEST_FAIL; + } + + /* Lookup via map__find_symbol transparently reloads the DSO. */ + reloaded =3D map__find_symbol(map, args.second_start); + if (!reloaded || strcmp(reloaded->name, args.second_name) !=3D 0) { + pr_debug("Failed to reload evicted symbol %s!\n", args.second_name); + free(args.second_name); + return TEST_FAIL; + } + + if (syms->cnt !=3D initial_cnt || !syms->sorted || !dso__loaded(dso)) { + pr_debug("Reloaded symbol table state mismatch (cnt=3D%u vs %u, sorted= =3D%d, loaded=3D%d)!\n", + syms->cnt, initial_cnt, syms->sorted, dso__loaded(dso)); + free(args.second_name); + return TEST_FAIL; + } + for (unsigned int i =3D 1; i < syms->cnt; i++) { + if (syms->symbols[i - 1]->start > syms->symbols[i]->start) { + pr_debug("Reloaded symbols out of order at %u!\n", i); + free(args.second_name); + return TEST_FAIL; + } + } + + free(args.second_name); + return TEST_OK; +} + static int test_file(struct test_info *ti, char *filename) { struct map *map =3D NULL; @@ -213,18 +717,272 @@ static int test_file(struct test_info *ti, char *fil= ename) /* Module dso is split into many dsos by section */ if (ret =3D=3D TEST_OK && dso__kernel(dso) !=3D DSO_SPACE__USER) ret =3D process_subdivided_dso(ti->machine, dso); + + if (ret =3D=3D TEST_OK) { + int shrink_ret =3D test_dso_shrink_and_reload(ti, filename, &map); + + if (shrink_ret !=3D TEST_SKIP) + ret =3D shrink_ret; + } out_put: map__put(map); =20 return ret; } =20 +static int test_symbols_sorted_insert(void) + __context_unsafe(/* single-threaded white-box test */) +{ + struct dso *dso =3D dso__new("/tmp/perf_test_sorted_insert"); + struct symbols *symbols; + int ret =3D TEST_FAIL; + + if (!dso) + return TEST_FAIL; + + symbols =3D dso__symbols(dso); + + /* + * Insert 100 odd-indexed symbols in ascending order via + * symbols__insert(), then insert 5 even-indexed symbols out of order via + * dso__insert_symbol() and verify symbols->sorted remains true. + */ + for (unsigned int i =3D 0; i < 100; i++) { + char name[32]; + u64 addr =3D (u64)(i * 2 + 1) * 0x100; + struct symbol *sym; + + snprintf(name, sizeof(name), "sym_%u", i * 2 + 1); + sym =3D symbol__new(addr, 0x40, STB_GLOBAL, STT_FUNC, name); + if (!sym || symbols__insert(symbols, sym)) + goto out; + } + if (!symbols->sorted || symbols->cnt !=3D 100) { + pr_debug("Expected sorted=3Dtrue, cnt=3D100 after ordered inserts\n"); + goto out; + } + + for (unsigned int i =3D 0; i < 5; i++) { + char name[32]; + u64 addr =3D (u64)(i * 20) * 0x100; + struct symbol *sym; + + snprintf(name, sizeof(name), "ins_%u", i * 20); + sym =3D symbol__new(addr, 0x40, STB_GLOBAL, STT_FUNC, name); + if (!sym || dso__insert_symbol(dso, sym)) + goto out; + if (!symbols->sorted) { + pr_debug("dso__insert_symbol did not preserve sorted invariant!\n"); + goto out; + } + } + + /* + * Now append 95 remaining even-indexed symbols in descending order via + * symbols__insert() to exercise the unsorted append + sort-on-lookup pat= h. + */ + for (unsigned int i =3D 99; i > 0; i--) { + char name[32]; + u64 addr; + struct symbol *sym; + + if ((i * 2) % 20 =3D=3D 0 && (i * 2) < 100) + continue; + addr =3D (u64)(i * 2) * 0x100; + snprintf(name, sizeof(name), "ins_%u", i * 2); + sym =3D symbol__new(addr, 0x40, STB_GLOBAL, STT_FUNC, name); + if (!sym || symbols__insert(symbols, sym)) + goto out; + } + if (symbols->sorted || symbols->cnt !=3D 200) { + pr_debug("Unexpected sorted=3D%d cnt=3D%u before lookup\n", + symbols->sorted, symbols->cnt); + goto out; + } + + for (unsigned int i =3D 0; i < 200; i++) { + u64 addr =3D (u64)i * 0x100 + 0x10; + struct symbol *sym =3D dso__find_symbol(dso, addr); + + if (!sym || sym->start !=3D (u64)i * 0x100) { + pr_debug("Lookup failed at idx %u (addr=3D%#" PRIx64 ")\n", i, addr); + goto out; + } + } + + /* + * Insert dynamic symbols into the unmerged sorted tail and verify + * lookups match merged-array semantics in all prefix/tail overlap and + * equal-start cases: + * - [0x0, 0x40) in prefix + [0x20, 0x30) in tail: 0x24 -> inner, + * 0x34 -> NULL (closer tail start shadows outer prefix symbol). + * - [0x100, 0x140) in prefix + [0x80, 0x180) in tail: 0x150 -> NULL + * (closer prefix start shadows outer tail symbol). + * - [0x200, 0x240) in prefix + [0x200, 0x260) in tail: 0x250 -> alias + * (equal-start group spans prefix and tail). + */ + { + struct symbol *inner =3D symbol__new(0x20, 0x10, STB_GLOBAL, STT_FUNC, + "inner_tail_sym"); + struct symbol *outer =3D symbol__new(0x80, 0x100, STB_GLOBAL, STT_FUNC, + "outer_tail_sym"); + struct symbol *alias =3D symbol__new(0x200, 0x60, STB_GLOBAL, STT_FUNC, + "longer_tail_alias"); + + if (!inner || dso__insert_symbol(dso, inner)) { + symbol__delete(outer); + symbol__delete(alias); + goto out; + } + if (!outer || dso__insert_symbol(dso, outer)) { + symbol__delete(alias); + goto out; + } + if (!alias || dso__insert_symbol(dso, alias)) + goto out; + if (symbols->sorted_cnt >=3D symbols->cnt) { + pr_debug("Expected unmerged sorted tail!\n"); + goto out; + } + if (dso__find_symbol(dso, 0x24) !=3D inner || + dso__find_symbol(dso, 0x34) !=3D NULL || + dso__find_symbol(dso, 0x150) !=3D NULL || + dso__find_symbol(dso, 0x250) !=3D alias) { + pr_debug("Unmerged tail lookup mismatch!\n"); + goto out; + } + symbols__sort_read_lock(symbols); + up_read(&symbols->lock); + if (dso__find_symbol(dso, 0x24) !=3D inner || + dso__find_symbol(dso, 0x34) !=3D NULL || + dso__find_symbol(dso, 0x150) !=3D NULL || + dso__find_symbol(dso, 0x250) !=3D alias) { + pr_debug("Merged lookup mismatch!\n"); + goto out; + } + } + + ret =3D TEST_OK; +out: + dso__put(dso); + return ret; +} + +static int test_symbols_equal_start_aliases(void) +{ + struct dso *dso =3D dso__new("/tmp/perf_test_equal_start_aliases"); + struct map *map =3D NULL; + struct symbols *symbols; + struct symbol *sized_sym, *zero_alias, *last_sized, *last_short, *found; + int ret =3D TEST_FAIL; + + if (!dso) + return TEST_FAIL; + + map =3D map__new2(0, dso); + if (!map) + goto out; + + symbols =3D dso__symbols(dso); + sized_sym =3D symbol__new(0x1000, 0x40, STB_GLOBAL, STT_FUNC, "sized_sym"= ); + zero_alias =3D symbol__new(0x1000, 0, STB_GLOBAL, STT_FUNC, "zero_alias"); + last_sized =3D symbol__new(0x2000, 0x80, STB_GLOBAL, STT_FUNC, "last_size= d"); + if (!sized_sym || !zero_alias || !last_sized) { + symbol__delete(sized_sym); + symbol__delete(zero_alias); + symbol__delete(last_sized); + goto out; + } + + if (symbols__insert(symbols, sized_sym)) { + symbol__delete(zero_alias); + symbol__delete(last_sized); + goto out; + } + if (symbols__insert(symbols, zero_alias)) { + symbol__delete(last_sized); + goto out; + } + if (symbols__insert(symbols, last_sized)) + goto out; + + /* + * With 3 entries [0x1000..0x1040, 0x1000..0x1000, 0x2000..0x2080], a + * lookup at 0x1020 must rewind past the trailing zero-length alias at + * 0x1000 and find sized_sym. + */ + found =3D dso__find_symbol(dso, 0x1020); + if (found !=3D sized_sym) { + pr_debug("Expected sized_sym at 0x1020, got %s\n", + found ? found->name : "NULL"); + goto out; + } + + /* + * symbols__fixup_end() must not inflate zero_alias to 0x2000 when + * sized_sym already provides a non-zero size at 0x1000. + */ + symbols__fixup_end(symbols, /*is_kallsyms=3D*/false); + if (zero_alias->end !=3D 0x1000) { + pr_debug("zero_alias inflated to %#" PRIx64 "\n", zero_alias->end); + goto out; + } + symbols__fixup_duplicate(symbols); + found =3D dso__find_symbol(dso, 0x1020); + if (found !=3D sized_sym || found->end !=3D 0x1040) { + pr_debug("After dedup expected sized_sym [0x1000, 0x1040), got %s\n", + found ? found->name : "NULL"); + goto out; + } + + /* + * Append a shorter alias at the final start address 0x2000 (as when + * symbol_conf.allow_aliases is set) and verify map__fixup_end() uses + * the maximum end across the equal-start group. + */ + last_short =3D symbol__new(0x2000, 0x10, STB_WEAK, STT_FUNC, "last_short"= ); + if (!last_short || symbols__insert(symbols, last_short)) + goto out; + + map__fixup_end(map); + if (map__end(map) !=3D 0x2080) { + pr_debug("Expected map end 0x2080, got %#" PRIx64 "\n", map__end(map)); + goto out; + } + + ret =3D TEST_OK; +out: + map__put(map); + dso__put(dso); + return ret; +} + static int test__symbols(struct test_suite *test __maybe_unused, int subte= st __maybe_unused) { char filename[PATH_MAX]; struct test_info ti; int ret; =20 + ret =3D test_symbols_sorted_insert(); + if (ret !=3D TEST_OK) + return ret; + + ret =3D test_symbols_equal_start_aliases(); + if (ret !=3D TEST_OK) + return ret; + + ret =3D test_symbols_shrink(); + if (ret !=3D TEST_OK) + return ret; + + ret =3D test_dsos_shrink(); + if (ret !=3D TEST_OK) + return ret; + + ret =3D test_session_alloc_shrink(); + if (ret !=3D TEST_OK) + return ret; + ret =3D init_test_info(&ti); if (ret !=3D TEST_OK) return ret; @@ -240,24 +998,28 @@ static int test__symbols(struct test_suite *test __ma= ybe_unused, int subtest __m =20 struct kallsyms_sym { u64 start; + u8 binding; const char *name; }; =20 /* * kallsyms from an x86 host where nf_tables was loaded in the page right * after the last symbol of dca, plus a kernel symbol followed closely by a - * module and a module far away from the others. + * module, a weak/global alias pair at the same address, and a module far + * away from the others. */ static const struct kallsyms_sym kallsyms_syms[] =3D { - { 0xffffffff81000000, "_stext" }, - { 0xffffffff81000ff0, "last_kernel_symbol" }, - { 0xffffffff81001000, "near_module_symbol\t[near]" }, - { 0xffffffffc0c4aa40, "dca_exit\t[dca]" }, - { 0xffffffffc0c4aa50, "dca_sysfs_exit\t[dca]" }, - { 0xffffffffc0c4b000, "__nft_trace_packet\t[nf_tables]" }, - { 0xffffffffc0c4b0b0, "nft_do_chain\t[nf_tables]" }, - { 0xffffffffc0c4b4e0, "nf_tables_core_module_exit\t[nf_tables]" }, - { 0xffffffffc2000000, "far_module_symbol\t[far]" }, + { 0xffffffff81000000, STB_GLOBAL, "_stext" }, + { 0xffffffff81000500, STB_WEAK, "weak_alias_symbol" }, + { 0xffffffff81000500, STB_GLOBAL, "global_target_symbol" }, + { 0xffffffff81000ff0, STB_GLOBAL, "last_kernel_symbol" }, + { 0xffffffff81001000, STB_GLOBAL, "near_module_symbol\t[near]" }, + { 0xffffffffc0c4aa40, STB_GLOBAL, "dca_exit\t[dca]" }, + { 0xffffffffc0c4aa50, STB_GLOBAL, "dca_sysfs_exit\t[dca]" }, + { 0xffffffffc0c4b000, STB_GLOBAL, "__nft_trace_packet\t[nf_tables]" }, + { 0xffffffffc0c4b0b0, STB_GLOBAL, "nft_do_chain\t[nf_tables]" }, + { 0xffffffffc0c4b4e0, STB_GLOBAL, "nf_tables_core_module_exit\t[nf_tables= ]" }, + { 0xffffffffc2000000, STB_GLOBAL, "far_module_symbol\t[far]" }, }; =20 static int check_symbol(struct dso *dso, u64 addr, const char *name, u64 e= nd) @@ -287,7 +1049,8 @@ static int test__kallsyms_fixup_end(struct test_suite = *test __maybe_unused, return TEST_FAIL; =20 for (unsigned int i =3D 0; i < ARRAY_SIZE(kallsyms_syms); i++) { - struct symbol *sym =3D symbol__new(kallsyms_syms[i].start, 0, 0, 0, + struct symbol *sym =3D symbol__new(kallsyms_syms[i].start, 0, + kallsyms_syms[i].binding, STT_FUNC, kallsyms_syms[i].name); =20 if (!sym) @@ -296,8 +1059,13 @@ static int test__kallsyms_fixup_end(struct test_suite= *test __maybe_unused, } =20 symbols__fixup_end(dso__symbols(dso), true); + symbols__fixup_duplicate(dso__symbols(dso)); =20 ret =3D TEST_OK; + /* Same-address weak/global alias pair resolves to global_target_symbol. = */ + if (check_symbol(dso, 0xffffffff81000510, "global_target_symbol", + 0xffffffff81000ff0)) + ret =3D TEST_FAIL; /* The next symbol is too close for the end of the page. */ if (check_symbol(dso, 0xffffffff81000ff8, "last_kernel_symbol", 0xffffffff81001000)) --=20 2.56.1.750.gf70dc682cf-goog