perf symbol: Sorted arrays, DSO-owned lifetimes, and memory shrinking
Ian Rogers
reviewerv8 cover perf symbol: Sorted arrays, DSO-owned lifetimes, and memory shrinking
When profiling large binaries or long-running workloads with many DSOs and threads, symbol and DSO tables frequently dominate perf's memory footprint and startup latency. Currently struct symbol still has several structural limitations:
1. Every struct symbol embeds a 24-byte struct rb_node for the dso->symbols address rbtree, scattering lookups across non-contiguous heap nodes.
2. dso__symbols() has no internal synchronization against concurrent readers/writers, and unreferenced DSOs and auxiliary symbol/debuginfo buffers cannot yet be reclaimed under memory pressure.
3. Sorting dso->symbols with qsort() does not take advantage of pre-ordered ascending runs in ELF symbol tables, and first_ending_after() in struct maps runs a full binary search even for ascending /proc/pid/maps synthesis.
Thirteen preparatory fixes, benchmarks, dso_symbol lifetime conversions, symbol_conf.priv_size removal, and ELF header caching patches from v4-v6 have landed in perf-tools-next. The remaining 10 patches convert symbol iteration to callbacks, replace the dso->symbols rbtree with a sorted pointer array, stage natural-run merge sort and incremental symbol insertion, and add memory shrinking APIs and unit tests:
- **Preparatory fix, maps tail fast-path, and symbol iteration (Patches 1-4)**:
- Patch 1 fixes an alloc_func_regex leak on error returns in
`builtin-kmem.c`'s `build_alloc_func_list()`.
- Patch 2 adds an O(1) tail fast-path check in first_ending_after() for ascending map insertions.
- Patch 3 converts symbols__for_each_entry(), dso__for_each_symbol(), and map__for_each_symbol() to callback-based iteration and updates existing callers.
- Patch 4 converts open-coded dso__first_symbol() / dso__next_symbol(), rb_first_cached(), and dso__symbol_names() loops to callback helpers and removes dso__{first,last,next}_symbol().
- **Sorted symbol arrays and staged sorting optimizations (Patches 5-7)**:
- Patch 5 replaces dso->symbols (rb_root_cached) and dso->symbol_names with a rw_semaphore-protected struct symbols container backed by sorted pointer arrays, removing struct rb_node from struct symbol (shrinking sizeof(struct symbol) from 48 to 24 bytes, or 16 bytes net per symbol after accounting for the array pointer).
- Patch 6 replaces qsort() on struct symbols with a stable natural-run merge sort.
- Patch 7 optimizes incremental dynamic symbol insertions (dso__insert_symbol()) and small appends using @sorted_cnt and a sorted tail buffer with amortized sqrt(N) merge.
- **Memory shrinking APIs and unit tests (Patches 8-10)**:
- Patch 8 adds symbols__shrink(), dso__shrink(), dsos__shrink(),
`machine__shrink()`, `machines__shrink()`, and `perf_session__shrink()`
to reclaim `symbols_by_name`, excess array capacity, cached DSO file
descriptors/data/DWARF state, and unreferenced user DSOs (`refcnt == 1`
with no annotated symbols), with transparent on-demand reload via
`dso__load()`. - Patch 9 adds dso__session() and perf_session__malloc() / zalloc() / calloc() / realloc() / strdup() wrappers (leaving production caller wiring for follow-up once lazy symbol loading is evaluated).
- Patch 10 adds unit tests in perf test symbols covering sorted symbol insertion, equal-start aliases, symbol/DSO shrinking, dso_symbol lifetime pinning, inline frame/srcline cleanup ordering, symbols_by_name on-demand rebuild, transparent DSO reload, and session allocation wrappers.
Changes in v8:
- Rebase onto tmp.perf-tools-next (eb79d2fbc230), adopting <linux/compiler-context-analysis.h> annotations (__guarded_by(&lock), __acquires_shared(&symbols->lock), __must_hold(&symbols->lock), __context_unsafe()) on struct symbols and dso / tests/symbols.c and adapting dso__shrink() / dso__try_evict() to dso__data_open_lock and close_dso().
- Pass first_unsorted (m = symbols->sorted_cnt) to symbols__insertion_sort_range() in symbols__sort_locked() (Patch 7) so the k <= 8 small-append fast path and allocation-failure fallbacks skip scanning the already-sorted prefix [0 .. m) (Sashiko).
Changes in v7:
- Rebase onto perf-tools-next (bb27ddbaee56), dropping the 3 patches from v6 that have been applied upstream.
- Drop nr_addr_sorted and nr_name_sorted incremental partial-sort state from struct maps, keeping only the first_ending_after() tail fast-path check (Patch 2) (Namhyung Kim).
- Split out the alloc_func_regex leak fix in builtin-kmem.c (Patch 1), the map__for_each_symbol() callback conversion (Patch 3), and the conversion of open-coded symbol loops (Patch 4) ahead of the rbtree to struct symbols array conversion (Patch 5) (Namhyung Kim).
- Split symbol sorting optimization into a simple natural-run merge sort patch without galloping (Patch 6) followed by incremental dynamic symbol insertion with a sorted tail (Patch 7) (Namhyung Kim).
Changes in v6:
- Fix symbols__find() when sorted_cnt < cnt so that if the slice (sorted prefix or unmerged sorted tail) with the higher start <= ip group ends before ip, symbols__find() returns NULL rather than falling back to an earlier outer symbol in the other slice, matching post-merge behavior, and add unmerged-vs-merged prefix/tail overlap and equal-start alias unit tests (Sashiko).
- Use positive ENOMEM rather than -ENOMEM on symbol__annotation() failure in symbol__annotate(), symbol__annotate2(), and __hist_entry__tui_annotate() to match symbol__strerror_disassemble(), check symbol__annotate() != 0 in hist_entry__get_data_type(), and guard against NULL notes / notes->src in find_disasm_line() (Sashiko).
v7: https://lore.kernel.org/linux-perf-users/[email protected]/
v6: https://lore.kernel.org/linux-perf-users/[email protected]/
v5: https://lore.kernel.org/linux-perf-users/[email protected]/
v4: https://lore.kernel.org/linux-perf-users/[email protected]/
v3: https://lore.kernel.org/linux-perf-users/[email protected]/
v2: https://lore.kernel.org/linux-perf-users/[email protected]/
v1: https://lore.kernel.org/lkml/[email protected]/
AI Assistance Disclosure (per Documentation/process/coding-assistants.rst and Documentation/process/generated-content.rst):
- Tools used: Google Antigravity / Jetski coding assistant and Sashiko automated patch review (sashiko.dev and internal Sashiko).
- Summary of prompts and assistance: Interactive pair-programming session to replace per-symbol refcounting with struct dso_symbol DSO-borrowed lifetimes, split symbol callback iteration and staged natural-run merge sort / incremental insertion patches, rebase onto tmp.perf-tools-next context-analysis annotations, and address LKML reviewer and Sashiko feedback across kmem, dso, map, maps, symbol, and tests/symbols.c.
- Testing performed: Built each commit ([1/10] through [10/10]) with Clang (-DWARN_CONTEXT_ANALYSIS -Wthread-safety -Wthread-safety-pointer -Wthread-safety-beta), AddressSanitizer, LeakSanitizer, and DEBUG=1 (REFCNT_CHECKING=1); ran perf test (including Symbols, Maps, DSO data, hists, thread, and annotate suites), perf bench internals (symbols and maps), and scripts/checkpatch.pl.
Ian Rogers (10):
perf kmem: Fix alloc_func_regex leak on error in
build_alloc_func_list()
perf maps: Add tail fast-path check in first_ending_after() perf symbol: Convert map__for_each_symbol() to callback-based
iteration
perf symbol: Use callback iteration instead of open-coded symbol loops perf symbol: Switch backing storage from rbtree to struct symbols
array
perf symbol: Replace qsort() with natural-run merge sort perf symbol: Optimize incremental symbol insertion with sorted tail perf symbol: Add memory shrinking for symbols, DSOs, and machines perf session: Add dso__session() and session-scoped allocation
wrappers
perf test symbols: Add tests for symbol shrinking and session alloc
wrappers
tools/perf/arch/powerpc/util/sym-handling.c | 34 +- tools/perf/builtin-annotate.c | 11 - tools/perf/builtin-kmem.c | 51 +- tools/perf/tests/hists_common.c | 5 +- tools/perf/tests/maps.c | 46 + tools/perf/tests/symbols.c | 851 ++++++++++++++- tools/perf/tests/vmlinux-kallsyms.c | 181 ++-- tools/perf/ui/browser.c | 3 + tools/perf/ui/browsers/hists.c | 3 +- tools/perf/ui/browsers/map.c | 62 +- tools/perf/util/auxtrace.c | 109 +- tools/perf/util/db-export.c | 4 +- tools/perf/util/dso.c | 324 +++++- tools/perf/util/dso.h | 90 +- tools/perf/util/dsos.c | 51 + tools/perf/util/dsos.h | 3 + tools/perf/util/intel-pt.c | 74 +- tools/perf/util/libbfd.c | 3 +- tools/perf/util/machine.c | 60 +- tools/perf/util/machine.h | 8 + tools/perf/util/map.c | 36 +- tools/perf/util/map.h | 8 +- tools/perf/util/maps.c | 4 + tools/perf/util/probe-event.c | 98 +- tools/perf/util/session.c | 78 ++ tools/perf/util/session.h | 8 + tools/perf/util/symbol-elf.c | 12 +- tools/perf/util/symbol.c | 1042 +++++++++++++++---- tools/perf/util/symbol.h | 84 +- tools/perf/util/symbol_fprintf.c | 25 +- 30 files changed, 2706 insertions(+), 662 deletions(-)
base-commit: eb79d2fbc230d41b009e49f20671303c6efbd946
Signature · 1 line
2.56.1.750.gf70dc682cf-goog
Ian Rogers
reviewerPATCH v8 1/10 perf kmem: Fix alloc_func_regex leak on error in build_alloc_func_list()
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.
--- tools/perf/builtin-kmem.c | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-)
tools/perf/builtin-kmem.c +4 -1
@@ -364,6 +364,7 @@ static int build_alloc_func_list(void) kernel_map =machine__kernel_map (machine);if (map__load (kernel_map) <0 ) {pr_err ("cannot load kernel map\n" ); +regfree (&alloc_func_regex);return -ENOENT ; }
@@ -373,8 +374,10 @@ static int build_alloc_func_list(void) func =realloc (alloc_func_list, (nr_alloc_funcs +1 ) *sizeof (*func)); -if (func ==NULL ) +if (func ==NULL ) { +regfree (&alloc_func_regex);return -ENOMEM ; + }pr_debug ("alloc func: %s\n" , sym->name); func[nr_alloc_funcs].start = sym->start;
Signature · 1 line
2.56.1.750.gf70dc682cf-goog
Ian Rogers
reviewerPATCH v8 2/10 perf maps: Add tail fast-path check in first_ending_after()
In reply to Ian RogersUser-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)# Conflicts:
# tools/perf/tests/maps.c
--- tools/perf/tests/maps.c | 46 +++++++++++++++++++++++++++++++++++++++++ tools/perf/util/maps.c | 4 ++++ 2 files changed, 50 insertions(+)
tools/perf/tests/maps.c +46 -0
@@ -392,10 +392,56 @@ static int test__maps__remove(struct test_suite *t __maybe_unused, int subtest _return TEST_OK ; } +static int test__maps__tail_insert (struct test_suite *t__maybe_unused , +int subtest__maybe_unused ) +{ +struct map_def ascending_maps[] = { + {"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 =machine__new_live (&host_env,/*kernel_maps=*/ false,getpid ()); + maps =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 =0 ; i <ARRAY_SIZE (ascending_maps); i++) { + map =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) ==0 ); +map__put (map); + } + + ret =check_maps (ascending_maps,ARRAY_SIZE (ascending_maps), maps); +TEST_ASSERT_VAL ("tail insert check_maps failed" , !ret); + + found =maps__find (maps,2500 ); +TEST_ASSERT_VAL ("failed to find map_a by address" , found &&map__start (found) ==2000 ); +map__zput (found); + +maps__zput (maps); +machine__delete (machine); +perf_env__exit (&host_env); +return TEST_OK ; +} +static struct test_case tests__maps[] = {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 =NULL , } };
tools/perf/util/maps.c +4 -0
@@ -907,6 +907,10 @@ static unsigned int first_ending_after(struct maps *maps, const struct map *map)assert (maps__maps_by_address_sorted (maps));if (low <= high &&map__end (maps_by_address[0 ]) >map__start (map))return 0 ; +if (low <= high && !RC_CHK_ACCESS (maps)->ends_broken && +map__end (maps_by_address[high]) <=map__start (map)) { +return first; + }while (low <= high) {int mid = (low + high) /2 ;
Signature · 1 line
2.56.1.750.gf70dc682cf-goog
Ian Rogers
reviewerPATCH v8 3/10 perf symbol: Convert map__for_each_symbol() to callback-based iteration
In reply to Ian RogersCurrently 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.
--- 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(-)
tools/perf/arch/powerpc/util/sym-handling.c +24 -10
@@ -115,13 +115,27 @@ void arch__fix_tev_from_maps(struct perf_probe_event *pev, }#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 *data) +{ +struct post_process_probe_trace_events_args *args = data; + +if (map__unmap_ip (args->map, sym->start) == 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 =NULL ; -struct rb_node *tmp;int i =0 ; map =get_target_map (pev->target, pev->nsi, pev->uprobes);
@@ -129,13 +143,13 @@ void arch__post_process_probe_trace_events(struct perf_probe_event *pev,return ;for (i =0 ; i < ntevs; i++) { - tev = &pev->tevs[i]; -map__for_each_symbol (map, sym, tmp) { -if (map__unmap_ip (map, sym->start) == tev->point.address) { -arch__fix_tev_from_maps (pev, tev, map, sym); -break ; - } - } +struct post_process_probe_trace_events_args args = { + .pev = pev, + .tev = &pev->tevs[i], + .map = map, + }; + +map__for_each_symbol (map, post_process_probe_trace_events_cb, &args); } }#endif /* HAVE_LIBELF_SUPPORT */
tools/perf/builtin-kmem.c +28 -24
70 lines not on this page · raw message
tools/perf/tests/vmlinux-kallsyms.c +93 -88
217 lines not on this page · raw message
tools/perf/util/dso.h +4 -4
@@ -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)static inline void *dso__a2l (const struct dso *dso) {
tools/perf/util/map.h +4 -4
@@ -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)/* map__for_each_symbol_with_name - iterate over the symbols in the given map * that have the given name
tools/perf/util/probe-event.c +48 -34
97 lines not on this page · raw message
tools/perf/util/symbol.c +19 -0
@@ -613,6 +613,25 @@ struct symbol *dso__find_symbol(struct dso *dso, u64 addr)return dso__last_find_result_symbol (dso); } +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 =rb_first_cached (symbols); nd; nd =rb_next (nd)) { + struct symbol *sym = rb_entry(nd, struct symbol, rb_node); +int ret =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);
tools/perf/util/symbol.h +8 -8
@@ -141,16 +141,16 @@ void symbol__set_annotate2(struct symbol *sym, bool annotate2);void symbol__set_inlined (struct symbol *sym,bool inlined);void symbol__set_ifunc_alias (struct symbol *sym,bool ifunc_alias); -/* 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 = rb_first_cached(symbols); \ - nd && (pos = rb_entry(nd, struct symbol, rb_node)); \ - nd = rb_next(nd)) +int symbols__visit (struct rb_root_cached *symbols, +int (*cb)(struct symbol *sym,void *data), +void *data);static inline size_t symbol__size (const struct symbol *sym) {
Signature · 1 line
2.56.1.750.gf70dc682cf-goog
Ian Rogers
reviewerPATCH v8 4/10 perf symbol: Use callback iteration instead of open-coded symbol loops
In reply to Ian RogersConvert 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().
--- 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(-)
tools/perf/tests/symbols.c +36 -25
@@ -116,39 +116,50 @@ static int create_map(struct test_info *ti, char *filename, struct map **map_p)return TEST_OK ; } +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 = data; +struct symbol *last_sym = args->last_sym; + +if (symbol__type (sym) !=STT_FUNC &&symbol__type (sym) !=STT_GNU_IFUNC ) +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 =TEST_FAIL ; + } +/* Check for zero-length function symbol */ +if (sym->start == sym->end) { +pr_debug ("Zero-length symbol:\n" ); +symbol__fprintf (sym, stderr); + args->ret =TEST_FAIL ; + } + args->last_sym = sym; +return 0 ; +} +static int test_dso (struct dso *dso) { -struct symbol *last_sym =NULL ; -struct rb_node *nd; -int ret =TEST_OK ; +struct test_dso_args args = { + .last_sym =NULL , + .ret =TEST_OK , + };/* dso__fprintf() prints all the symbols */ if (verbose >1 )dso__fprintf (dso, stderr); -for (nd =rb_first_cached (dso__symbols (dso)); nd; nd =rb_next (nd)) { - struct symbol *sym = rb_entry(nd, struct symbol, rb_node); +dso__for_each_symbol (dso, test_dso_cb, &args); -if (symbol__type (sym) !=STT_FUNC &&symbol__type (sym) !=STT_GNU_IFUNC ) -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 =TEST_FAIL ; - } -/* Check for zero-length function symbol */ -if (sym->start == sym->end) { -pr_debug ("Zero-length symbol:\n" ); -symbol__fprintf (sym, stderr); - ret =TEST_FAIL ; - } - last_sym = sym; - } - -return ret; +return args.ret; }static int subdivided_dso_cb (struct dso *dso,struct machine *machine__maybe_unused ,void *d)
tools/perf/util/auxtrace.c +72 -37
133 lines not on this page · raw message
tools/perf/util/dso.c +23 -11
@@ -1998,22 +1998,34 @@ static size_t dso__fprintf_buildid(struct dso *dso, FILE *fp)return fprintf (fp,"%s" , sbuild_id); } +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 = data; + + args->ret +=symbol__fprintf (pos, args->fp); +return 0 ; +} +size_t dso__fprintf (struct dso *dso,FILE *fp) { -struct rb_node *nd; -size_t ret =fprintf (fp,"dso: %s (" ,dso__short_name (dso)); +struct dso__fprintf_cb_args args = { + .fp = fp, + .ret =fprintf (fp,"dso: %s (" ,dso__short_name (dso)), + };if (dso__short_name (dso) !=dso__long_name (dso)) - ret +=fprintf (fp,"%s, " ,dso__long_name (dso)); - ret +=fprintf (fp,"%sloaded, " ,dso__loaded (dso) ?"" :"NOT " ); - ret +=dso__fprintf_buildid (dso, fp); - ret +=fprintf (fp,")\n" ); -for (nd =rb_first_cached (dso__symbols (dso)); nd; nd =rb_next (nd)) { - struct symbol *pos = rb_entry(nd, struct symbol, rb_node); - ret +=symbol__fprintf (pos, fp); - } + args.ret +=fprintf (fp,"%s, " ,dso__long_name (dso)); + args.ret +=fprintf (fp,"%sloaded, " ,dso__loaded (dso) ?"" :"NOT " ); + args.ret +=dso__fprintf_buildid (dso, fp); + args.ret +=fprintf (fp,")\n" ); +dso__for_each_symbol (dso, dso__fprintf_cb, &args); -return ret; +return args.ret; }enum dso_type dso__type (struct dso *dso,struct machine *machine)
tools/perf/util/dso.h +3 -0
@@ -368,6 +368,9 @@ int dso_id__cmp(const struct dso_id *a, const struct dso_id *b);#define dso__for_each_symbol (dso, cb, data) \ symbols__visit(dso__symbols(dso), cb, data) +#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;
tools/perf/util/intel-pt.c +45 -29
94 lines not on this page · raw message
tools/perf/util/machine.c +17 -11
@@ -1125,29 +1125,35 @@ int machine__create_extra_kernel_map(struct machine *machine,return err; } -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[] = { +static const char *const syms[] = {"_entry_trampoline" ,"__entry_trampoline_start" ,"entry_SYSCALL_64_trampoline" , }; -struct symbol *sym =dso__first_symbol (dso); -unsigned int i; +u64 *addr = data; -for (; sym; sym =dso__next_symbol (sym)) { -if (symbol__binding (sym) !=STB_GLOBAL ) -continue ; -for (i =0 ; i <ARRAY_SIZE (syms); i++) { -if (!strcmp (sym->name, syms[i])) -return sym->start; +if (symbol__binding (sym) !=STB_GLOBAL ) +return 0 ; +for (unsigned int i =0 ; i <ARRAY_SIZE (syms); i++) { +if (!strcmp (sym->name, syms[i])) { + *addr = sym->start; +return 1 ; } } -return 0 ; } +static u64 find_entry_trampoline (struct dso *dso) +{ +u64 addr =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 entry * trampolines in kallsyms.
tools/perf/util/probe-event.c +10 -6
@@ -3788,6 +3788,15 @@ void cleanup_perf_probe_events(struct perf_probe_event *pevs, int npevs) } } +static int show_available_funcs_cb (struct symbol *pos,void *data) +{ +struct strfilter *_filter = 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 (); -for (size_t i =0 ; i <dso__symbol_names_len (dso); i++) { -struct symbol *pos =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 ();
tools/perf/util/symbol.c +12 -40
67 lines not on this page · raw message
tools/perf/util/symbol.h +3 -4
@@ -197,10 +197,9 @@ struct symbol *dso__find_symbol_nocache(struct dso *dso, u64 addr);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);enum dso_type dso__type_fd (int fd);
tools/perf/util/symbol_fprintf.c +18 -7
@@ -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); } +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 = data; + + args->ret +=fprintf (args->fp,"%s\n" , pos->name); +return 0 ; +} +size_t dso__fprintf_symbols_by_name (struct dso *dso,FILE *fp) { -size_t ret =0 ; - -for (size_t i =0 ; i <dso__symbol_names_len (dso); i++) { -struct symbol *pos =dso__symbol_names (dso)[i]; +struct fprintf_symbols_by_name_args args = { + .fp = fp, + }; - ret +=fprintf (fp,"%s\n" , pos->name); - } -return ret; +dso__for_each_symbol_by_name (dso, fprintf_symbols_by_name_cb, &args); +return args.ret; }
Signature · 1 line
2.56.1.750.gf70dc682cf-goog
Ian Rogers
reviewerPATCH v8 5/10 perf symbol: Switch backing storage from rbtree to struct symbols array
In reply to Ian RogersPreviously, 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)
--- 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(-)
tools/perf/builtin-annotate.c +0 -11
@@ -258,17 +258,6 @@ static int add_sample(struct perf_sample *sample, (al->sym == NULL || strcmp(ann->sym_hist_filter, al->sym->name) != 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 !=NULL ) { -struct dso *dso =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 ; }
tools/perf/tests/hists_common.c +4 -1
@@ -146,7 +146,10 @@ struct machine *setup_fake_machine(struct machines *machines) goto out; } -symbols__insert (dso__symbols (dso), sym); +if (symbols__insert (dso__symbols (dso), sym)) { +dso__put (dso); + goto out; + } }dso__put (dso);
tools/perf/ui/browser.c +3 -0
@@ -622,6 +622,9 @@ static int ui_browser__color_config(const char *var, const char *value,void ui_browser__argv_seek (struct ui_browser *browser,off_t offset,int whence) { +if (browser->nr_entries ==0 ) +return ; +switch (whence) {case SEEK_SET : browser->top = browser->entries;
tools/perf/ui/browsers/hists.c +2 -1
@@ -2532,7 +2532,8 @@ static struct symbol *symbol__new_unresolved(u64 addr, struct map *map)return NULL ; } -dso__insert_symbol (map__dso (map), sym); +if (dso__insert_symbol (map__dso (map), sym)) +return NULL ; }return sym;
tools/perf/ui/browsers/map.c +41 -21
92 lines not on this page · raw message
tools/perf/util/db-export.c +2 -2
@@ -289,8 +289,8 @@ static int db_ids_from_al(struct db_export *dbe, struct addr_location *al,if (!al->sym) { al->sym =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 =NULL ; }if (al->sym) {
tools/perf/util/dso.c +8 -12
@@ -1802,12 +1802,13 @@ bool dso__loaded(const struct dso *dso)bool dso__sorted_by_name (const struct dso *dso) { -return RC_CHK_ACCESS (dso)->sorted_by_name; -} +struct symbols *symbols = (struct symbols *)&RC_CHK_ACCESS (dso)->symbols; +bool res; -void dso__set_sorted_by_name (struct dso *dso) -{ -RC_CHK_ACCESS (dso)->sorted_by_name = true; +down_read (&symbols->lock); + res = symbols->sorted_by_name; +up_read (&symbols->lock); +return res; }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 struct dso_id *id) dso->id = *id;dso__set_long_name_id (res, dso->name, false);dso__set_short_name (res, dso->name, false); - dso->symbols =RB_ROOT_CACHED ; - dso->symbol_names =NULL ; - dso->symbol_names_len =0 ; +symbols__init (&dso->symbols); dso->inlined_nodes =RB_ROOT_CACHED ; dso->srclines =RB_ROOT_CACHED ; dso->data_types =RB_ROOT ;
@@ -1838,7 +1837,6 @@ struct dso *dso__new_id(const char *name, const struct dso_id *id) dso->is_64_bit = (sizeof (void *) ==8 ); dso->loaded =0 ; dso->rel =0 ; - dso->sorted_by_name =0 ; dso->has_srcline =1 ; dso->a2l_fails =1 ; dso->kernel =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 =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));
tools/perf/util/dso.h +11 -54
127 lines not on this page · raw message
tools/perf/util/libbfd.c +2 -1
@@ -453,7 +453,8 @@ int dso__load_bfd_symbols(struct dso *dso, const char *debugfile)if (!symbol) goto out_free; -symbols__insert (dso__symbols (dso), symbol); +if (symbols__insert (dso__symbols (dso), symbol)) + goto out_free; }#ifdef bfd_get_section#undef bfd_asymbol_section
tools/perf/util/machine.c +1 -1
@@ -822,7 +822,7 @@ static int machine__process_ksymbol_register(struct machine *machine, err = -ENOMEM ; goto out; } -dso__insert_symbol (dso, sym); + err =dso__insert_symbol (dso, sym); out:map__put (map);dso__put (dso);
tools/perf/util/map.c +22 -14
@@ -304,27 +304,35 @@ void map__put(struct map *map)void map__fixup_start (struct map *map) { -struct dso *dso =map__dso (map); -struct rb_root_cached *symbols =dso__symbols (dso); -struct rb_node *nd =rb_first_cached (symbols); - -if (nd !=NULL ) { - struct symbol *sym = rb_entry(nd, struct symbol, rb_node); +struct symbols *symbols =dso__symbols (map__dso (map)); -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); }void map__fixup_end (struct map *map) { -struct dso *dso =map__dso (map); -struct rb_root_cached *symbols =dso__symbols (dso); -struct rb_node *nd =rb_last (&symbols->rb_root); +struct symbols *symbols =dso__symbols (map__dso (map)); -if (nd !=NULL ) { - struct symbol *sym = 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 = symbols->symbols[symbols->cnt -1 ]->start; +u64 end = symbols->symbols[symbols->cnt -1 ]->end; + +for (unsigned int i = symbols->cnt -1 ; i >0 ; i--) { +u64 sym_end; + +if (symbols->symbols[i -1 ]->start != last_start) +break ; + sym_end = symbols->symbols[i -1 ]->end; +if (sym_end > end) + end = sym_end; + } +map__set_end (map, end); } +up_read (&symbols->lock); }#define DSO__DELETED "(deleted)"
tools/perf/util/symbol-elf.c +8 -4
@@ -698,7 +698,8 @@ static int dso__synthesize_plt_got_symbols(struct dso *dso, Elf *elf, sym =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 =0 ; out:
@@ -752,7 +753,8 @@ int dso__synthesize_plt_symbols(struct dso *dso, struct symsrc *ss) plt_sym =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;/* 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; plt_offset += plt_entry_size; -symbols__insert (dso__symbols (dso), f); +if (symbols__insert (dso__symbols (dso), f)) + goto out_elf_end; ++nr; }
@@ -1938,7 +1941,8 @@ dso__load_sym_internal(struct dso *dso, struct map *map, struct symsrc *syms_ss,arch__sym_update (f, &sym); -__symbols__insert (dso__symbols (curr_dso), f); +if (symbols__insert (dso__symbols (curr_dso), f)) + goto out_elf_end; nr++; }dso__put (curr_dso);
tools/perf/util/symbol.c +453 -203
889 lines not on this page · raw message
tools/perf/util/symbol.h +47 -14
108 lines not on this page · raw message
Signature · 1 line
2.56.1.750.gf70dc682cf-goog
Ian Rogers
reviewerPATCH v8 6/10 perf symbol: Replace qsort() with natural-run merge sort
In reply to Ian RogersELF .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 <= 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)--- tools/perf/util/symbol.c | 183 +++++++++++++++++++++++++++++++++++++-- 1 file changed, 174 insertions(+), 9 deletions(-)
tools/perf/util/symbol.c +174 -9
@@ -265,14 +265,171 @@ static inline bool symbol__less_or_equal(const struct symbol *a, const struct syreturn a->start <= b->start; } -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 = *((const struct symbol **)vlhs); -const struct symbol *rhs = *((const struct symbol **)vrhs); +unsigned int low =0 , high = len; -if (lhs->start != rhs->start) -return lhs->start < rhs->start ?-1 :1 ; -return 0 ; +while (low < high) { +unsigned int mid = low + (high - low) /2 ; + +if (symbol__less_or_equal (arr[mid], sym)) + low = mid +1 ; +else + high = mid; + } +return low; +} + +static void symbols__insertion_sort_range (struct symbol **arr, +unsigned int start, +unsigned int end) +{ +for (unsigned int i = start +1 ; i < end; i++) { +struct symbol *sym = arr[i]; + +if (!symbol__less_or_equal (arr[i -1 ], sym)) { +unsigned int pos = start + +symbols__upper_bound (&arr[start], i - start, sym); + +memmove (&arr[pos +1 ], &arr[pos], + (i - pos) *sizeof (struct symbol *)); + arr[pos] = 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 >= mid || mid >= right) +return ; +if (symbol__less_or_equal (arr[mid -1 ], arr[mid])) +return ; + + first_left = left +symbols__upper_bound (&arr[left], mid - left, arr[mid]); + left_len = mid - first_left; + right_len = right - mid; + +if (left_len <= right_len) { +memcpy (tmp, &arr[first_left], left_len *sizeof (struct symbol *)); + i =0 ; + j = mid; + dst = first_left; +while (i < left_len && j < right) { +if (symbol__less_or_equal (tmp[i], arr[j])) + arr[dst++] = tmp[i++]; +else + arr[dst++] = 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 = mid; + j = right_len; + dst = right; +while (i > first_left && j >0 ) { +if (symbol__less_or_equal (arr[i -1 ], tmp[j -1 ])) + arr[--dst] = tmp[--j]; +else + arr[--dst] = 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 =0 ; +unsigned int i =0 ; + +if (n <=32 ) { +symbols__insertion_sort_range (arr,0 , n); +return ; + } + +while (i < n) { +unsigned int start = 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 = start, hi = i -1 ; lo < hi; lo++, hi--) { +struct symbol *swap = arr[lo]; + + arr[lo] = arr[hi]; + arr[hi] = swap; + } + } + } + +if (i - start <32 && i < n) { + i =min (start +32U , n); +symbols__insertion_sort_range (arr, start, i); + } + + runs[nr_runs++] = (struct symbol_run ){ + .start = start, + .len = i - start, + }; + +while (nr_runs >1 ) { +unsigned int r = nr_runs -2 ; + +if (nr_runs >=3 && + runs[nr_runs -3 ].len <= + runs[nr_runs -2 ].len + runs[nr_runs -1 ].len) { +if (runs[nr_runs -3 ].len < runs[nr_runs -1 ].len) + r = 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 += runs[r +1 ].len; +if (r +2 < nr_runs) + runs[r +1 ] = runs[r +2 ]; + nr_runs--; + } + } + +while (nr_runs >1 ) { +unsigned int r = nr_runs -2 ; + +if (nr_runs >=3 && runs[nr_runs -3 ].len < runs[nr_runs -1 ].len) + r = 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 += runs[r +1 ].len; +if (r +2 < nr_runs) + runs[r +1 ] = runs[r +2 ]; + nr_runs--; + } }static void symbols__sort_locked (struct symbols *symbols)
@@ -281,9 +438,17 @@ static void symbols__sort_locked(struct symbols *symbols)if (symbols->sorted)return ; -if (symbols->cnt >1 ) { -qsort (symbols->symbols, symbols->cnt,sizeof (struct symbol *), - symbols__sort_cmp); +if (symbols->cnt <=64 ) { +symbols__insertion_sort_range (symbols->symbols,0 , symbols->cnt); + }else { +struct symbol **tmp =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 = true; }
Signature · 1 line
2.56.1.750.gf70dc682cf-goog
Ian Rogers
reviewerPATCH v8 7/10 perf symbol: Optimize incremental symbol insertion with sorted tail
In reply to Ian RogersDynamic 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 <= 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 <= 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)# 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(-)
tools/perf/util/symbol.c +188 -18
@@ -220,6 +220,7 @@ void symbols__init(struct symbols *symbols) symbols->symbols =NULL ; symbols->symbols_by_name =NULL ; symbols->cnt =0 ; + symbols->sorted_cnt =0 ; symbols->allocated =0 ; symbols->num_by_name =0 ; symbols->sorted = true;
@@ -235,6 +236,7 @@ static void symbols__delete_locked(struct symbols *symbols)zfree (&symbols->symbols);zfree (&symbols->symbols_by_name); symbols->cnt =0 ; + symbols->sorted_cnt =0 ; symbols->allocated =0 ; symbols->num_by_name =0 ; symbols->sorted = true;
@@ -283,9 +285,10 @@ static unsigned int symbols__upper_bound(struct symbol **arr, unsigned int len,static void symbols__insertion_sort_range (struct symbol **arr,unsigned int start, +unsigned int first_unsorted,unsigned int end) { -for (unsigned int i = start +1 ; i < end; i++) { +for (unsigned int i =max (first_unsorted, start +1 ); i < end; i++) {struct symbol *sym = arr[i];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 =0 ;if (n <=32 ) { -symbols__insertion_sort_range (arr,0 , n); +symbols__insertion_sort_range (arr,0 ,1 , n);return ; }
@@ -383,8 +386,10 @@ static void symbols__sort_range_with_tmp(struct symbol **arr, unsigned int n, }if (i - start <32 && i < n) { +unsigned int run_end = i; + i =min (start +32U , n); -symbols__insertion_sort_range (arr, start, i); +symbols__insertion_sort_range (arr, start, run_end, i); } runs[nr_runs++] = (struct symbol_run ){
@@ -435,32 +440,79 @@ static void symbols__sort_range_with_tmp(struct symbol **arr, unsigned int n,static void symbols__sort_locked (struct symbols *symbols) __must_hold(&symbols->lock) { -if (symbols->sorted) +unsigned int m = symbols->sorted_cnt; +unsigned int k; + +if (symbols->sorted && symbols->sorted_cnt == symbols->cnt)return ; -if (symbols->cnt <=64 ) { -symbols__insertion_sort_range (symbols->symbols,0 , symbols->cnt); - }else { +if (m > symbols->cnt) + m =0 ; + k = symbols->cnt - m; + +if (k ==0 ) { + symbols->sorted = 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 <=8 || symbols->cnt <=64 ) { +symbols__insertion_sort_range (symbols->symbols,0 , m, symbols->cnt); + symbols->sorted_cnt = symbols->cnt; + symbols->sorted = 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 =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 <=1 ) {struct symbol **tmp =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__insertion_sort_range (symbols->symbols,0 , m, symbols->cnt); + } + }else { +struct symbol **tmp =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 = symbols->cnt; symbols->sorted = true; }/* * 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 = write_idx +1 ; + symbols->sorted_cnt = symbols->cnt;zfree (&symbols->symbols_by_name); symbols->num_by_name =0 ; symbols->sorted_by_name = false;
@@ -685,9 +738,15 @@ static int __symbols__insert(struct symbols *symbols, struct symbol *sym) symbols->allocated = to_allocate; } -if (symbols->sorted && symbols->cnt >0 && - !symbol__less_or_equal (symbols->symbols[symbols->cnt -1 ], sym)) +if (symbols->sorted && symbols->sorted_cnt == symbols->cnt) { +if (symbols->cnt ==0 || +symbol__less_or_equal (symbols->symbols[symbols->cnt -1 ], sym)) + symbols->sorted_cnt = symbols->cnt +1 ; +else + symbols->sorted = false; + }else { symbols->sorted = false; + } symbols->symbols[symbols->cnt++] = sym;zfree (&symbols->symbols_by_name);
@@ -696,6 +755,70 @@ static int __symbols__insert(struct symbols *symbols, struct symbol *sym)return 0 ; } +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 == symbols->allocated) { +unsigned int to_allocate = symbols->allocated ? symbols->allocated *2 :32 ; +struct symbol **temp =realloc (symbols->symbols, +sizeof (struct symbol *) * to_allocate); + +if (!temp) { +symbol__delete (sym); +return -ENOMEM ; + } + symbols->symbols = temp; + symbols->allocated = to_allocate; + } + +if (symbols->sorted_cnt == symbols->cnt) { +if (symbols->cnt ==0 || +symbol__less_or_equal (symbols->symbols[symbols->cnt -1 ], sym)) { + symbols->symbols[symbols->cnt++] = sym; + symbols->sorted_cnt = symbols->cnt; + }else if (symbols->cnt <64 ) { + idx =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] = sym; + symbols->cnt++; + symbols->sorted_cnt = 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++] = sym; + } + }else { +unsigned int tail_cnt = symbols->cnt - symbols->sorted_cnt; + + idx = 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] = sym; + symbols->cnt++; + tail_cnt++; + +if (tail_cnt >=256 && + (size_t )tail_cnt * tail_cnt >= symbols->sorted_cnt) +symbols__sort_locked (symbols); + } + +zfree (&symbols->symbols_by_name); + symbols->num_by_name =0 ; + symbols->sorted_by_name = 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 >= start && (ip < end || (ip == end && ip == start)); } -static struct symbol *symbols__find_range (struct symbol **arr,unsigned int cnt,u64 ip) +static struct symbol *symbols__find_range (struct symbol **arr,unsigned int cnt, +u64 ip,bool *has_candidate, +u64 *candidate_start) {unsigned int low =0 , high = cnt, idx;u64 start;
@@ -727,8 +852,10 @@ static struct symbol *symbols__find_range(struct symbol **arr, unsigned int cnt,else high = mid; } -if (low ==0 ) +if (low ==0 ) { + *has_candidate = false;return NULL ; + }/* * 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 = low -1 ; start = arr[idx]->start; + *has_candidate = true; + *candidate_start = start;while (idx >0 && arr[idx -1 ]->start == start) idx--;for (; idx < low; idx++) {
@@ -753,12 +882,38 @@ static struct symbol *symbols__find_range(struct symbol **arr, unsigned int cnt,static struct symbol *symbols__find (struct symbols *symbols,u64 ip) {struct symbol *res; +bool has_prefix; +u64 prefix_start =0 ;if (symbols ==NULL )return NULL ; -symbols__sort_read_lock (symbols); - res =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 =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 =0 ; + + tail_res =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 = tail_res; +else if (tail_start == prefix_start && !res) + res = tail_res; + } + }up_read (&symbols->lock);return res;
@@ -904,7 +1059,13 @@ static struct symbol *symbols__find_by_name(struct symbol *symbols[],int dso__insert_symbol (struct dso *dso,struct symbol *sym) { -return symbols__insert (dso__symbols (dso), sym); +struct symbols *symbols =dso__symbols (dso); +int ret; + +down_write (&symbols->lock); + ret =__symbols__insert_sorted (symbols, sym); +up_write (&symbols->lock); +return ret; }void dso__delete_symbol (struct dso *dso,struct symbol *sym)
@@ -912,11 +1073,15 @@ void dso__delete_symbol(struct dso *dso, struct symbol *sym)struct symbols *symbols =dso__symbols (dso);down_write (&symbols->lock); -for (unsigned int i =0 ; i < symbols->cnt; i++) { +for (unsigned int i = symbols->cnt; i-- >0 ; ) {if (symbols->symbols[i] == 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 == symbols->cnt) + symbols->sorted = true;zfree (&symbols->symbols_by_name); symbols->num_by_name =0 ; symbols->sorted_by_name = false;
@@ -1263,6 +1428,7 @@ static int maps__split_kallsyms_for_kcore(struct maps *kmaps, struct dso *dso) old_cnt = root->cnt; root->symbols =NULL ; root->cnt =0 ; + root->sorted_cnt =0 ; root->allocated =0 ; root->sorted = true;zfree (&root->symbols_by_name);
@@ -1337,6 +1503,7 @@ static int maps__split_kallsyms(struct maps *kmaps, struct dso *dso, u64 delta, old_allocated = root->allocated; root->symbols =NULL ; root->cnt =0 ; + root->sorted_cnt =0 ; root->allocated =0 ; root->sorted = true;zfree (&root->symbols_by_name);
@@ -1487,6 +1654,7 @@ static int maps__split_kallsyms(struct maps *kmaps, struct dso *dso, u64 delta,if (root->cnt ==0 ) { root->symbols = old_symbols; root->cnt = write_idx; + root->sorted_cnt = write_idx; root->allocated = old_allocated; root->sorted = true; old_symbols =NULL ;
@@ -1516,12 +1684,14 @@ static int maps__split_kallsyms(struct maps *kmaps, struct dso *dso, u64 delta,if (root->cnt ==0 ) { root->symbols = old_symbols; root->cnt = write_idx; + root->sorted_cnt = (delta ==0 ) ? write_idx :0 ; root->allocated = old_allocated; root->sorted = (delta ==0 ); old_symbols =NULL ; }else {for (unsigned int j =0 ; j < write_idx; j++)__symbols__insert (root, old_symbols[j]); + root->sorted_cnt =0 ; root->sorted = false; }zfree (&root->symbols_by_name);
tools/perf/util/symbol.h +10 -1
@@ -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); };
Signature · 1 line
2.56.1.750.gf70dc682cf-goog
Ian Rogers
reviewerPATCH v8 8/10 perf symbol: Add memory shrinking for symbols, DSOs, and machines
In reply to Ian RogersWhen 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 == 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 == 1, not kernel, 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.
--- 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(-)
tools/perf/util/dso.c +243 -20
@@ -3,6 +3,7 @@#include <assert.h> #include <errno.h> +#include <stdatomic.h> #include <stdlib.h> #include <asm/bug.h>
@@ -16,6 +17,7 @@#include <sys/types.h> #include <unistd.h> +#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 static void -dso_cache__free (struct dso *dso) +__dso_cache__free (struct dso *dso) +__must_hold (dso__lock (dso)) {struct rb_root *root = &dso__data (dso)->cache;struct rb_node *next =rb_first (root); -mutex_lock (dso__lock (dso));while (next) {struct dso_cache *cache;
@@ -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)); }static struct dso_cache *__dso_cache__find (struct dso *dso,u64 offset) +__must_hold (dso__lock (dso)) {const struct rb_root *root = &dso__data (dso)->cache;struct rb_node *const *p = &root->rb_node;
@@ -1218,27 +1228,30 @@ static struct dso_cache *dso_cache__populate(struct dso *dso,return cache; } -static struct dso_cache *dso_cache__find (struct dso *dso, -struct machine *machine, -u64 offset, -ssize_t *ret) -{ -struct dso_cache *cache =__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 =0 ; - cache =dso_cache__find (dso, machine, offset, &ret); -if (!cache) -return ret; +mutex_lock (dso__lock (dso)); + cache =__dso_cache__find (dso, offset); +while (!cache) { +mutex_unlock (dso__lock (dso)); + cache =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 =__dso_cache__find (dso, offset); + } -return dso_cache__memcpy (cache, offset, data, size, out); + ret =dso_cache__memcpy (cache, offset, data, size, out); +mutex_unlock (dso__lock (dso)); +return ret; }/*
@@ -1797,7 +1810,7 @@ int dso__name_len(const struct dso *dso)bool dso__loaded (const struct dso *dso) { -return RC_CHK_ACCESS (dso)->loaded; +return atomic_load_explicit (&RC_CHK_ACCESS (dso)->loaded, memory_order_acquire); }bool dso__sorted_by_name (const struct dso *dso)
@@ -1835,7 +1848,7 @@ struct dso *dso__new_id(const char *name, const struct dso_id *id) dso->binary_type =DSO_BINARY_TYPE__NOT_FOUND ; dso->dbginfo_type =DSO_BINARY_TYPE__NOT_FOUND ; dso->is_64_bit = (sizeof (void *) ==8 ); - dso->loaded =0 ; +atomic_init (&dso->loaded, false); dso->rel =0 ; dso->has_srcline =1 ; dso->a2l_fails =1 ;
@@ -1859,7 +1872,7 @@ struct dso *dso__new(const char *name)return dso__new_id (name,NULL ); } -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 = false; } -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); } +void dso__delete (struct dso *dso) +{ +__dso__delete (dso,/*close_data=*/ 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 =dso__long_name (dso); +if (!name || name[0 ] =='[' ||is_perf_pid_map_name (name) || +strstr (name," (deleted)" ) !=NULL ) +return false; + +return true; +} + +static bool dso__has_annotated_inlines (struct dso *dso) +{ +struct rb_root_cached *tree =dso__inlined_nodes (dso); +struct rb_node *nd; + +for (nd =rb_first_cached (tree); nd; nd =rb_next (nd)) { + struct inline_node *node = 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 = 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 =0 ; + +if (!dso) +return 0 ; + +if (mutex_trylock (&dso__data_open_lock)) { +if (dso__data (dso)->fd >=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) !=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)) ==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 +=symbols__shrink (dso__symbols (dso)); + } + +mutex_unlock (dso__lock (dso)); +return freed; +} + +/* +* Try to evict an unreferenced @dso from its owning struct dsos (whose write +* lock must be held by the caller) without blocking on any lock. +*/ +bool dso__try_evict (struct dso *dso) +{ +bool can_evict = 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)) !=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)) ==1 && +mutex_trylock (dso__lock (dso))) { + can_evict = !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=*/ false); +else +RC_CHK_PUT (dso); +return true; +} +struct dso *dso__get (struct dso *dso) {struct dso *result;
tools/perf/util/dso.h +12 -2
@@ -6,6 +6,7 @@#include <linux/types.h> #include <linux/rbtree.h> #include <sys/types.h> +#include <stdatomic.h> #include <stdbool.h> #include <stdio.h> #include <linux/bitops.h>
@@ -343,7 +344,7 @@ DECLARE_RC_STRUCT(dso) { u8 is_64_bit:1; u8 bintype_searched:1; u8 debuginfo_searched:1; -bool loaded; + _Atomicbool loaded;u8 rel;char name[]; };
@@ -599,7 +600,7 @@ static inline enum dso_load_errno *dso__load_errno(struct dso *dso)static inline void dso__set_loaded (struct dso *dso) { -RC_CHK_ACCESS (dso)->loaded = true; +atomic_store_explicit (&RC_CHK_ACCESS (dso)->loaded, true, memory_order_release); }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; } +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 *filename);bool dso__sorted_by_name (const struct dso *dso);
tools/perf/util/dsos.c +50 -0
59 lines not on this page · raw message
tools/perf/util/dsos.h +2 -0
@@ -51,4 +51,6 @@ struct dso *dsos__find_kernel_dso(struct dsos *dsos);int dsos__for_each_dso (struct dsos *dsos,int (*cb)(struct dso *dso,void *data),void *data); +size_t dsos__shrink (struct dsos *dsos); +#endif /* __PERF_DSOS */
tools/perf/util/machine.c +29 -0
@@ -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 =machine__shrink (&machines->host); + +down_read (&machines->lock); +for (nd =rb_first_cached (&machines->guests); nd; nd =rb_next (nd)) { + struct machine *pos = rb_entry(nd, struct machine, rb_node); + + freed +=machine__shrink (pos); + } +up_read (&machines->lock); + +return freed; +}
tools/perf/util/machine.h +3 -0
@@ -339,4 +339,7 @@ int machine__resolve(struct machine *machine, struct addr_location *al,int machine__hit_all_dsos (struct machine *machine); +size_t machine__shrink (struct machine *machine); +size_t machines__shrink (struct machines *machines); +#endif /* __PERF_MACHINE_H */
tools/perf/util/session.c +8 -0
@@ -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); +}
tools/perf/util/session.h +2 -0
@@ -211,4 +211,6 @@ int perf_event__process_finished_round(const struct perf_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); +size_t perf_session__shrink (struct perf_session *session); +#endif /* __PERF_SESSION_H */
tools/perf/util/symbol.c +67 -1
93 lines not on this page · raw message
tools/perf/util/symbol.h +3 -0
@@ -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(&symbols->lock);static inline u8 symbol__type (const struct symbol *sym)
Signature · 1 line
2.56.1.750.gf70dc682cf-goog
Ian Rogers
reviewerPATCH v8 9/10 perf session: Add dso__session() and session-scoped allocation wrappers
In reply to Ian RogersAdd 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.
--- 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(+)
tools/perf/util/dso.c +7 -0
@@ -1912,6 +1912,13 @@ void dso__delete(struct dso *dso)__dso__delete (dso,/*close_data=*/ true); } +struct perf_session *dso__session (const struct dso *dso) +{ +struct dsos *dsos = 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;
tools/perf/util/dso.h +2 -0
@@ -20,6 +20,7 @@struct machine ;struct map ;struct perf_env ; +struct perf_session ;#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);char *dso__filename_with_chroot (const struct dso *dso,const char *filename);
tools/perf/util/dsos.c +1 -0
@@ -19,6 +19,7 @@ void dsos__init(struct dsos *dsos) {init_rwsem (&dsos->lock); + dsos->machine =NULL ; dsos->cnt =0 ; dsos->allocated =0 ; dsos->dsos =NULL ;
tools/perf/util/dsos.h +1 -0
@@ -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);
tools/perf/util/machine.c +1 -0
@@ -81,6 +81,7 @@ int machine__init(struct machine *machine, const char *root_dir, pid_t pid)memset (machine,0 ,sizeof (*machine));RB_CLEAR_NODE (&machine->rb_node);dsos__init (&machine->dsos); + machine->dsos.machine = machine;threads__init (&machine->threads); machine->kmaps =maps__new (machine);
tools/perf/util/machine.h +5 -0
@@ -165,6 +165,11 @@ static inline struct perf_session *machines__session(struct machines *machines)return machines->session; } +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);
tools/perf/util/session.c +70 -0
73 lines not on this page · raw message
tools/perf/util/session.h +6 -0
@@ -213,4 +213,10 @@ uint16_t perf_session__e_machine(struct perf_session *session, uint32_t *e_flagssize_t perf_session__shrink (struct perf_session *session); +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,size_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 */
Signature · 1 line
2.56.1.750.gf70dc682cf-goog
Ian Rogers
reviewerPATCH v8 10/10 perf test symbols: Add tests for symbol shrinking and session alloc wrappers
In reply to Ian RogersEnsure 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=1).
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().
--- tools/perf/tests/symbols.c | 790 ++++++++++++++++++++++++++++++++++++- 1 file changed, 779 insertions(+), 11 deletions(-)
tools/perf/tests/symbols.c +779 -11
@@ -1,20 +1,34 @@// SPDX-License-Identifier: GPL-2.0 #include <linux/compiler.h> +#include <linux/list.h> #include <linux/string.h> +#include <linux/zalloc.h> #include <sys/mman.h> #include <elf.h> +#include <errno.h> #include <inttypes.h> #include <limits.h> +#include <pthread.h> +#include <stdatomic.h> +#include <stdbool.h> +#include <stddef.h> +#include <stdio.h> #include <stdlib.h> +#include <string.h> #include <unistd.h> +#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" struct test_info {
@@ -182,6 +196,496 @@ static int process_subdivided_dso(struct machine *machine, struct dso *dso)return ret <0 ?TEST_FAIL :TEST_OK ; } +static int noop_visit_cb (struct symbol *sym__maybe_unused ,void *data__maybe_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 =TEST_FAIL ; + +symbols__init (&symbols); + + sym1 =symbol__new (0x100 ,0x50 ,STB_GLOBAL ,STT_FUNC ,"sym1" ); + sym2 =symbol__new (0x200 ,0x50 ,STB_GLOBAL ,STT_FUNC ,"sym2" ); + sym3 =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 <= 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) !=2 || symbols.cnt !=3 || + symbols.allocated !=3 || symbols.symbols_by_name !=NULL ) { +pr_debug ("First symbols__shrink failed (cnt=%u, allocated=%u)!\n" , + symbols.cnt, symbols.allocated); + goto out; + } + +/* +* Second shrink with no symbols_by_name and no excess capacity is a no-op. +*/ +if (symbols__shrink (&symbols) !=0 || symbols.cnt !=3 ) { +pr_debug ("Second symbols__shrink failed (cnt=%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 !=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 !=0 ) { +pr_debug ("symbols__try_delete_unannotated failed after clearing annotation!\n" ); + goto out; + } + + ret =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 =TEST_FAIL ; + +dsos__init (&dsos); + + dso1 =dsos__findnew_id (&dsos,"/tmp/perf_test_dso1" ,NULL ); + dso2 =dsos__findnew_id (&dsos,"/tmp/perf_test_dso2" ,NULL ); + vdso =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 == 1 and no symbols, so it is evicted; +* dso1 (refcnt == 2) and vdso (dso__is_vdso() == true) are retained. +*/ +if (dsos__shrink (&dsos) !=1 || dsos.cnt !=2 ) { +pr_debug ("First dsos__shrink failed (cnt=%u)!\n" , dsos.cnt); +dso__put (dso1); + goto out; + } + +dso__put (dso1); +if (dsos__shrink (&dsos) !=1 || dsos.cnt !=1 || !dso__is_vdso (dsos.dsos[0 ])) { +pr_debug ("Second dsos__shrink failed (cnt=%u)!\n" , dsos.cnt); + goto out; + } + + ret =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 = 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 =zalloc (sizeof (*session)); +struct dso *dso; +struct thread *th; +pid_t pid =getpid (); +char *p1 =NULL , *p2 =NULL , *p3 =NULL , *s =NULL , *tmp; +int ret =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 = &session->header.env; +if (machine__session (&session->machines.host) != session) { +pr_debug ("machine__session did not return owning session!\n" ); + goto out; + } + + dso =machine__findnew_dso (&session->machines.host,"/tmp/perf_test_session_dso" ); +if (!dso) + goto out; +if (dso__session (dso) != session) { +pr_debug ("dso__session did not return owning session!\n" ); +dso__put (dso); + goto out; + } +dso__put (dso); + + p1 =perf_session__malloc (session,64 ); + p2 =perf_session__zalloc (session,64 ); + p3 =perf_session__calloc (session,4 ,16 ); + s =perf_session__strdup (session,"perf_session_alloc_test" ); +if (!p1 || !p2 || !p3 || !s ||strcmp (s,"perf_session_alloc_test" ) !=0 ) { +pr_debug ("perf_session allocation wrappers failed!\n" ); + goto out; + } + + tmp =perf_session__realloc (session, p1,128 ); +if (!tmp) { +pr_debug ("perf_session__realloc failed!\n" ); + goto out; + } + p1 = tmp; + +if (perf_session__shrink (session) ==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 !=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 =machine__findnew_dso (&session->machines.host,"/tmp/perf_test_contended_dso" ); +if (!dso) + goto out; + { +bool was_singlethreaded = perf_singlethreaded; +struct shrink_lock_race_args race_args = { + .dso = dso, + .stop = false, + }; +pthread_t worker; + +perf_set_multithreaded (); +if (pthread_create (&worker,NULL , shrink_lock_race_worker, &race_args) !=0 ) { +if (was_singlethreaded) +perf_set_singlethreaded (); +dso__put (dso); + goto out; + } +for (int i =0 ; i <200 ; i++) { +struct dso *evict =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 =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 = perf_singlethreaded; +uint16_t e_machine; + +perf_set_multithreaded (); + th =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 =perf_session__e_machine (session,NULL ); +if (was_singlethreaded) +perf_set_singlethreaded (); +if (e_machine ==EM_NONE ) { +pr_debug ("perf_session__e_machine failed!\n" ); + goto out; + } + } + + ret =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 = data; + +if (!args->kept) { + args->kept = sym; + args->first_start = sym->start; + args->max_end = sym->end; +return 0 ; + } +if (!args->second_name && sym->start >= args->max_end) { + args->second_start = sym->start; + args->second_name =strdup (sym->name); +if (!args->second_name) +return -ENOMEM ; + } +if (sym->end > args->max_end) + args->max_end = 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 = { + .kept =NULL , + .first_start =0 , + .second_start =0 , + .second_name =NULL , + .max_end =0 , + }; +struct map *map = *map_p; +struct dso *dso =map__dso (map); +struct symbols *syms =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 = 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 =0 ; +struct symbol *expected_next = syms->symbols_by_name[1 ]; +u8 hdr_byte =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) ==0 || syms->cnt != initial_cnt || + syms->symbols_by_name !=NULL ||dso__data (dso)->fd >=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) != expected_next || idx !=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 =dso__find_symbol (dso, args.first_start); +if (sym != 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 = { + .dso = dso, + .sym = 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 != initial_cnt || +dso__find_symbol (pinned.dso, args.first_start) != 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 =zalloc (sizeof (*inode)); + inlined_sym =new_inline_sym (pinned.dso, pinned.sym,"inlined_helper" ); + srcline =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 = 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, srcline); +dso_symbol__exit (&pinned); + } + +if (dsos__shrink (&ti->machine->dsos) ==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) !=TEST_OK ) { +free (args.second_name); +return TEST_FAIL ; + } + map = *map_p; + dso =map__dso (map); + syms =dso__symbols (dso); +if (!dso__hit (dso) || syms->cnt !=0 ||dso__loaded (dso) || +inlines__tree_find (dso__inlined_nodes (dso), args.first_start) !=NULL || +srcline__tree_find (dso__srclines (dso), args.first_start) !=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 =map__find_symbol (map, args.second_start); +if (!reloaded ||strcmp (reloaded->name, args.second_name) !=0 ) { +pr_debug ("Failed to reload evicted symbol %s!\n" , args.second_name); +free (args.second_name); +return TEST_FAIL ; + } + +if (syms->cnt != initial_cnt || !syms->sorted || !dso__loaded (dso)) { +pr_debug ("Reloaded symbol table state mismatch (cnt=%u vs %u, sorted=%d, loaded=%d)!\n" , + syms->cnt, initial_cnt, syms->sorted,dso__loaded (dso)); +free (args.second_name); +return TEST_FAIL ; + } +for (unsigned int i =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 =NULL ;
@@ -213,18 +717,272 @@ static int test_file(struct test_info *ti, char *filename)/* Module dso is split into many dsos by section */ if (ret ==TEST_OK &&dso__kernel (dso) !=DSO_SPACE__USER ) ret =process_subdivided_dso (ti->machine, dso); + +if (ret ==TEST_OK ) { +int shrink_ret =test_dso_shrink_and_reload (ti, filename, &map); + +if (shrink_ret !=TEST_SKIP ) + ret = shrink_ret; + } out_put:map__put (map);return ret; } +static int test_symbols_sorted_insert (void ) +__context_unsafe (/* single-threaded white-box test */ ) +{ +struct dso *dso =dso__new ("/tmp/perf_test_sorted_insert" ); +struct symbols *symbols; +int ret =TEST_FAIL ; + +if (!dso) +return TEST_FAIL ; + + symbols =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 =0 ; i <100 ; i++) { +char name[32 ]; +u64 addr = (u64)(i *2 +1 ) *0x100 ; +struct symbol *sym; + +snprintf (name,sizeof (name),"sym_%u" , i *2 +1 ); + sym =symbol__new (addr,0x40 ,STB_GLOBAL ,STT_FUNC , name); +if (!sym ||symbols__insert (symbols, sym)) + goto out; + } +if (!symbols->sorted || symbols->cnt !=100 ) { +pr_debug ("Expected sorted=true, cnt=100 after ordered inserts\n" ); + goto out; + } + +for (unsigned int i =0 ; i <5 ; i++) { +char name[32 ]; +u64 addr = (u64)(i *20 ) *0x100 ; +struct symbol *sym; + +snprintf (name,sizeof (name),"ins_%u" , i *20 ); + sym =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 path. +*/ +for (unsigned int i =99 ; i >0 ; i--) { +char name[32 ]; +u64 addr; +struct symbol *sym; + +if ((i *2 ) %20 ==0 && (i *2 ) <100 ) +continue ; + addr = (u64)(i *2 ) *0x100 ; +snprintf (name,sizeof (name),"ins_%u" , i *2 ); + sym =symbol__new (addr,0x40 ,STB_GLOBAL ,STT_FUNC , name); +if (!sym ||symbols__insert (symbols, sym)) + goto out; + } +if (symbols->sorted || symbols->cnt !=200 ) { +pr_debug ("Unexpected sorted=%d cnt=%u before lookup\n" , + symbols->sorted, symbols->cnt); + goto out; + } + +for (unsigned int i =0 ; i <200 ; i++) { +u64 addr = (u64 )i *0x100 +0x10 ; +struct symbol *sym =dso__find_symbol (dso, addr); + +if (!sym || sym->start != (u64 )i *0x100 ) { +pr_debug ("Lookup failed at idx %u (addr=%#" 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 =symbol__new (0x20 ,0x10 ,STB_GLOBAL ,STT_FUNC , +"inner_tail_sym" ); +struct symbol *outer =symbol__new (0x80 ,0x100 ,STB_GLOBAL ,STT_FUNC , +"outer_tail_sym" ); +struct symbol *alias =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 >= symbols->cnt) { +pr_debug ("Expected unmerged sorted tail!\n" ); + goto out; + } +if (dso__find_symbol (dso,0x24 ) != inner || +dso__find_symbol (dso,0x34 ) !=NULL || +dso__find_symbol (dso,0x150 ) !=NULL || +dso__find_symbol (dso,0x250 ) != 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 ) != inner || +dso__find_symbol (dso,0x34 ) !=NULL || +dso__find_symbol (dso,0x150 ) !=NULL || +dso__find_symbol (dso,0x250 ) != alias) { +pr_debug ("Merged lookup mismatch!\n" ); + goto out; + } + } + + ret =TEST_OK ; +out: +dso__put (dso); +return ret; +} + +static int test_symbols_equal_start_aliases (void ) +{ +struct dso *dso =dso__new ("/tmp/perf_test_equal_start_aliases" ); +struct map *map =NULL ; +struct symbols *symbols; +struct symbol *sized_sym, *zero_alias, *last_sized, *last_short, *found; +int ret =TEST_FAIL ; + +if (!dso) +return TEST_FAIL ; + + map =map__new2 (0 , dso); +if (!map) + goto out; + + symbols =dso__symbols (dso); + sized_sym =symbol__new (0x1000 ,0x40 ,STB_GLOBAL ,STT_FUNC ,"sized_sym" ); + zero_alias =symbol__new (0x1000 ,0 ,STB_GLOBAL ,STT_FUNC ,"zero_alias" ); + last_sized =symbol__new (0x2000 ,0x80 ,STB_GLOBAL ,STT_FUNC ,"last_sized" ); +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 =dso__find_symbol (dso,0x1020 ); +if (found != 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=*/ false); +if (zero_alias->end !=0x1000 ) { +pr_debug ("zero_alias inflated to %#" PRIx64"\n" , zero_alias->end); + goto out; + } +symbols__fixup_duplicate (symbols); + found =dso__find_symbol (dso,0x1020 ); +if (found != sized_sym || found->end !=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 =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) !=0x2080 ) { +pr_debug ("Expected map end 0x2080, got %#" PRIx64"\n" ,map__end (map)); + goto out; + } + + ret =TEST_OK ; +out: +map__put (map); +dso__put (dso); +return ret; +} +static int test__symbols (struct test_suite *test__maybe_unused ,int subtest__maybe_unused ) {char filename[PATH_MAX ];struct test_info ti;int ret; + ret =test_symbols_sorted_insert (); +if (ret !=TEST_OK ) +return ret; + + ret =test_symbols_equal_start_aliases (); +if (ret !=TEST_OK ) +return ret; + + ret =test_symbols_shrink (); +if (ret !=TEST_OK ) +return ret; + + ret =test_dsos_shrink (); +if (ret !=TEST_OK ) +return ret; + + ret =test_session_alloc_shrink (); +if (ret !=TEST_OK ) +return ret; + ret =init_test_info (&ti);if (ret !=TEST_OK )return ret;
@@ -240,24 +998,28 @@ static int test__symbols(struct test_suite *test __maybe_unused, int subtest __mstruct kallsyms_sym {u64 start; +u8 binding;const char *name; };/* * 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[] = { - {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]" }, };static int check_symbol (struct dso *dso,u64 addr,const char *name,u64 end)
@@ -287,7 +1049,8 @@ static int test__kallsyms_fixup_end(struct test_suite *test __maybe_unused,return TEST_FAIL ;for (unsigned int i =0 ; i <ARRAY_SIZE (kallsyms_syms); i++) { -struct symbol *sym =symbol__new (kallsyms_syms[i].start,0 ,0 ,0 , +struct symbol *sym =symbol__new (kallsyms_syms[i].start,0 , + kallsyms_syms[i].binding,STT_FUNC , kallsyms_syms[i].name);if (!sym)
@@ -296,8 +1059,13 @@ static int test__kallsyms_fixup_end(struct test_suite *test __maybe_unused, }symbols__fixup_end (dso__symbols (dso), true); +symbols__fixup_duplicate (dso__symbols (dso)); ret =TEST_OK ; +/* Same-address weak/global alias pair resolves to global_target_symbol. */ +if (check_symbol (dso,0xffffffff81000510 ,"global_target_symbol" , +0xffffffff81000ff0 )) + ret =TEST_FAIL ;/* The next symbol is too close for the end of the page. */ if (check_symbol (dso,0xffffffff81000ff8 ,"last_kernel_symbol" ,0xffffffff81001000 ))
Signature · 1 line
2.56.1.750.gf70dc682cf-goog
[email protected]
AI reviewSashiko has reviewed this 10-patch series and found no issues.
Sashiko has reviewed this 10-patch series and found no issues.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]
Hi Ian,
Quoted 16 lines · Ian Rogers
When profiling large binaries or long-running workloads with many DSOs and threads, symbol and DSO tables frequently dominate perf's memory footprint and startup latency. Currently
struct symbolstill has several structural limitations:1. Every
struct symbolembeds a 24-bytestruct rb_nodefor thedso->symbolsaddress rbtree, scattering lookups across non-contiguous heap nodes.
2.dso__symbols()has no internal synchronization against concurrent readers/writers, and unreferenced DSOs and auxiliary symbol/debuginfo buffers cannot yet be reclaimed under memory pressure.
3. Sortingdso->symbolswithqsort()does not take advantage of pre-ordered ascending runs in ELF symbol tables, andfirst_ending_after()instruct mapsruns a full binary search even for ascending/proc/pid/mapssynthesis.
Quoted 6 lines
Thirteen preparatory fixes, benchmarks,
dso_symbollifetime conversions,symbol_conf.priv_sizeremoval, and ELF header caching patches from v4-v6 have landed inperf-tools-next. The remaining 10 patches convert symbol iteration to callbacks, replace thedso->symbolsrbtree with a sorted pointer array, stage natural-run merge sort and incremental symbol insertion, and add memory shrinking APIs and unit tests:
I've applied the first 6 patches to perf-tools-next.
The patch 7 was bigger than I expected. Can you simplify it more?
Also I don't plan to merge the rest patches as of now. Let's wait for the lazy loading and try that for a while.
Thanks,
Namhyung
Quoted 161 lines
- **Preparatory fix,
mapstail fast-path, and symbol iteration (Patches 1-4)**:
- Patch 1 fixes analloc_func_regexleak on error returns in`builtin-kmem.c`'s `build_alloc_func_list()`.- Patch 2 adds an O(1) tail fast-path check in
first_ending_after()for ascending map insertions.
- Patch 3 convertssymbols__for_each_entry(),dso__for_each_symbol(), andmap__for_each_symbol()to callback-based iteration and updates existing callers.
- Patch 4 converts open-codeddso__first_symbol()/dso__next_symbol(),rb_first_cached(), anddso__symbol_names()loops to callback helpers and removesdso__{first,last,next}_symbol().
- **Sorted symbol arrays and staged sorting optimizations (Patches 5-7)**:
- Patch 5 replacesdso->symbols(rb_root_cached) anddso->symbol_nameswith arw_semaphore-protectedstruct symbolscontainer backed by sorted pointer arrays, removingstruct rb_nodefromstruct symbol(shrinkingsizeof(struct symbol)from 48 to 24 bytes, or 16 bytes net per symbol after accounting for the array pointer).
- Patch 6 replacesqsort()onstruct symbolswith a stable natural-run merge sort.
- Patch 7 optimizes incremental dynamic symbol insertions (dso__insert_symbol()) and small appends using@sorted_cntand a sorted tail buffer with amortizedsqrt(N)merge.
- **Memory shrinking APIs and unit tests (Patches 8-10)**:
- Patch 8 addssymbols__shrink(),dso__shrink(),dsos__shrink(),`machine__shrink()`, `machines__shrink()`, and `perf_session__shrink()` to reclaim `symbols_by_name`, excess array capacity, cached DSO file descriptors/data/DWARF state, and unreferenced user DSOs (`refcnt == 1` with no annotated symbols), with transparent on-demand reload via `dso__load()`.- Patch 9 adds
dso__session()andperf_session__malloc()/zalloc()/calloc()/realloc()/strdup()wrappers (leaving production caller wiring for follow-up once lazy symbol loading is evaluated).
- Patch 10 adds unit tests inperf test symbolscovering sorted symbol insertion, equal-start aliases, symbol/DSO shrinking,dso_symbollifetime pinning, inline frame/srcline cleanup ordering,symbols_by_nameon-demand rebuild, transparent DSO reload, and session allocation wrappers.Changes in v8:
- Rebase ontotmp.perf-tools-next(eb79d2fbc230), adopting<linux/compiler-context-analysis.h>annotations (__guarded_by(&lock),__acquires_shared(&symbols->lock),__must_hold(&symbols->lock),__context_unsafe()) onstruct symbolsanddso/tests/symbols.cand adaptingdso__shrink()/dso__try_evict()todso__data_open_lockandclose_dso().
- Passfirst_unsorted(m = symbols->sorted_cnt) tosymbols__insertion_sort_range()insymbols__sort_locked()(Patch 7) so thek <= 8small-append fast path and allocation-failure fallbacks skip scanning the already-sorted prefix[0 .. m)(Sashiko).Changes in v7:
- Rebase ontoperf-tools-next(bb27ddbaee56), dropping the 3 patches from v6 that have been applied upstream.
- Dropnr_addr_sortedandnr_name_sortedincremental partial-sort state fromstruct maps, keeping only thefirst_ending_after()tail fast-path check (Patch 2) (Namhyung Kim).
- Split out thealloc_func_regexleak fix inbuiltin-kmem.c(Patch 1), themap__for_each_symbol()callback conversion (Patch 3), and the conversion of open-coded symbol loops (Patch 4) ahead of therbtreetostruct symbolsarray conversion (Patch 5) (Namhyung Kim).
- Split symbol sorting optimization into a simple natural-run merge sort patch without galloping (Patch 6) followed by incremental dynamic symbol insertion with a sorted tail (Patch 7) (Namhyung Kim).Changes in v6:
- Fixsymbols__find()whensorted_cnt < cntso that if the slice (sorted prefix or unmerged sorted tail) with the higherstart <= ipgroup ends beforeip,symbols__find()returnsNULLrather than falling back to an earlier outer symbol in the other slice, matching post-merge behavior, and add unmerged-vs-merged prefix/tail overlap and equal-start alias unit tests (Sashiko).
- Use positiveENOMEMrather than-ENOMEMonsymbol__annotation()failure insymbol__annotate(),symbol__annotate2(), and__hist_entry__tui_annotate()to matchsymbol__strerror_disassemble(), checksymbol__annotate() != 0inhist_entry__get_data_type(), and guard againstNULLnotes/notes->srcinfind_disasm_line()(Sashiko).v7: https://lore.kernel.org/linux-perf-users/[email protected]/
v6: https://lore.kernel.org/linux-perf-users/[email protected]/
v5: https://lore.kernel.org/linux-perf-users/[email protected]/
v4: https://lore.kernel.org/linux-perf-users/[email protected]/
v3: https://lore.kernel.org/linux-perf-users/[email protected]/
v2: https://lore.kernel.org/linux-perf-users/[email protected]/
v1: https://lore.kernel.org/lkml/[email protected]/AI Assistance Disclosure (per
Documentation/process/coding-assistants.rstandDocumentation/process/generated-content.rst):
- Tools used: Google Antigravity / Jetski coding assistant and Sashiko automated patch review (sashiko.dev and internal Sashiko).
- Summary of prompts and assistance: Interactive pair-programming session to replace per-symbol refcounting withstruct dso_symbolDSO-borrowed lifetimes, split symbol callback iteration and staged natural-run merge sort / incremental insertion patches, rebase ontotmp.perf-tools-nextcontext-analysis annotations, and address LKML reviewer and Sashiko feedback acrosskmem,dso,map,maps,symbol, andtests/symbols.c.
- Testing performed: Built each commit ([1/10]through[10/10]) with Clang (-DWARN_CONTEXT_ANALYSIS -Wthread-safety -Wthread-safety-pointer -Wthread-safety-beta), AddressSanitizer, LeakSanitizer, andDEBUG=1(REFCNT_CHECKING=1); ranperf test(includingSymbols,Maps,DSO data,hists,thread, andannotatesuites),perf bench internals(symbolsandmaps), andscripts/checkpatch.pl.Ian Rogers (10):
perf kmem: Fixalloc_func_regexleak on error in
build_alloc_func_list()
perf maps: Add tail fast-path check infirst_ending_after()perf symbol: Convertmap__for_each_symbol()to callback-based
iteration
perf symbol: Use callback iteration instead of open-coded symbol loops perf symbol: Switch backing storage from rbtree to struct symbols
array
perf symbol: Replaceqsort()with natural-run merge sort perf symbol: Optimize incremental symbol insertion with sorted tail perf symbol: Add memory shrinking for symbols, DSOs, and machines perf session: Adddso__session()and session-scoped allocation
wrappers
perf test symbols: Add tests for symbol shrinking and session alloc
wrapperstools/perf/arch/powerpc/util/sym-handling.c | 34 +- tools/perf/builtin-annotate.c | 11 - tools/perf/builtin-kmem.c | 51 +- tools/perf/tests/hists_common.c | 5 +- tools/perf/tests/maps.c | 46 + tools/perf/tests/symbols.c | 851 ++++++++++++++- tools/perf/tests/vmlinux-kallsyms.c | 181 ++-- tools/perf/ui/browser.c | 3 + tools/perf/ui/browsers/hists.c | 3 +- tools/perf/ui/browsers/map.c | 62 +- tools/perf/util/auxtrace.c | 109 +- tools/perf/util/db-export.c | 4 +- tools/perf/util/dso.c | 324 +++++- tools/perf/util/dso.h | 90 +- tools/perf/util/dsos.c | 51 + tools/perf/util/dsos.h | 3 + tools/perf/util/intel-pt.c | 74 +- tools/perf/util/libbfd.c | 3 +- tools/perf/util/machine.c | 60 +- tools/perf/util/machine.h | 8 + tools/perf/util/map.c | 36 +- tools/perf/util/map.h | 8 +- tools/perf/util/maps.c | 4 + tools/perf/util/probe-event.c | 98 +- tools/perf/util/session.c | 78 ++ tools/perf/util/session.h | 8 + tools/perf/util/symbol-elf.c | 12 +- tools/perf/util/symbol.c | 1042 +++++++++++++++---- tools/perf/util/symbol.h | 84 +- tools/perf/util/symbol_fprintf.c | 25 +- 30 files changed, 2706 insertions(+), 662 deletions(-)base-commit:
eb79d2fbc230d41b009e49f20671303c6efbd946Signature · 1 line
2.56.1.750.gf70dc682cf-goog
Ian Rogers
reviewerQuoted 27 lines · Namhyung Kim
Hi Ian,
Quoted 16 lines · Ian Rogers
When profiling large binaries or long-running workloads with many DSOs and threads, symbol and DSO tables frequently dominate perf's memory footprint and startup latency. Currently
struct symbolstill has several structural limitations:1. Every
struct symbolembeds a 24-bytestruct rb_nodefor thedso->symbolsaddress rbtree, scattering lookups across non-contiguous heap nodes.
2.dso__symbols()has no internal synchronization against concurrent readers/writers, and unreferenced DSOs and auxiliary symbol/debuginfo buffers cannot yet be reclaimed under memory pressure.
3. Sortingdso->symbolswithqsort()does not take advantage of pre-ordered ascending runs in ELF symbol tables, andfirst_ending_after()instruct mapsruns a full binary search even for ascending/proc/pid/mapssynthesis.Quoted 6 lines
Thirteen preparatory fixes, benchmarks,
dso_symbollifetime conversions,symbol_conf.priv_sizeremoval, and ELF header caching patches from v4-v6 have landed inperf-tools-next. The remaining 10 patches convert symbol iteration to callbacks, replace thedso->symbolsrbtree with a sorted pointer array, stage natural-run merge sort and incremental symbol insertion, and add memory shrinking APIs and unit tests:
Quoted 6 lines
I've applied the first 6 patches to perf-tools-next.
The patch 7 was bigger than I expected. Can you simplify it more?
Also I don't plan to merge the rest patches as of now. Let's wait for the lazy loading and try that for a while.
Thanks for merging those ones. I will split patch 7 and rebase. Patch 8, shrinking DSOs, etc. is kind of the whole point of the series.
Thanks,
Ian
Quoted 164 lines
Thanks,
NamhyungQuoted 161 lines
- **Preparatory fix,
mapstail fast-path, and symbol iteration (Patches 1-4)**:
- Patch 1 fixes analloc_func_regexleak on error returns in`builtin-kmem.c`'s `build_alloc_func_list()`.- Patch 2 adds an O(1) tail fast-path check in
first_ending_after()for ascending map insertions.
- Patch 3 convertssymbols__for_each_entry(),dso__for_each_symbol(), andmap__for_each_symbol()to callback-based iteration and updates existing callers.
- Patch 4 converts open-codeddso__first_symbol()/dso__next_symbol(),rb_first_cached(), anddso__symbol_names()loops to callback helpers and removesdso__{first,last,next}_symbol().
- **Sorted symbol arrays and staged sorting optimizations (Patches 5-7)**:
- Patch 5 replacesdso->symbols(rb_root_cached) anddso->symbol_nameswith arw_semaphore-protectedstruct symbolscontainer backed by sorted pointer arrays, removingstruct rb_nodefromstruct symbol(shrinkingsizeof(struct symbol)from 48 to 24 bytes, or 16 bytes net per symbol after accounting for the array pointer).
- Patch 6 replacesqsort()onstruct symbolswith a stable natural-run merge sort.
- Patch 7 optimizes incremental dynamic symbol insertions (dso__insert_symbol()) and small appends using@sorted_cntand a sorted tail buffer with amortizedsqrt(N)merge.
- **Memory shrinking APIs and unit tests (Patches 8-10)**:
- Patch 8 addssymbols__shrink(),dso__shrink(),dsos__shrink(),`machine__shrink()`, `machines__shrink()`, and `perf_session__shrink()` to reclaim `symbols_by_name`, excess array capacity, cached DSO file descriptors/data/DWARF state, and unreferenced user DSOs (`refcnt == 1` with no annotated symbols), with transparent on-demand reload via `dso__load()`.- Patch 9 adds
dso__session()andperf_session__malloc()/zalloc()/calloc()/realloc()/strdup()wrappers (leaving production caller wiring for follow-up once lazy symbol loading is evaluated).
- Patch 10 adds unit tests inperf test symbolscovering sorted symbol insertion, equal-start aliases, symbol/DSO shrinking,dso_symbollifetime pinning, inline frame/srcline cleanup ordering,symbols_by_nameon-demand rebuild, transparent DSO reload, and session allocation wrappers.Changes in v8:
- Rebase ontotmp.perf-tools-next(eb79d2fbc230), adopting<linux/compiler-context-analysis.h>annotations (__guarded_by(&lock),__acquires_shared(&symbols->lock),__must_hold(&symbols->lock),__context_unsafe()) onstruct symbolsanddso/tests/symbols.cand adaptingdso__shrink()/dso__try_evict()todso__data_open_lockandclose_dso().
- Passfirst_unsorted(m = symbols->sorted_cnt) tosymbols__insertion_sort_range()insymbols__sort_locked()(Patch 7) so thek <= 8small-append fast path and allocation-failure fallbacks skip scanning the already-sorted prefix[0 .. m)(Sashiko).Changes in v7:
- Rebase ontoperf-tools-next(bb27ddbaee56), dropping the 3 patches from v6 that have been applied upstream.
- Dropnr_addr_sortedandnr_name_sortedincremental partial-sort state fromstruct maps, keeping only thefirst_ending_after()tail fast-path check (Patch 2) (Namhyung Kim).
- Split out thealloc_func_regexleak fix inbuiltin-kmem.c(Patch 1), themap__for_each_symbol()callback conversion (Patch 3), and the conversion of open-coded symbol loops (Patch 4) ahead of therbtreetostruct symbolsarray conversion (Patch 5) (Namhyung Kim).
- Split symbol sorting optimization into a simple natural-run merge sort patch without galloping (Patch 6) followed by incremental dynamic symbol insertion with a sorted tail (Patch 7) (Namhyung Kim).Changes in v6:
- Fixsymbols__find()whensorted_cnt < cntso that if the slice (sorted prefix or unmerged sorted tail) with the higherstart <= ipgroup ends beforeip,symbols__find()returnsNULLrather than falling back to an earlier outer symbol in the other slice, matching post-merge behavior, and add unmerged-vs-merged prefix/tail overlap and equal-start alias unit tests (Sashiko).
- Use positiveENOMEMrather than-ENOMEMonsymbol__annotation()failure insymbol__annotate(),symbol__annotate2(), and__hist_entry__tui_annotate()to matchsymbol__strerror_disassemble(), checksymbol__annotate() != 0inhist_entry__get_data_type(), and guard againstNULLnotes/notes->srcinfind_disasm_line()(Sashiko).v7: https://lore.kernel.org/linux-perf-users/[email protected]/
v6: https://lore.kernel.org/linux-perf-users/[email protected]/
v5: https://lore.kernel.org/linux-perf-users/[email protected]/
v4: https://lore.kernel.org/linux-perf-users/[email protected]/
v3: https://lore.kernel.org/linux-perf-users/[email protected]/
v2: https://lore.kernel.org/linux-perf-users/[email protected]/
v1: https://lore.kernel.org/lkml/[email protected]/AI Assistance Disclosure (per
Documentation/process/coding-assistants.rstandDocumentation/process/generated-content.rst):
- Tools used: Google Antigravity / Jetski coding assistant and Sashiko automated patch review (sashiko.dev and internal Sashiko).
- Summary of prompts and assistance: Interactive pair-programming session to replace per-symbol refcounting withstruct dso_symbolDSO-borrowed lifetimes, split symbol callback iteration and staged natural-run merge sort / incremental insertion patches, rebase ontotmp.perf-tools-nextcontext-analysis annotations, and address LKML reviewer and Sashiko feedback acrosskmem,dso,map,maps,symbol, andtests/symbols.c.
- Testing performed: Built each commit ([1/10]through[10/10]) with Clang (-DWARN_CONTEXT_ANALYSIS -Wthread-safety -Wthread-safety-pointer -Wthread-safety-beta), AddressSanitizer, LeakSanitizer, andDEBUG=1(REFCNT_CHECKING=1); ranperf test(includingSymbols,Maps,DSO data,hists,thread, andannotatesuites),perf bench internals(symbolsandmaps), andscripts/checkpatch.pl.Ian Rogers (10):
perf kmem: Fixalloc_func_regexleak on error in
build_alloc_func_list()
perf maps: Add tail fast-path check infirst_ending_after()perf symbol: Convertmap__for_each_symbol()to callback-based
iteration
perf symbol: Use callback iteration instead of open-coded symbol loops perf symbol: Switch backing storage from rbtree to struct symbols
array
perf symbol: Replaceqsort()with natural-run merge sort perf symbol: Optimize incremental symbol insertion with sorted tail perf symbol: Add memory shrinking for symbols, DSOs, and machines perf session: Adddso__session()and session-scoped allocation
wrappers
perf test symbols: Add tests for symbol shrinking and session alloc
wrapperstools/perf/arch/powerpc/util/sym-handling.c | 34 +- tools/perf/builtin-annotate.c | 11 - tools/perf/builtin-kmem.c | 51 +- tools/perf/tests/hists_common.c | 5 +- tools/perf/tests/maps.c | 46 + tools/perf/tests/symbols.c | 851 ++++++++++++++- tools/perf/tests/vmlinux-kallsyms.c | 181 ++-- tools/perf/ui/browser.c | 3 + tools/perf/ui/browsers/hists.c | 3 +- tools/perf/ui/browsers/map.c | 62 +- tools/perf/util/auxtrace.c | 109 +- tools/perf/util/db-export.c | 4 +- tools/perf/util/dso.c | 324 +++++- tools/perf/util/dso.h | 90 +- tools/perf/util/dsos.c | 51 + tools/perf/util/dsos.h | 3 + tools/perf/util/intel-pt.c | 74 +- tools/perf/util/libbfd.c | 3 +- tools/perf/util/machine.c | 60 +- tools/perf/util/machine.h | 8 + tools/perf/util/map.c | 36 +- tools/perf/util/map.h | 8 +- tools/perf/util/maps.c | 4 + tools/perf/util/probe-event.c | 98 +- tools/perf/util/session.c | 78 ++ tools/perf/util/session.h | 8 + tools/perf/util/symbol-elf.c | 12 +- tools/perf/util/symbol.c | 1042 +++++++++++++++---- tools/perf/util/symbol.h | 84 +- tools/perf/util/symbol_fprintf.c | 25 +- 30 files changed, 2706 insertions(+), 662 deletions(-)base-commit:
eb79d2fbc230d41b009e49f20671303c6efbd946--
2.56.1.750.gf70dc682cf-goog
Hi Ian, Namhyung,
Quoted 5 lines
Quoted 5 lines
I've applied the first 6 patches to perf-tools-next.
The patch 7 was bigger than I expected. Can you simplify it more?
Quoted 9 lines
Quoted 2 lines
Also I don't plan to merge the rest patches as of now. Let's wait for the lazy loading and try that for a while.
Thanks for merging those ones. I will split patch 7 and rebase. Patch 8, shrinking DSOs, etc. is kind of the whole point of the series.
Thanks,
Ian
The lazy loading v9 is rebased onto perf-tools-next with the first six patches, so it now works on the sorted symbol array instead of the rb-tree. I'm going through review fixes and should post it later this week.
Ian, it uses symbols__visit(), symbols__sort_read_lock() and the symbols array directly, so if the split of patch 7 changes those, I'll rebase on whichever lands first. I'm also happy to run your remaining patches on top of v9 against the same profile as in the cover letter and send the numbers, since the two should save memory in different places.
Thanks,
Alireza
Ian Rogers
reviewerQuoted 23 lines · Alireza Haghdoost
Hi Ian, Namhyung,
Quoted 5 lines
Quoted 5 lines
I've applied the first 6 patches to perf-tools-next.
The patch 7 was bigger than I expected. Can you simplify it more?
Quoted 9 lines
Quoted 2 lines
Also I don't plan to merge the rest patches as of now. Let's wait for the lazy loading and try that for a while.
Thanks for merging those ones. I will split patch 7 and rebase. Patch 8, shrinking DSOs, etc. is kind of the whole point of the series.
Thanks,
IanThe lazy loading v9 is rebased onto perf-tools-next with the first six patches, so it now works on the sorted symbol array instead of the rb-tree. I'm going through review fixes and should post it later this week.
Quoted 6 lines
Ian, it uses
symbols__visit(),symbols__sort_read_lock()and the symbols array directly, so if the split of patch 7 changes those, I'll rebase on whichever lands first. I'm also happy to run your remaining patches on top of v9 against the same profile as in the cover letter and send the numbers, since the two should save memory in different places.
Thanks! In v9 (sending out shortly), symbols__visit() and symbols__sort_read_lock() keep the same signatures and contract:symbols__sort_read_lock() merges any secondary sorted run or unsorted tail so symbols->symbols[0 .. symbols->cnt) is a single contiguous sorted array under the read lock.
The only struct symbols field change to watch for if lazy loading populates struct symbols directly (rather than via symbols__insert()) is that num_by_name, sorted_by_name, and the sorted boolean were dropped in favor of sorted_cnt and sorted_tail_cnt (so sorted = true becomes sorted_cnt = cnt; sorted_tail_cnt = 0, and zfree(&symbols_by_name) alone invalidates the name index).
Running the shrinking patches on top of lazy loading v9 against your profile sounds great—thank you for offering to test and share the numbers!
Thanks,
Ian
Quoted 2 lines
Thanks,
Alireza