mirror of https://lore.kernel.org/lkml/
 help / color / mirror / Atom feed
* [PATCH v7 0/15] perf tools: Annotate fixes, stdio progress indication, debuginfo-client in more places
@ 2026-09-17 15:55 Arnaldo Carvalho de Melo
  2026-09-17 15:55 ` [PATCH 01/15] perf debuginfo: Fetch debuginfo keyed by build ID using debuginfod Arnaldo Carvalho de Melo
                   ` (14 more replies)
  0 siblings, 15 replies; 18+ messages in thread
From: Arnaldo Carvalho de Melo @ 2026-09-17 15:55 UTC (permalink / raw)
  To: Namhyung Kim
  Cc: Ingo Molnar, Thomas Gleixner, James Clark, Jiri Olsa, Ian Rogers,
	Adrian Hunter, Clark Williams, linux-kernel, linux-perf-users,
	Arnaldo Carvalho de Melo

Hi,

This came out of work on data type profiling, but none of it depends on that
work and nothing in this series needs anything from it, so sending it
separately.

The fixes:

  - 'perf report -s type' spins forever on the dwz compressed debug info of
    zlib-ng (libz.so.1): die_collect_vars() saves a type DIE offset that is
    relative to the file the DIE lives in, the dwz alt file for types shared
    by several CUs, and resolving it in the main file parses whatever is at
    that offset, here a typedef whose DW_AT_type refers to itself, making the
    typedef/qualifier chase spin (patch 12), with the chases bounded so that
    other kinds of broken debug info don't hang perf either (patches 10, 11
    and 13);

  - the data type browser's samples view (-n) prints a local count that is
    initialized to zero and never updated, so every member has no samples
    (patch 7);

The features:

  - 'perf report --progress' prints the current phase and how far along it is
    to stderr (patch 8);

  - the debuginfo of a DSO, and the kernel symbols, can be fetched keyed by
    the build ID recorded in perf.data using debuginfod (patch 1), with
    DEBUGINFOD_URLS set from /etc/debuginfod when needed (patch 2) and
    opt-outs that clear it for libdwfl's own client too;

  - a slow fetch can be skipped ('s') or disabled for the session ('d'), with
    the progress shown on stderr or in a TUI window over the browser (patches
    4 and 5; perf_config__set_variable() moves to util/config.c, patch 3);

  - 'perf mem record' requests PERF_SAMPLE_CPU (patch 14) and uses the IBS
    swfilt filter when the kernel exposes it (patch 15).

Requires elfutils 0.160 for dwarf_cu_getdwarf(), so the libdw feature test
probes for it and Makefile.config says 0.160: older versions now disable
dwarf support with that message instead of failing to link.

What changed from v6 (d39be25e74340e7afa631ff40fa3810a205f04e7):

  General: commit logs and code comments were made more concise throughout,
  following Namhyung Kim's review of the v6 posting
  [<aqsX6GfGu9QnqX5u@google.com>]; no functional change.

  PATCH 1/15, "perf debuginfo: Fetch debuginfo keyed by build ID using
  debuginfod", was split [Namhyung Kim review of PATCH v6 2/12,
  <aqrjA6UCNId2Vebq@google.com>]: the fetch is patch 1, the DEBUGINFOD_URLS
  handling, now with the copy perf owns, is patch 2.

  PATCH 12/15, "perf annotate-data: Resolve type DIEs in the debug file they
  came from", was split [Namhyung Kim review of PATCH v6 10/12,
  <aqsN1si6jjWrocIQ@google.com>]: the generic bound on the dwarf-aux type
  chases is patch 10, die_same_file()/die_get_type_die() and the elfutils
  0.160 requirement are patch 11, the fix using them is patch 12, and the
  member nesting bound is the separate patch 13.

  PATCH 3/15, "perf config: Move perf_config__set_variable() to util/config.c"
  [sashiko-bot review of the two v6 postings]:

  - The system_config choice is derived from the file being rewritten, so
    rewriting the system wide file doesn't truncate it;

  - added the <limits.h> include for PATH_MAX;

  - all config file access is serialized with a mutex.

  PATCH 4/15, "perf debuginfo: Let the user skip and disable debuginfod
  fetches" [Namhyung Kim, <aqrlw1YzYHFBdvcz@google.com>, and sashiko-bot]:

  - The 's'/'d' keys are drained with read()s that return zero when nothing
    was typed, so the fetch isn't held up waiting for a keypress;

  - the disable empties the DEBUGINFOD_URLS copy perf owns, not a setenv()
    racing other threads' getenv()s.

  PATCH 5/15, "perf debuginfo: Show the debuginfod fetch progress and keys in
  the TUI" [sashiko-bot]: the progress window clamps its width.

  PATCH 6/15, "perf symbol: Fall back to fetching the vmlinux by build ID"
  [sashiko-bot]: mapping the x86-64 entry trampolines is idempotent.

  PATCH 1/16, "perf test: Skip data_type_profiling when the PMU cannot
  record memory events", was merged upstream as 29f320d2 and is not part
  of this series anymore.

  Patches 7, 8, 9, 14 and 15 have no content changes from v6, only the
  trimming.

What changed from v5 (ef0ac8e44d43d2aa86842d2f83ad41d1c058d949):

  PATCH 2/9, "perf debuginfo: Fetch debuginfo keyed by build ID using
  debuginfod", was split [Namhyung Kim review of PATCH v3 2/8,
  <aqdPNG6szS6YJjOi@google.com>]: the fetch stays in patch 2, the way
  to get out of a slow fetch, that was folded at the end of patch 2 in
  v5, is now patches 3 to 5, each separately cherry-pickable, and
  carrying on their own the answer to his "I'm not sure what would be
  the good default.  But with this, it can slow down the process
  especially when the binary is not in the debuginfod": on by default,
  with the way to skip the one in progress and to disable the feature
  right where the wait is felt.  Patch 3, "perf config: Move
  perf_config__set_variable() to util/config.c", is the prep patch,
  patch 4, "perf debuginfo: Let the user skip and disable debuginfod
  fetches", has the stdio 's'/'d' keys, and patch 5, "perf debuginfo:
  Show the debuginfod fetch progress and keys in the TUI", the TUI
  window over the browser.

  PATCH 4/12, "perf debuginfo: Let the user skip and disable debuginfod
  fetches" [that same review of the 'd' key semantics]:

  - 'd' now writes core.debuginfod=false into the configuration file
    directly, the user's ~/.perfconfig or the one named by PERF_CONFIG,
    via perf_config__set_variable(), moved from builtin-config.c to
    util/config.c by the prep patch so that util/debuginfo.c can use
    it, and clears DEBUGINFOD_URLS so that libdwfl's own debuginfod
    client stops for the rest of the session too: in v5 it only
    disabled debuginfod for the rest of the session and pointed at
    'perf config' to make that permanent.

  PATCH 5/12, "perf debuginfo: Show the debuginfod fetch progress and
  keys in the TUI":

  - The progress and the keys are no longer stdio-only: printing to
    stderr would garble the TUI browser display, so in v5 a fetch in
    progress in the TUI showed nothing and there was no way to skip or
    disable it, the thing that makes a slow fetch indistinguishable
    from a stuck perf.  The TUI now draws a window over the browser
    with the fetch progress and drains the 's'/'d' keys from the TUI
    input queue: the TUI owns the terminal and its input queue, and the
    browser thread is the one doing the fetch, so nobody else is
    reading from it while the fetch blocks it.  No terminal settings or
    signal dispositions are touched in that case, the terminal is the
    TUI's own and so are the SIGINT/SIGTERM handlers, that restore it
    before exiting.

  - The slang calls stay in ui/tui/, behind the ui__key_pending()/
    ui__key_read()/ui__progress_window()/ui__progress_window_end()
    primitives declared in ui/util.h and implemented in ui/tui/util.c,
    with inline stubs for builds without slang: the plan is to reduce
    the number of libraries perf needs to build, or swap slang for
    something else, such as ncurses, at some point, so nothing outside
    ui/ calls slang directly.  The text in the window is word wrapped
    to the available columns, as constrained terminals, such as a
    smartphone running termux, crop the tail of a long line and would
    hide the 'd' option hint.

  Patches 1, 3, 4, 5, 6, 7, 8 and 9 are unchanged from v5, renumbered
  as 1, 6, 7, 8, 9, 10, 11 and 12 with the split.

What changed from v4 (f801de4e80289566):

  PATCH 1/8, "perf test: Skip data_type_profiling when the PMU cannot
  record memory events" [Namhyung Kim review of PATCH v3 1/8]:

  - Namhyung suggested adding a fallback to the 'swfilt' term for
    ibs_op instead of only skipping the test on a PMU that refuses
    per-thread memory events.  The new PATCH 9 does that for the ibs_op
    memory events, using the swfilt software privilege filter the
    kernel exposes as a format term since v6.14, which makes the
    per-thread 'perf mem record' the test does work on AMD; the skip
    stays for kernels without it.  The term is in the event name even
    for records that end up without exclude bits, e.g. plain system
    wide ones: 'perf record' adds those bits itself when the first
    open fails with EACCES, after the name was built, and the retry
    only succeeds with the term already in the name:

      $ perf record -v -e ibs_op/ldlat=0/ -- true
      kernel.perf_event_paranoid=2, trying to fall back to excluding kernel and hypervisor  samples
      Failure to open event 'ibs_op/ldlat=0/u' on PMU 'ibs_op' which will be removed.
      Invalid event (ibs_op/ldlat=0/u) in per-thread mode, enable system wide with '-a'.

    with no exclude bits the kernel discards nothing.  The 'Test data
    symbol' shell test matches the event string, so its regex now
    accepts terms added after ldlat=150.

  PATCH 2/8, "perf debuginfo: Fetch debuginfo keyed by build ID using
  debuginfod" [sashiko-bot review of PATCH v4 2/8]:

  - debuginfod__setup_urls_env() moved from util/debuginfo.c to
    util/util.c, next to perf_debuginfod_setup(), and its declaration
    from util/debuginfo.h to util/util.h: debuginfo.o is only built with
    CONFIG_LIBDW, so with libdebuginfod but without libdw the
    declaration was an empty stub and the setup was skipped exactly for
    build-id.c and probe-event.c, the debuginfod users that are built
    without libdw and that the commit message lists as reading
    DEBUGINFOD_URLS in every debuginfod_begin().

  PATCH 8/8, "perf mem record: Request PERF_SAMPLE_CPU by default"
  [sashiko-bot review of PATCH v4 8/8]:

  - The rec_argv array now reserves room for the fixed arguments
    __cmd_record() adds, up to eight with all the optional flags; a
    pre-existing under-allocation, the array was nine arguments per
    memory PMU plus the user arguments, and on a PMU with separate load
    and store events the four event arguments plus the fixed ones
    already filled it to the last slot, so this new --sample-cpu
    argument would write past it, e.g. with --phys-data --data-page-size
    --all-user.

  Patches 1, 3, 4, 5, 6 and 7 are unchanged from v4: sashiko-bot found
  no issues in them.

What changed from v3 (2433e9f0bf86cfc3):

  PATCH 2/8, "perf debuginfo: Fetch debuginfo keyed by build ID using
  debuginfod" [sashiko-bot review of PATCH v3 2/8]:

  - DEBUGINFOD_URLS is no longer set from the fetch path: setenv() is
    not thread safe and libdebuginfod reads it with getenv() in every
    debuginfod_begin(), which perf also does from build-id.c,
    probe-event.c and probe-finder.c, paths that don't go through the
    fetch lock, so a thread taking one of them could race with the
    setenv() a fetch was doing.  This is now done from symbol__init(),
    before the threads are started, from the .urls files in
    /etc/debuginfod when it isn't set, and the pthread_once() and the
    call in debuginfod__fetch() are gone with it.

  - The in-flight fetch wait was dead code and is gone: with
    debuginfod__fetch_lock held across the whole lookup and fetch, no
    second thread could ever see an entry being fetched, so the
    condition variable, the waiters and the publication dance could not
    run.  debuginfo_lookup__new() became debuginfo_lookup__add(), called
    after a fetch that brought a file back: lookups remember only the
    successful fetches, one entry each, answered with a strdup() and
    re-fetched if that file goes away, and a request for a build ID
    being fetched waits for the lock and is answered from the misses
    list or from the entry, so a download still can't happen twice.
    debuginfod__missed_lock, always taken under the fetch lock, is gone
    with it.

  PATCH 3/8, "perf symbol: Fall back to fetching the vmlinux by build ID"
  [sashiko-bot review of PATCH v3 3/8]:

  - The check for a concurrent load, made after taking dso->lock back
    from the fetch, is now dso__has_symbols() and not dso__loaded():
    dso__load() sets the latter even for an attempt that failed, so a
    thread whose fetch failed could make a thread whose fetch succeeded
    discard the vmlinux it just downloaded and carry on with an empty
    kernel dso, as loaded is set and nothing would try again.

  PATCH 6/8, "perf scripts: Add perf-stuck, to tell where a running perf
  is stuck" [sashiko-bot review of PATCH v3 6/8]:

  - The review asked whether the %s of a dwarf_diename() that returns
    NULL in perf-die-chain would abort the macro.  Checked, not changed:
    with GDB 17.2, printf prints "(null)" for a NULL char *, including
    for an inferior call returning one, and the macro carries on.  The
    other %s in the file, dloc->ms->sym->name in perf-dso, can't be NULL
    either: the only caller of find_data_type() dereferences ms->sym and
    ms->map to build the data_loc_info before that frame can exist, so
    no change there as well.

  - Patches 1, 4, 5, 7 and 8 are unchanged from v3: sashiko-bot found
    no issues in them.

What changed from v2 (00cffc7df5abfa68):

  PATCH 2/8, "perf debuginfo: Fetch debuginfo keyed by build ID using
  debuginfod" [sashiko-bot review of PATCH v2 2/8]:

  - The conditions to fetch, debuginfod being enabled, the build-id cache
    being on and the build ID not having been a miss already, are now
    looked at with the fetch lock held, as they are the state the fetch
    itself changes: deciding them outside the lock and fetching inside it
    let a second thread repeat the fetch the first one had just made, or
    repeat one that had just been turned off, and put the same build ID
    on the misses list twice.

  - A build ID that is already being fetched is waited for, instead of
    fetched again: there was nothing that said "this one is in flight", so
    a second thread wanting it blocked on the fetch lock and then did its
    own complete fetch, which, while the first one is still running, is a
    second download of the same file, with a second client, a second
    progress line and a second turn at the terminal, for the same answer.
    It now sleeps on a condition variable and is woken with whatever the
    fetch settled: the file, when there is one, or the not available, when
    it found nothing or the user cancelled it, with no retry.

  - And a fetch that brought a file back is remembered, so that the ones
    that need the same build ID later, e.g. annotating another symbol of
    the same DSO, are answered with a strdup() instead of another client:
    the file stays in the debuginfod client cache, and its path is checked
    before being handed out, in case that cache gets cleaned from under
    us.

  - The fetches are still one at a time, so a fetch for one build ID waits
    for a fetch for another one: the terminal mode, the signal
    dispositions, the progress line and the 's'/'d' keys are process
    global, and sharing them between concurrent fetches, refcounted, is
    left for later, noted in the code.  It matters less than it sounds,
    now that the build IDs of a workload are answered from memory after
    the first pass over them.

  PATCH 3/8, "perf symbol: Fall back to fetching the vmlinux by build ID"
  [sashiko-bot review of PATCH v2 3/8]:

  - The fetch is no longer made with dso->lock held: dso__load() holds it
    across dso__load_kernel_sym(), and a fetch can block for a long time
    on the network, or on the terminal, waiting for the user, which would
    stall every other thread that needs the kernel dso.  It is dropped
    just around the fetch, nothing of the dso is touched while it is, and
    the symbols are loaded with the lock held again, the same way
    dso__debuginfo() already does it for the debuginfo of a DSO.  If
    another thread got the symbols for the dso in the meantime, the file
    that came back is not loaded a second time.

  PATCH 5/8, "perf report: Add --progress option" [sashiko-bot review of
  PATCH v2 5/8]:

  - A phase that starts when the progress stack is full is now just not
    shown, and its finish() is swallowed, instead of force completing the
    phase that encloses it to make room: that one still gets its own
    finish() later, which would then complete the phase above it, and so
    on, one premature completion per nesting level.  Reproduced by
    building with STDIO_PROGRESS__MAX_DEPTH set to 1: v2 prints
    "Processing events... [100.0%]" while it is at 99.7%, before the
    nested phase even runs, v3 warns and keeps the outer phase to
    complete when it really does.  With the 8 slots in the tree this
    cannot be hit, the phases perf has nest at most 2 deep, but the
    bookkeeping was wrong.

  PATCH 6/8, "perf scripts: Add perf-stuck, to tell where a running perf
  is stuck" [sashiko-bot review of PATCH v2 6/8]:

  - The perf-dso GDB macro read dloc->ms.map->dso->name and
    dloc->ms.sym->name, but struct data_loc_info.ms is a
    'struct map_symbol *', so GDB's C evaluator needs -> there: as it
    was, 'perf-stuck.sh -g' would have failed to evaluate it.

  - The one pre-existing issue in PATCH 7/8, the unbounded member type
    chase in die_get_member_type() and the unbounded recursion in
    die_find_member(), is not addressed here, it went to the perf TODO
    list as item 180, as it is not on the path this series fixes.

  Other changes since v2:

  - PATCH 2/8: a refetch made because the cached file was cleaned from
    under us now updates the entry the same way the first fetch does,
    and an entry with no path and no error is fetched again instead of
    answered; as it was, the entry kept the first fetch's success with
    no path, so the later lookups it existed for returned success with
    a NULL path, which debuginfo__new_build_id() cannot open and the
    vmlinux fallback in PATCH 3 would take as a file that came back
    and dereference.

  - PATCH 3/8: the commit message said the ignore_vmlinux_buildid that
    'perf record' and 'perf probe' set internally is what keeps them
    away from the fallback, but 'perf probe' only sets it for the
    commands other than --list, --del and --add when given an offline
    vmlinux; the message now says that and that a 'perf probe' that
    does not set it, e.g. --funcs or --add without --vmlinux on a
    system with a restricted /proc/kallsyms, can have the kernel
    debuginfo fetched, like the other tools.

  - PATCH 7/8: the kerneldoc of die_get_type_die() said the type would
    be looked up in the main file and then in the alt file, using the
    one that has a DIE with the saved tag, but the function
    deliberately resolves in only the file the offset was recorded as
    belonging to, with no fallback, and @from_alt was missing from the
    parameter list; it now describes that, and the die_collect_vars()
    and die_collect_global_vars() kerneldocs, which still said the
    type could be retrieved with dwarf_offdie() and the offset alone,
    now point at die_get_type_die().

  - PATCH 7/8: the comment on the member->truncated flag said the
    browser reads it, but the browser picks between ';' and '{' from
    the children list, so a member cut by the nesting limit is drawn
    like a complete leaf; the comment now says the flag is for the
    JSON exporter added in a later series.

  - PATCH 2/8: a search aborted by the user, with 's' or a signal, is
    now remembered for the rest of the session: the threads already
    waiting for that fetch were told there was nothing to share, but a
    request that arrived later started a new download of the same file,
    which the user may have skipped for being too big.  debuginfod__misses
    now records such a cancellation as a cancellation, the 's' message
    says the build ID will not be fetched again in this session and the
    debug message tells a cancellation and a server miss apart.  The
    lookup entry is also now allocated and published by a
    debuginfo_lookup__new() helper called before the fetch, instead of
    an allocation whose failure was only checked after it.

  - Patches 1, 4 and 8 are unchanged from v2: sashiko-bot found no
    issues in them.

What changed from v1 (060dccedab1617dc):

  PATCH 2/8, "perf debuginfo: Fetch debuginfo keyed by build ID using
  debuginfod" [sashiko-bot review of PATCH 2/8]:

  - Included <limits.h> for PATH_MAX, that was coming in through a
    glibc transitive include and fails to build with musl libc.

  - debuginfod__setup_urls_env() now goes through pthread_once, so that
    the setenv() of DEBUGINFOD_URLS happens exactly once: setenv() is
    not thread safe and this is on the fetch path, which
    dso__debuginfo() deliberately takes outside dso__lock.

  - The fetch now runs with debuginfod__fetch_lock held, so that the
    process global state it uses — the terminal settings, the SIGINT/
    SIGTERM dispositions and the progress and cancellation state — is
    only ever touched by one fetch at a time.  A second concurrent
    fetch would otherwise have taken the first one's raw mode as the
    state to restore, leaving the terminal broken when it was done, and
    would reset the cancellation state from under the fetch already in
    progress.  Serializing also keeps two fetches from racing for the
    same keypresses and the same progress line, and a second fetch has
    nothing to gain from running in parallel with a first one reading
    the same kind of file off the same servers.

  - An interrupt that lands after the fetch already succeeded is no
    longer swallowed: at that point the terminal and the signal
    dispositions are the original ones again, so the signal is re-raised,
    the same way the failure path does, instead of perf carrying on as
    if the user had not asked it to stop.

  PATCH 6/8, "perf scripts: Add perf-stuck, to tell where a running perf
  is stuck" [sashiko-bot review of PATCH 6/8]:

  - /proc/<pid>/stat is now parsed with the parenthesized command name
    removed first, so that a process with spaces in its name no longer
    shifts every field after it: watching a process named 'my sleep'
    used to report "sleep)" as its state and a garbage RSS.

  - The CPU time is printed with awk's printf "%d" instead of relying on
    its default output format, that switches to scientific notation,
    which the bash arithmetic below cannot parse, once the sum of utime
    and stime goes past six digits, i.e. some 16 minutes of CPU at
    100 Hz.

  - The process can go away between the '-d /proc/<pid>' check and the
    read of /proc/<pid>/stat, so the read is now checked: a failed or
    empty one reports "process gone" instead of 'set -u' aborting the
    script on an unbound field, which is what would have hidden the
    very exit the script is meant to report.

  - The command line printed when the script starts has its control
    characters stripped, so that a process started with escape sequences
    in its arguments, e.g. one replaying a log line, does not get them
    replayed on the terminal of whoever runs this.

  - The two pre-existing issues sashiko-bot raised that are outside the
    scope of this series, the child entries and their hists arrays
    leaked by the data type browser teardown and the missing <stdio.h>
    and <stdlib.h> includes in ui/browsers/annotate-data.c, are
    recorded as items 178 and 179 of the perf TODO list for follow-up
    work.

  - Patches 1, 3, 4, 5, 7 and 8 are unchanged from v1: sashiko-bot
    found no issues in them.

Arnaldo Carvalho de Melo (15):
  perf debuginfo: Fetch debuginfo keyed by build ID using debuginfod
  perf debuginfo: Set DEBUGINFOD_URLS from /etc/debuginfod when unset
  perf config: Move perf_config__set_variable() to util/config.c
  perf debuginfo: Let the user skip and disable debuginfod fetches
  perf debuginfo: Show the debuginfod fetch progress and keys in the TUI
  perf symbol: Fall back to fetching the vmlinux by build ID
  perf annotate-data: Show the sample count in the data-type browser
  perf report: Add --progress option
  perf scripts: Add perf-stuck, to tell where a running perf is stuck
  perf dwarf-aux: Bound the type chases for broken debug info
  perf dwarf-aux: Add die_same_file() and die_get_type_die()
  perf annotate-data: Resolve type DIEs in the debug file they came from
  perf annotate-data: Bound the member nesting recursion
  perf mem record: Request PERF_SAMPLE_CPU by default
  perf mem record: Use the IBS swfilt filter when available

 tools/build/feature/test-libdw.c           |  13 +-
 tools/perf/Documentation/perf-annotate.txt |  10 +
 tools/perf/Documentation/perf-config.txt   |  19 +
 tools/perf/Documentation/perf-mem.txt      |   4 +
 tools/perf/Documentation/perf-report.txt   |  31 ++
 tools/perf/Documentation/perf-top.txt      |  16 +
 tools/perf/Makefile.config                 |   2 +-
 tools/perf/arch/x86/util/mem-events.c      |  14 +-
 tools/perf/builtin-annotate.c              |   3 +
 tools/perf/builtin-config.c                |  70 +--
 tools/perf/builtin-mem.c                   |  11 +-
 tools/perf/builtin-report.c                |  17 +
 tools/perf/builtin-top.c                   |   7 +
 tools/perf/scripts/perf-stuck.gdb          | 104 +++++
 tools/perf/scripts/perf-stuck.sh           | 194 +++++++++
 tools/perf/tests/shell/test_data_symbol.sh |   6 +-
 tools/perf/ui/Build                        |   1 +
 tools/perf/ui/browsers/annotate-data.c     |   2 +-
 tools/perf/ui/progress.h                   |   2 +
 tools/perf/ui/stdio/progress.c             | 163 +++++++
 tools/perf/ui/tui/util.c                   | 171 ++++++++
 tools/perf/ui/util.h                       |  27 ++
 tools/perf/util/annotate-data.c            |  53 ++-
 tools/perf/util/annotate-data.h            |   3 +
 tools/perf/util/config.c                   |  99 ++++-
 tools/perf/util/config.h                   |   2 +
 tools/perf/util/debuginfo.c                | 481 +++++++++++++++++++++
 tools/perf/util/debuginfo.h                |  35 ++
 tools/perf/util/dso.c                      |  10 +
 tools/perf/util/dwarf-aux.c                | 150 ++++++-
 tools/perf/util/dwarf-aux.h                |  17 +
 tools/perf/util/machine.c                  |  11 +-
 tools/perf/util/mem-events.c               |  18 +-
 tools/perf/util/mem-events.h               |   2 +
 tools/perf/util/ordered-events.c           |  16 +-
 tools/perf/util/session.c                  |  12 +-
 tools/perf/util/symbol.c                   |  64 ++-
 tools/perf/util/symbol_conf.h              |   1 +
 tools/perf/util/util.c                     | 151 ++++++-
 tools/perf/util/util.h                     |   9 +
 40 files changed, 1887 insertions(+), 134 deletions(-)
 create mode 100644 tools/perf/scripts/perf-stuck.gdb
 create mode 100755 tools/perf/scripts/perf-stuck.sh
 create mode 100644 tools/perf/ui/stdio/progress.c
base-commit: 29f320d221c1c4c082c7eafb2251fedf8a4868ec
v6-head: d39be25e74340e7afa631ff40fa3810a205f04e7
v5-head: ef0ac8e44d43d2aa86842d2f83ad41d1c058d949
v4-head: f801de4e80289566670e6b735198606b672e74e8
v3-head: 2433e9f0bf86cfc3d9966b467042563596c9ebdb
v2-head: 00cffc7df5abfa6850beb360deb830d8495163ce
v1-head: 060dccedab1617dcbf6e2be64ed97afe3f3fac63
--
Assisted-by: LLM

^ permalink raw reply	[flat|nested] 18+ messages in thread

* [PATCH 01/15] perf debuginfo: Fetch debuginfo keyed by build ID using debuginfod
  2026-09-17 15:55 [PATCH v7 0/15] perf tools: Annotate fixes, stdio progress indication, debuginfo-client in more places Arnaldo Carvalho de Melo
@ 2026-09-17 15:55 ` Arnaldo Carvalho de Melo
  2026-09-17 17:58   ` Ian Rogers
  2026-09-17 15:55 ` [PATCH 02/15] perf debuginfo: Set DEBUGINFOD_URLS from /etc/debuginfod when unset Arnaldo Carvalho de Melo
                   ` (13 subsequent siblings)
  14 siblings, 1 reply; 18+ messages in thread
From: Arnaldo Carvalho de Melo @ 2026-09-17 15:55 UTC (permalink / raw)
  To: Namhyung Kim
  Cc: Ingo Molnar, Thomas Gleixner, James Clark, Jiri Olsa, Ian Rogers,
	Adrian Hunter, Clark Williams, linux-kernel, linux-perf-users,
	Arnaldo Carvalho de Melo

From: Arnaldo Carvalho de Melo <acme@redhat.com>

Add debuginfo__find_build_id(), which uses the debuginfod client to
locate a debuginfo file keyed by the build ID - checking its local cache
first and then the servers in DEBUGINFOD_URLS - and
debuginfo__new_build_id(), which opens the DWARF in the file it finds.
dso__debuginfo() falls back to it for DSOs whose debuginfo is not
installed locally, e.g. the vmlinux of a kernel profiled on another
machine or upgraded since, doing the fetch outside dso__lock.

Querying servers, possibly third party ones, sends the build IDs of the
binaries being analysed off-box, and a fetch can take a while, so this
is opt-out: --no-debuginfod, core.debuginfod=false,
report.debuginfod/top.debuginfod, and off also when the build-id cache
is disabled.  Fetches are serialized and misses are remembered, as both
the lookup state and the fetch interaction are process global.

Assisted-by: LLM
Signed-off-by: Arnaldo Carvalho de Melo <acme@redhat.com>
---
 tools/perf/Documentation/perf-annotate.txt |   8 +
 tools/perf/Documentation/perf-config.txt   |  19 ++
 tools/perf/Documentation/perf-report.txt   |  12 +
 tools/perf/Documentation/perf-top.txt      |  11 +
 tools/perf/builtin-annotate.c              |   3 +
 tools/perf/builtin-report.c                |   7 +
 tools/perf/builtin-top.c                   |   7 +
 tools/perf/util/config.c                   |   3 +
 tools/perf/util/debuginfo.c                | 327 +++++++++++++++++++++
 tools/perf/util/debuginfo.h                |  35 +++
 tools/perf/util/dso.c                      |  10 +
 tools/perf/util/symbol.c                   |   2 +
 tools/perf/util/symbol_conf.h              |   1 +
 13 files changed, 445 insertions(+)

diff --git a/tools/perf/Documentation/perf-annotate.txt b/tools/perf/Documentation/perf-annotate.txt
index 1a90b09a12d5abb1..12edc3337b86f099 100644
--- a/tools/perf/Documentation/perf-annotate.txt
+++ b/tools/perf/Documentation/perf-annotate.txt
@@ -58,6 +58,14 @@ OPTIONS
 --ignore-vmlinux::
 	Ignore vmlinux files.
 
+--debuginfod::
+--no-debuginfod::
+	Fetch debuginfo keyed by build ID from the debuginfod servers
+	configured in DEBUGINFOD_URLS, checking the local debuginfod
+	client cache first, when it is not available locally, on for
+	these commands by default.  See the --debuginfod option of
+	'perf report' for how to turn it off.
+
 --itrace::
 	Options for decoding instruction tracing data. The options are:
 
diff --git a/tools/perf/Documentation/perf-config.txt b/tools/perf/Documentation/perf-config.txt
index 9b223f8928299945..688306abe847a0df 100644
--- a/tools/perf/Documentation/perf-config.txt
+++ b/tools/perf/Documentation/perf-config.txt
@@ -216,6 +216,14 @@ core.*::
 	addr2line-timeout::
 		Sets a timeout (in milliseconds) for parsing 'addr2line'
 		output.  The default timeout is 5s.
+	debuginfod::
+		When set to 'false', disable fetching debuginfo keyed by
+		build ID from the debuginfod servers configured in
+		DEBUGINFOD_URLS.  It is on by default, can be overridden per
+		tool with the 'report.debuginfod' and 'top.debuginfod'
+		options and per invocation with --no-debuginfod; it is off
+		too when the local build-id cache is disabled, e.g.
+		'buildid.dir' set to /dev/null.
 
 tui.*, gtk.*::
 	Subcommands that can be configured here are 'top', 'report' and 'annotate'.
@@ -562,6 +570,14 @@ report.*::
 		This option can change default stat behavior with empty results.
 		If it's set true, 'perf report --stat' will not show 0 stats.
 
+	report.debuginfod::
+		Fetch debuginfo keyed by build ID from the debuginfod
+		servers configured in DEBUGINFOD_URLS, checking the local
+		debuginfod client cache first, when it is not available
+		locally.  On by default, set to 'false' to disable it for
+		'perf report', globally with 'core.debuginfod=false' or per
+		invocation with --no-debuginfod.
+
 top.*::
 	top.children::
 		Same as 'report.children'. So if it is enabled, the output of 'top'
@@ -569,6 +585,9 @@ top.*::
 		column by default.
 		The default is 'true'.
 
+	top.debuginfod::
+		Same as 'report.debuginfod', for 'perf top'.
+
 	top.call-graph::
 		This is identical to 'call-graph.record-mode', except it is
 		applicable only for 'top' subcommand. This option ONLY setup
diff --git a/tools/perf/Documentation/perf-report.txt b/tools/perf/Documentation/perf-report.txt
index 1a4706329c6cef1d..2e11c0a97a016853 100644
--- a/tools/perf/Documentation/perf-report.txt
+++ b/tools/perf/Documentation/perf-report.txt
@@ -366,6 +366,18 @@ OPTIONS
 --ignore-vmlinux::
 	Ignore vmlinux files.
 
+--debuginfod::
+--no-debuginfod::
+	Fetch debuginfo keyed by build ID from the debuginfod servers
+	configured in DEBUGINFOD_URLS, checking the local debuginfod
+	client cache first, when it is not available locally, on for
+	these commands by default.  It can be turned off per invocation
+	with --no-debuginfod, per tool with the "report.debuginfod"
+	config option or globally with "core.debuginfod" set to false.
+	It is disabled as well when the local build-id cache is turned
+	off, e.g. "buildid.dir" set to /dev/null, as that asks for
+	fetched files not to be kept on the box.
+
 --kallsyms=<file>::
         kallsyms pathname
 
diff --git a/tools/perf/Documentation/perf-top.txt b/tools/perf/Documentation/perf-top.txt
index 2da2a16bbf260685..345dd9ee9b6bab88 100644
--- a/tools/perf/Documentation/perf-top.txt
+++ b/tools/perf/Documentation/perf-top.txt
@@ -83,6 +83,17 @@ Default is to monitor all CPUS.
 --ignore-vmlinux::
 	Ignore vmlinux files.
 
+--debuginfod::
+--no-debuginfod::
+	Fetch debuginfo keyed by build ID from the debuginfod servers
+	configured in DEBUGINFOD_URLS, checking the local debuginfod
+	client cache first, when it is not available locally, on for
+	these commands by default.  Turn it off per invocation with
+	--no-debuginfod, with the "top.debuginfod" config option or
+	globally with "core.debuginfod" set to false.  Disabled as well
+	when the build-id cache is off, e.g. "buildid.dir" set to
+	/dev/null.
+
 --kallsyms=<file>::
 	kallsyms pathname
 
diff --git a/tools/perf/builtin-annotate.c b/tools/perf/builtin-annotate.c
index 850fc72fa75fe7df..d6a201c1866d363f 100644
--- a/tools/perf/builtin-annotate.c
+++ b/tools/perf/builtin-annotate.c
@@ -733,6 +733,9 @@ int cmd_annotate(int argc, const char **argv)
 	OPT_BOOLEAN(0, "stdio2", &annotate.use_stdio2, "Use the stdio interface"),
 	OPT_BOOLEAN(0, "ignore-vmlinux", &symbol_conf.ignore_vmlinux,
                     "don't load vmlinux even if found"),
+	OPT_BOOLEAN(0, "debuginfod", &symbol_conf.debuginfod,
+		    "fetch debuginfo keyed by build ID from the debuginfod "
+		    "servers, on by default, use --no-debuginfod to turn off"),
 	OPT_STRING('k', "vmlinux", &symbol_conf.vmlinux_name,
 		   "file", "vmlinux pathname"),
 	OPT_BOOLEAN('m', "modules", &symbol_conf.use_modules,
diff --git a/tools/perf/builtin-report.c b/tools/perf/builtin-report.c
index 279e61c2366cb294..442c0822e614197f 100644
--- a/tools/perf/builtin-report.c
+++ b/tools/perf/builtin-report.c
@@ -134,6 +134,10 @@ static int report__config(const char *var, const char *value, void *cb)
 		symbol_conf.event_group = perf_config_bool(var, value);
 		return 0;
 	}
+	if (!strcmp(var, "report.debuginfod")) {
+		symbol_conf.debuginfod = perf_config_bool(var, value);
+		return 0;
+	}
 	if (!strcmp(var, "report.percent-limit")) {
 		double pcnt = strtof(value, NULL);
 
@@ -1346,6 +1350,9 @@ int cmd_report(int argc, const char **argv)
 		   "file", "vmlinux pathname"),
 	OPT_BOOLEAN(0, "ignore-vmlinux", &symbol_conf.ignore_vmlinux,
                     "don't load vmlinux even if found"),
+	OPT_BOOLEAN(0, "debuginfod", &symbol_conf.debuginfod,
+		    "fetch debuginfo keyed by build ID from the debuginfod "
+		    "servers, on by default, use --no-debuginfod to turn off"),
 	OPT_STRING(0, "kallsyms", &symbol_conf.kallsyms_name,
 		   "file", "kallsyms pathname"),
 	OPT_BOOLEAN('f', "force", &symbol_conf.force, "don't complain, do it"),
diff --git a/tools/perf/builtin-top.c b/tools/perf/builtin-top.c
index c2562d49be46a9a1..2be6859fd4aee141 100644
--- a/tools/perf/builtin-top.c
+++ b/tools/perf/builtin-top.c
@@ -1436,6 +1436,10 @@ static int perf_top_config(const char *var, const char *value, void *cb __maybe_
 		symbol_conf.cumulate_callchain = perf_config_bool(var, value);
 		return 0;
 	}
+	if (!strcmp(var, "top.debuginfod")) {
+		symbol_conf.debuginfod = perf_config_bool(var, value);
+		return 0;
+	}
 
 	return 0;
 }
@@ -1508,6 +1512,9 @@ int cmd_top(int argc, const char **argv)
 		   "file", "vmlinux pathname"),
 	OPT_BOOLEAN(0, "ignore-vmlinux", &symbol_conf.ignore_vmlinux,
 		    "don't load vmlinux even if found"),
+	OPT_BOOLEAN(0, "debuginfod", &symbol_conf.debuginfod,
+		    "fetch debuginfo keyed by build ID from the debuginfod "
+		    "servers, on by default, use --no-debuginfod to turn off"),
 	OPT_STRING(0, "kallsyms", &symbol_conf.kallsyms_name,
 		   "file", "kallsyms pathname"),
 	OPT_BOOLEAN('K', "hide_kernel_symbols", &top.hide_kernel_symbols,
diff --git a/tools/perf/util/config.c b/tools/perf/util/config.c
index b2972c35c1eca68c..31c6618d3b3daf22 100644
--- a/tools/perf/util/config.c
+++ b/tools/perf/util/config.c
@@ -470,6 +470,9 @@ static int perf_default_core_config(const char *var, const char *value)
 	if (!strcmp(var, "core.addr2line-disable-warn"))
 		symbol_conf.addr2line_disable_warn = perf_config_bool(var, value);
 
+	if (!strcmp(var, "core.debuginfod"))
+		symbol_conf.debuginfod = perf_config_bool(var, value);
+
 	/* Add other config variables here. */
 	return 0;
 }
diff --git a/tools/perf/util/debuginfo.c b/tools/perf/util/debuginfo.c
index 84a78b30ceac1066..be5882d9c2204797 100644
--- a/tools/perf/util/debuginfo.c
+++ b/tools/perf/util/debuginfo.c
@@ -7,16 +7,22 @@
 
 #include <errno.h>
 #include <fcntl.h>
+#include <limits.h>
+#include <pthread.h>
+#include <stdbool.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
 #include <unistd.h>
+#include <linux/list.h>
 #include <linux/zalloc.h>
+#include <api/fs/fs.h>
 
 #include "build-id.h"
 #include "dso.h"
 #include "debug.h"
 #include "debuginfo.h"
+#include "mutex.h"
 #include "symbol.h"
 
 #ifdef HAVE_DEBUGINFOD_SUPPORT
@@ -139,6 +145,327 @@ struct debuginfo *debuginfo__new(const char *path)
 	return __debuginfo__new(buf);
 }
 
+#ifdef HAVE_DEBUGINFOD_SUPPORT
+/*
+ * Users can disable the local build-id/.debug cache by setting
+ * buildid.dir to /dev/null, meaning they don't want fetched
+ * binaries/debuginfo stored on the box; the debuginfod client keeps
+ * its own cache in ~/.cache/debuginfod_client, so honour that intent
+ * and don't fetch at all in that case.
+ */
+static bool debuginfod__cache_disabled(void)
+{
+	return !strcmp(buildid_dir, "/dev/null");
+}
+
+/*
+ * Build IDs that shouldn't be searched for again in this session: the
+ * ones already searched for on the debuginfod servers without success,
+ * so that callers that see the same DSO over and over, such as the data
+ * type profiler switching between DSOs on every hist entry, don't pay a
+ * server round trip again for each miss.  The cache of successes is the
+ * debuginfod client's own, in the local filesystem.
+ *
+ * Guarded by debuginfod__fetch_lock: it is only read by the lookups
+ * below, that run with that lock held, and written by fetches, that run
+ * with it held too.
+ */
+struct debuginfod_miss {
+	struct list_head	node;
+	struct build_id		bid;
+};
+
+static LIST_HEAD(debuginfod__misses);
+
+/*
+ * Was the search for this build ID already made and settled, i.e. the
+ * servers had nothing for it?
+ */
+static bool debuginfod__missed(const struct build_id *bid)
+{
+	struct debuginfod_miss *miss;
+
+	list_for_each_entry(miss, &debuginfod__misses, node) {
+		if (miss->bid.size == bid->size &&
+		    !memcmp(miss->bid.data, bid->data, bid->size))
+			return true;
+	}
+
+	return false;
+}
+
+static void debuginfod__miss_add(const struct build_id *bid)
+{
+	struct debuginfod_miss *miss = zalloc(sizeof(*miss));
+
+	if (miss == NULL)
+		return;
+
+	miss->bid = *bid;
+
+	list_add(&miss->node, &debuginfod__misses);
+}
+
+/*
+ * One fetch at a time.
+ *
+ * The lookup state below is process global, so two concurrent fetches,
+ * which dso__debuginfo() makes possible by taking the fetch out of
+ * dso__lock, would race for it: the second one could answer from a list
+ * the first one is concurrently updating, and put the same build ID on
+ * the misses list twice.
+ *
+ * Serializing also means a second request for a build ID that is being
+ * fetched waits here for the fetch to finish, instead of starting a second
+ * download of the same file, and is then answered from the entry the fetch
+ * published, or from the misses list, with no client at all.  Should the
+ * fetches ever run in parallel, that wait has to come back explicitly, with
+ * this lock split in two: one only for the lookup state, that the waiters
+ * sleep on, and one held around each fetch, with the thread that finds a
+ * fetch in progress waiting on the former for the entry to be published.
+ *
+ * What that costs is that a fetch for one build ID blocks a fetch for
+ * another one, and it is what parallel downloads would fix.  Worth doing
+ * only if the wait turns out to be long, because it mostly is not: the
+ * lookups below answer the second and later requests for a build ID from
+ * memory, so after the first pass over the build IDs of a workload, which
+ * is the only time anything is fetched at all, the serialization has
+ * nothing left to serialize.  Start there if a profile with many DSOs to
+ * fetch shows up in a profile of perf itself.
+ */
+static struct mutex debuginfod__fetch_lock;
+
+static void debuginfod__fetch_lock_setup(void)
+{
+	mutex_init(&debuginfod__fetch_lock);
+}
+
+static void debuginfod__fetch_lock_init(void)
+{
+	static pthread_once_t once = PTHREAD_ONCE_INIT;
+
+	pthread_once(&once, debuginfod__fetch_lock_setup);
+}
+
+/*
+ * The build IDs already fetched in this session, and the path of the file
+ * that came back for each, so that the repeated requests for the same build
+ * ID, dso__debuginfo() is called per symbol annotated, are answered with a
+ * strdup() instead of another client: the file is in the debuginfod client
+ * cache already and its path checked before being handed out, in case that
+ * cache is cleaned from under us.
+ *
+ * Guarded by debuginfod__fetch_lock.  Only a fetch that brought a file back
+ * gets an entry: one that didn't is recorded in debuginfod__misses as a miss,
+ * and that is what keeps the rest of the session from asking for it again.
+ * Like debuginfod__misses this grows with the number of build IDs in the
+ * workload, one small entry each, and is not trimmed.
+ */
+struct debuginfo_lookup {
+	struct list_head	 node;
+	struct build_id		 bid;
+	char			*path;
+};
+
+static LIST_HEAD(debuginfo_lookups);
+
+static bool build_id__equal(const struct build_id *a, const struct build_id *b)
+{
+	return a->size == b->size && memcmp(a->data, b->data, a->size) == 0;
+}
+
+static struct debuginfo_lookup *debuginfo_lookup__find(const struct build_id *bid)
+{
+	struct debuginfo_lookup *lookup;
+
+	list_for_each_entry(lookup, &debuginfo_lookups, node) {
+		if (build_id__equal(&lookup->bid, bid))
+			return lookup;
+	}
+
+	return NULL;
+}
+
+static void debuginfo_lookup__delete(struct debuginfo_lookup *lookup)
+{
+	list_del(&lookup->node);
+	zfree(&lookup->path);
+	free(lookup);
+}
+
+/*
+ * Remember that this build ID was fetched, with the file at @path, so that
+ * the next request for it is answered from memory.  Called with
+ * debuginfod__fetch_lock held.  Out of memory just means not sharing this
+ * one, the file is fetched and the caller has its path.
+ */
+static void debuginfo_lookup__add(const struct build_id *bid, const char *path)
+{
+	struct debuginfo_lookup *lookup = zalloc(sizeof(*lookup));
+
+	if (lookup == NULL)
+		return;
+
+	lookup->bid = *bid;
+	lookup->path = strdup(path);
+	if (lookup->path == NULL) {
+		free(lookup);
+		return;
+	}
+
+	list_add(&lookup->node, &debuginfo_lookups);
+}
+
+/*
+ * The fetch itself.  Called with debuginfod__fetch_lock held for the
+ * whole of it, see the comment there.
+ */
+static int debuginfod__fetch(const struct build_id *bid, char **path)
+{
+	char sbuild_id[SBUILD_ID_SIZE];
+	debuginfod_client *c;
+	int fd;
+
+	c = debuginfod_begin();
+	if (c == NULL)
+		return -1;
+
+	fd = debuginfod_find_debuginfo(c, bid->data, bid->size, path);
+
+	debuginfod_end(c);
+
+	if (fd < 0) {
+		build_id__snprintf(bid, sbuild_id, sizeof(sbuild_id));
+		pr_debug("No debuginfo found for build ID %s in debuginfod\n",
+			 sbuild_id);
+		debuginfod__miss_add(bid);
+		return -1;
+	}
+
+	close(fd);
+
+	return 0;
+}
+
+/*
+ * Look the build ID up in the files already fetched in this session,
+ * fetching it if it isn't there yet.  Called, and left, with
+ * debuginfod__fetch_lock held, which also means that no fetch for this
+ * build ID can be running anywhere else: a second request for a build ID
+ * being fetched waits for the lock and is answered from the entry the fetch
+ * published, or from the misses list, with no client at all.
+ */
+static int debuginfo_lookup__find_build_id(const struct build_id *bid, char **path)
+{
+	struct debuginfo_lookup *lookup = debuginfo_lookup__find(bid);
+
+	if (lookup != NULL) {
+		/*
+		 * The file stays in the debuginfod client cache, but that
+		 * cache can be cleaned from under us, so check that it is
+		 * still there before handing its path out.  If it isn't,
+		 * forget the entry and look for the file again below,
+		 * remembering the new answer the same way the first fetch
+		 * does, so that the next lookup shares it instead of
+		 * fetching it a third time.
+		 */
+		if (access(lookup->path, R_OK) == 0) {
+			*path = strdup(lookup->path);
+			return *path != NULL ? 0 : -1;
+		}
+
+		debuginfo_lookup__delete(lookup);
+	}
+
+	if (debuginfod__fetch(bid, path) < 0)
+		return -1;
+
+	debuginfo_lookup__add(bid, *path);
+
+	return 0;
+}
+
+/*
+ * Find a debuginfo file keyed by the build ID, using the debuginfod
+ * client, which checks its local cache first and then queries the
+ * servers in DEBUGINFOD_URLS.  Used when the debuginfo is not available
+ * locally under the name the DSO was opened with, for instance the
+ * vmlinux for the kernel the profile was recorded on, when processing
+ * the profile on another machine or after the kernel or its debuginfo
+ * package got upgraded in between.
+ *
+ * Querying servers, possibly third party, sends the build IDs of the
+ * binaries being analysed off the box, so this is opt-out: on by
+ * default, switchable off with --no-debuginfod, with
+ * core.debuginfod=false, with the per-tool
+ * report.debuginfod/top.debuginfod, and it is off too when the user
+ * disabled the local build-id/.debug cache, e.g. with
+ * buildid.dir = /dev/null, as is the case for users that don't want
+ * any of this stored locally.
+ *
+ * On success the path is stored in *@path and must be freed by the
+ * caller, the file remains available in the debuginfod client cache.
+ */
+int debuginfo__find_build_id(const struct build_id *bid, char **path)
+{
+	int err = -1;
+
+	*path = NULL;
+
+	if (!build_id__is_defined(bid))
+		return -1;
+
+	/*
+	 * The checks below have to be made with the lock held, as they look
+	 * at the state the fetch changes: a build ID the fetch in progress
+	 * just settled as a miss is settled for whoever is waiting for the
+	 * lock as well.  Deciding here and fetching there would repeat a
+	 * fetch that was already made, and put the same build ID on the
+	 * misses list twice.
+	 */
+	debuginfod__fetch_lock_init();
+	mutex_lock(&debuginfod__fetch_lock);
+
+	if (symbol_conf.debuginfod) {
+		if (debuginfod__cache_disabled()) {
+			pr_debug("Build-id cache disabled (buildid dir is '%s'), not using debuginfod\n",
+				 buildid_dir);
+		} else if (debuginfod__missed(bid)) {
+			char sbuild_id[SBUILD_ID_SIZE];
+
+			build_id__snprintf(bid, sbuild_id, sizeof(sbuild_id));
+			pr_debug("Not searching build ID %s in debuginfod again, it was a miss earlier\n",
+				 sbuild_id);
+		} else {
+			err = debuginfo_lookup__find_build_id(bid, path);
+		}
+	}
+
+	mutex_unlock(&debuginfod__fetch_lock);
+
+	return err;
+}
+
+struct debuginfo *debuginfo__new_build_id(const struct build_id *bid)
+{
+	char sbuild_id[SBUILD_ID_SIZE];
+	char *path = NULL;
+	struct debuginfo *dbg;
+
+	if (debuginfo__find_build_id(bid, &path))
+		return NULL;
+
+	dbg = __debuginfo__new(path);
+	if (dbg == NULL) {
+		build_id__snprintf(bid, sbuild_id, sizeof(sbuild_id));
+		pr_debug("Failed to open DWARF in debuginfo fetched for build ID %s: %s\n",
+			 sbuild_id, path);
+	}
+	free(path);
+	return dbg;
+}
+#endif /* HAVE_DEBUGINFOD_SUPPORT */
+
 void debuginfo__delete(struct debuginfo *dbg)
 {
 	if (dbg) {
diff --git a/tools/perf/util/debuginfo.h b/tools/perf/util/debuginfo.h
index a52d69932815cd72..ef44a7557a9d6192 100644
--- a/tools/perf/util/debuginfo.h
+++ b/tools/perf/util/debuginfo.h
@@ -5,6 +5,8 @@
 #include <errno.h>
 #include <linux/compiler.h>
 
+struct build_id;
+
 #ifdef HAVE_LIBDW_SUPPORT
 
 #include "dwarf-aux.h"
@@ -54,6 +56,27 @@ static inline int debuginfo__get_text_offset(struct debuginfo *dbg __maybe_unuse
 #ifdef HAVE_DEBUGINFOD_SUPPORT
 int get_source_from_debuginfod(const char *raw_path, const char *sbuild_id,
 			       char **new_path);
+
+/*
+ * These need libdw to open the DWARF, so they live in debuginfo.o,
+ * built only with CONFIG_LIBDW.
+ */
+#ifdef HAVE_LIBDW_SUPPORT
+int debuginfo__find_build_id(const struct build_id *bid, char **path);
+struct debuginfo *debuginfo__new_build_id(const struct build_id *bid);
+#else
+static inline int debuginfo__find_build_id(const struct build_id *bid __maybe_unused,
+					   char **path __maybe_unused)
+{
+	return -ENOTSUP;
+}
+
+static inline struct debuginfo *
+debuginfo__new_build_id(const struct build_id *bid __maybe_unused)
+{
+	return NULL;
+}
+#endif /* HAVE_LIBDW_SUPPORT */
 #else /* HAVE_DEBUGINFOD_SUPPORT */
 static inline int get_source_from_debuginfod(const char *raw_path __maybe_unused,
 					     const char *sbuild_id __maybe_unused,
@@ -61,6 +84,18 @@ static inline int get_source_from_debuginfod(const char *raw_path __maybe_unused
 {
 	return -ENOTSUP;
 }
+
+static inline int debuginfo__find_build_id(const struct build_id *bid __maybe_unused,
+					   char **path __maybe_unused)
+{
+	return -ENOTSUP;
+}
+
+static inline struct debuginfo *
+debuginfo__new_build_id(const struct build_id *bid __maybe_unused)
+{
+	return NULL;
+}
 #endif /* HAVE_DEBUGINFOD_SUPPORT */
 
 #endif /* _PERF_DEBUGINFO_H */
diff --git a/tools/perf/util/dso.c b/tools/perf/util/dso.c
index 42bfe30a3b518e80..b0079ef17c597011 100644
--- a/tools/perf/util/dso.c
+++ b/tools/perf/util/dso.c
@@ -32,6 +32,7 @@
 #include "string2.h"
 #include "vdso.h"
 #include "annotate-data.h"
+#include "debuginfo.h"
 #include "libdw.h"
 
 static const char * const debuglink_paths[] = {
@@ -2073,5 +2074,14 @@ struct debuginfo *dso__debuginfo(struct dso *dso)
 
 	mutex_unlock(dso__lock(dso));
 	free(name);
+
+	/*
+	 * The debuginfo for a DSO in the profile may not be installed locally,
+	 * fall back to fetching it keyed by the build ID recorded in perf.data.
+	 * Do it outside dso__lock, a fetch can take a while.
+	 */
+	if (dinfo == NULL)
+		dinfo = debuginfo__new_build_id(dso__bid(dso));
+
 	return dinfo;
 }
diff --git a/tools/perf/util/symbol.c b/tools/perf/util/symbol.c
index 3587ad243159074f..b1a2684c813c5d8d 100644
--- a/tools/perf/util/symbol.c
+++ b/tools/perf/util/symbol.c
@@ -76,6 +76,8 @@ struct symbol_conf symbol_conf = {
 	.inline_name		= true,
 	.res_sample		= 0,
 	.addr2line_timeout_ms	= 5 * 1000,
+	/* Fetching debuginfo by build ID, off via --no-debuginfod, etc */
+	.debuginfod		= true,
 };
 
 struct map_list_node {
diff --git a/tools/perf/util/symbol_conf.h b/tools/perf/util/symbol_conf.h
index 71f60081a85bb18d..a56b1d2d843b9ff1 100644
--- a/tools/perf/util/symbol_conf.h
+++ b/tools/perf/util/symbol_conf.h
@@ -45,6 +45,7 @@ struct symbol_conf {
 			force,
 			ignore_vmlinux,
 			ignore_vmlinux_buildid,
+			debuginfod,
 			show_kernel_path,
 			use_modules,
 			allow_aliases,
-- 
2.55.0


^ permalink raw reply	[flat|nested] 18+ messages in thread

* [PATCH 02/15] perf debuginfo: Set DEBUGINFOD_URLS from /etc/debuginfod when unset
  2026-09-17 15:55 [PATCH v7 0/15] perf tools: Annotate fixes, stdio progress indication, debuginfo-client in more places Arnaldo Carvalho de Melo
  2026-09-17 15:55 ` [PATCH 01/15] perf debuginfo: Fetch debuginfo keyed by build ID using debuginfod Arnaldo Carvalho de Melo
@ 2026-09-17 15:55 ` Arnaldo Carvalho de Melo
  2026-09-17 15:55 ` [PATCH 03/15] perf config: Move perf_config__set_variable() to util/config.c Arnaldo Carvalho de Melo
                   ` (12 subsequent siblings)
  14 siblings, 0 replies; 18+ messages in thread
From: Arnaldo Carvalho de Melo @ 2026-09-17 15:55 UTC (permalink / raw)
  To: Namhyung Kim
  Cc: Ingo Molnar, Thomas Gleixner, James Clark, Jiri Olsa, Ian Rogers,
	Adrian Hunter, Clark Williams, linux-kernel, linux-perf-users,
	Arnaldo Carvalho de Melo

From: Arnaldo Carvalho de Melo <acme@redhat.com>

The debuginfod client fails when DEBUGINFOD_URLS isn't set even when
what it wants is in its local cache, and the distro setup scripts that
populate it from the files in /etc/debuginfod don't reach cron jobs,
systemd services and CI, so set it from those .urls files from
symbol__init(), before any thread that can call getenv() is started:
setenv() is not thread safe and libdebuginfod reads the variable in
every debuginfod_begin().

Install it via putenv() as a string perf owns, so that it can be
emptied in place mid-session when the user disables debuginfod, and
when debuginfod is off, with --no-debuginfod, core.debuginfod=false or
by disabling the build-id cache, set the empty string, that both
libdebuginfod and libdwfl's own client read as an opt-out, instead of
exporting the variable for libdwfl to fetch behind perf's back.  Tools
that manage DEBUGINFOD_URLS themselves are left alone.

Assisted-by: LLM
Signed-off-by: Arnaldo Carvalho de Melo <acme@redhat.com>
---
 tools/perf/util/symbol.c |   7 ++
 tools/perf/util/util.c   | 151 +++++++++++++++++++++++++++++++++++++--
 tools/perf/util/util.h   |   9 +++
 3 files changed, 161 insertions(+), 6 deletions(-)

diff --git a/tools/perf/util/symbol.c b/tools/perf/util/symbol.c
index b1a2684c813c5d8d..fbad770cb96f8294 100644
--- a/tools/perf/util/symbol.c
+++ b/tools/perf/util/symbol.c
@@ -2536,6 +2536,13 @@ int symbol__init(struct perf_env *env)
 	if (symbol_conf.initialized)
 		return 0;
 
+	/*
+	 * Set DEBUGINFOD_URLS from the distro .urls files before any thread
+	 * that getenv()s it is started: setenv() is not thread safe and
+	 * libdebuginfod reads it in every debuginfod_begin().
+	 */
+	debuginfod__setup_urls_env();
+
 	symbol_conf.priv_size = PERF_ALIGN(symbol_conf.priv_size, sizeof(u64));
 
 	symbol__elf_init();
diff --git a/tools/perf/util/util.c b/tools/perf/util/util.c
index 8f7cd32f524dc10e..d502fd867f38196b 100644
--- a/tools/perf/util/util.c
+++ b/tools/perf/util/util.c
@@ -21,9 +21,11 @@
 #include <linux/time64.h>
 #include <linux/overflow.h>
 #include <unistd.h>
+#include "build-id.h"
 #include "cap.h"
 #include "strlist.h"
 #include "string2.h"
+#include "symbol_conf.h"
 
 /*
  * XXX We need to find a better place for these things...
@@ -431,19 +433,66 @@ char *perf_exe(char *buf, int len)
 	return strcpy(buf, "perf");
 }
 
+static bool debuginfod__urls_set_by_tool;
+
+#define DEBUGINFOD_URLS_ENV "DEBUGINFOD_URLS"
+
+/*
+ * The DEBUGINFOD_URLS string perf owns: it has to change mid-session
+ * when the user disables debuginfod, and setenv() then could race with
+ * another thread's getenv().  With the string owned by perf, disabling
+ * it is just writing a NUL over its first byte.  The string is never
+ * freed: from putenv() on it is the environment's own storage.
+ */
+static char *debuginfod_urls_env;
+
+static void debuginfod__set_urls_env(const char *urls)
+{
+	size_t len = strlen(DEBUGINFOD_URLS_ENV "=") + strlen(urls) + 1;
+	char *env = malloc(len);
+
+	if (env == NULL)
+		return;
+
+	snprintf(env, len, DEBUGINFOD_URLS_ENV "=%s", urls);
+	debuginfod_urls_env = env;
+	putenv(env);
+}
+
+/*
+ * Empty the copy of DEBUGINFOD_URLS installed by
+ * debuginfod__set_urls_env(), which both libdebuginfod and libdwfl's
+ * own client read as an opt-out.  No environ array write and no free(),
+ * so a racing getenv() sees a valid string.
+ */
+void debuginfod__disable_urls_env(void)
+{
+	if (debuginfod_urls_env != NULL)
+		debuginfod_urls_env[sizeof(DEBUGINFOD_URLS_ENV "=") - 1] = '\0';
+}
+
 void perf_debuginfod_setup(struct perf_debuginfod *di)
 {
 	/*
 	 * By default '!di->set' we clear DEBUGINFOD_URLS, so debuginfod
 	 * processing is not triggered, otherwise we set it to 'di->urls'
-	 * value. If 'di->urls' is "system" we keep DEBUGINFOD_URLS value.
+	 * value. If 'di->urls' is "system" we keep DEBUGINFOD_URLS value,
+	 * but as a copy perf owns, so that it can still be emptied
+	 * mid-session, see debuginfod__disable_urls_env().
 	 */
-	if (!di->set)
-		setenv("DEBUGINFOD_URLS", "", 1);
-	else if (di->urls && strcmp(di->urls, "system"))
-		setenv("DEBUGINFOD_URLS", di->urls, 1);
+	if (!di->set) {
+		debuginfod__set_urls_env("");
+	} else if (di->urls == NULL || !strcmp(di->urls, "system")) {
+		const char *urls = getenv(DEBUGINFOD_URLS_ENV);
+
+		if (urls != NULL)
+			debuginfod__set_urls_env(urls);
+	} else {
+		debuginfod__set_urls_env(di->urls);
+	}
 
-	pr_debug("DEBUGINFOD_URLS=%s\n", getenv("DEBUGINFOD_URLS"));
+	debuginfod__urls_set_by_tool = true;
+	pr_debug("DEBUGINFOD_URLS=%s\n", getenv(DEBUGINFOD_URLS_ENV));
 
 #ifndef HAVE_DEBUGINFOD_SUPPORT
 	if (di->set)
@@ -451,6 +500,96 @@ void perf_debuginfod_setup(struct perf_debuginfod *di)
 #endif
 }
 
+#ifdef HAVE_DEBUGINFOD_SUPPORT
+/*
+ * The debuginfod client checks its local cache only as part of the
+ * server query flow, so with no servers configured it fails even when
+ * the file is cached; the distro setup scripts that export
+ * DEBUGINFOD_URLS from /etc/debuginfod don't reach cron jobs, systemd
+ * services and CI, so do it here when the variable isn't set.  An
+ * explicitly empty DEBUGINFOD_URLS is an opt-out and is left alone.
+ *
+ * Done from symbol__init(), on the single-threaded setup: setenv() is
+ * not thread safe and libdebuginfod reads it in every
+ * debuginfod_begin().  When debuginfod is off, set the empty opt-out
+ * instead of exporting it, so that libdwfl's own client doesn't fetch.
+ * The value is a copy owned by perf, see debuginfod__set_urls_env().
+ */
+void debuginfod__setup_urls_env(void)
+{
+	const char *env_urls;
+	char *urls = NULL;
+	DIR *dir;
+	struct dirent *dent;
+
+	/*
+	 * Tools that set DEBUGINFOD_URLS themselves already made their choice,
+	 * leave it alone.
+	 */
+	if (debuginfod__urls_set_by_tool)
+		return;
+
+	if (!symbol_conf.debuginfod || !strcmp(buildid_dir, "/dev/null")) {
+		debuginfod__set_urls_env("");
+		pr_debug("DEBUGINFOD_URLS cleared, debuginfod is disabled\n");
+		return;
+	}
+
+	env_urls = getenv(DEBUGINFOD_URLS_ENV);
+	if (env_urls != NULL) {
+		/*
+		 * Take ownership of the value, so that it can be emptied mid-session
+		 * with the 'd' key.
+		 */
+		debuginfod__set_urls_env(env_urls);
+		return;
+	}
+
+	dir = opendir("/etc/debuginfod");
+	if (dir == NULL)
+		return;
+
+	while ((dent = readdir(dir)) != NULL) {
+		char *content = NULL;
+		char *new_urls;
+		char path[PATH_MAX];
+		size_t len = strlen(dent->d_name), i, size;
+		int n;
+
+		if (len < 5 || strcmp(dent->d_name + len - 5, ".urls"))
+			continue;
+
+		snprintf(path, sizeof(path), "/etc/debuginfod/%s", dent->d_name);
+		if (filename__read_str(path, &content, &size) < 0)
+			continue;
+
+		for (i = 0; i < size; i++)
+			if (content[i] == '\n' || content[i] == '\r')
+				content[i] = ' ';
+
+		if (urls == NULL) {
+			urls = strdup(content);
+		} else {
+			n = asprintf(&new_urls, "%s %s", urls, content);
+			if (n < 0) {
+				free(content);
+				continue;
+			}
+			free(urls);
+			urls = new_urls;
+		}
+		free(content);
+	}
+	closedir(dir);
+
+	if (urls != NULL) {
+		debuginfod__set_urls_env(urls);
+		pr_debug("Set DEBUGINFOD_URLS from /etc/debuginfod: %s\n", urls);
+	}
+	free(urls);
+}
+#endif /* HAVE_DEBUGINFOD_SUPPORT */
+
 /*
  * Return a new filename prepended with task's root directory if it's in
  * a chroot.  Callers should free the returned string.
diff --git a/tools/perf/util/util.h b/tools/perf/util/util.h
index f8f1ff603c728086..42feccf18f0d163f 100644
--- a/tools/perf/util/util.h
+++ b/tools/perf/util/util.h
@@ -81,6 +81,15 @@ struct perf_debuginfod {
 	bool		 set;
 };
 void perf_debuginfod_setup(struct perf_debuginfod *di);
+void debuginfod__disable_urls_env(void);
+
+#ifdef HAVE_DEBUGINFOD_SUPPORT
+void debuginfod__setup_urls_env(void);
+#else
+static inline void debuginfod__setup_urls_env(void)
+{
+}
+#endif
 
 const char *perf_basename(const char *path);
 
-- 
2.55.0


^ permalink raw reply	[flat|nested] 18+ messages in thread

* [PATCH 03/15] perf config: Move perf_config__set_variable() to util/config.c
  2026-09-17 15:55 [PATCH v7 0/15] perf tools: Annotate fixes, stdio progress indication, debuginfo-client in more places Arnaldo Carvalho de Melo
  2026-09-17 15:55 ` [PATCH 01/15] perf debuginfo: Fetch debuginfo keyed by build ID using debuginfod Arnaldo Carvalho de Melo
  2026-09-17 15:55 ` [PATCH 02/15] perf debuginfo: Set DEBUGINFOD_URLS from /etc/debuginfod when unset Arnaldo Carvalho de Melo
@ 2026-09-17 15:55 ` Arnaldo Carvalho de Melo
  2026-09-17 15:55 ` [PATCH 04/15] perf debuginfo: Let the user skip and disable debuginfod fetches Arnaldo Carvalho de Melo
                   ` (11 subsequent siblings)
  14 siblings, 0 replies; 18+ messages in thread
From: Arnaldo Carvalho de Melo @ 2026-09-17 15:55 UTC (permalink / raw)
  To: Namhyung Kim
  Cc: Ingo Molnar, Thomas Gleixner, James Clark, Jiri Olsa, Ian Rogers,
	Adrian Hunter, Clark Williams, linux-kernel, linux-perf-users,
	Arnaldo Carvalho de Melo

From: Arnaldo Carvalho de Melo <acme@redhat.com>

Move perf_config__set_variable() out of the 'perf config' builtin so
that util/debuginfo.c can use it to write core.debuginfod=false when the
user disables debuginfod for the rest of the session.  The set_config()
body becomes perf_config_set__write(), with the system_config choice as
an argument, as the builtin's use_system_config/use_user_config statics
are not available outside it, and it has to honour PERF_CONFIG and keep
the entries marked as coming from the system config when rewriting the
system wide file.

All config file access shares the static parser state and can now run on
more than one thread, with the debuginfod fetch writing the config while
perf top's display thread reads it, so serialize parsing and rewriting
with a mutex.

Assisted-by: LLM
Signed-off-by: Arnaldo Carvalho de Melo <acme@redhat.com>
---
 tools/perf/builtin-config.c | 70 +--------------------------
 tools/perf/util/config.c    | 96 ++++++++++++++++++++++++++++++++++++-
 tools/perf/util/config.h    |  2 +
 3 files changed, 98 insertions(+), 70 deletions(-)

diff --git a/tools/perf/builtin-config.c b/tools/perf/builtin-config.c
index cefd042e4f853466..3b074aca8d344539 100644
--- a/tools/perf/builtin-config.c
+++ b/tools/perf/builtin-config.c
@@ -41,37 +41,7 @@ static struct option config_options[] = {
 
 static int set_config(struct perf_config_set *set, const char *file_name)
 {
-	struct perf_config_section *section = NULL;
-	struct perf_config_item *item = NULL;
-	const char *first_line = "# this file is auto-generated.";
-	FILE *fp;
-
-	if (set == NULL)
-		return -1;
-
-	fp = fopen(file_name, "w");
-	if (!fp)
-		return -1;
-
-	fprintf(fp, "%s\n", first_line);
-
-	/* overwrite configvariables */
-	perf_config_items__for_each_entry(&set->sections, section) {
-		if (!use_system_config && section->from_system_config)
-			continue;
-		fprintf(fp, "[%s]\n", section->name);
-
-		perf_config_items__for_each_entry(&section->items, item) {
-			if (!use_system_config && item->from_system_config)
-				continue;
-			if (item->value)
-				fprintf(fp, "\t%s = %s\n",
-					item->name, item->value);
-		}
-	}
-	fclose(fp);
-
-	return 0;
+	return perf_config_set__write(set, file_name, use_system_config);
 }
 
 static int show_spec_config(struct perf_config_set *set, const char *var)
@@ -158,44 +128,6 @@ static int parse_config_arg(char *arg, char **var, char **value)
 	return 0;
 }
 
-int perf_config__set_variable(const char *var, const char *value)
-{
-	char path[PATH_MAX];
-	char *user_config = mkpath(path, sizeof(path), "%s/.perfconfig", getenv("HOME"));
-	const char *config_filename;
-	struct perf_config_set *set;
-	int ret = -1;
-
-	if (use_system_config)
-		config_exclusive_filename = perf_etc_perfconfig();
-	else if (use_user_config)
-		config_exclusive_filename = user_config;
-
-	if (!config_exclusive_filename)
-		config_filename = user_config;
-	else
-		config_filename = config_exclusive_filename;
-
-	set = perf_config_set__new();
-	if (!set)
-		goto out_err;
-
-	if (perf_config_set__collect(set, config_filename, var, value) < 0) {
-		pr_err("Failed to add '%s=%s'\n", var, value);
-		goto out_err;
-	}
-
-	if (set_config(set, config_filename) < 0) {
-		pr_err("Failed to set the configs on %s\n", config_filename);
-		goto out_err;
-	}
-
-	ret = 0;
-out_err:
-	perf_config_set__delete(set);
-	return ret;
-}
-
 int cmd_config(int argc, const char **argv)
 {
 	int i, ret = -1;
diff --git a/tools/perf/util/config.c b/tools/perf/util/config.c
index 31c6618d3b3daf22..d926360bccfd23a0 100644
--- a/tools/perf/util/config.c
+++ b/tools/perf/util/config.c
@@ -12,6 +12,8 @@
 #include "config.h"
 
 #include <errno.h>
+#include <limits.h>
+#include <pthread.h>
 #include <stdbool.h>
 #include <stdio.h>
 #include <stdlib.h>
@@ -542,11 +544,20 @@ int perf_default_config(const char *var, const char *value,
 	return 0;
 }
 
+/*
+ * Serialize config file access: parsing and rewriting share the static
+ * parser state and can run on more than one thread, with the debuginfod
+ * fetch writing core.debuginfod=false while perf top's display thread
+ * calls perf_config().
+ */
+static pthread_mutex_t config_mutex = PTHREAD_MUTEX_INITIALIZER;
+
 static int perf_config_from_file(config_fn_t fn, const char *filename, void *data)
 {
 	int ret;
 	FILE *f = fopen(filename, "r");
 
+	pthread_mutex_lock(&config_mutex);
 	ret = -1;
 	if (f) {
 		config_file = f;
@@ -557,6 +568,7 @@ static int perf_config_from_file(config_fn_t fn, const char *filename, void *dat
 		fclose(f);
 		config_file_name = NULL;
 	}
+	pthread_mutex_unlock(&config_mutex);
 	return ret;
 }
 
@@ -776,8 +788,13 @@ static int collect_config(const char *var, const char *value,
 int perf_config_set__collect(struct perf_config_set *set, const char *file_name,
 			     const char *var, const char *value)
 {
+	int ret;
+
+	pthread_mutex_lock(&config_mutex);
 	config_file_name = file_name;
-	return collect_config(var, value, set);
+	ret = collect_config(var, value, set);
+	pthread_mutex_unlock(&config_mutex);
+	return ret;
 }
 
 static int perf_config_set__init(struct perf_config_set *set)
@@ -876,6 +893,83 @@ void perf_config__exit(void)
 	config_set = NULL;
 }
 
+int perf_config_set__write(struct perf_config_set *set,
+			   const char *file_name, bool system_config)
+{
+	struct perf_config_section *section = NULL;
+	struct perf_config_item *item = NULL;
+	FILE *fp;
+
+	pthread_mutex_lock(&config_mutex);
+	fp = fopen(file_name, "w");
+	if (!fp) {
+		pthread_mutex_unlock(&config_mutex);
+		return -1;
+	}
+
+	fprintf(fp, "# this file is auto-generated.\n");
+
+	/* overwrite configvariables */
+	perf_config_sections__for_each_entry(&set->sections, section) {
+		if (!system_config && section->from_system_config)
+			continue;
+		fprintf(fp, "[%s]\n", section->name);
+
+		perf_config_items__for_each_entry(&section->items, item) {
+			if (!system_config && item->from_system_config)
+				continue;
+			if (item->value)
+				fprintf(fp, "\t%s = %s\n",
+					item->name, item->value);
+		}
+	}
+	fclose(fp);
+	pthread_mutex_unlock(&config_mutex);
+
+	return 0;
+}
+
+/*
+ * Set @var=@value in the configuration file perf is using: the user's
+ * ~/.perfconfig, or the file named by PERF_CONFIG, which makes perf
+ * read only that file, so writing ~/.perfconfig would replace it with
+ * the exclusive file's entries.  The rewrite is the same 'perf config'
+ * does, comments are not preserved.
+ */
+int perf_config__set_variable(const char *var, const char *value)
+{
+	char path[PATH_MAX];
+	char *user_config = mkpath(path, sizeof(path), "%s/.perfconfig", getenv("HOME"));
+	const char *config_filename = config_exclusive_filename ?: user_config;
+	/*
+	 * When rewriting the system wide file (e.g. with
+	 * PERF_CONFIG=/etc/perfconfig) all entries are marked as coming from it
+	 * and must be kept, or the file would be truncated down to its header.
+	 */
+	bool system_config = strcmp(config_filename, perf_etc_perfconfig()) == 0;
+	struct perf_config_set *set;
+	int ret = -1;
+
+	set = perf_config_set__new();
+	if (!set)
+		goto out_err;
+
+	if (perf_config_set__collect(set, config_filename, var, value) < 0) {
+		pr_err("Failed to add '%s=%s'\n", var, value);
+		goto out_err;
+	}
+
+	if (perf_config_set__write(set, config_filename, system_config) < 0) {
+		pr_err("Failed to set the configs on %s\n", config_filename);
+		goto out_err;
+	}
+
+	ret = 0;
+out_err:
+	perf_config_set__delete(set);
+	return ret;
+}
+
 static void perf_config_item__delete(struct perf_config_item *item)
 {
 	zfree(&item->name);
diff --git a/tools/perf/util/config.h b/tools/perf/util/config.h
index 987b47cf54c350ba..9098f8a045850c97 100644
--- a/tools/perf/util/config.h
+++ b/tools/perf/util/config.h
@@ -33,6 +33,8 @@ int perf_config_scan(const char *name, const char *fmt, ...) __scanf(2, 3);
 const char *perf_config_get(const char *name);
 int perf_config_set(struct perf_config_set *set,
 		    config_fn_t fn, void *data);
+int perf_config_set__write(struct perf_config_set *set,
+			   const char *file_name, bool system_config);
 int perf_config_int(int *dest, const char *, const char *);
 int perf_config_u8(u8 *dest, const char *name, const char *value);
 int perf_config_u64(u64 *dest, const char *, const char *);
-- 
2.55.0


^ permalink raw reply	[flat|nested] 18+ messages in thread

* [PATCH 04/15] perf debuginfo: Let the user skip and disable debuginfod fetches
  2026-09-17 15:55 [PATCH v7 0/15] perf tools: Annotate fixes, stdio progress indication, debuginfo-client in more places Arnaldo Carvalho de Melo
                   ` (2 preceding siblings ...)
  2026-09-17 15:55 ` [PATCH 03/15] perf config: Move perf_config__set_variable() to util/config.c Arnaldo Carvalho de Melo
@ 2026-09-17 15:55 ` Arnaldo Carvalho de Melo
  2026-09-17 15:55 ` [PATCH 05/15] perf debuginfo: Show the debuginfod fetch progress and keys in the TUI Arnaldo Carvalho de Melo
                   ` (10 subsequent siblings)
  14 siblings, 0 replies; 18+ messages in thread
From: Arnaldo Carvalho de Melo @ 2026-09-17 15:55 UTC (permalink / raw)
  To: Namhyung Kim
  Cc: Ingo Molnar, Thomas Gleixner, James Clark, Jiri Olsa, Ian Rogers,
	Adrian Hunter, Clark Williams, linux-kernel, linux-perf-users,
	Arnaldo Carvalho de Melo

From: Arnaldo Carvalho de Melo <acme@redhat.com>

In the stdio case, while a fetch is in progress: 's' aborts it through
the debuginfod client's progress callback and remembers the build ID, so
that the rest of the session does not ask for it again; 'd' additionally
disables debuginfod for the session, emptying the DEBUGINFOD_URLS copy
perf owns (libdwfl's own client reads it in every query) and writing
core.debuginfod=false to the config file with
perf_config__set_variable().  SIGINT, SIGQUIT and SIGTERM are
intercepted while the terminal is in raw mode and re-raised after it is
restored.

The keys are drained with read()s that do not block: the terminal is in
raw mode with VMIN and VTIME zero, so read() returns zero when nothing
was typed and the callback returns to the client, which carries on with
the fetch.  In the TUI nothing is shown yet, that comes in the next
patch.

Assisted-by: LLM
Signed-off-by: Arnaldo Carvalho de Melo <acme@redhat.com>
---
 tools/perf/Documentation/perf-annotate.txt |   4 +-
 tools/perf/Documentation/perf-report.txt   |  11 +-
 tools/perf/Documentation/perf-top.txt      |  10 +-
 tools/perf/util/debuginfo.c                | 375 +++++++++++++++------
 4 files changed, 283 insertions(+), 117 deletions(-)

diff --git a/tools/perf/Documentation/perf-annotate.txt b/tools/perf/Documentation/perf-annotate.txt
index 12edc3337b86f099..25af1d166dc4c877 100644
--- a/tools/perf/Documentation/perf-annotate.txt
+++ b/tools/perf/Documentation/perf-annotate.txt
@@ -64,7 +64,9 @@ OPTIONS
 	configured in DEBUGINFOD_URLS, checking the local debuginfod
 	client cache first, when it is not available locally, on for
 	these commands by default.  See the --debuginfod option of
-	'perf report' for how to turn it off.
+	'perf report' for how to turn it off, including the 's' and
+	'd' keys that skip a fetch in progress while 'perf' is
+	waiting for it.
 
 --itrace::
 	Options for decoding instruction tracing data. The options are:
diff --git a/tools/perf/Documentation/perf-report.txt b/tools/perf/Documentation/perf-report.txt
index 2e11c0a97a016853..0a821490d6a0f895 100644
--- a/tools/perf/Documentation/perf-report.txt
+++ b/tools/perf/Documentation/perf-report.txt
@@ -374,9 +374,14 @@ OPTIONS
 	these commands by default.  It can be turned off per invocation
 	with --no-debuginfod, per tool with the "report.debuginfod"
 	config option or globally with "core.debuginfod" set to false.
-	It is disabled as well when the local build-id cache is turned
-	off, e.g. "buildid.dir" set to /dev/null, as that asks for
-	fetched files not to be kept on the box.
+	While a fetch is in progress, 's' skips the current fetch and
+	'd' skips it and disables debuginfod for the rest of the
+	session, writing core.debuginfod=false to the configuration
+	file so that it stays disabled in the next runs too; in the
+	stdio interface the progress is a line on stderr.  It is
+	disabled as well when the local build-id cache is turned off,
+	e.g. "buildid.dir" set to /dev/null, as that asks for fetched
+	files not to be kept on the box.
 
 --kallsyms=<file>::
         kallsyms pathname
diff --git a/tools/perf/Documentation/perf-top.txt b/tools/perf/Documentation/perf-top.txt
index 345dd9ee9b6bab88..f38b54267125cb08 100644
--- a/tools/perf/Documentation/perf-top.txt
+++ b/tools/perf/Documentation/perf-top.txt
@@ -90,9 +90,13 @@ Default is to monitor all CPUS.
 	client cache first, when it is not available locally, on for
 	these commands by default.  Turn it off per invocation with
 	--no-debuginfod, with the "top.debuginfod" config option or
-	globally with "core.debuginfod" set to false.  Disabled as well
-	when the build-id cache is off, e.g. "buildid.dir" set to
-	/dev/null.
+	globally with "core.debuginfod" set to false.  While a fetch is
+	in progress, 's' skips the current fetch and 'd' skips it and
+	disables debuginfod for the rest of the session, writing
+	core.debuginfod=false to the configuration file so that it
+	stays disabled in the next runs too; in the stdio interface the
+	progress is a line on stderr.  Disabled as well when the
+	build-id cache is off, e.g. "buildid.dir" set to /dev/null.
 
 --kallsyms=<file>::
 	kallsyms pathname
diff --git a/tools/perf/util/debuginfo.c b/tools/perf/util/debuginfo.c
index be5882d9c2204797..0ec11e1ad7508edc 100644
--- a/tools/perf/util/debuginfo.c
+++ b/tools/perf/util/debuginfo.c
@@ -9,21 +9,25 @@
 #include <fcntl.h>
 #include <limits.h>
 #include <pthread.h>
+#include <signal.h>
 #include <stdbool.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
+#include <termios.h>
 #include <unistd.h>
 #include <linux/list.h>
 #include <linux/zalloc.h>
 #include <api/fs/fs.h>
 
 #include "build-id.h"
+#include "config.h"
 #include "dso.h"
 #include "debug.h"
 #include "debuginfo.h"
 #include "mutex.h"
 #include "symbol.h"
+#include "term.h"
 
 #ifdef HAVE_DEBUGINFOD_SUPPORT
 #include <elfutils/debuginfod.h>
@@ -147,11 +151,137 @@ struct debuginfo *debuginfo__new(const char *path)
 
 #ifdef HAVE_DEBUGINFOD_SUPPORT
 /*
- * Users can disable the local build-id/.debug cache by setting
- * buildid.dir to /dev/null, meaning they don't want fetched
- * binaries/debuginfo stored on the box; the debuginfod client keeps
- * its own cache in ~/.cache/debuginfod_client, so honour that intent
- * and don't fetch at all in that case.
+ * use_browser tells whether a full screen UI, the TUI for now, owns
+ * the terminal and its input queue: the fetch progress and the
+ * skip/disable keys below are stdio only when it doesn't.
+ */
+#include "ui/ui.h"
+
+static bool debuginfod_progress_started;
+static bool debuginfod_fetch_cancelled;
+
+/*
+ * While stdin is in raw mode, SIGINT, SIGQUIT and SIGTERM are only
+ * recorded by the handler; the callback aborts the query and
+ * debuginfod__fetch() restores the terminal and re-raises the signal.
+ */
+static volatile sig_atomic_t debuginfod_signal;
+
+static void debuginfod_signal_handler(int sig)
+{
+	debuginfod_signal = sig;
+}
+
+/*
+ * Say that the fetch in progress was skipped, and where disabling it
+ * lands.
+ */
+static void debuginfod__skipped(const char *msg)
+{
+	fprintf(stderr, "\n%s\n", msg);
+}
+
+/*
+ * 's': skip this fetch, and remember the build ID so that the rest of
+ * the session doesn't ask for it again, the query is aborted by
+ * returning a non-zero value from the progress callback, as the
+ * debuginfod client docs prescribe.  'd': also disable debuginfod for
+ * the rest of the session, emptying the copy of DEBUGINFOD_URLS that
+ * util/util.c installed at setup, so that libdwfl's own client, that
+ * reads it in every query, stops fetching too, without a setenv() here
+ * racing other threads' getenv()s, and
+ * write core.debuginfod=false to the configuration file, the same
+ * rewrite 'perf config' does, the comments are not preserved as the
+ * config set carries just the key-value pairs, pointing at
+ * 'perf config' when that rewrite can't be done.
+ */
+static void debuginfod__cancel_key(int key)
+{
+	if (key == 's' || key == 'S') {
+		debuginfod_fetch_cancelled = true;
+		debuginfod__skipped("Skipping this debuginfod fetch, this build ID will not be fetched again in this session, press 'd' to also disable it for the other ones");
+	} else if (key == 'd' || key == 'D') {
+		debuginfod_fetch_cancelled = true;
+		symbol_conf.debuginfod = false;
+		/*
+		 * libdwfl's own client reads DEBUGINFOD_URLS in every query, clear the
+		 * perf-owned copy to stop it too.
+		 */
+		debuginfod__disable_urls_env();
+		if (perf_config__set_variable("core.debuginfod", "false"))
+			debuginfod__skipped("Skipping this debuginfod fetch and disabling debuginfod for this session, run 'perf config core.debuginfod=false' to also disable it permanently");
+		else if (config_exclusive_filename)
+			debuginfod__skipped("Skipping this debuginfod fetch and disabling debuginfod for this session and in the configuration file");
+		else
+			debuginfod__skipped("Skipping this debuginfod fetch and disabling debuginfod for this session and in ~/.perfconfig");
+	}
+}
+
+/*
+ * The terminal is in raw mode with VMIN and VTIME zero, so read()
+ * returns zero when nothing was typed: this drains the keys typed so
+ * far and returns, it doesn't wait for a keypress.
+ */
+static void debuginfod__poll_cancel_keys(void)
+{
+	char ch;
+
+	while (read(STDIN_FILENO, &ch, 1) == 1)
+		debuginfod__cancel_key(ch);
+}
+
+/*
+ * Print a warning and a progress indicator when the debuginfod client
+ * ends up fetching a file, which can be big, such as the vmlinux for a
+ * kernel profiled on another machine or before it got upgraded, so that
+ * users know perf is not stuck, and let them bail out: 's' skips this
+ * fetch and remembers the build ID, so that the rest of the session
+ * doesn't ask for it again, 'd' also disables debuginfod for the rest
+ * of the session.
+ *
+ * The client invokes this both while fetching, where 'a' is the number
+ * of bytes transferred so far and 'b' the total size, zero when it
+ * doesn't know it yet, and, before committing to a server, from the
+ * cache cleanup, that scans the debuginfod client cache, with 'a' being
+ * the number of cache files scanned so far and 'b' zero.
+ *
+ * In the stdio case the progress goes to stderr, a \r terminated line,
+ * the keys are drained from stdin, that debuginfod__fetch() put in raw
+ * mode.
+ */
+static int debuginfod_progress_fn(debuginfod_client *c __maybe_unused,
+				  long a, long b)
+{
+	if (debuginfod_signal)
+		return 1;
+
+	if (!isatty(STDERR_FILENO) || use_browser)
+		return 0;
+
+	if (isatty(STDIN_FILENO)) {
+		debuginfod__poll_cancel_keys();
+		if (debuginfod_fetch_cancelled)
+			return 1;
+	}
+
+	if (!debuginfod_progress_started) {
+		fprintf(stderr, "Fetching debuginfo by build ID from the debuginfod servers, this may take a while for large files such as the vmlinux, press 's' to skip, 'd' to skip and disable\n");
+		debuginfod_progress_started = true;
+	}
+
+	if (a >= 0) {
+		if (b > 0)
+			fprintf(stderr, "  %ld/%ld MiB fetched\r", a >> 20, b >> 20);
+		else
+			fprintf(stderr, "  %ld MiB fetched\r", a >> 20);
+	}
+
+	return 0;
+}
+
+/*
+ * Setting buildid.dir to /dev/null means no fetched files stored
+ * locally, honour it and don't fetch at all.
  */
 static bool debuginfod__cache_disabled(void)
 {
@@ -159,42 +289,39 @@ static bool debuginfod__cache_disabled(void)
 }
 
 /*
- * Build IDs that shouldn't be searched for again in this session: the
- * ones already searched for on the debuginfod servers without success,
- * so that callers that see the same DSO over and over, such as the data
- * type profiler switching between DSOs on every hist entry, don't pay a
- * server round trip again for each miss.  The cache of successes is the
- * debuginfod client's own, in the local filesystem.
- *
- * Guarded by debuginfod__fetch_lock: it is only read by the lookups
- * below, that run with that lock held, and written by fetches, that run
- * with it held too.
+ * Build IDs already searched for without success or cancelled by the
+ * user, so that callers revisiting DSOs don't pay a server round trip
+ * per miss.  Guarded by debuginfod__fetch_lock.
  */
 struct debuginfod_miss {
 	struct list_head	node;
 	struct build_id		bid;
+	bool			cancelled;
 };
 
 static LIST_HEAD(debuginfod__misses);
 
-/*
- * Was the search for this build ID already made and settled, i.e. the
- * servers had nothing for it?
- */
-static bool debuginfod__missed(const struct build_id *bid)
+/* Was the search for this build ID already settled, or cancelled? */
+static bool debuginfod__missed(const struct build_id *bid, bool *cancelled)
 {
 	struct debuginfod_miss *miss;
+	bool found = false;
+
+	*cancelled = false;
 
 	list_for_each_entry(miss, &debuginfod__misses, node) {
 		if (miss->bid.size == bid->size &&
-		    !memcmp(miss->bid.data, bid->data, bid->size))
-			return true;
+		    !memcmp(miss->bid.data, bid->data, bid->size)) {
+			found = true;
+			*cancelled = miss->cancelled;
+			break;
+		}
 	}
 
-	return false;
+	return found;
 }
 
-static void debuginfod__miss_add(const struct build_id *bid)
+static void debuginfod__miss_add(const struct build_id *bid, bool cancelled)
 {
 	struct debuginfod_miss *miss = zalloc(sizeof(*miss));
 
@@ -202,36 +329,18 @@ static void debuginfod__miss_add(const struct build_id *bid)
 		return;
 
 	miss->bid = *bid;
+	miss->cancelled = cancelled;
 
 	list_add(&miss->node, &debuginfod__misses);
 }
 
 /*
- * One fetch at a time.
- *
- * The lookup state below is process global, so two concurrent fetches,
- * which dso__debuginfo() makes possible by taking the fetch out of
- * dso__lock, would race for it: the second one could answer from a list
- * the first one is concurrently updating, and put the same build ID on
- * the misses list twice.
- *
- * Serializing also means a second request for a build ID that is being
- * fetched waits here for the fetch to finish, instead of starting a second
- * download of the same file, and is then answered from the entry the fetch
- * published, or from the misses list, with no client at all.  Should the
- * fetches ever run in parallel, that wait has to come back explicitly, with
- * this lock split in two: one only for the lookup state, that the waiters
- * sleep on, and one held around each fetch, with the thread that finds a
- * fetch in progress waiting on the former for the entry to be published.
- *
- * What that costs is that a fetch for one build ID blocks a fetch for
- * another one, and it is what parallel downloads would fix.  Worth doing
- * only if the wait turns out to be long, because it mostly is not: the
- * lookups below answer the second and later requests for a build ID from
- * memory, so after the first pass over the build IDs of a workload, which
- * is the only time anything is fetched at all, the serialization has
- * nothing left to serialize.  Start there if a profile with many DSOs to
- * fetch shows up in a profile of perf itself.
+ * One fetch at a time: the lookup state below and the interaction state
+ * (terminal mode, signal dispositions, progress line and keys) are
+ * process global, so serializing avoids two fetches racing for them.
+ * A request for a build ID being fetched waits here and is answered
+ * from the published entry, or from the misses list, with no second
+ * download.
  */
 static struct mutex debuginfod__fetch_lock;
 
@@ -248,18 +357,9 @@ static void debuginfod__fetch_lock_init(void)
 }
 
 /*
- * The build IDs already fetched in this session, and the path of the file
- * that came back for each, so that the repeated requests for the same build
- * ID, dso__debuginfo() is called per symbol annotated, are answered with a
- * strdup() instead of another client: the file is in the debuginfod client
- * cache already and its path checked before being handed out, in case that
- * cache is cleaned from under us.
- *
- * Guarded by debuginfod__fetch_lock.  Only a fetch that brought a file back
- * gets an entry: one that didn't is recorded in debuginfod__misses as a miss,
- * and that is what keeps the rest of the session from asking for it again.
- * Like debuginfod__misses this grows with the number of build IDs in the
- * workload, one small entry each, and is not trimmed.
+ * Build IDs fetched in this session and the path of the file that came
+ * back, so repeated requests are answered with a strdup() instead of
+ * another client.  Guarded by debuginfod__fetch_lock.
  */
 struct debuginfo_lookup {
 	struct list_head	 node;
@@ -294,10 +394,9 @@ static void debuginfo_lookup__delete(struct debuginfo_lookup *lookup)
 }
 
 /*
- * Remember that this build ID was fetched, with the file at @path, so that
- * the next request for it is answered from memory.  Called with
- * debuginfod__fetch_lock held.  Out of memory just means not sharing this
- * one, the file is fetched and the caller has its path.
+ * Remember that this build ID was fetched, with the file at @path, so
+ * that the next request is answered from memory.  Called with
+ * debuginfod__fetch_lock held.
  */
 static void debuginfo_lookup__add(const struct build_id *bid, const char *path)
 {
@@ -317,12 +416,16 @@ static void debuginfo_lookup__add(const struct build_id *bid, const char *path)
 }
 
 /*
- * The fetch itself.  Called with debuginfod__fetch_lock held for the
- * whole of it, see the comment there.
+ * The fetch itself, and, in the stdio case, the terminal in raw mode:
+ * the caller has to hold debuginfod__fetch_lock for the whole of it.
  */
 static int debuginfod__fetch(const struct build_id *bid, char **path)
 {
 	char sbuild_id[SBUILD_ID_SIZE];
+	struct termios orig_termios;
+	struct sigaction sa, orig_sigint, orig_sigquit, orig_sigterm;
+	bool term_set = false, sigint_set = false, sigquit_set = false;
+	bool sigterm_set = false;
 	debuginfod_client *c;
 	int fd;
 
@@ -330,30 +433,102 @@ static int debuginfod__fetch(const struct build_id *bid, char **path)
 	if (c == NULL)
 		return -1;
 
+	debuginfod_set_progressfn(c, debuginfod_progress_fn);
+
+	debuginfod_fetch_cancelled = false;
+	debuginfod_signal = 0;
+
+	/*
+	 * Make stdin deliver keypresses without waiting for a newline,
+	 * the progress callback above polls it for the 's'/'d' keys,
+	 * only in the stdio case with both stdin and stderr being a
+	 * terminal: the pipe cases have no business being poked here,
+	 * and in the TUI the terminal and its input queue are the
+	 * browser's own.  Intercept SIGINT, SIGQUIT and SIGTERM so that
+	 * the terminal is restored before the process dies, the handler
+	 * only records the signal and the callback aborts the query.
+	 * The handlers go in before the terminal mode changes, so that a
+	 * signal landing in between is caught and the raw mode is
+	 * restored.
+	 */
+	if (isatty(STDIN_FILENO) && isatty(STDERR_FILENO) && !use_browser) {
+		memset(&sa, 0, sizeof(sa));
+		sa.sa_handler = debuginfod_signal_handler;
+		sigemptyset(&sa.sa_mask);
+		if (sigaction(SIGINT, &sa, &orig_sigint) == 0)
+			sigint_set = true;
+		if (sigaction(SIGQUIT, &sa, &orig_sigquit) == 0)
+			sigquit_set = true;
+		if (sigaction(SIGTERM, &sa, &orig_sigterm) == 0)
+			sigterm_set = true;
+
+		set_term_quiet_input(&orig_termios);
+		term_set = true;
+	}
+
 	fd = debuginfod_find_debuginfo(c, bid->data, bid->size, path);
 
-	debuginfod_end(c);
+	if (term_set)
+		tcsetattr(STDIN_FILENO, TCSANOW, &orig_termios);
+	if (sigint_set)
+		sigaction(SIGINT, &orig_sigint, NULL);
+	if (sigquit_set)
+		sigaction(SIGQUIT, &orig_sigquit, NULL);
+	if (sigterm_set)
+		sigaction(SIGTERM, &orig_sigterm, NULL);
 
+	debuginfod_end(c);
+	if (debuginfod_progress_started) {
+		fputc('\n', stderr);
+		debuginfod_progress_started = false;
+	}
 	if (fd < 0) {
 		build_id__snprintf(bid, sbuild_id, sizeof(sbuild_id));
+		if (debuginfod_fetch_cancelled || debuginfod_signal) {
+			pr_debug("debuginfod search for build ID %s cancelled by the user\n",
+				 sbuild_id);
+			/*
+			 * Remember it so that the rest of the session doesn't
+			 * ask for the same file again: the user may have
+			 * skipped it for being too big.
+			 */
+			debuginfod__miss_add(bid, true);
+			/*
+			 * The terminal is restored, die as the user asked;
+			 * the original dispositions are back in place.
+			 */
+			if (debuginfod_signal)
+				raise(debuginfod_signal);
+			return -1;
+		}
 		pr_debug("No debuginfo found for build ID %s in debuginfod\n",
 			 sbuild_id);
-		debuginfod__miss_add(bid);
+		debuginfod__miss_add(bid, false);
 		return -1;
 	}
 
 	close(fd);
 
+	/*
+	 * The interrupt can land after the file is already here, in which
+	 * case there is no failure to report, but the user still asked for
+	 * perf to stop, and the terminal and the signal dispositions are
+	 * back to what they were, so honour it here as well instead of
+	 * swallowing it and going on.
+	 */
+	if (debuginfod_signal) {
+		build_id__snprintf(bid, sbuild_id, sizeof(sbuild_id));
+		pr_debug("debuginfod found the debuginfo for build ID %s, but the search was interrupted, exiting\n",
+			 sbuild_id);
+		raise(debuginfod_signal);
+	}
+
 	return 0;
 }
 
 /*
- * Look the build ID up in the files already fetched in this session,
- * fetching it if it isn't there yet.  Called, and left, with
- * debuginfod__fetch_lock held, which also means that no fetch for this
- * build ID can be running anywhere else: a second request for a build ID
- * being fetched waits for the lock and is answered from the entry the fetch
- * published, or from the misses list, with no client at all.
+ * Look the build ID up in the files already fetched, fetching it if it
+ * isn't there yet.  Called, and left, with debuginfod__fetch_lock held.
  */
 static int debuginfo_lookup__find_build_id(const struct build_id *bid, char **path)
 {
@@ -361,13 +536,8 @@ static int debuginfo_lookup__find_build_id(const struct build_id *bid, char **pa
 
 	if (lookup != NULL) {
 		/*
-		 * The file stays in the debuginfod client cache, but that
-		 * cache can be cleaned from under us, so check that it is
-		 * still there before handing its path out.  If it isn't,
-		 * forget the entry and look for the file again below,
-		 * remembering the new answer the same way the first fetch
-		 * does, so that the next lookup shares it instead of
-		 * fetching it a third time.
+		 * The file may have been cleaned from the debuginfod client cache:
+		 * if it is gone, forget the entry and fetch it again below.
 		 */
 		if (access(lookup->path, R_OK) == 0) {
 			*path = strdup(lookup->path);
@@ -386,25 +556,10 @@ static int debuginfo_lookup__find_build_id(const struct build_id *bid, char **pa
 }
 
 /*
- * Find a debuginfo file keyed by the build ID, using the debuginfod
- * client, which checks its local cache first and then queries the
- * servers in DEBUGINFOD_URLS.  Used when the debuginfo is not available
- * locally under the name the DSO was opened with, for instance the
- * vmlinux for the kernel the profile was recorded on, when processing
- * the profile on another machine or after the kernel or its debuginfo
- * package got upgraded in between.
- *
- * Querying servers, possibly third party, sends the build IDs of the
- * binaries being analysed off the box, so this is opt-out: on by
- * default, switchable off with --no-debuginfod, with
- * core.debuginfod=false, with the per-tool
- * report.debuginfod/top.debuginfod, and it is off too when the user
- * disabled the local build-id/.debug cache, e.g. with
- * buildid.dir = /dev/null, as is the case for users that don't want
- * any of this stored locally.
- *
- * On success the path is stored in *@path and must be freed by the
- * caller, the file remains available in the debuginfod client cache.
+ * Find a debuginfo file keyed by the build ID using the debuginfod
+ * client, which checks its local cache first and then the servers in
+ * DEBUGINFOD_URLS.  On success the path is stored in *@path and must be
+ * freed by the caller.
  */
 int debuginfo__find_build_id(const struct build_id *bid, char **path)
 {
@@ -416,26 +571,26 @@ int debuginfo__find_build_id(const struct build_id *bid, char **path)
 		return -1;
 
 	/*
-	 * The checks below have to be made with the lock held, as they look
-	 * at the state the fetch changes: a build ID the fetch in progress
-	 * just settled as a miss is settled for whoever is waiting for the
-	 * lock as well.  Deciding here and fetching there would repeat a
-	 * fetch that was already made, and put the same build ID on the
-	 * misses list twice.
+	 * These check the state the fetch changes, so they have to run with
+	 * the lock held.
 	 */
 	debuginfod__fetch_lock_init();
 	mutex_lock(&debuginfod__fetch_lock);
 
 	if (symbol_conf.debuginfod) {
+		bool cancelled;
+
 		if (debuginfod__cache_disabled()) {
 			pr_debug("Build-id cache disabled (buildid dir is '%s'), not using debuginfod\n",
 				 buildid_dir);
-		} else if (debuginfod__missed(bid)) {
+		} else if (debuginfod__missed(bid, &cancelled)) {
 			char sbuild_id[SBUILD_ID_SIZE];
 
 			build_id__snprintf(bid, sbuild_id, sizeof(sbuild_id));
-			pr_debug("Not searching build ID %s in debuginfod again, it was a miss earlier\n",
-				 sbuild_id);
+			pr_debug("Not searching build ID %s in debuginfod again, %s\n",
+				 sbuild_id,
+				 cancelled ? "the user cancelled the search earlier" :
+					     "it was a miss earlier");
 		} else {
 			err = debuginfo_lookup__find_build_id(bid, path);
 		}
-- 
2.55.0


^ permalink raw reply	[flat|nested] 18+ messages in thread

* [PATCH 05/15] perf debuginfo: Show the debuginfod fetch progress and keys in the TUI
  2026-09-17 15:55 [PATCH v7 0/15] perf tools: Annotate fixes, stdio progress indication, debuginfo-client in more places Arnaldo Carvalho de Melo
                   ` (3 preceding siblings ...)
  2026-09-17 15:55 ` [PATCH 04/15] perf debuginfo: Let the user skip and disable debuginfod fetches Arnaldo Carvalho de Melo
@ 2026-09-17 15:55 ` Arnaldo Carvalho de Melo
  2026-09-17 15:55 ` [PATCH 06/15] perf symbol: Fall back to fetching the vmlinux by build ID Arnaldo Carvalho de Melo
                   ` (9 subsequent siblings)
  14 siblings, 0 replies; 18+ messages in thread
From: Arnaldo Carvalho de Melo @ 2026-09-17 15:55 UTC (permalink / raw)
  To: Namhyung Kim
  Cc: Ingo Molnar, Thomas Gleixner, James Clark, Jiri Olsa, Ian Rogers,
	Adrian Hunter, Clark Williams, linux-kernel, linux-perf-users,
	Arnaldo Carvalho de Melo

From: Arnaldo Carvalho de Melo <acme@redhat.com>

The stdio only fetch UI left a TUI fetch in progress with nothing on
screen, indistinguishable from a stuck perf, with no way out of it.
Draw a window over the browser with the fetch progress, and drain the
's'/'d' keys from the TUI input queue, through the new
ui__key_pending()/ui__key_read()/ui__progress_window()/
ui__progress_window_end() primitives declared in ui/util.h and
implemented in ui/tui/util.c, with no-ops for builds without slang:
slang stays behind the ui/ layer and callers stay free of #ifdefs.

The text is word wrapped to the available columns so that narrow
terminals get the 'd' option hint too, and the width is clamped, never
negative.

Assisted-by: LLM
Signed-off-by: Arnaldo Carvalho de Melo <acme@redhat.com>
---
 tools/perf/Documentation/perf-report.txt |   9 +-
 tools/perf/Documentation/perf-top.txt    |   5 +-
 tools/perf/ui/tui/util.c                 | 171 +++++++++++++++++++++++
 tools/perf/ui/util.h                     |  27 ++++
 tools/perf/util/debuginfo.c              |  97 +++++++------
 5 files changed, 254 insertions(+), 55 deletions(-)

diff --git a/tools/perf/Documentation/perf-report.txt b/tools/perf/Documentation/perf-report.txt
index 0a821490d6a0f895..0a4f61283b9542f7 100644
--- a/tools/perf/Documentation/perf-report.txt
+++ b/tools/perf/Documentation/perf-report.txt
@@ -378,10 +378,11 @@ OPTIONS
 	'd' skips it and disables debuginfod for the rest of the
 	session, writing core.debuginfod=false to the configuration
 	file so that it stays disabled in the next runs too; in the
-	stdio interface the progress is a line on stderr.  It is
-	disabled as well when the local build-id cache is turned off,
-	e.g. "buildid.dir" set to /dev/null, as that asks for fetched
-	files not to be kept on the box.
+	stdio interface the progress is a line on stderr, in the TUI a
+	window over the browser.  It is disabled as well when the local
+	build-id cache is turned off, e.g. "buildid.dir" set to
+	/dev/null, as that asks for fetched files not to be kept on the
+	box.
 
 --kallsyms=<file>::
         kallsyms pathname
diff --git a/tools/perf/Documentation/perf-top.txt b/tools/perf/Documentation/perf-top.txt
index f38b54267125cb08..3ab8121480175b51 100644
--- a/tools/perf/Documentation/perf-top.txt
+++ b/tools/perf/Documentation/perf-top.txt
@@ -95,8 +95,9 @@ Default is to monitor all CPUS.
 	disables debuginfod for the rest of the session, writing
 	core.debuginfod=false to the configuration file so that it
 	stays disabled in the next runs too; in the stdio interface the
-	progress is a line on stderr.  Disabled as well when the
-	build-id cache is off, e.g. "buildid.dir" set to /dev/null.
+	progress is a line on stderr, in the TUI a window over the
+	browser.  Disabled as well when the build-id cache is off, e.g.
+	"buildid.dir" set to /dev/null.
 
 --kallsyms=<file>::
 	kallsyms pathname
diff --git a/tools/perf/ui/tui/util.c b/tools/perf/ui/tui/util.c
index e4d322ce0b54cbc6..280865e980ef5491 100644
--- a/tools/perf/ui/tui/util.c
+++ b/tools/perf/ui/tui/util.c
@@ -4,6 +4,7 @@
 #include <string.h>
 #include <stdlib.h>
 #include <sys/ttydefaults.h>
+#include <linux/kernel.h>
 
 #include "../browser.h"
 #include "../keysyms.h"
@@ -11,6 +12,7 @@
 #include "../ui.h"
 #include "../util.h"
 #include "../libslang.h"
+#include "units.h"
 
 static void ui_browser__argv_write(struct ui_browser *browser,
 				   void *entry, int row)
@@ -272,3 +274,172 @@ struct perf_error_ops perf_tui_eops = {
 	.error		= perf_tui__error,
 	.warning	= perf_tui__warning,
 };
+
+/*
+ * The debuginfod fetch progress window, drawn over the browser while a
+ * fetch is in progress: with nothing on screen the browser looks hung.
+ * Redraw only when the fetched bytes change, the callback is called at
+ * every write chunk.
+ */
+#define PROGRESS_WINDOW_MAX_LINES 12
+
+static bool progress_window__shown;
+static char progress_window__bytes[64];
+static int progress_window__y, progress_window__rows;
+
+/*
+ * Word wrap @text, on spaces, into lines of at most @width characters,
+ * breaking words that don't fit whole, returning the number of lines.
+ */
+static int progress_window__wrap(const char *text, int width,
+				 char lines[PROGRESS_WINDOW_MAX_LINES][256])
+{
+	int nr_lines = 0;
+	const char *p = text;
+
+	if (width <= 0)
+		return 0;
+
+	while (*p && nr_lines < PROGRESS_WINDOW_MAX_LINES) {
+		char *line = lines[nr_lines++];
+		int len = 0;
+		bool space = false;
+
+		line[0] = '\0';
+		while (*p) {
+			const char *word;
+			int wlen, avail;
+
+			while (*p == ' ' || *p == '\n')
+				++p;
+			if (*p == '\0')
+				break;
+			word = p;
+			while (*p && *p != ' ' && *p != '\n')
+				++p;
+			wlen = p - word;
+			avail = width - len - (space ? 1 : 0);
+			if (wlen > avail) {
+				if (len > 0) {
+					p = word;
+					break;
+				}
+				if (avail > 0) {
+					/* The word doesn't fit whole */
+					memcpy(line, word, avail);
+					len = avail;
+					line[len] = '\0';
+					p = word + avail;
+				}
+				break;
+			}
+			if (space)
+				line[len++] = ' ';
+			memcpy(line + len, word, wlen);
+			len += wlen;
+			line[len] = '\0';
+			space = true;
+		}
+	}
+
+	return nr_lines;
+}
+
+void ui__progress_window(const char *title, const char *text,
+			 u64 fetched, u64 total)
+{
+	static char lines[PROGRESS_WINDOW_MAX_LINES][256];
+	char buf_cur[20], buf_tot[20], bytes[64];
+	size_t len;
+	int y, height, nr_lines, inner, i;
+
+	if (use_browser != 1)
+		return;
+
+	unit_number__scnprintf(buf_cur, sizeof(buf_cur), fetched);
+	if (total) {
+		unit_number__scnprintf(buf_tot, sizeof(buf_tot), total);
+		scnprintf(bytes, sizeof(bytes), "  %s / %s fetched",
+			  buf_cur, buf_tot);
+	} else {
+		scnprintf(bytes, sizeof(bytes),
+			  "  %s fetched, size unknown", buf_cur);
+	}
+
+	if (progress_window__shown && !strcmp(bytes, progress_window__bytes))
+		return;
+
+	scnprintf(progress_window__bytes, sizeof(progress_window__bytes),
+		  "%s", bytes);
+	progress_window__shown = true;
+
+	ui__refresh_dimensions(false);
+	mutex_lock(&ui__lock);
+	/*
+	 * SLsmg_write_nstring() takes the width as an unsigned int, so never
+	 * let a narrow terminal make it negative.  Clamp it.
+	 */
+	inner = SLtt_Screen_Cols - 2;
+	if (inner < 0)
+		inner = 0;
+	else if (inner > 255)
+		inner = 255;
+	nr_lines = progress_window__wrap(text, inner, lines);
+	height = nr_lines + 3;
+
+	SLsmg_set_color(0);
+	if (progress_window__rows)
+		SLsmg_fill_region(progress_window__y, 0, progress_window__rows,
+				  SLtt_Screen_Cols, ' ');
+	y = (SLtt_Screen_Rows - height) / 2;
+	if (y < 0)
+		y = 0;
+	progress_window__y = y;
+	progress_window__rows = height;
+
+	SLsmg_draw_box(y, 0, height, SLtt_Screen_Cols);
+	SLsmg_gotorc(y++, 1);
+	len = strlen(title);
+	if (len > (size_t)inner)
+		len = inner;
+	SLsmg_write_nchars(title, len);
+	for (i = 0; i < nr_lines; i++, y++) {
+		SLsmg_gotorc(y, 1);
+		SLsmg_write_nstring(lines[i], inner);
+	}
+	SLsmg_gotorc(y, 1);
+	SLsmg_write_nstring(bytes, inner);
+	SLsmg_refresh();
+	mutex_unlock(&ui__lock);
+}
+
+void ui__progress_window_end(void)
+{
+	if (!progress_window__shown || use_browser != 1)
+		return;
+
+	progress_window__shown = false;
+	progress_window__bytes[0] = '\0';
+
+	mutex_lock(&ui__lock);
+	SLsmg_set_color(0);
+	SLsmg_fill_region(progress_window__y, 0, progress_window__rows,
+			  SLtt_Screen_Cols, ' ');
+	progress_window__rows = 0;
+	SLsmg_refresh();
+	mutex_unlock(&ui__lock);
+}
+
+/*
+ * The keys typed while the fetch blocked the browser are in the TUI
+ * input queue: nobody else is reading it, drain them through these.
+ */
+bool ui__key_pending(void)
+{
+	return use_browser == 1 && SLang_input_pending(0) > 0;
+}
+
+int ui__key_read(void)
+{
+	return SLang_getkey();
+}
diff --git a/tools/perf/ui/util.h b/tools/perf/ui/util.h
index e30cea807564f92f..c264a8b2d5016110 100644
--- a/tools/perf/ui/util.h
+++ b/tools/perf/ui/util.h
@@ -2,9 +2,36 @@
 #ifndef _PERF_UI_UTIL_H_
 #define _PERF_UI_UTIL_H_ 1
 
+#include <stdbool.h>
 #include <stdarg.h>
+#include <linux/compiler.h>
+#include <linux/types.h>
 
 int ui__getch(int delay_secs);
+
+/*
+ * The TUI owns the terminal and its input queue, so the rest of perf
+ * asks for the progress display and for pending keys through these,
+ * keeping slang behind the ui/ layer.  Without slang they are no-ops,
+ * so callers stay free of #ifdefs.
+ */
+#ifndef HAVE_SLANG_SUPPORT
+/* No-ops without the TUI, keeping callers free of #ifdefs. */
+static inline bool ui__key_pending(void) { return false; }
+static inline int ui__key_read(void) { return -1; }
+static inline void ui__progress_window(const char *title __maybe_unused,
+				       const char *text __maybe_unused,
+				       u64 fetched __maybe_unused,
+				       u64 total __maybe_unused) {}
+static inline void ui__progress_window_end(void) {}
+#else /* HAVE_SLANG_SUPPORT */
+bool ui__key_pending(void);
+int ui__key_read(void);
+void ui__progress_window(const char *title, const char *text,
+			 u64 fetched, u64 total);
+void ui__progress_window_end(void);
+#endif /* HAVE_SLANG_SUPPORT */
+
 int ui__popup_menu(int argc, char * const argv[], int *keyp);
 int ui__help_window(const char *text);
 int ui__dialog_yesno(const char *msg);
diff --git a/tools/perf/util/debuginfo.c b/tools/perf/util/debuginfo.c
index 0ec11e1ad7508edc..737dd445d42bb72f 100644
--- a/tools/perf/util/debuginfo.c
+++ b/tools/perf/util/debuginfo.c
@@ -151,11 +151,13 @@ struct debuginfo *debuginfo__new(const char *path)
 
 #ifdef HAVE_DEBUGINFOD_SUPPORT
 /*
- * use_browser tells whether a full screen UI, the TUI for now, owns
- * the terminal and its input queue: the fetch progress and the
- * skip/disable keys below are stdio only when it doesn't.
+ * The TUI side of the fetch interaction is behind the ui/ layer:
+ * slang stays in ui/tui/ and callers use the ui__ primitives in
+ * ui/util.h.
  */
 #include "ui/ui.h"
+#include "ui/util.h"
+#include "ui/helpline.h"
 
 static bool debuginfod_progress_started;
 static bool debuginfod_fetch_cancelled;
@@ -172,28 +174,19 @@ static void debuginfod_signal_handler(int sig)
 	debuginfod_signal = sig;
 }
 
-/*
- * Say that the fetch in progress was skipped, and where disabling it
- * lands.
- */
+/* Say that the fetch in progress was skipped, and where disabling lands. */
 static void debuginfod__skipped(const char *msg)
 {
-	fprintf(stderr, "\n%s\n", msg);
+	if (use_browser > 0)
+		ui_helpline__puts(msg);
+	else
+		fprintf(stderr, "\n%s\n", msg);
 }
 
 /*
- * 's': skip this fetch, and remember the build ID so that the rest of
- * the session doesn't ask for it again, the query is aborted by
- * returning a non-zero value from the progress callback, as the
- * debuginfod client docs prescribe.  'd': also disable debuginfod for
- * the rest of the session, emptying the copy of DEBUGINFOD_URLS that
- * util/util.c installed at setup, so that libdwfl's own client, that
- * reads it in every query, stops fetching too, without a setenv() here
- * racing other threads' getenv()s, and
- * write core.debuginfod=false to the configuration file, the same
- * rewrite 'perf config' does, the comments are not preserved as the
- * config set carries just the key-value pairs, pointing at
- * 'perf config' when that rewrite can't be done.
+ * 's': skip this fetch and remember the build ID, so that the rest of
+ * the session doesn't ask for it again.  'd': also disable debuginfod
+ * for the session and write core.debuginfod=false to the config file.
  */
 static void debuginfod__cancel_key(int key)
 {
@@ -230,24 +223,22 @@ static void debuginfod__poll_cancel_keys(void)
 		debuginfod__cancel_key(ch);
 }
 
+/*
+ * The browser thread is the one doing the fetch, so its input queue has
+ * the keys typed while it was busy, drain those.
+ */
+static void debuginfod__tui_poll_cancel_keys(void)
+{
+	while (ui__key_pending())
+		debuginfod__cancel_key(ui__key_read());
+}
+
 /*
  * Print a warning and a progress indicator when the debuginfod client
- * ends up fetching a file, which can be big, such as the vmlinux for a
- * kernel profiled on another machine or before it got upgraded, so that
- * users know perf is not stuck, and let them bail out: 's' skips this
- * fetch and remembers the build ID, so that the rest of the session
- * doesn't ask for it again, 'd' also disables debuginfod for the rest
- * of the session.
- *
- * The client invokes this both while fetching, where 'a' is the number
- * of bytes transferred so far and 'b' the total size, zero when it
- * doesn't know it yet, and, before committing to a server, from the
- * cache cleanup, that scans the debuginfod client cache, with 'a' being
- * the number of cache files scanned so far and 'b' zero.
- *
- * In the stdio case the progress goes to stderr, a \r terminated line,
- * the keys are drained from stdin, that debuginfod__fetch() put in raw
- * mode.
+ * fetches a file, which can be big, so that users know perf is not
+ * stuck, and let them bail out with 's' or 'd'.  In the stdio case the
+ * progress goes to stderr and the keys are drained from stdin; in the
+ * TUI they come from the input queue, see the comment on ui/util.h.
  */
 static int debuginfod_progress_fn(debuginfod_client *c __maybe_unused,
 				  long a, long b)
@@ -255,7 +246,18 @@ static int debuginfod_progress_fn(debuginfod_client *c __maybe_unused,
 	if (debuginfod_signal)
 		return 1;
 
-	if (!isatty(STDERR_FILENO) || use_browser)
+	if (use_browser > 0) {
+		ui__progress_window("Fetching debuginfo by build ID from the debuginfod servers",
+				    "This may take a while for large files such as the vmlinux, press 's' to skip, 'd' to skip and disable",
+				    a > 0 ? (u64)a : 0, b > 0 ? (u64)b : 0);
+
+		debuginfod__tui_poll_cancel_keys();
+		if (debuginfod_fetch_cancelled)
+			return 1;
+		return 0;
+	}
+
+	if (!isatty(STDERR_FILENO))
 		return 0;
 
 	if (isatty(STDIN_FILENO)) {
@@ -439,17 +441,12 @@ static int debuginfod__fetch(const struct build_id *bid, char **path)
 	debuginfod_signal = 0;
 
 	/*
-	 * Make stdin deliver keypresses without waiting for a newline,
-	 * the progress callback above polls it for the 's'/'d' keys,
-	 * only in the stdio case with both stdin and stderr being a
-	 * terminal: the pipe cases have no business being poked here,
-	 * and in the TUI the terminal and its input queue are the
-	 * browser's own.  Intercept SIGINT, SIGQUIT and SIGTERM so that
-	 * the terminal is restored before the process dies, the handler
-	 * only records the signal and the callback aborts the query.
-	 * The handlers go in before the terminal mode changes, so that a
-	 * signal landing in between is caught and the raw mode is
-	 * restored.
+	 * In the stdio case, with stdin and stderr a terminal, put stdin in raw
+	 * mode so the 's'/'d' keys are delivered without waiting for a newline,
+	 * and intercept SIGINT, SIGQUIT and SIGTERM so the terminal is restored
+	 * before the process dies; the TUI uses its own primitives and
+	 * handlers.  The handlers go in before the terminal mode changes, so a
+	 * signal landing in between still restores it.
 	 */
 	if (isatty(STDIN_FILENO) && isatty(STDERR_FILENO) && !use_browser) {
 		memset(&sa, 0, sizeof(sa));
@@ -478,7 +475,9 @@ static int debuginfod__fetch(const struct build_id *bid, char **path)
 		sigaction(SIGTERM, &orig_sigterm, NULL);
 
 	debuginfod_end(c);
-	if (debuginfod_progress_started) {
+	if (use_browser > 0)
+		ui__progress_window_end();
+	else if (debuginfod_progress_started) {
 		fputc('\n', stderr);
 		debuginfod_progress_started = false;
 	}
-- 
2.55.0


^ permalink raw reply	[flat|nested] 18+ messages in thread

* [PATCH 06/15] perf symbol: Fall back to fetching the vmlinux by build ID
  2026-09-17 15:55 [PATCH v7 0/15] perf tools: Annotate fixes, stdio progress indication, debuginfo-client in more places Arnaldo Carvalho de Melo
                   ` (4 preceding siblings ...)
  2026-09-17 15:55 ` [PATCH 05/15] perf debuginfo: Show the debuginfod fetch progress and keys in the TUI Arnaldo Carvalho de Melo
@ 2026-09-17 15:55 ` Arnaldo Carvalho de Melo
  2026-09-17 15:55 ` [PATCH 07/15] perf annotate-data: Show the sample count in the data-type browser Arnaldo Carvalho de Melo
                   ` (8 subsequent siblings)
  14 siblings, 0 replies; 18+ messages in thread
From: Arnaldo Carvalho de Melo @ 2026-09-17 15:55 UTC (permalink / raw)
  To: Namhyung Kim
  Cc: Ingo Molnar, Thomas Gleixner, James Clark, Jiri Olsa, Ian Rogers,
	Adrian Hunter, Clark Williams, linux-kernel, linux-perf-users,
	Arnaldo Carvalho de Melo

From: Arnaldo Carvalho de Melo <acme@redhat.com>

A profile recorded on a kernel that is no longer installed, e.g. one
processed on another machine or after a kernel upgrade, cannot have its
kernel symbols resolved: /proc/kallsyms does not match it and the
build-id cache may carry only a kallsyms copy with zeroed addresses.
Fetch the vmlinux keyed by the build ID recorded in perf.data, using
debuginfod, as a last resort when no local source was found, honoring
symbol_conf.ignore_vmlinux and ignore_vmlinux_buildid like the other
vmlinux sources.

The fetch runs with dso->lock dropped, like dso__debuginfo(), and the
file is loaded with the lock held again, only if no other thread got the
symbols meanwhile (dso__has_symbols(), not dso__loaded(): the latter is
set even for failed attempts).  With the lock dropped two threads can
map the x86-64 entry trampolines at once, so that mapping is now
idempotent.

Assisted-by: LLM
Signed-off-by: Arnaldo Carvalho de Melo <acme@redhat.com>
---
 tools/perf/util/machine.c | 11 ++++++--
 tools/perf/util/symbol.c  | 55 ++++++++++++++++++++++++++++++++++++++-
 2 files changed, 63 insertions(+), 3 deletions(-)

diff --git a/tools/perf/util/machine.c b/tools/perf/util/machine.c
index a1288fbed8330a23..8aa9f5f12d3ea4bf 100644
--- a/tools/perf/util/machine.c
+++ b/tools/perf/util/machine.c
@@ -1139,12 +1139,19 @@ static int machine__map_x86_64_entry_trampolines_cb(struct map *map, void *data)
 	if (!kmap || !is_entry_trampoline(kmap->name))
 		return 0;
 
+	args->found = true;
+
+	/*
+	 * pgoff is a virtual address when the trampoline maps are created and
+	 * a vmlinux offset once mapped, so a second pass, e.g. a concurrent
+	 * dso__load() of the kernel dso, finds no map and has nothing to
+	 * translate: leave the map alone, never dereference a NULL dest_map.
+	 */
 	dest_map = maps__find(args->kmaps, map__pgoff(map));
-	if (RC_CHK_ACCESS(dest_map) != RC_CHK_ACCESS(map))
+	if (dest_map != NULL && RC_CHK_ACCESS(dest_map) != RC_CHK_ACCESS(map))
 		map__set_pgoff(map, map__map_ip(dest_map, map__pgoff(map)));
 
 	map__put(dest_map);
-	args->found = true;
 	return 0;
 }
 
diff --git a/tools/perf/util/symbol.c b/tools/perf/util/symbol.c
index fbad770cb96f8294..7a84dc8420975ab6 100644
--- a/tools/perf/util/symbol.c
+++ b/tools/perf/util/symbol.c
@@ -20,6 +20,7 @@
 #include "cap.h"
 #include "cpumap.h"
 #include "debug.h"
+#include "debuginfo.h"
 #include "demangle-cxx.h"
 #include "demangle-java.h"
 #include "demangle-ocaml.h"
@@ -2191,12 +2192,28 @@ static char *dso__find_kallsyms(struct dso *dso, struct map *map)
 	return strdup(path);
 }
 
+/*
+ * Last resort when the symbols for the kernel the profile was recorded
+ * on can't be found locally: fetch the vmlinux keyed by the build ID
+ * recorded in perf.data, e.g. when processing the profile on another
+ * machine or after the kernel got upgraded in between.
+ */
+/* Called by dso__load_kernel_sym() with dso->lock dropped, see there. */
+static int dso__fetch_vmlinux_build_id(struct dso *dso, char **path)
+{
+	if (!dso__has_build_id(dso))
+		return -1;
+
+	return debuginfo__find_build_id(dso__bid(dso), path);
+}
+
 static int dso__load_kernel_sym(struct dso *dso, struct map *map)
 {
 	int err;
 	const char *kallsyms_filename = NULL;
 	char *kallsyms_allocated_filename = NULL;
 	char *filename = NULL;
+	bool user_kallsyms = false;
 
 	/*
 	 * Step 1: if the user specified a kallsyms or vmlinux filename, use
@@ -2215,6 +2232,7 @@ static int dso__load_kernel_sym(struct dso *dso, struct map *map)
 	 */
 	if (symbol_conf.kallsyms_name != NULL) {
 		kallsyms_filename = symbol_conf.kallsyms_name;
+		user_kallsyms = true;
 		goto do_kallsyms;
 	}
 
@@ -2257,7 +2275,42 @@ static int dso__load_kernel_sym(struct dso *dso, struct map *map)
 		pr_debug("Using %s for symbols\n", kallsyms_filename);
 	free(kallsyms_allocated_filename);
 
-	if (err > 0 && !dso__is_kcore(dso)) {
+	/*
+	 * The kallsyms may be unavailable or restricted, try to fetch the
+	 * vmlinux keyed by the build ID using debuginfod as a last resort,
+	 * honoring ignore_vmlinux/ignore_vmlinux_buildid like the sources above.
+	 */
+	if (err <= 0 && !user_kallsyms &&
+	    !symbol_conf.ignore_vmlinux &&
+	    !symbol_conf.ignore_vmlinux_buildid) {
+		char *fetched_path = NULL;
+
+		/*
+		 * dso__load() holds dso->lock while it calls us, and the fetch below
+		 * can block for a long time: do it with the lock dropped, like
+		 * dso__debuginfo(), and load the symbols with the lock held again.
+		 */
+		mutex_unlock(dso__lock(dso));
+		err = dso__fetch_vmlinux_build_id(dso, &fetched_path);
+		mutex_lock(dso__lock(dso));
+
+		if (err) {
+			zfree(&fetched_path);
+		} else if (dso__has_symbols(dso)) {
+			/*
+			 * Somebody else got the symbols while the lock was dropped for the
+			 * fetch, use those instead.  dso__has_symbols() and not dso__loaded():
+			 * the latter is set even for failed attempts.
+			 */
+			pr_debug("%s got its symbols while its vmlinux was being fetched, using them\n",
+				 dso__name(dso));
+			zfree(&fetched_path);
+			err = 1;
+		} else {
+			/* Takes ownership of 'fetched_path' even when it fails */
+			err = dso__load_vmlinux(dso, map, fetched_path, true);
+		}
+	} else if (err > 0 && !dso__is_kcore(dso)) {
 		struct maps *kmaps = map__kmaps(map);
 
 		dso__set_binary_type(dso, DSO_BINARY_TYPE__KALLSYMS);
-- 
2.55.0


^ permalink raw reply	[flat|nested] 18+ messages in thread

* [PATCH 07/15] perf annotate-data: Show the sample count in the data-type browser
  2026-09-17 15:55 [PATCH v7 0/15] perf tools: Annotate fixes, stdio progress indication, debuginfo-client in more places Arnaldo Carvalho de Melo
                   ` (5 preceding siblings ...)
  2026-09-17 15:55 ` [PATCH 06/15] perf symbol: Fall back to fetching the vmlinux by build ID Arnaldo Carvalho de Melo
@ 2026-09-17 15:55 ` Arnaldo Carvalho de Melo
  2026-09-17 15:55 ` [PATCH 08/15] perf report: Add --progress option Arnaldo Carvalho de Melo
                   ` (7 subsequent siblings)
  14 siblings, 0 replies; 18+ messages in thread
From: Arnaldo Carvalho de Melo @ 2026-09-17 15:55 UTC (permalink / raw)
  To: Namhyung Kim
  Cc: Ingo Molnar, Thomas Gleixner, James Clark, Jiri Olsa, Ian Rogers,
	Adrian Hunter, Clark Williams, linux-kernel, linux-perf-users,
	Arnaldo Carvalho de Melo

From: Arnaldo Carvalho de Melo <acme@redhat.com>

The samples view (-n, annotate.show_nr_samples) prints a local
nr_samples variable that is initialized to zero and never updated, so
every member is listed as having no samples while the period and percent
columns for the same entry are filled in.  Print the histogram entry's
own count instead.

Fixes: d001c7a7f4736743 ("perf annotate-data: Add hist_entry__annotate_data_tui()")
Assisted-by: LLM
Signed-off-by: Arnaldo Carvalho de Melo <acme@redhat.com>
---
 tools/perf/ui/browsers/annotate-data.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/tools/perf/ui/browsers/annotate-data.c b/tools/perf/ui/browsers/annotate-data.c
index c6e07a9b64089ab5..a15608f6ee53335f 100644
--- a/tools/perf/ui/browsers/annotate-data.c
+++ b/tools/perf/ui/browsers/annotate-data.c
@@ -374,7 +374,7 @@ static void browser__write_overhead(struct ui_browser *uib,
 	u64 period = hist->period;
 	double percent = total->period ? (100.0 * period / total->period) : 0;
 	bool current = ui_browser__is_current_entry(uib, row);
-	int nr_samples = 0;
+	int nr_samples = hist->nr_samples;
 
 	ui_browser__set_percent_color(uib, percent, current);
 
-- 
2.55.0


^ permalink raw reply	[flat|nested] 18+ messages in thread

* [PATCH 08/15] perf report: Add --progress option
  2026-09-17 15:55 [PATCH v7 0/15] perf tools: Annotate fixes, stdio progress indication, debuginfo-client in more places Arnaldo Carvalho de Melo
                   ` (6 preceding siblings ...)
  2026-09-17 15:55 ` [PATCH 07/15] perf annotate-data: Show the sample count in the data-type browser Arnaldo Carvalho de Melo
@ 2026-09-17 15:55 ` Arnaldo Carvalho de Melo
  2026-09-17 15:55 ` [PATCH 09/15] perf scripts: Add perf-stuck, to tell where a running perf is stuck Arnaldo Carvalho de Melo
                   ` (6 subsequent siblings)
  14 siblings, 0 replies; 18+ messages in thread
From: Arnaldo Carvalho de Melo @ 2026-09-17 15:55 UTC (permalink / raw)
  To: Namhyung Kim
  Cc: Ingo Molnar, Thomas Gleixner, James Clark, Jiri Olsa, Ian Rogers,
	Adrian Hunter, Clark Williams, linux-kernel, linux-perf-users,
	Arnaldo Carvalho de Melo

From: Arnaldo Carvalho de Melo <acme@redhat.com>

Processing a large session with stdio output gives no feedback about
which phase perf is in or how far along it is: the ui_progress updates
are only shown by the TUI.  Add --progress, installing a stdio backend
for ui_progress (ui/stdio/progress.c) that prints the phase title, the
percentage and the current/total counts to stderr:

  Processing events... [ 42.3%] 317M / 746M
  Merging related events... [ 61.0%] 309026 / 506686

Phases can be nested, so the backend keeps track of the ones started so
far to complete the right one on ui_progress__finish().  That requires
init()/finish() to be paired, and the paths that returned early without
the finish, in ordered-events.c and in the pipe and directory event
processing, are fixed.

Assisted-by: LLM
Signed-off-by: Arnaldo Carvalho de Melo <acme@redhat.com>
---
 tools/perf/Documentation/perf-report.txt |  13 ++
 tools/perf/builtin-report.c              |  10 ++
 tools/perf/ui/Build                      |   1 +
 tools/perf/ui/progress.h                 |   2 +
 tools/perf/ui/stdio/progress.c           | 163 +++++++++++++++++++++++
 tools/perf/util/ordered-events.c         |  16 ++-
 tools/perf/util/session.c                |  12 +-
 7 files changed, 210 insertions(+), 7 deletions(-)
 create mode 100644 tools/perf/ui/stdio/progress.c

diff --git a/tools/perf/Documentation/perf-report.txt b/tools/perf/Documentation/perf-report.txt
index 0a4f61283b9542f7..8fc1d5d56d54f698 100644
--- a/tools/perf/Documentation/perf-report.txt
+++ b/tools/perf/Documentation/perf-report.txt
@@ -29,6 +29,19 @@ OPTIONS
 --quiet::
 	Do not show any warnings or messages.  (Suppress -v)
 
+--progress::
+	Show progress for each of the processing phases, printing the
+	percentage done and the current/total counts: the first phase
+	counts the bytes of the perf.data file processed so far, the
+	merge and sort phases count hist entries, e.g.:
+
+	Processing events... [ 42.3%] 4G / 10G
+	Merging related events... [  7.1%] 1024 / 14387
+	Sorting events for output... [ 98.2%] 14132 / 14387
+
+	It is a no-op when using the TUI or GTK browsers, that already
+	present progress information.
+
 -n::
 --show-nr-samples::
 	Show the number of samples for each symbol
diff --git a/tools/perf/builtin-report.c b/tools/perf/builtin-report.c
index 442c0822e614197f..e3ac2f15c9fd5c4f 100644
--- a/tools/perf/builtin-report.c
+++ b/tools/perf/builtin-report.c
@@ -87,6 +87,7 @@ struct report {
 	bool			use_gtk;
 #endif
 	bool			use_stdio;
+	bool			progress;
 	bool			show_full_info;
 	bool			show_threads;
 	bool			inverted_callchain;
@@ -1374,6 +1375,8 @@ int cmd_report(int argc, const char **argv)
 		    "Use the stdio interface"),
 	OPT_BOOLEAN(0, "weights", &symbol_conf.annotate_weight,
 			"Show or hide weight columns in annotation. Default show if non-zero."),
+	OPT_BOOLEAN(0, "progress", &report.progress,
+		    "Show progress while processing the perf.data file"),
 	OPT_BOOLEAN(0, "header", &report.header, "Show data header."),
 	OPT_BOOLEAN(0, "header-only", &report.header_only,
 		    "Show only data header."),
@@ -1766,6 +1769,13 @@ int cmd_report(int argc, const char **argv)
 	else
 		use_browser = 0;
 
+	/*
+	 * For the stdio case: print the percentage of the perf.data file
+	 * processed so far for each processing phase.
+	 */
+	if (report.progress && use_browser == 0)
+		stdio_progress__init();
+
 	if (report.data_type && use_browser == 1) {
 		symbol_conf.annotate_data_member = true;
 		symbol_conf.annotate_data_sample = true;
diff --git a/tools/perf/ui/Build b/tools/perf/ui/Build
index 6005f813c9e3990c..a7b1740d51c80f23 100644
--- a/tools/perf/ui/Build
+++ b/tools/perf/ui/Build
@@ -4,6 +4,7 @@ perf-ui-y += progress.o
 perf-ui-y += util.o
 perf-ui-y += hist.o
 perf-ui-y += stdio/hist.o
+perf-ui-y += stdio/progress.o
 
 CFLAGS_setup.o += -DLIBDIR="BUILD_STR($(LIBDIR))"
 
diff --git a/tools/perf/ui/progress.h b/tools/perf/ui/progress.h
index 4f52c37b2f099a82..03f1a8bb260ba076 100644
--- a/tools/perf/ui/progress.h
+++ b/tools/perf/ui/progress.h
@@ -23,6 +23,8 @@ void __ui_progress__init(struct ui_progress *p, u64 total,
 
 void ui_progress__update(struct ui_progress *p, u64 adv);
 
+void stdio_progress__init(void);
+
 struct ui_progress_ops {
 	void (*init)(struct ui_progress *p);
 	void (*update)(struct ui_progress *p);
diff --git a/tools/perf/ui/stdio/progress.c b/tools/perf/ui/stdio/progress.c
new file mode 100644
index 0000000000000000..d8465e13ad50e4f6
--- /dev/null
+++ b/tools/perf/ui/stdio/progress.c
@@ -0,0 +1,163 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Progress feedback for the stdio (non-TUI/GTK) case, enabled with
+ * 'perf report --progress'.
+ */
+#include <inttypes.h>
+#include <stdio.h>
+#include <unistd.h>
+#include <linux/kernel.h>
+#include "../../util/debug.h"
+#include "../../util/units.h"
+#include "../progress.h"
+
+/*
+ * Phases can be nested, so keep track of the ones started so far to be
+ * able to complete the right one on ui_progress__finish(), which gets
+ * no arguments.
+ */
+#define STDIO_PROGRESS__MAX_DEPTH 8
+
+struct stdio_progress_phase {
+	struct ui_progress	*p;
+	u64			last_printed;
+	size_t			last_len;
+};
+
+static struct stdio_progress_phase stdio_progress__stack[STDIO_PROGRESS__MAX_DEPTH];
+static int stdio_progress__depth;
+static bool stdio_progress__is_tty;
+/* Phases that didn't fit on the stack are not shown. */
+static int stdio_progress__dropped;
+
+static void stdio_progress__print_phase(struct stdio_progress_phase *phase,
+					u64 curr)
+{
+	struct ui_progress *p = phase->p;
+	char buf_cur[20], buf_tot[20], buf[128];
+	double percent = p->total ? 100.0 * (double)curr / (double)p->total : 0.0;
+	size_t len;
+
+	/*
+	 * Only the completion line shows 100.0%: a 99.99% progress would round
+	 * up to it and look like a duplicate at finish time.
+	 */
+	if (curr < p->total && percent > 99.9)
+		percent = 99.9;
+
+	if (p->size) {
+		unit_number__scnprintf(buf_cur, sizeof(buf_cur), curr);
+		unit_number__scnprintf(buf_tot, sizeof(buf_tot), p->total);
+		len = scnprintf(buf, sizeof(buf), "%s [%5.1f%%] %s / %s",
+				p->title, percent, buf_cur, buf_tot);
+	} else {
+		len = scnprintf(buf, sizeof(buf), "%s [%5.1f%%] %" PRIu64 " / %" PRIu64,
+				p->title, percent, curr, p->total);
+	}
+
+	if (!stdio_progress__is_tty) {
+		fprintf(stderr, "%s\n", buf);
+		goto out;
+	}
+
+	/* Pad to the length of the previous line to erase its leftovers. */
+	fprintf(stderr, "\r%s%*s", buf,
+		(int)(len < phase->last_len ? phase->last_len - len : 0), "");
+	phase->last_len = len;
+out:
+	phase->last_printed = curr;
+	fflush(stderr);
+}
+
+static void __stdio_progress__init(struct ui_progress *p)
+{
+	/* The default step is meant for the TUI bar, use 1% steps for stdio. */
+	p->next = p->step = p->total / 100 ?: 1;
+
+	if (stdio_progress__depth == STDIO_PROGRESS__MAX_DEPTH) {
+		/*
+		 * Out of room: don't start this phase, its finish() is swallowed below
+		 * and its updates are ignored, so it doesn't complete the phase that
+		 * encloses it.
+		 */
+		pr_warning("progress phases nested deeper than %d, not showing progress for %s\n",
+			   STDIO_PROGRESS__MAX_DEPTH, p->title);
+		stdio_progress__dropped++;
+		return;
+	}
+
+	/* Start a nested phase in a line of its own. */
+	if (stdio_progress__depth && stdio_progress__is_tty)
+		fputc('\n', stderr);
+
+	stdio_progress__stack[stdio_progress__depth++] =
+		(struct stdio_progress_phase) {
+			.p = p,
+			.last_printed = 0,
+			.last_len = 0,
+		};
+
+	stdio_progress__print_phase(&stdio_progress__stack[stdio_progress__depth - 1],
+				    p->curr);
+}
+
+static void stdio_progress__update(struct ui_progress *p)
+{
+	/*
+	 * An update that doesn't match the innermost running phase means
+	 * something got out of sync: print nothing rather than another phase's
+	 * numbers, or read past the stack.
+	 */
+	if (!stdio_progress__depth ||
+	    stdio_progress__stack[stdio_progress__depth - 1].p != p)
+		return;
+
+	stdio_progress__print_phase(&stdio_progress__stack[stdio_progress__depth - 1],
+				    p->curr);
+}
+
+static void stdio_progress__finish(void)
+{
+	struct stdio_progress_phase *phase;
+
+	/*
+	 * Being the innermost phase, its finish() comes first: swallow it, or
+	 * it would complete the phase that encloses it.
+	 */
+	if (stdio_progress__dropped) {
+		stdio_progress__dropped--;
+		return;
+	}
+
+	if (!stdio_progress__depth)
+		return;
+
+	phase = &stdio_progress__stack[--stdio_progress__depth];
+
+	/*
+	 * The last line may have stopped short of the total, close this phase
+	 * showing it as complete unless that was already printed.
+	 */
+	if (phase->last_printed != phase->p->total)
+		stdio_progress__print_phase(phase, phase->p->total);
+
+	phase->last_printed	= 0;
+	phase->last_len		= 0;
+
+	if (stdio_progress__is_tty)
+		fputc('\n', stderr);
+
+	fflush(stderr);
+}
+
+static struct ui_progress_ops stdio_progress__ops = {
+	.init	= __stdio_progress__init,
+	.update	= stdio_progress__update,
+	.finish	= stdio_progress__finish,
+};
+
+void stdio_progress__init(void)
+{
+	stdio_progress__is_tty = isatty(STDERR_FILENO) == 1;
+	ui_progress__ops = &stdio_progress__ops;
+}
diff --git a/tools/perf/util/ordered-events.c b/tools/perf/util/ordered-events.c
index a5857f9f5af2d3de..54c85663e733be4d 100644
--- a/tools/perf/util/ordered-events.c
+++ b/tools/perf/util/ordered-events.c
@@ -237,14 +237,16 @@ static int do_flush(struct ordered_events *oe, bool show_progress)
 		ui_progress__init(&prog, oe->nr_events, "Processing time ordered events...");
 
 	list_for_each_entry_safe(iter, tmp, head, list) {
-		if (session_done())
-			return 0;
+		if (session_done()) {
+			ret = 0;
+			goto out_progress;
+		}
 
 		if (iter->timestamp > limit)
 			break;
 		ret = oe->deliver(oe, iter);
 		if (ret < 0)
-			return ret;
+			goto out_progress;
 
 		ordered_events__delete(oe, iter);
 		oe->last_flush = iter->timestamp;
@@ -258,10 +260,16 @@ static int do_flush(struct ordered_events *oe, bool show_progress)
 	else if (last_ts <= limit)
 		oe->last = list_entry(head->prev, struct ordered_event, list);
 
+	ret = 0;
+out_progress:
+	/*
+	 * Always pair ui_progress__init() with ui_progress__finish(), the
+	 * stdio backend tracks the phases on a stack.
+	 */
 	if (show_progress)
 		ui_progress__finish();
 
-	return 0;
+	return ret;
 }
 
 static int __ordered_events__flush(struct ordered_events *oe, enum oe_flush how,
diff --git a/tools/perf/util/session.c b/tools/perf/util/session.c
index a5b596cd14be6186..50f3e1d6c17d3147 100644
--- a/tools/perf/util/session.c
+++ b/tools/perf/util/session.c
@@ -3248,8 +3248,12 @@ static int __perf_session__process_pipe_events(struct perf_session *session)
 	cur_size = sizeof(union perf_event);
 
 	buf = malloc(cur_size);
-	if (!buf)
-		return -errno;
+	if (!buf) {
+		err = -errno;
+		if (update_prog)
+			ui_progress__finish();
+		return err;
+	}
 	ordered_events__set_copy_on_queue(oe, true);
 more:
 	event = buf;
@@ -3748,8 +3752,10 @@ static int __perf_session__process_dir_events(struct perf_session *session)
 	}
 
 	rd = calloc(nr_readers, sizeof(struct reader));
-	if (!rd)
+	if (!rd) {
+		ui_progress__finish();
 		return -ENOMEM;
+	}
 
 	rd[0] = (struct reader) {
 		.fd		 = perf_data__fd(session->data),
-- 
2.55.0


^ permalink raw reply	[flat|nested] 18+ messages in thread

* [PATCH 09/15] perf scripts: Add perf-stuck, to tell where a running perf is stuck
  2026-09-17 15:55 [PATCH v7 0/15] perf tools: Annotate fixes, stdio progress indication, debuginfo-client in more places Arnaldo Carvalho de Melo
                   ` (7 preceding siblings ...)
  2026-09-17 15:55 ` [PATCH 08/15] perf report: Add --progress option Arnaldo Carvalho de Melo
@ 2026-09-17 15:55 ` Arnaldo Carvalho de Melo
  2026-09-17 15:55 ` [PATCH 10/15] perf dwarf-aux: Bound the type chases for broken debug info Arnaldo Carvalho de Melo
                   ` (5 subsequent siblings)
  14 siblings, 0 replies; 18+ messages in thread
From: Arnaldo Carvalho de Melo @ 2026-09-17 15:55 UTC (permalink / raw)
  To: Namhyung Kim
  Cc: Ingo Molnar, Thomas Gleixner, James Clark, Jiri Olsa, Ian Rogers,
	Adrian Hunter, Clark Williams, linux-kernel, linux-perf-users,
	Arnaldo Carvalho de Melo

From: Arnaldo Carvalho de Melo <acme@redhat.com>

A perf that takes forever is hard to tell apart from one stuck in a
loop, and when it is stuck there is no way to see where without
attaching gdb and looking around.  perf-stuck.sh samples a running
process' /proc entries and its progress line at a fixed interval, and
with -g runs gdb (perf-stuck.gdb, adding the perf-die-chain command)
when no progress is made across two samples, printing the DIE chain a
DWARF type chase is walking when it is stuck in one of those.

It is a prototype: the plan is to turn it into a first class 'perf
stuck' command sampling a process from inside perf.

Assisted-by: LLM
Signed-off-by: Arnaldo Carvalho de Melo <acme@redhat.com>
---
 tools/perf/scripts/perf-stuck.gdb | 104 ++++++++++++++++
 tools/perf/scripts/perf-stuck.sh  | 194 ++++++++++++++++++++++++++++++
 2 files changed, 298 insertions(+)
 create mode 100644 tools/perf/scripts/perf-stuck.gdb
 create mode 100755 tools/perf/scripts/perf-stuck.sh

diff --git a/tools/perf/scripts/perf-stuck.gdb b/tools/perf/scripts/perf-stuck.gdb
new file mode 100644
index 0000000000000000..53e9019828b6ef62
--- /dev/null
+++ b/tools/perf/scripts/perf-stuck.gdb
@@ -0,0 +1,104 @@
+# SPDX-License-Identifier: GPL-2.0
+#
+# gdb commands for a perf that is stuck, used by perf-stuck.sh -g and usable
+# directly:
+#
+#   gdb -p $(pgrep -x perf) -batch -x perf-stuck.gdb -ex bt
+#
+# PROTOTYPE: part of the perf-stuck.sh stopgap, see the note at the start of
+# that script: this wants to move into a first class 'perf stuck' command,
+# which would print these DIE chains by itself, without gdb.
+#
+# The settings are the ones that keep a batch attach from stopping to ask
+# questions (debuginfod, pagination) and that make the output readable.
+#
+# The commands are for the DWARF type chasers in util/dwarf-aux.c, the
+# functions a data type profiling 'perf report -s type' spins in when a
+# debug info file has a type chain that got into a cycle:
+#
+#   perf-die-chain <function> <die variable> [iterations]
+#   perf-die-chain-all [iterations]
+#   perf-dso
+#
+# For each iteration of the chasing loop they print the DIE address, the
+# CU it came from, its offset in the debug file, its tag and its name: a
+# cycle shows up as the same handful of (addr, cu) pairs repeating, and a
+# CU that changes from one iteration to the next means the chase is
+# hopping between a debug file and its dwz common file.
+
+set pagination off
+set confirm off
+set debuginfod enabled off
+set print pretty on
+set height 0
+set width 0
+
+define perf-die-chain
+  if $argc < 2
+    printf "usage: perf-die-chain <function> <die variable> [iterations]\n"
+  else
+    frame function $arg0
+    if $argc == 3
+      set $perf_die_chain_n = $arg2
+    else
+      set $perf_die_chain_n = 10
+    end
+    set $perf_die_chain_head = $pc
+    set $perf_die_chain_i = 0
+    while $perf_die_chain_i < $perf_die_chain_n
+      printf "chain[%d] die=%p addr=%p cu=%p off=0x%lx tag=%d name=%s\n", $perf_die_chain_i, $arg1, $arg1->addr, $arg1->cu, ((Dwarf_Off) dwarf_dieoffset($arg1)), ((int) dwarf_tag($arg1)), ((char *) dwarf_diename($arg1))
+      until *$perf_die_chain_head
+      set $perf_die_chain_i = $perf_die_chain_i + 1
+    end
+  end
+end
+
+document perf-die-chain
+Print the DIE chain being walked by a DWARF type chasing loop.
+usage: perf-die-chain <function> <die variable> [iterations]
+  perf-die-chain die_get_pointer_type type_die
+  perf-die-chain __die_get_real_type vr_die
+  perf-die-chain die_get_real_type vr_die
+end
+
+define perf-die-chain-all
+  if $argc == 0
+    set $perf_die_chain_n = 10
+  else
+    set $perf_die_chain_n = $arg0
+  end
+  if $_any_caller_is("die_get_pointer_type", 20)
+    printf "stuck in die_get_pointer_type():\n"
+    perf-die-chain die_get_pointer_type type_die $perf_die_chain_n
+  else
+    if $_any_caller_is("__die_get_real_type", 20)
+      printf "stuck in __die_get_real_type():\n"
+      perf-die-chain __die_get_real_type vr_die $perf_die_chain_n
+    else
+      if $_any_caller_is("die_get_real_type", 20)
+        printf "stuck in die_get_real_type():\n"
+        perf-die-chain die_get_real_type vr_die $perf_die_chain_n
+      else
+        printf "not in a DWARF type chaser, try: bt\n"
+      end
+    end
+  end
+end
+
+document perf-die-chain-all
+Find which DWARF type chaser the process is in and print the DIE chain.
+usage: perf-die-chain-all [iterations]
+end
+
+define perf-dso
+  if $_any_caller_is("find_data_type", 20)
+    frame function find_data_type
+    printf "dso=%s ip=0x%lx sym=%s\n", dloc->ms->map->dso->name, dloc->ip, dloc->ms->sym->name
+  else
+    printf "not in find_data_type()\n"
+  end
+end
+
+document perf-dso
+Print the dso, ip and symbol of the data location being resolved.
+end
diff --git a/tools/perf/scripts/perf-stuck.sh b/tools/perf/scripts/perf-stuck.sh
new file mode 100755
index 0000000000000000..70e59192b1d9658e
--- /dev/null
+++ b/tools/perf/scripts/perf-stuck.sh
@@ -0,0 +1,194 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0
+#
+# perf-stuck - tell a spinning perf apart from a blocked or recursing one
+#
+# Arnaldo Carvalho de Melo <acme@redhat.com>
+#
+# PROTOTYPE: this wants to become a first class 'perf stuck' command, that
+# samples a running perf, or any other process, from inside perf, with the
+# knowledge of the phases perf goes through and of the DWARF type chasing
+# loops built in, instead of this shell script poking at /proc and shelling
+# out to gdb.  It is here as a stopgap, to be able to tell where a perf is
+# stuck while looking at hangs such as the one 'perf report -s type' hits
+# on dwz compressed debug info.
+#
+# Samples /proc/<pid> at a fixed interval and prints, for each sample:
+#
+#   the CPU time used since the previous sample, so a process burning a
+#   full interval's worth of ticks is spinning, while one using none is
+#   blocked
+#
+#   the [stack] mapping start, which moves down as the stack grows, the
+#   giveaway for runaway recursion, together with its size
+#
+#   the last line of a progress log, when one is given, e.g. the stderr
+#   of 'perf report --progress', to see which phase is stuck
+#
+# A process that burns CPU with a constant stack and no progress is in an
+# unbounded loop, e.g. a die_get_pointer_type() chain that got into a
+# cycle, while one whose [stack] start keeps moving down is recursing.
+#
+# With -g it runs gdb, using the perf-stuck.gdb that sits next to this
+# script, when no progress is made for two consecutive samples, which for
+# a perf in a DWARF type chasing loop prints the DIE chain it is walking.
+#
+# usage: perf-stuck.sh [options] <pid|process-name>
+
+set -u
+
+usage() {
+	cat <<-EOF
+	usage: perf-stuck.sh [options] <pid|process-name>
+
+	  -i <secs>   sampling interval (default: 10)
+	  -n <count>  stop after this many samples (default: watch till it exits)
+	  -l <file>   progress log, its last line is printed with every sample
+	  -g          run gdb with perf-stuck.gdb when no progress is made for
+	              two consecutive samples, writing the output to a temp file
+	  -x <file>   use this gdb command file instead of perf-stuck.gdb
+	  -h          this help
+	EOF
+	exit "${1:-0}"
+}
+
+interval=10
+count=0
+progress_log=
+use_gdb=
+gdb_cmds=
+
+while getopts "i:n:l:gx:h" opt; do
+	case "$opt" in
+	i) interval=$OPTARG ;;
+	n) count=$OPTARG ;;
+	l) progress_log=$OPTARG ;;
+	g) use_gdb=1 ;;
+	x) gdb_cmds=$OPTARG ;;
+	h) usage 0 ;;
+	*) usage 1 ;;
+	esac
+done
+shift $((OPTIND - 1))
+
+[ $# -eq 1 ] || usage 1
+
+if [[ "$1" =~ ^[0-9]+$ ]]; then
+	pid=$1
+else
+	pid=$(pgrep -x "$1" | head -1)
+	[ -n "$pid" ] || { echo "no process named '$1'"; exit 1; }
+fi
+
+[ -d /proc/"$pid" ] || { echo "no process $pid"; exit 1; }
+
+if [ -n "$use_gdb" ] && [ -z "$gdb_cmds" ]; then
+	gdb_cmds=$(dirname "$0")/perf-stuck.gdb
+	[ -r "$gdb_cmds" ] || { echo "cannot read $gdb_cmds"; exit 1; }
+fi
+
+hz=$(getconf CLK_TCK)
+psz=$(getconf PAGESIZE)
+prev_cpu=
+prev_stack=
+prev_progress=
+stuck=0
+gdb_done=
+nsample=0
+
+# The command line is whatever the process was started with, so drop the
+# control characters from it: a process started with escape sequences in
+# its arguments, e.g. one replaying a log line, would otherwise get them
+# replayed on the terminal of whoever runs this.
+cmdline=$(tr '\0' ' ' < /proc/"$pid"/cmdline | tr -d '[:cntrl:]')
+
+echo "watching $pid ($cmdline) every ${interval}s"
+
+while :; do
+	if [ ! -d /proc/"$pid" ]; then
+		echo "$(date +%T) process gone"
+		break
+	fi
+
+	# Field 2, the command name, is in parentheses and can contain
+	# spaces, so drop it together with the pid before splitting: the
+	# fields after it then line up, with the state, the utime+stime
+	# pair and the RSS landing where they are read below.  Printing the
+	# CPU time with %d instead of relying on awk's default output format
+	# keeps it out of scientific notation, that bash arithmetic cannot
+	# parse, once it goes past six digits, i.e. some 16 minutes of CPU
+	# at 100 Hz.
+	if ! stat_line=$(awk '{ sub(/^[^ ]+ \(.*\) /, "");
+			       printf "%s %d %d\n", $1, $12 + $13, $22 }' \
+			 /proc/"$pid"/stat 2>/dev/null); then
+		echo "$(date +%T) process gone"
+		break
+	fi
+
+	# The process can be gone between the check above and this read, in
+	# which case there is nothing to report: 'set -u' would otherwise
+	# turn the unbound fields into an aborted script.
+	if [ -z "$stat_line" ]; then
+		echo "$(date +%T) process gone"
+		break
+	fi
+
+	stat=($stat_line)
+	state=${stat[0]}
+	cpu=${stat[1]}
+	# field 24 of /proc/<pid>/stat, the resident set size in pages
+	rss=$(( stat[2] * psz / 1024 ))
+
+	stack=$(awk '/\[stack\]/{print $1; exit}' /proc/"$pid"/maps 2>/dev/null)
+	if [ -n "$stack" ]; then
+		stack_start=0x${stack%-*}
+		stack_size=$(( 0x${stack#*-} - stack_start ))
+		stack_txt="$stack size=$((stack_size / 1024))kB"
+	else
+		stack_start=
+		stack_txt="-"
+	fi
+
+	progress=
+	[ -n "$progress_log" ] && [ -s "$progress_log" ] && progress=$(tail -1 "$progress_log")
+
+	if [ -n "$prev_cpu" ]; then
+		cpu_delta=$(( cpu - prev_cpu ))
+		# With a progress log, count the samples that show no progress,
+		# without one there is no progress to look at, so count them all:
+		# -g then looks at where the process is after two intervals.
+		if [ -z "$progress_log" ] ||
+		   { [ -n "$progress" ] && [ "$progress" = "$prev_progress" ]; }; then
+			stuck=$((stuck + 1))
+		else
+			stuck=0
+		fi
+		stuck_txt="stuck=${stuck}"
+		[ "$stack_start" != "$prev_stack" ] && stuck_txt="$stuck_txt STACK"
+	else
+		cpu_delta=0
+		stuck_txt=""
+	fi
+
+	printf '%s state=%s cpu=+%d (%d.%02ds) rss=%dkB stack=%s %s %s\n' \
+	       "$(date +%T)" "$state" "$cpu_delta" \
+	       $(( cpu_delta / hz )) $(( (cpu_delta % hz) * 100 / hz )) \
+	       "$rss" "$stack_txt" "$stuck_txt" "${progress:-(no progress log)}"
+
+	if [ -n "$use_gdb" ] && [ -z "$gdb_done" ] && [ "$stuck" -ge 2 ]; then
+		gdb_log=$(mktemp /tmp/perf-stuck-gdb.XXXXXX)
+		gdb -p "$pid" -batch -x "$gdb_cmds" -ex bt \
+		    -ex 'perf-die-chain-all' -ex perf-dso -ex detach > "$gdb_log" 2>&1
+		gdb_done=1
+		echo "... gdb output of $pid in $gdb_log"
+	fi
+
+	prev_cpu=$cpu
+	prev_stack=$stack_start
+	prev_progress=$progress
+
+	nsample=$((nsample + 1))
+	[ "$count" -gt 0 ] && [ "$nsample" -ge "$count" ] && break
+
+	sleep "$interval"
+done
-- 
2.55.0


^ permalink raw reply	[flat|nested] 18+ messages in thread

* [PATCH 10/15] perf dwarf-aux: Bound the type chases for broken debug info
  2026-09-17 15:55 [PATCH v7 0/15] perf tools: Annotate fixes, stdio progress indication, debuginfo-client in more places Arnaldo Carvalho de Melo
                   ` (8 preceding siblings ...)
  2026-09-17 15:55 ` [PATCH 09/15] perf scripts: Add perf-stuck, to tell where a running perf is stuck Arnaldo Carvalho de Melo
@ 2026-09-17 15:55 ` Arnaldo Carvalho de Melo
  2026-09-17 15:55 ` [PATCH 11/15] perf dwarf-aux: Add die_same_file() and die_get_type_die() Arnaldo Carvalho de Melo
                   ` (4 subsequent siblings)
  14 siblings, 0 replies; 18+ messages in thread
From: Arnaldo Carvalho de Melo @ 2026-09-17 15:55 UTC (permalink / raw)
  To: Namhyung Kim
  Cc: Ingo Molnar, Thomas Gleixner, James Clark, Jiri Olsa, Ian Rogers,
	Adrian Hunter, Clark Williams, linux-kernel, linux-perf-users,
	Arnaldo Carvalho de Melo

From: Arnaldo Carvalho de Melo <acme@redhat.com>

A DIE that is not what it looks like, e.g. one parsed at an offset that
is not the start of a DIE, can have a DW_AT_type that refers back to
itself, making the typedef/qualifier chases in die_get_real_type() and
die_get_pointer_type() spin forever, and the same for the type name
recursion in die_get_typename_from_type(); 'perf report -s type' did
exactly that on the dwz compressed debug info of zlib-ng (libz.so.1).

No sane chain of typedefs and qualifiers is 32 DIEs long, so give up on
the type with a pr_debug instead of hanging.

Assisted-by: LLM
Signed-off-by: Arnaldo Carvalho de Melo <acme@redhat.com>
---
 tools/perf/util/dwarf-aux.c | 88 ++++++++++++++++++++++++++++---------
 1 file changed, 68 insertions(+), 20 deletions(-)

diff --git a/tools/perf/util/dwarf-aux.c b/tools/perf/util/dwarf-aux.c
index d7160f87ac7d7ab3..b5ffeea54446408d 100644
--- a/tools/perf/util/dwarf-aux.c
+++ b/tools/perf/util/dwarf-aux.c
@@ -266,16 +266,29 @@ Dwarf_Die *die_get_type(Dwarf_Die *vr_die, Dwarf_Die *die_mem)
 		return NULL;
 }
 
+/*
+ * A DIE that is not what it looks like, e.g. one parsed at an offset
+ * that is not the start of a DIE, can have a DW_AT_type that refers
+ * back to itself, making these chases spin forever: bound them and
+ * report, instead of hanging.
+ */
+#define MAX_TYPE_CHASE 32
+
 /* Get a type die, but skip qualifiers */
 Dwarf_Die *__die_get_real_type(Dwarf_Die *vr_die, Dwarf_Die *die_mem)
 {
-	int tag;
+	int tag, chase = 0;
 
 	do {
 		vr_die = die_get_type(vr_die, die_mem);
 		if (!vr_die)
-			break;
+			return NULL;
 		tag = dwarf_tag(vr_die);
+		if (++chase > MAX_TYPE_CHASE) {
+			pr_debug("DWARF: qualifier chase limit reached at DIE 0x%lx\n",
+				 (unsigned long)dwarf_dieoffset(vr_die));
+			return NULL;
+		}
 	} while (tag == DW_TAG_const_type ||
 		 tag == DW_TAG_restrict_type ||
 		 tag == DW_TAG_volatile_type ||
@@ -296,8 +309,15 @@ Dwarf_Die *__die_get_real_type(Dwarf_Die *vr_die, Dwarf_Die *die_mem)
  */
 Dwarf_Die *die_get_real_type(Dwarf_Die *vr_die, Dwarf_Die *die_mem)
 {
+	int chase = 0;
+
 	do {
 		vr_die = __die_get_real_type(vr_die, die_mem);
+		if (++chase > MAX_TYPE_CHASE) {
+			pr_debug("DWARF: typedef chase limit reached at DIE 0x%lx\n",
+				 vr_die ? (unsigned long)dwarf_dieoffset(vr_die) : 0);
+			return NULL;
+		}
 	} while (vr_die && dwarf_tag(vr_die) == DW_TAG_typedef);
 
 	return vr_die;
@@ -314,7 +334,7 @@ Dwarf_Die *die_get_real_type(Dwarf_Die *vr_die, Dwarf_Die *die_mem)
  */
 Dwarf_Die *die_get_pointer_type(Dwarf_Die *type_die, Dwarf_Die *die_mem)
 {
-	int tag;
+	int tag, chase = 0;
 
 	do {
 		tag = dwarf_tag(type_die);
@@ -324,6 +344,11 @@ Dwarf_Die *die_get_pointer_type(Dwarf_Die *type_die, Dwarf_Die *die_mem)
 		    tag != DW_TAG_restrict_type && tag != DW_TAG_volatile_type &&
 		    tag != DW_TAG_shared_type)
 			return NULL;
+		if (++chase > MAX_TYPE_CHASE) {
+			pr_debug("DWARF: pointer type chase limit reached at DIE 0x%lx\n",
+				 (unsigned long)dwarf_dieoffset(type_die));
+			return NULL;
+		}
 		type_die = die_get_type(type_die, die_mem);
 	} while (type_die);
 
@@ -1118,17 +1143,25 @@ Dwarf_Die *die_find_member(Dwarf_Die *st_die, const char *name,
 			      die_mem);
 }
 
-/**
- * die_get_typename_from_type - Get the name of given type DIE
- * @type_die: a type DIE
- * @buf: a strbuf for result type name
- *
- * Get the name of @type_die and stores it to @buf. Return 0 if succeeded.
- * and Return -ENOENT if failed to find type name.
- * Note that the result will stores typedef name if possible, and stores
- * "*(function_type)" if the type is a function pointer.
+/*
+ * The name follows DW_AT_type, so a self-referring DIE makes this
+ * recurse forever: bound it like the chases above.
  */
-int die_get_typename_from_type(Dwarf_Die *type_die, struct strbuf *buf)
+static int __die_get_typename_from_type(Dwarf_Die *type_die, struct strbuf *buf,
+					int depth);
+
+static int __die_get_typename(Dwarf_Die *vr_die, struct strbuf *buf, int depth)
+{
+	Dwarf_Die type;
+
+	if (__die_get_real_type(vr_die, &type) == NULL)
+		return -ENOENT;
+
+	return __die_get_typename_from_type(&type, buf, depth);
+}
+
+static int __die_get_typename_from_type(Dwarf_Die *type_die, struct strbuf *buf,
+					int depth)
 {
 	int tag, ret;
 	const char *tmp = "";
@@ -1155,7 +1188,12 @@ int die_get_typename_from_type(Dwarf_Die *type_die, struct strbuf *buf)
 		/* Write a base name */
 		return strbuf_addf(buf, "%s%s", tmp, name ?: "");
 	}
-	ret = die_get_typename(type_die, buf);
+	if (depth >= MAX_TYPE_CHASE) {
+		pr_debug("DWARF: type name recursion limit reached at DIE 0x%lx\n",
+			 (unsigned long)dwarf_dieoffset(type_die));
+		return -ENOENT;
+	}
+	ret = __die_get_typename(type_die, buf, depth + 1);
 	if (ret < 0) {
 		/* void pointer has no type attribute */
 		if (tag == DW_TAG_pointer_type && ret == -ENOENT)
@@ -1166,6 +1204,21 @@ int die_get_typename_from_type(Dwarf_Die *type_die, struct strbuf *buf)
 	return strbuf_addstr(buf, tmp);
 }
 
+/**
+ * die_get_typename_from_type - Get the name of given type DIE
+ * @type_die: a type DIE
+ * @buf: a strbuf for result type name
+ *
+ * Get the name of @type_die and stores it to @buf. Return 0 if succeeded.
+ * and Return -ENOENT if failed to find type name.
+ * Note that the result will stores typedef name if possible, and stores
+ * "*(function_type)" if the type is a function pointer.
+ */
+int die_get_typename_from_type(Dwarf_Die *type_die, struct strbuf *buf)
+{
+	return __die_get_typename_from_type(type_die, buf, 0);
+}
+
 /**
  * die_get_typename - Get the name of given variable DIE
  * @vr_die: a variable DIE
@@ -1178,12 +1231,7 @@ int die_get_typename_from_type(Dwarf_Die *type_die, struct strbuf *buf)
  */
 int die_get_typename(Dwarf_Die *vr_die, struct strbuf *buf)
 {
-	Dwarf_Die type;
-
-	if (__die_get_real_type(vr_die, &type) == NULL)
-		return -ENOENT;
-
-	return die_get_typename_from_type(&type, buf);
+	return __die_get_typename(vr_die, buf, 0);
 }
 
 /**
-- 
2.55.0


^ permalink raw reply	[flat|nested] 18+ messages in thread

* [PATCH 11/15] perf dwarf-aux: Add die_same_file() and die_get_type_die()
  2026-09-17 15:55 [PATCH v7 0/15] perf tools: Annotate fixes, stdio progress indication, debuginfo-client in more places Arnaldo Carvalho de Melo
                   ` (9 preceding siblings ...)
  2026-09-17 15:55 ` [PATCH 10/15] perf dwarf-aux: Bound the type chases for broken debug info Arnaldo Carvalho de Melo
@ 2026-09-17 15:55 ` Arnaldo Carvalho de Melo
  2026-09-17 15:55 ` [PATCH 12/15] perf annotate-data: Resolve type DIEs in the debug file they came from Arnaldo Carvalho de Melo
                   ` (3 subsequent siblings)
  14 siblings, 0 replies; 18+ messages in thread
From: Arnaldo Carvalho de Melo @ 2026-09-17 15:55 UTC (permalink / raw)
  To: Namhyung Kim
  Cc: Ingo Molnar, Thomas Gleixner, James Clark, Jiri Olsa, Ian Rogers,
	Adrian Hunter, Clark Williams, linux-kernel, linux-perf-users,
	Arnaldo Carvalho de Melo

From: Arnaldo Carvalho de Melo <acme@redhat.com>

dwarf_dieoffset() is relative to the file the DIE is in, so an offset
saved by die_collect_vars()/die_collect_global_vars() is only
meaningful in that file: add die_same_file(), comparing the Dwarf each
DIE's CU belongs to, to record which file that is, and
die_get_type_die() to resolve the offset in it, with the saved tag as a
sanity check.  Resolving the offset in the main file instead parses
whatever is at it when it came from the dwz common file.

dwarf_cu_getdwarf() is new in elfutils 0.160, so the libdw feature test
probes for it and Makefile.config says 0.160.

Assisted-by: LLM
Signed-off-by: Arnaldo Carvalho de Melo <acme@redhat.com>
---
 tools/build/feature/test-libdw.c | 13 ++++++-
 tools/perf/Makefile.config       |  2 +-
 tools/perf/util/dwarf-aux.c      | 62 ++++++++++++++++++++++++++++++--
 tools/perf/util/dwarf-aux.h      | 17 +++++++++
 4 files changed, 90 insertions(+), 4 deletions(-)

diff --git a/tools/build/feature/test-libdw.c b/tools/build/feature/test-libdw.c
index aabd63ca76b4d7e6..0ebe7bb4adf9d0bc 100644
--- a/tools/build/feature/test-libdw.c
+++ b/tools/build/feature/test-libdw.c
@@ -49,8 +49,19 @@ int test_elfutils(void)
 	return 0;
 }
 
+/*
+ * dwarf_cu_getdwarf() needs elfutils 0.160: take its address only, so
+ * that older versions fail the probe instead of the link.
+ */
+int test_libdw_cu_getdwarf(void)
+{
+	void *sym = (void *)dwarf_cu_getdwarf;
+
+	return sym == NULL;
+}
+
 int main(void)
 {
 	return test_libdw() + test_libdw_unwind() + test_libdw_getlocations() +
-	       test_libdw_getcfi() + test_elfutils();
+	       test_libdw_getcfi() + test_libdw_cu_getdwarf() + test_elfutils();
 }
diff --git a/tools/perf/Makefile.config b/tools/perf/Makefile.config
index 4ee7393a39f91d85..0585d71e3182c6dd 100644
--- a/tools/perf/Makefile.config
+++ b/tools/perf/Makefile.config
@@ -470,7 +470,7 @@ else
   else
     ifneq ($(feature-libdw), 1)
       ifndef NO_LIBDW
-        $(warning No libdw.h found or old libdw.h found or elfutils is older than 0.157, disables dwarf support. Please install new elfutils-devel/libdw-dev)
+        $(warning No libdw.h found or old libdw.h found or elfutils is older than 0.160, disables dwarf support. Please install new elfutils-devel/libdw-dev)
         NO_LIBDW := 1
       endif
     endif # Dwarf support
diff --git a/tools/perf/util/dwarf-aux.c b/tools/perf/util/dwarf-aux.c
index b5ffeea54446408d..de14d18a9d2f87d8 100644
--- a/tools/perf/util/dwarf-aux.c
+++ b/tools/perf/util/dwarf-aux.c
@@ -1680,6 +1680,16 @@ Dwarf_Die *die_find_variable_by_addr(Dwarf_Die *sc_die, Dwarf_Addr addr,
 	return result;
 }
 
+/*
+ * Whether two DIEs live in the same debug file, i.e. whether their
+ * offsets have to be resolved in the same file: dwarf_dieoffset() is
+ * relative to the file the DIE is in.
+ */
+bool die_same_file(Dwarf_Die *die_a, Dwarf_Die *die_b)
+{
+	return dwarf_cu_getdwarf(die_a->cu) == dwarf_cu_getdwarf(die_b->cu);
+}
+
 static int __die_collect_vars_cb(Dwarf_Die *die_mem, void *arg)
 {
 	struct die_var_type **var_types = arg;
@@ -1724,6 +1734,8 @@ static int __die_collect_vars_cb(Dwarf_Die *die_mem, void *arg)
 			vt->is_reg_var_addr = true;
 
 		vt->die_off = dwarf_dieoffset(&type_die);
+		vt->die_tag = dwarf_tag(&type_die);
+		vt->from_alt = !die_same_file(die_mem, &type_die);
 		vt->addr = start;
 		vt->end = end;
 		vt->has_range = (end != 0 || start != 0);
@@ -1743,7 +1755,8 @@ static int __die_collect_vars_cb(Dwarf_Die *die_mem, void *arg)
  *
  * Save all variables and parameters in the @sc_die and save them to @var_types.
  * The @var_types is a singly-linked list containing type and location info.
- * Actual type can be retrieved using dwarf_offdie() with 'die_off' later.
+ * Actual type can be retrieved using die_get_type_die() with 'die_off',
+ * 'die_tag' and 'from_alt' later.
  *
  * Callers should free @var_types.
  */
@@ -1789,6 +1802,8 @@ static int __die_collect_global_vars_cb(Dwarf_Die *die_mem, void *arg)
 		return DIE_FIND_CB_END;
 
 	vt->die_off = dwarf_dieoffset(&type_die);
+	vt->die_tag = dwarf_tag(&type_die);
+	vt->from_alt = !die_same_file(die_mem, &type_die);
 	vt->addr = ops->number;
 	vt->end = 0;
 	vt->has_range = false;
@@ -1800,6 +1815,48 @@ static int __die_collect_global_vars_cb(Dwarf_Die *die_mem, void *arg)
 	return DIE_FIND_CB_SIBLING;
 }
 
+/**
+ * die_get_type_die - Get a type DIE saved by die_collect_vars()
+ * @dbg: the main debug info
+ * @die_off: offset of the type DIE, from dwarf_dieoffset()
+ * @die_tag: tag that DIE had when the offset was saved
+ * @from_alt: whether the type DIE is in the dwz alt file
+ * @die_mem: where to store the resulting DIE
+ *
+ * Resolve @die_off in the file it was recorded as belonging to: the
+ * offset is only meaningful there, and there is deliberately no
+ * fallback, as resolving an alt file offset in the main file parses
+ * whatever is at it.  @die_tag is a sanity check.
+ */
+Dwarf_Die *die_get_type_die(Dwarf *dbg, u64 die_off, int die_tag, bool from_alt,
+			    Dwarf_Die *die_mem)
+{
+	Dwarf *target = dbg;
+	Dwarf_Die die;
+
+	if (from_alt) {
+		/*
+		 * No fallback to the main file: resolving an alt file offset in it
+		 * does not fail, it parses whatever is there as a DIE.
+		 */
+		target = dwarf_getalt(dbg);
+		if (target == NULL) {
+			pr_debug("DWARF: no alt (dwz) debug file to resolve the type DIE at offset 0x%lx in\n",
+				 (unsigned long)die_off);
+			return NULL;
+		}
+	}
+
+	if (dwarf_offdie(target, die_off, &die) && dwarf_tag(&die) == die_tag) {
+		*die_mem = die;
+		return die_mem;
+	}
+
+	pr_debug("DWARF: no DIE with tag %d at offset 0x%lx in the %s debug file\n",
+		 die_tag, (unsigned long)die_off, from_alt ? "alt" : "main");
+	return NULL;
+}
+
 /**
  * die_collect_global_vars - Save all global variables
  * @cu_die: a CU DIE
@@ -1807,7 +1864,8 @@ static int __die_collect_global_vars_cb(Dwarf_Die *die_mem, void *arg)
  *
  * Save all global variables in the @cu_die and save them to @var_types.
  * The @var_types is a singly-linked list containing type and location info.
- * Actual type can be retrieved using dwarf_offdie() with 'die_off' later.
+ * Actual type can be retrieved using die_get_type_die() with 'die_off',
+ * 'die_tag' and 'from_alt' later.
  *
  * Callers should free @var_types.
  */
diff --git a/tools/perf/util/dwarf-aux.h b/tools/perf/util/dwarf-aux.h
index 161f0bf980b6ee6a..299ffddab0358baa 100644
--- a/tools/perf/util/dwarf-aux.h
+++ b/tools/perf/util/dwarf-aux.h
@@ -152,6 +152,8 @@ int die_get_scopes(Dwarf_Die *cu_die, Dwarf_Addr pc, Dwarf_Die **scopes);
 struct die_var_type {
 	struct die_var_type *next;
 	u64 die_off;
+	int die_tag;
+	bool from_alt;	/* die_off is relative to the alt (dwz) file */
 	u64 addr;
 	u64 end;        /* end address of location range */
 	int reg;
@@ -183,6 +185,21 @@ Dwarf_Die *die_find_variable_by_addr(Dwarf_Die *sc_die, Dwarf_Addr addr,
 /* Save all variables and parameters in this scope */
 void die_collect_vars(Dwarf_Die *sc_die, struct die_var_type **var_types);
 
+/*
+ * Get the type DIE saved by die_collect_vars()/die_collect_global_vars().
+ *
+ * Those save the dwarf_dieoffset() of the type DIE, which is relative
+ * to the file it lives in, so @from_alt, recorded when the offset was
+ * saved, says which file to resolve it in; @die_tag is a sanity check.
+ * Resolving an alt file offset in the main file parses whatever is at
+ * it, which is what hung 'perf report -s type'.
+ */
+Dwarf_Die *die_get_type_die(Dwarf *dbg, u64 die_off, int die_tag, bool from_alt,
+			    Dwarf_Die *die_mem);
+
+/* Whether two DIEs live in the same debug file */
+bool die_same_file(Dwarf_Die *die_a, Dwarf_Die *die_b);
+
 /* Save all global variables in this CU */
 void die_collect_global_vars(Dwarf_Die *cu_die, struct die_var_type **var_types);
 
-- 
2.55.0


^ permalink raw reply	[flat|nested] 18+ messages in thread

* [PATCH 12/15] perf annotate-data: Resolve type DIEs in the debug file they came from
  2026-09-17 15:55 [PATCH v7 0/15] perf tools: Annotate fixes, stdio progress indication, debuginfo-client in more places Arnaldo Carvalho de Melo
                   ` (10 preceding siblings ...)
  2026-09-17 15:55 ` [PATCH 11/15] perf dwarf-aux: Add die_same_file() and die_get_type_die() Arnaldo Carvalho de Melo
@ 2026-09-17 15:55 ` Arnaldo Carvalho de Melo
  2026-09-17 15:55 ` [PATCH 13/15] perf annotate-data: Bound the member nesting recursion Arnaldo Carvalho de Melo
                   ` (2 subsequent siblings)
  14 siblings, 0 replies; 18+ messages in thread
From: Arnaldo Carvalho de Melo @ 2026-09-17 15:55 UTC (permalink / raw)
  To: Namhyung Kim
  Cc: Ingo Molnar, Thomas Gleixner, James Clark, Jiri Olsa, Ian Rogers,
	Adrian Hunter, Clark Williams, linux-kernel, linux-perf-users,
	Arnaldo Carvalho de Melo

From: Arnaldo Carvalho de Melo <acme@redhat.com>

'perf report -s type' hangs, burning all of a CPU with no output, when
resolving a hist entry on the dwz compressed debug info of libz.so.1
(zlib-ng): die_collect_vars() saves the dwarf_dieoffset() of the type
DIE, which is relative to the file it lives in - the dwz alt file for
the types shared by more than one CU - and update_var_state() resolves
that offset in the main debug file, where it parses whatever is at that
offset, here a typedef whose DW_AT_type refers to itself, making the
type chase spin forever.

Record whether the type DIE came from the alt file and resolve the
offset with die_get_type_die() in that file, with no fallback:
resolving an alt file offset in the main file is exactly the misparse
above.

Fixes: 06b2ce75386df04b ("perf annotate-data: Maintain variable type info")
Fixes: 55ee3d005d62279d ("perf annotate-data: Add a cache for global variable types")
Assisted-by: LLM
Signed-off-by: Arnaldo Carvalho de Melo <acme@redhat.com>
---
 tools/perf/util/annotate-data.c | 21 +++++++++++++++------
 1 file changed, 15 insertions(+), 6 deletions(-)

diff --git a/tools/perf/util/annotate-data.c b/tools/perf/util/annotate-data.c
index aff60a630fd05b01..2ad6d012e069c522 100644
--- a/tools/perf/util/annotate-data.c
+++ b/tools/perf/util/annotate-data.c
@@ -645,6 +645,8 @@ struct global_var_entry {
 	u64 start;
 	u64 end;
 	u64 die_offset;
+	int die_tag;
+	bool from_alt;	/* die_offset is relative to the alt (dwz) file */
 };
 
 static int global_var_cmp(const void *_key, const struct rb_node *node)
@@ -682,7 +684,7 @@ static struct global_var_entry *global_var__find(struct data_loc_info *dloc, u64
 }
 
 static bool global_var__add(struct data_loc_info *dloc, u64 addr,
-			    const char *name, Dwarf_Die *type_die)
+			    const char *name, Dwarf_Die *type_die, bool from_alt)
 {
 	struct dso *dso = map__dso(dloc->ms->map);
 	struct global_var_entry *gvar;
@@ -704,6 +706,8 @@ static bool global_var__add(struct data_loc_info *dloc, u64 addr,
 	gvar->start = addr;
 	gvar->end = addr + size;
 	gvar->die_offset = dwarf_dieoffset(type_die);
+	gvar->die_tag = dwarf_tag(type_die);
+	gvar->from_alt = from_alt;
 
 	rb_add(&gvar->node, dso__global_vars(dso), global_var_less);
 	return true;
@@ -778,12 +782,14 @@ static void global_var__collect(struct data_loc_info *dloc)
 			if (pos->reg != -1)
 				continue;
 
-			if (!dwarf_offdie(dwarf, pos->die_off, &type_die))
+			if (!die_get_type_die(dwarf, pos->die_off, pos->die_tag,
+					      pos->from_alt, &type_die))
 				continue;
 
 			get_global_var_info(dloc, pos->addr, &var_name, &var_offset);
 
-			global_var__add(dloc, pos->addr, var_name, &type_die);
+			global_var__add(dloc, pos->addr, var_name, &type_die,
+					pos->from_alt);
 		}
 
 		delete_var_types(var_types);
@@ -808,7 +814,8 @@ bool get_global_var_type(Dwarf_Die *cu_die, struct data_loc_info *dloc,
 
 	gvar = global_var__find(dloc, var_addr);
 	if (gvar) {
-		if (!dwarf_offdie(dloc->di->dbg, gvar->die_offset, type_die))
+		if (!die_get_type_die(dloc->di->dbg, gvar->die_offset,
+				      gvar->die_tag, gvar->from_alt, type_die))
 			return false;
 
 		*var_offset = var_addr - gvar->start;
@@ -838,7 +845,8 @@ bool get_global_var_type(Dwarf_Die *cu_die, struct data_loc_info *dloc,
 
 ok:
 	/* The address should point to the start of the variable */
-	global_var__add(dloc, var_addr - *var_offset, var_name, type_die);
+	global_var__add(dloc, var_addr - *var_offset, var_name, type_die,
+			!die_same_file(cu_die, type_die));
 	return true;
 }
 
@@ -893,7 +901,8 @@ static void update_var_state(struct type_state *state, struct data_loc_info *dlo
 				continue;
 		}
 		/* Get the type DIE using the offset */
-		if (!dwarf_offdie(dloc->di->dbg, var->die_off, &mem_die))
+		if (!die_get_type_die(dloc->di->dbg, var->die_off,
+				      var->die_tag, var->from_alt, &mem_die))
 			continue;
 
 		if (var->reg == DWARF_REG_FB || var->reg == fbreg || var->reg == state->stack_reg) {
-- 
2.55.0


^ permalink raw reply	[flat|nested] 18+ messages in thread

* [PATCH 13/15] perf annotate-data: Bound the member nesting recursion
  2026-09-17 15:55 [PATCH v7 0/15] perf tools: Annotate fixes, stdio progress indication, debuginfo-client in more places Arnaldo Carvalho de Melo
                   ` (11 preceding siblings ...)
  2026-09-17 15:55 ` [PATCH 12/15] perf annotate-data: Resolve type DIEs in the debug file they came from Arnaldo Carvalho de Melo
@ 2026-09-17 15:55 ` Arnaldo Carvalho de Melo
  2026-09-17 15:55 ` [PATCH 14/15] perf mem record: Request PERF_SAMPLE_CPU by default Arnaldo Carvalho de Melo
  2026-09-17 15:55 ` [PATCH 15/15] perf mem record: Use the IBS swfilt filter when available Arnaldo Carvalho de Melo
  14 siblings, 0 replies; 18+ messages in thread
From: Arnaldo Carvalho de Melo @ 2026-09-17 15:55 UTC (permalink / raw)
  To: Namhyung Kim
  Cc: Ingo Molnar, Thomas Gleixner, James Clark, Jiri Olsa, Ian Rogers,
	Adrian Hunter, Clark Williams, linux-kernel, linux-perf-users,
	Arnaldo Carvalho de Melo

From: Arnaldo Carvalho de Melo <acme@redhat.com>

Members are added recursively, and the same kind of broken DIE can make
a member's type point back at one of its own ancestors, recursing until
the stack is gone; nothing usable comes out of nesting members 8 deep
anyway, so stop there, marking the member as truncated (reported by the
JSON exporter added in a later series) and giving up on member types
that don't resolve.

Assisted-by: LLM
Signed-off-by: Arnaldo Carvalho de Melo <acme@redhat.com>
---
 tools/perf/util/annotate-data.c | 32 ++++++++++++++++++++++++++------
 tools/perf/util/annotate-data.h |  3 +++
 2 files changed, 29 insertions(+), 6 deletions(-)

diff --git a/tools/perf/util/annotate-data.c b/tools/perf/util/annotate-data.c
index 2ad6d012e069c522..c67bb6005e23c516 100644
--- a/tools/perf/util/annotate-data.c
+++ b/tools/perf/util/annotate-data.c
@@ -221,6 +221,13 @@ static bool data_type_less(struct rb_node *node_a, const struct rb_node *node_b)
 	return strcmp(a->self.type_name, b->self.type_name) < 0;
 }
 
+/*
+ * Members are added recursively; bound the nesting so that a broken
+ * type that points back at one of its own ancestors doesn't recurse
+ * until the stack is gone.
+ */
+#define MAX_MEMBER_DEPTH 8
+
 /* Recursively add new members for struct/union */
 static int __add_member_cb(Dwarf_Die *die, void *arg)
 {
@@ -235,6 +242,16 @@ static int __add_member_cb(Dwarf_Die *die, void *arg)
 	if (dwarf_tag(die) != DW_TAG_member)
 		return DIE_FIND_CB_SIBLING;
 
+	if (__die_get_real_type(die, &member_type) == NULL)
+		return DIE_FIND_CB_SIBLING;
+
+	if (dwarf_tag(&member_type) == DW_TAG_typedef) {
+		if (die_get_real_type(&member_type, &die_mem) == NULL)
+			return DIE_FIND_CB_SIBLING;
+	} else {
+		die_mem = member_type;
+	}
+
 	member = zalloc(sizeof(*member));
 	if (member == NULL)
 		return DIE_FIND_CB_END;
@@ -242,12 +259,6 @@ static int __add_member_cb(Dwarf_Die *die, void *arg)
 	strbuf_init(&sb, 32);
 	die_get_typename(die, &sb);
 
-	__die_get_real_type(die, &member_type);
-	if (dwarf_tag(&member_type) == DW_TAG_typedef)
-		die_get_real_type(&member_type, &die_mem);
-	else
-		die_mem = member_type;
-
 	if (dwarf_aggregate_size(&die_mem, &size) < 0)
 		size = 0;
 
@@ -289,10 +300,19 @@ static int __add_member_cb(Dwarf_Die *die, void *arg)
 	}
 	member->size = size;
 	member->offset = loc + parent->offset;
+	member->depth = parent->depth + 1;
 	INIT_LIST_HEAD(&member->children);
 	list_add_tail(&member->node, &parent->children);
 
 	tag = dwarf_tag(&die_mem);
+	if (member->depth >= MAX_MEMBER_DEPTH) {
+		/* Reported by the JSON exporter so consumers can tell a truncated tree. */
+		member->truncated = true;
+		pr_debug_dtp("member nesting limit reached at %s\n",
+			     member->type_name ?: "(unknown type)");
+		return DIE_FIND_CB_SIBLING;
+	}
+
 	switch (tag) {
 	case DW_TAG_structure_type:
 	case DW_TAG_union_type:
diff --git a/tools/perf/util/annotate-data.h b/tools/perf/util/annotate-data.h
index ca2096a9ee62cbfe..cc576232f55b5fb0 100644
--- a/tools/perf/util/annotate-data.h
+++ b/tools/perf/util/annotate-data.h
@@ -57,6 +57,9 @@ struct annotated_member {
 	char *var_name;
 	int offset;
 	int size;
+	unsigned int depth;
+	/* Children not expanded because the nesting limit was reached */
+	bool truncated;
 };
 
 /**
-- 
2.55.0


^ permalink raw reply	[flat|nested] 18+ messages in thread

* [PATCH 14/15] perf mem record: Request PERF_SAMPLE_CPU by default
  2026-09-17 15:55 [PATCH v7 0/15] perf tools: Annotate fixes, stdio progress indication, debuginfo-client in more places Arnaldo Carvalho de Melo
                   ` (12 preceding siblings ...)
  2026-09-17 15:55 ` [PATCH 13/15] perf annotate-data: Bound the member nesting recursion Arnaldo Carvalho de Melo
@ 2026-09-17 15:55 ` Arnaldo Carvalho de Melo
  2026-09-17 15:55 ` [PATCH 15/15] perf mem record: Use the IBS swfilt filter when available Arnaldo Carvalho de Melo
  14 siblings, 0 replies; 18+ messages in thread
From: Arnaldo Carvalho de Melo @ 2026-09-17 15:55 UTC (permalink / raw)
  To: Namhyung Kim
  Cc: Ingo Molnar, Thomas Gleixner, James Clark, Jiri Olsa, Ian Rogers,
	Adrian Hunter, Clark Williams, linux-kernel, linux-perf-users,
	Arnaldo Carvalho de Melo

From: Arnaldo Carvalho de Melo <acme@redhat.com>

The data type profiling per-sample stream keys cross-CPU contention on
sample->cpu; without PERF_SAMPLE_CPU that field is the (u32)-1 "no CPU
info" sentinel, so same-instance accesses from different cores are
indistinguishable from same-CPU traffic.  'perf mem record' already
passes -d (addr) and -W (weight) explicitly to the record parser, add
--sample-cpu as well and document it in perf-mem(1).

The rec_argv array only had room for nine arguments per PMU plus the
user arguments, not counting the up to eight __cmd_record() adds itself,
which a new argument would overflow on PMUs with separate load and store
events; reserve space for the fixed arguments too.

Assisted-by: LLM
Signed-off-by: Arnaldo Carvalho de Melo <acme@redhat.com>
---
 tools/perf/Documentation/perf-mem.txt |  4 ++++
 tools/perf/builtin-mem.c              | 11 +++++++++--
 2 files changed, 13 insertions(+), 2 deletions(-)

diff --git a/tools/perf/Documentation/perf-mem.txt b/tools/perf/Documentation/perf-mem.txt
index 4d164836d0943119..fe51c5e3333dc4a0 100644
--- a/tools/perf/Documentation/perf-mem.txt
+++ b/tools/perf/Documentation/perf-mem.txt
@@ -14,6 +14,10 @@ DESCRIPTION
 -----------
 "perf mem record" runs a command and gathers memory operation data
 from it, into perf.data. Perf record options are accepted and are passed through.
+It also requests the address (-d), the weight (-W, where supported) and the
+CPU id (--sample-cpu) of every sampled access by default; the CPU id is what
+lets per-sample analysis tell reads and writes to the same data from
+different cores apart from same-CPU traffic.
 
 "perf mem report" displays the result. It invokes perf report with the
 right set of options to display a memory access profile. By default, loads
diff --git a/tools/perf/builtin-mem.c b/tools/perf/builtin-mem.c
index 6101a26b3a781e69..f25592bc52728655 100644
--- a/tools/perf/builtin-mem.c
+++ b/tools/perf/builtin-mem.c
@@ -99,8 +99,8 @@ static int __cmd_record(int argc, const char **argv, struct perf_mem *mem,
 	argc = parse_options(argc, argv, options, record_usage,
 			     PARSE_OPT_KEEP_UNKNOWN);
 
-	/* Max number of arguments multiplied by number of PMUs that can support them. */
-	rec_argc = argc + 9 * (perf_pmu__mem_events_num_mem_pmus(pmu) + 1);
+	/* Max number of arguments per PMU plus the fixed ones added below. */
+	rec_argc = argc + 8 + 9 * (perf_pmu__mem_events_num_mem_pmus(pmu) + 1);
 
 	if (mem->cpu_list)
 		rec_argc += 2;
@@ -135,6 +135,13 @@ static int __cmd_record(int argc, const char **argv, struct perf_mem *mem,
 
 	rec_argv[i++] = "-d";
 
+	/*
+	 * The data type profiling per-sample stream keys cross-CPU contention
+	 * on sample->cpu; without PERF_SAMPLE_CPU it is the (u32)-1 'no CPU
+	 * info' sentinel.
+	 */
+	rec_argv[i++] = "--sample-cpu";
+
 	if (mem->phys_addr)
 		rec_argv[i++] = "--phys-data";
 
-- 
2.55.0


^ permalink raw reply	[flat|nested] 18+ messages in thread

* [PATCH 15/15] perf mem record: Use the IBS swfilt filter when available
  2026-09-17 15:55 [PATCH v7 0/15] perf tools: Annotate fixes, stdio progress indication, debuginfo-client in more places Arnaldo Carvalho de Melo
                   ` (13 preceding siblings ...)
  2026-09-17 15:55 ` [PATCH 14/15] perf mem record: Request PERF_SAMPLE_CPU by default Arnaldo Carvalho de Melo
@ 2026-09-17 15:55 ` Arnaldo Carvalho de Melo
  14 siblings, 0 replies; 18+ messages in thread
From: Arnaldo Carvalho de Melo @ 2026-09-17 15:55 UTC (permalink / raw)
  To: Namhyung Kim
  Cc: Ingo Molnar, Thomas Gleixner, James Clark, Jiri Olsa, Ian Rogers,
	Adrian Hunter, Clark Williams, linux-kernel, linux-perf-users,
	Arnaldo Carvalho de Melo

From: Arnaldo Carvalho de Melo <acme@redhat.com>

IBS events with exclude_{user,kernel} bits, as used for per-thread
recording when kernel samples are not allowed, are rejected by the
kernel on hardware without the privilege filter, so per-thread 'perf mem
record' fails on AMD:

  $ perf mem record -o /dev/null -- true
  Error:
  Failure to open event 'ibs_op/ldlat=0/u' on PMU 'ibs_op' which will be removed.
  Invalid event (ibs_op/ldlat=0/u) in per-thread mode, enable system wide with '-a'.

Kernel v6.14 added swfilt, a software privilege filter exposed as the
'swfilt' format term, making those events usable per-thread:

  $ perf record -e ibs_op/ldlat=0,swfilt=1/ -- true

Give the ibs_op memory events a name variant with the swfilt term, used
when the PMU exposes it, even when the record ends up without exclude
bits: 'perf record' adds those bits itself when the first open fails,
after the name was built, and that retry needs the term.  This makes the
per-thread 'perf mem record' the data type profiling shell test does
work on AMD kernels with swfilt, and the test's event regex is adjusted
for the added term.

Suggested-by: Namhyung Kim <namhyung@kernel.org>
Assisted-by: LLM
Signed-off-by: Arnaldo Carvalho de Melo <acme@redhat.com>
---
 tools/perf/arch/x86/util/mem-events.c      | 14 +++++++++++---
 tools/perf/tests/shell/test_data_symbol.sh |  6 ++++--
 tools/perf/util/mem-events.c               | 18 ++++++++++++++----
 tools/perf/util/mem-events.h               |  2 ++
 4 files changed, 31 insertions(+), 9 deletions(-)

diff --git a/tools/perf/arch/x86/util/mem-events.c b/tools/perf/arch/x86/util/mem-events.c
index b38f519020ff8c6f..a12d410247dfd47e 100644
--- a/tools/perf/arch/x86/util/mem-events.c
+++ b/tools/perf/arch/x86/util/mem-events.c
@@ -7,7 +7,10 @@
 
 #define MEM_LOADS_AUX		0x8203
 
-#define E(t, n, s, l, a) { .tag = t, .name = n, .event_name = s, .ldlat = l, .aux_event = a }
+#define E_INIT(t, n, s, l, a, sf) {					\
+	.tag = t, .name = n, .event_name = s, .swfilt_name = sf,	\
+	.ldlat = l, .aux_event = a }
+#define E(t, n, s, l, a) E_INIT(t, n, s, l, a, NULL)
 
 struct perf_mem_event perf_mem_events_intel[PERF_MEM_EVENTS__MAX] = {
 	E("ldlat-loads",	"%s/mem-loads,ldlat=%u/P",	"mem-loads",	true,	0),
@@ -21,14 +24,19 @@ struct perf_mem_event perf_mem_events_intel_aux[PERF_MEM_EVENTS__MAX] = {
 	E(NULL,			NULL,				NULL,		false,	0),
 };
 
+/*
+ * IBS events with exclude bits, as used for per-thread recording, are
+ * rejected without the swfilt software filter, so carry a name variant
+ * with the term, used when the PMU exposes it.
+ */
 struct perf_mem_event perf_mem_events_amd[PERF_MEM_EVENTS__MAX] = {
 	E(NULL,		NULL,		NULL,	false,	0),
 	E(NULL,		NULL,		NULL,	false,	0),
-	E("mem-ldst",	"%s//",		NULL,	false,	0),
+	E_INIT("mem-ldst",	"%s//",		NULL,	false,	0, "%s/swfilt=1/"),
 };
 
 struct perf_mem_event perf_mem_events_amd_ldlat[PERF_MEM_EVENTS__MAX] = {
 	E(NULL,		NULL,		NULL,	false,	0),
 	E(NULL,		NULL,		NULL,	false,	0),
-	E("mem-ldst",	"%s/ldlat=%u/",	NULL,	true,	0),
+	E_INIT("mem-ldst",	"%s/ldlat=%u/",	NULL,	true,	0, "%s/ldlat=%u,swfilt=1/"),
 };
diff --git a/tools/perf/tests/shell/test_data_symbol.sh b/tools/perf/tests/shell/test_data_symbol.sh
index d61b5659a46d9a77..52c837fddb639595 100755
--- a/tools/perf/tests/shell/test_data_symbol.sh
+++ b/tools/perf/tests/shell/test_data_symbol.sh
@@ -65,15 +65,17 @@ if (($is_amd >= 1)); then
 	# --ldlat on AMD:
 	# o Zen4 and earlier uarch does not support ldlat
 	# o Even on supported platforms, it's disabled (--ldlat=0) by default.
+	# o Kernels with the swfilt term add it even when ldlat is not
+	#   supported, so only check ldlat when the term is present.
 	ldlat=${BASH_REMATCH[1]}
-	if [[ -n $ldlat ]]; then
+	if [[ $ldlat == *ldlat=* ]]; then
 		if ! [[ "$ldlat" =~ ldlat=0 ]]; then
 			echo "ERROR: ldlat not initialized to 0?"
 			exit 1
 		fi
 
 		mem_events="$(perf mem record -v --ldlat=150 -e list 2>&1)"
-		if ! [[ "$mem_events" =~ ^mem-ldst.*ibs_op/ldlat=150/.*available ]]; then
+		if ! [[ "$mem_events" =~ ^mem-ldst.*ibs_op/ldlat=150[,/].*available ]]; then
 			echo "ERROR: --ldlat not honored?"
 			exit 1
 		fi
diff --git a/tools/perf/util/mem-events.c b/tools/perf/util/mem-events.c
index 0b49fce251fcc184..f45598aa89825d79 100644
--- a/tools/perf/util/mem-events.c
+++ b/tools/perf/util/mem-events.c
@@ -82,6 +82,7 @@ static const char *perf_pmu__mem_events_name(struct perf_pmu *pmu, int i,
 					     char *buf, size_t buf_size)
 {
 	struct perf_mem_event *e;
+	const char *name;
 
 	if (i >= PERF_MEM_EVENTS__MAX || !pmu)
 		return NULL;
@@ -90,24 +91,33 @@ static const char *perf_pmu__mem_events_name(struct perf_pmu *pmu, int i,
 	if (!e || !e->name)
 		return NULL;
 
+	/*
+	 * Use the swfilt variant when the PMU exposes the term: 'perf record'
+	 * adds exclude bits itself when the first open fails, after this name
+	 * was built, and that retry needs the term in the name.
+	 */
+	name = e->name;
+	if (e->swfilt_name && perf_pmu__has_format(pmu, "swfilt"))
+		name = e->swfilt_name;
+
 	if (i == PERF_MEM_EVENTS__LOAD || i == PERF_MEM_EVENTS__LOAD_STORE) {
 		if (e->ldlat) {
 			if (!e->aux_event) {
 				/* ARM and Most of Intel */
 				scnprintf(buf, buf_size,
-					  e->name, pmu->name,
+					  name, pmu->name,
 					  perf_mem_events__loads_ldlat);
 			} else {
 				/* Intel with mem-loads-aux event */
 				scnprintf(buf, buf_size,
-					  e->name, pmu->name, pmu->name,
+					  name, pmu->name, pmu->name,
 					  perf_mem_events__loads_ldlat);
 			}
 		} else {
 			if (!e->aux_event) {
 				/* AMD and POWER */
 				scnprintf(buf, buf_size,
-					  e->name, pmu->name);
+					  name, pmu->name);
 			} else {
 				return NULL;
 			}
@@ -117,7 +127,7 @@ static const char *perf_pmu__mem_events_name(struct perf_pmu *pmu, int i,
 
 	if (i == PERF_MEM_EVENTS__STORE) {
 		scnprintf(buf, buf_size,
-			  e->name, pmu->name);
+			  name, pmu->name);
 		return buf;
 	}
 
diff --git a/tools/perf/util/mem-events.h b/tools/perf/util/mem-events.h
index 5b98076904b0b689..41f628fad10709b9 100644
--- a/tools/perf/util/mem-events.h
+++ b/tools/perf/util/mem-events.h
@@ -11,6 +11,8 @@ struct perf_mem_event {
 	u32		aux_event;
 	const char	*tag;
 	const char	*name;
+	/* Name with the swfilt software privilege filter, when supported. */
+	const char	*swfilt_name;
 	const char	*event_name;
 };
 
-- 
2.55.0


^ permalink raw reply	[flat|nested] 18+ messages in thread

* Re: [PATCH 01/15] perf debuginfo: Fetch debuginfo keyed by build ID using debuginfod
  2026-09-17 15:55 ` [PATCH 01/15] perf debuginfo: Fetch debuginfo keyed by build ID using debuginfod Arnaldo Carvalho de Melo
@ 2026-09-17 17:58   ` Ian Rogers
  2026-09-17 20:36     ` Arnaldo Carvalho de Melo
  0 siblings, 1 reply; 18+ messages in thread
From: Ian Rogers @ 2026-09-17 17:58 UTC (permalink / raw)
  To: Arnaldo Carvalho de Melo
  Cc: Namhyung Kim, Ingo Molnar, Thomas Gleixner, James Clark,
	Jiri Olsa, Adrian Hunter, Clark Williams, linux-kernel,
	linux-perf-users, Arnaldo Carvalho de Melo

On Thu, Sep 17, 2026 at 8:55 AM Arnaldo Carvalho de Melo
<acme@kernel.org> wrote:

[snip]

> +/*
> + * The build IDs already fetched in this session, and the path of the file
> + * that came back for each, so that the repeated requests for the same build
> + * ID, dso__debuginfo() is called per symbol annotated, are answered with a
> + * strdup() instead of another client: the file is in the debuginfod client
> + * cache already and its path checked before being handed out, in case that
> + * cache is cleaned from under us.
> + *
> + * Guarded by debuginfod__fetch_lock.  Only a fetch that brought a file back
> + * gets an entry: one that didn't is recorded in debuginfod__misses as a miss,
> + * and that is what keeps the rest of the session from asking for it again.
> + * Like debuginfod__misses this grows with the number of build IDs in the
> + * workload, one small entry each, and is not trimmed.
> + */
> +struct debuginfo_lookup {
> +       struct list_head         node;
> +       struct build_id          bid;
> +       char                    *path;
> +};
> +
> +static LIST_HEAD(debuginfo_lookups);

I'd still prefer keeping the debuginfos owned by the DSOs rather than
having debuginfo use a global cache of debuginfos - I expect the
debuginfos to have some non-trivial memory overhead. With the
debuginfo in the DSO, when/if the DSO goes away we can reclaim all the
memory without worrying about a separate global data structure. We can
find DSOs in multiple ways with dsos__findnew_id:
https://web.git.kernel.org/pub/scm/linux/kernel/git/perf/perf-tools-next.git/tree/tools/perf/util/dsos.c#n343
We match by name, but if those differ:
https://web.git.kernel.org/pub/scm/linux/kernel/git/perf/perf-tools-next.git/tree/tools/perf/util/dsos.c#n117
We match by inode and/or build ID:
https://web.git.kernel.org/pub/scm/linux/kernel/git/perf/perf-tools-next.git/tree/tools/perf/util/dso.c#n1473

So struct dsos is a build ID indexed store of DSOs and their owned
debuginfo. We find DSOs off a machine, but I believe we always have
access to the relevant struct machine. In the worst case for probes,
for example, we need to set up a host machine. Using machines
inherently provides some lock sharding, and they also have the ability
to reclaim memory.

Thanks,
Ian

^ permalink raw reply	[flat|nested] 18+ messages in thread

* Re: [PATCH 01/15] perf debuginfo: Fetch debuginfo keyed by build ID using debuginfod
  2026-09-17 17:58   ` Ian Rogers
@ 2026-09-17 20:36     ` Arnaldo Carvalho de Melo
  0 siblings, 0 replies; 18+ messages in thread
From: Arnaldo Carvalho de Melo @ 2026-09-17 20:36 UTC (permalink / raw)
  To: Ian Rogers
  Cc: Namhyung Kim, Ingo Molnar, Thomas Gleixner, James Clark,
	Jiri Olsa, Adrian Hunter, Clark Williams, linux-kernel,
	linux-perf-users, Arnaldo Carvalho de Melo

On Thu, Sep 17, 2026 at 10:58:15AM -0700, Ian Rogers wrote:
> On Thu, Sep 17, 2026 at 8:55 AM Arnaldo Carvalho de Melo
> <acme@kernel.org> wrote:
> 
> [snip]
> 
> > +/*
> > + * The build IDs already fetched in this session, and the path of the file
> > + * that came back for each, so that the repeated requests for the same build
> > + * ID, dso__debuginfo() is called per symbol annotated, are answered with a
> > + * strdup() instead of another client: the file is in the debuginfod client
> > + * cache already and its path checked before being handed out, in case that
> > + * cache is cleaned from under us.
> > + *
> > + * Guarded by debuginfod__fetch_lock.  Only a fetch that brought a file back
> > + * gets an entry: one that didn't is recorded in debuginfod__misses as a miss,
> > + * and that is what keeps the rest of the session from asking for it again.
> > + * Like debuginfod__misses this grows with the number of build IDs in the
> > + * workload, one small entry each, and is not trimmed.
> > + */
> > +struct debuginfo_lookup {
> > +       struct list_head         node;
> > +       struct build_id          bid;
> > +       char                    *path;
> > +};
> > +
> > +static LIST_HEAD(debuginfo_lookups);
> 
> I'd still prefer keeping the debuginfos owned by the DSOs rather than
> having debuginfo use a global cache of debuginfos - I expect the
> debuginfos to have some non-trivial memory overhead. With the
> debuginfo in the DSO, when/if the DSO goes away we can reclaim all the
> memory without worrying about a separate global data structure. We can
> find DSOs in multiple ways with dsos__findnew_id:
> https://web.git.kernel.org/pub/scm/linux/kernel/git/perf/perf-tools-next.git/tree/tools/perf/util/dsos.c#n343
> We match by name, but if those differ:
> https://web.git.kernel.org/pub/scm/linux/kernel/git/perf/perf-tools-next.git/tree/tools/perf/util/dsos.c#n117
> We match by inode and/or build ID:
> https://web.git.kernel.org/pub/scm/linux/kernel/git/perf/perf-tools-next.git/tree/tools/perf/util/dso.c#n1473
> 
> So struct dsos is a build ID indexed store of DSOs and their owned
> debuginfo. We find DSOs off a machine, but I believe we always have
> access to the relevant struct machine. In the worst case for probes,
> for example, we need to set up a host machine. Using machines
> inherently provides some lock sharding, and they also have the ability
> to reclaim memory.

Working on it, no preference, so doing it the way you describe seems ok,
will post later.

- Arnaldo

^ permalink raw reply	[flat|nested] 18+ messages in thread

end of thread, other threads:[~2026-09-17 20:36 UTC | newest]

Thread overview: 18+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2026-09-17 15:55 [PATCH v7 0/15] perf tools: Annotate fixes, stdio progress indication, debuginfo-client in more places Arnaldo Carvalho de Melo
2026-09-17 15:55 ` [PATCH 01/15] perf debuginfo: Fetch debuginfo keyed by build ID using debuginfod Arnaldo Carvalho de Melo
2026-09-17 17:58   ` Ian Rogers
2026-09-17 20:36     ` Arnaldo Carvalho de Melo
2026-09-17 15:55 ` [PATCH 02/15] perf debuginfo: Set DEBUGINFOD_URLS from /etc/debuginfod when unset Arnaldo Carvalho de Melo
2026-09-17 15:55 ` [PATCH 03/15] perf config: Move perf_config__set_variable() to util/config.c Arnaldo Carvalho de Melo
2026-09-17 15:55 ` [PATCH 04/15] perf debuginfo: Let the user skip and disable debuginfod fetches Arnaldo Carvalho de Melo
2026-09-17 15:55 ` [PATCH 05/15] perf debuginfo: Show the debuginfod fetch progress and keys in the TUI Arnaldo Carvalho de Melo
2026-09-17 15:55 ` [PATCH 06/15] perf symbol: Fall back to fetching the vmlinux by build ID Arnaldo Carvalho de Melo
2026-09-17 15:55 ` [PATCH 07/15] perf annotate-data: Show the sample count in the data-type browser Arnaldo Carvalho de Melo
2026-09-17 15:55 ` [PATCH 08/15] perf report: Add --progress option Arnaldo Carvalho de Melo
2026-09-17 15:55 ` [PATCH 09/15] perf scripts: Add perf-stuck, to tell where a running perf is stuck Arnaldo Carvalho de Melo
2026-09-17 15:55 ` [PATCH 10/15] perf dwarf-aux: Bound the type chases for broken debug info Arnaldo Carvalho de Melo
2026-09-17 15:55 ` [PATCH 11/15] perf dwarf-aux: Add die_same_file() and die_get_type_die() Arnaldo Carvalho de Melo
2026-09-17 15:55 ` [PATCH 12/15] perf annotate-data: Resolve type DIEs in the debug file they came from Arnaldo Carvalho de Melo
2026-09-17 15:55 ` [PATCH 13/15] perf annotate-data: Bound the member nesting recursion Arnaldo Carvalho de Melo
2026-09-17 15:55 ` [PATCH 14/15] perf mem record: Request PERF_SAMPLE_CPU by default Arnaldo Carvalho de Melo
2026-09-17 15:55 ` [PATCH 15/15] perf mem record: Use the IBS swfilt filter when available Arnaldo Carvalho de Melo

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox

all inboxes | Powered by JetHome®