summaryrefslogtreecommitdiff
path: root/tools/perf/scripts/python/flamegraph.py
diff options
context:
space:
mode:
authorLinus Torvalds <torvalds@linux-foundation.org>2026-10-30 21:54:38 -0700
committerLinus Torvalds <torvalds@linux-foundation.org>2026-10-30 21:54:38 -0700
commitdd384658c738d15783a786d3af2851e02490f171 (patch)
tree63b96f8ba0e7b33ddc8d44506dce5ac39fed77aa /tools/perf/scripts/python/flamegraph.py
parent60aba79a50127e92d8c4a663d35b855e52a9da01 (diff)
parent4626d370ae89b8af4d46a45372b269f926ec662d (diff)
Merge tag 'perf-tools-for-v7.4-1-2026-10-30' of git://git.kernel.org/pub/scm/linux/kernel/git/perf/perf-tools-next
Pull perf tool updates from Arnaldo Carvalho de Melo: - Support instruction tracking on arm64 for data type profiling, resolving stack, global, per-CPU and 'current' variable accesses, so that 'perf annotate --data-type' resolves types on arm64 the way it does on x86. - Port the Python scripts to the perf module and standalone execution, and improve the module: lazy sample callchains and event copies, GIL handling, better session/thread lookup, new treport, flamegraph and sqlite/postgres exporters. - Reenable and fix the attribute expectation test suite: per-PMU bit masks, other core PMUs' events, dummy tracking events, group checks and spelled out skip reasons. - perf trace: filter the target's tasks in BPF, open the BPF output event on every CPU, add an option to disable syscall augmentation and raise TRACE_AUG_MAX_BUF. - perf jitdump: harden record parsing, validating unwinding sizes and symbol names, byte-swapping debug entries via safe accessors and fixing frees on error paths. - perf annotate-data fixes: bound the member nesting recursion, resolve type DIEs in the debug file they came from, adjust the offset for flex-arrays and show the sample count in the data-type browser. - perf symbol and debug info: try linked debug files for DSOs, avoid repeated failing searches, set binary/symtab types for split kallsyms, JIT maps and the build-id cache, fix libbfd symbol loading. - perf config: serialize config file access with a mutex, add the DEFINE_MUTEX() and DO_ONCE() primitives and a robust process shared mutex, add the core.hybrid-merge option. - perf report: add --progress and --no-progress options. - perf mem: add a false sharing workload to 'perf test', request PERF_SAMPLE_CPU by default, use the IBS swfilt filter when available and decode L0 in the memory level. - perf test: take turns using the perf mlock budget in the mmaping tests, add the 'needs_mlock' suite flag, scope the probe based tests to their PID and make more tests non-exclusive. - perf vendor events intel: update events and metrics to TMA 5.2, refresh the event tables and fix umask encodings. - perf build: run shellcheck, mypy and pylint in parallel, make pylint opt-out with NO_PYLINT=1, fix clean and install dependencies. - Add a script and a 'make sync-headers' target to sync the tools/ copies of kernel headers with the kernel sources, plus the resulting syncs of the cpufeatures, KVM, fs, mount, fcntl, socket, rtnetlink, if_addr and sound headers. - Fix cs-etm HW_ID mapping synthesis for raw trace, queue teardown leaks and duplicate v0 global mappings. - Add a 'perf bench atomic' benchmark for atomic operations. - Filter events before creating lock_stat in 'perf lock contention'. - Add a 'perf test' case for events re-armed with PERF_EVENT_IOC_REFRESH. - Fix memory leaks on 'perf c2c' output fields and add function view stdio coverage to its test. - Fix a NULL dereference resolving callchains in 'perf machine'. - Optimize the libdw fallback when DWARF is missing and try the symbol file first when checking for debuginfo. - Don't call eprintf() in pr_debugN() when not verbose. - Don't delete cumulative caller entries before the stat_acc decays in 'perf report'. - Fix ring buffer cursor handling: keep the consumed cursor in forward mode and use the head selected by read_init. - Fix 'perf test mmap-basic' user rdpmc detection and only test userspace reading on supported platforms. - Build fixes: include sys/types.h for ssize_t, errno.h before kernel headers and fix jevents.py type annotations for mypy 2.x. * tag 'perf-tools-for-v7.4-1-2026-10-30' of git://git.kernel.org/pub/scm/linux/kernel/git/perf/perf-tools-next: (425 commits) perf machine: Fix NULL deref in thread__resolve_callchain_sample() perf pmu-events: Fix jevents.py type annotations for mypy 2.x perf parse-events: Include errno.h before kernel headers perf print_insn: Include sys/types.h for ssize_t perf tests mmap-basic: Fix user rdpmc detection logic perf tests mmap-basic: Only test userspace reading on supported platforms perf mmap: Preserve the consumed cursor in forward mode perf mmap: Use the head selected by read_init perf hist: Do not delete cumulative caller entries before stat_acc decays perf debug: Avoid calling eprintf() in pr_debugN() when verbose < n perf libdw: Optimize fallback logic for missing DWARF tools headers: Sync KVM headers with the kernel sources tools headers: Sync UAPI sound/asound.h with the kernel sources tools headers: Sync UAPI linux/mount.h with the kernel sources tools headers: Sync UAPI linux/fs.h with the kernel sources tools headers: Sync UAPI linux/fcntl.h with the kernel sources tools headers: Sync linux/socket.h with the kernel sources tools arch x86: Sync the cpufeatures.h copy with the kernel sources tools headers UAPI: Sync linux/rtnetlink.h with the kernel sources tools headers UAPI: Sync linux/if_addr.h with the kernel sources ...
Diffstat (limited to 'tools/perf/scripts/python/flamegraph.py')
-rwxr-xr-xtools/perf/scripts/python/flamegraph.py267
1 files changed, 0 insertions, 267 deletions
diff --git a/tools/perf/scripts/python/flamegraph.py b/tools/perf/scripts/python/flamegraph.py
deleted file mode 100755
index ad735990c5be..000000000000
--- a/tools/perf/scripts/python/flamegraph.py
+++ /dev/null
@@ -1,267 +0,0 @@
-# flamegraph.py - create flame graphs from perf samples
-# SPDX-License-Identifier: GPL-2.0
-#
-# Usage:
-#
-# perf record -a -g -F 99 sleep 60
-# perf script report flamegraph
-#
-# Combined:
-#
-# perf script flamegraph -a -F 99 sleep 60
-#
-# Written by Andreas Gerstmayr <agerstmayr@redhat.com>
-# Flame Graphs invented by Brendan Gregg <bgregg@netflix.com>
-# Works in tandem with d3-flame-graph by Martin Spier <mspier@netflix.com>
-#
-# pylint: disable=missing-module-docstring
-# pylint: disable=missing-class-docstring
-# pylint: disable=missing-function-docstring
-
-import argparse
-import hashlib
-import io
-import json
-import os
-import subprocess
-import sys
-from typing import Dict, Optional, Union
-import urllib.request
-
-MINIMAL_HTML = """<head>
- <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/d3-flame-graph@4.1.3/dist/d3-flamegraph.css">
-</head>
-<body>
- <div id="chart"></div>
- <script type="text/javascript" src="https://d3js.org/d3.v7.js"></script>
- <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/d3-flame-graph@4.1.3/dist/d3-flamegraph.min.js"></script>
- <script type="text/javascript">
- const stacks = [/** @flamegraph_json **/];
- // Note, options is unused.
- const options = [/** @options_json **/];
-
- var chart = flamegraph();
- d3.select("#chart")
- .datum(stacks[0])
- .call(chart);
- </script>
-</body>
-"""
-
-# pylint: disable=too-few-public-methods
-class Node:
- def __init__(self, name: str, libtype: str):
- self.name = name
- # "root" | "kernel" | ""
- # "" indicates user space
- self.libtype = libtype
- self.value: int = 0
- self.children: list[Node] = []
-
- def to_json(self) -> Dict[str, Union[str, int, list[Dict]]]:
- return {
- "n": self.name,
- "l": self.libtype,
- "v": self.value,
- "c": [x.to_json() for x in self.children]
- }
-
-
-class FlameGraphCLI:
- def __init__(self, args):
- self.args = args
- self.stack = Node("all", "root")
-
- @staticmethod
- def get_libtype_from_dso(dso: Optional[str]) -> str:
- """
- when kernel-debuginfo is installed,
- dso points to /usr/lib/debug/lib/modules/*/vmlinux
- """
- if dso and (dso == "[kernel.kallsyms]" or dso.endswith("/vmlinux")):
- return "kernel"
-
- return ""
-
- @staticmethod
- def find_or_create_node(node: Node, name: str, libtype: str) -> Node:
- for child in node.children:
- if child.name == name:
- return child
-
- child = Node(name, libtype)
- node.children.append(child)
- return child
-
- def process_event(self, event) -> None:
- # ignore events where the event name does not match
- # the one specified by the user
- if self.args.event_name and event.get("ev_name") != self.args.event_name:
- return
-
- pid = event.get("sample", {}).get("pid", 0)
- # event["dso"] sometimes contains /usr/lib/debug/lib/modules/*/vmlinux
- # for user-space processes; let's use pid for kernel or user-space distinction
- if pid == 0:
- comm = event["comm"]
- libtype = "kernel"
- else:
- comm = f"{event['comm']} ({pid})"
- libtype = ""
- node = self.find_or_create_node(self.stack, comm, libtype)
-
- if "callchain" in event:
- for entry in reversed(event["callchain"]):
- name = entry.get("sym", {}).get("name", "[unknown]")
- libtype = self.get_libtype_from_dso(entry.get("dso"))
- node = self.find_or_create_node(node, name, libtype)
- else:
- name = event.get("symbol", "[unknown]")
- libtype = self.get_libtype_from_dso(event.get("dso"))
- node = self.find_or_create_node(node, name, libtype)
- node.value += 1
-
- def get_report_header(self) -> str:
- if self.args.input == "-":
- # when this script is invoked with "perf script flamegraph",
- # no perf.data is created and we cannot read the header of it
- return ""
-
- try:
- # if the file name other than perf.data is given,
- # we read the header of that file
- if self.args.input:
- output = subprocess.check_output(["perf", "report", "--header-only",
- "-i", self.args.input])
- else:
- output = subprocess.check_output(["perf", "report", "--header-only"])
-
- result = output.decode("utf-8")
- if self.args.event_name:
- result += "\nFocused event: " + self.args.event_name
- return result
- except Exception as err: # pylint: disable=broad-except
- print(f"Error reading report header: {err}", file=sys.stderr)
- return ""
-
- def trace_end(self) -> None:
- stacks_json = json.dumps(self.stack, default=lambda x: x.to_json())
-
- if self.args.format == "html":
- report_header = self.get_report_header()
- options = {
- "colorscheme": self.args.colorscheme,
- "context": report_header
- }
- options_json = json.dumps(options)
-
- template_md5sum = None
- if self.args.format == "html":
- if os.path.isfile(self.args.template):
- template = f"file://{self.args.template}"
- else:
- if not self.args.allow_download:
- print(f"""Warning: Flame Graph template '{self.args.template}'
-does not exist. To avoid this please install a package such as the
-js-d3-flame-graph or libjs-d3-flame-graph, specify an existing flame
-graph template (--template PATH) or use another output format (--format
-FORMAT).""",
- file=sys.stderr)
- if self.args.input == "-":
- print(
-"""Not attempting to download Flame Graph template as script command line
-input is disabled due to using live mode. If you want to download the
-template retry without live mode. For example, use 'perf record -a -g
--F 99 sleep 60' and 'perf script report flamegraph'. Alternatively,
-download the template from:
-https://cdn.jsdelivr.net/npm/d3-flame-graph@4.1.3/dist/templates/d3-flamegraph-base.html
-and place it at:
-/usr/share/d3-flame-graph/d3-flamegraph-base.html""",
- file=sys.stderr)
- sys.exit(1)
- s = None
- while s not in ["y", "n"]:
- s = input("Do you wish to download a template from cdn.jsdelivr.net?" +
- "(this warning can be suppressed with --allow-download) [yn] "
- ).lower()
- if s == "n":
- sys.exit(1)
- template = ("https://cdn.jsdelivr.net/npm/d3-flame-graph@4.1.3/dist/templates/"
- "d3-flamegraph-base.html")
- template_md5sum = "143e0d06ba69b8370b9848dcd6ae3f36"
-
- try:
- with urllib.request.urlopen(template) as url_template:
- output_str = "".join([
- l.decode("utf-8") for l in url_template.readlines()
- ])
- except Exception as err:
- print(f"Error reading template {template}: {err}\n"
- "a minimal flame graph will be generated", file=sys.stderr)
- output_str = MINIMAL_HTML
- template_md5sum = None
-
- if template_md5sum:
- download_md5sum = hashlib.md5(output_str.encode("utf-8")).hexdigest()
- if download_md5sum != template_md5sum:
- s = None
- while s not in ["y", "n"]:
- s = input(f"""Unexpected template md5sum.
-{download_md5sum} != {template_md5sum}, for:
-{output_str}
-continue?[yn] """).lower()
- if s == "n":
- sys.exit(1)
-
- output_str = output_str.replace("/** @options_json **/", options_json)
- output_str = output_str.replace("/** @flamegraph_json **/", stacks_json)
-
- output_fn = self.args.output or "flamegraph.html"
- else:
- output_str = stacks_json
- output_fn = self.args.output or "stacks.json"
-
- if output_fn == "-":
- with io.open(sys.stdout.fileno(), "w", encoding="utf-8", closefd=False) as out:
- out.write(output_str)
- else:
- print(f"dumping data to {output_fn}")
- try:
- with io.open(output_fn, "w", encoding="utf-8") as out:
- out.write(output_str)
- except IOError as err:
- print(f"Error writing output file: {err}", file=sys.stderr)
- sys.exit(1)
-
-
-if __name__ == "__main__":
- parser = argparse.ArgumentParser(description="Create flame graphs.")
- parser.add_argument("-f", "--format",
- default="html", choices=["json", "html"],
- help="output file format")
- parser.add_argument("-o", "--output",
- help="output file name")
- parser.add_argument("--template",
- default="/usr/share/d3-flame-graph/d3-flamegraph-base.html",
- help="path to flame graph HTML template")
- parser.add_argument("--colorscheme",
- default="blue-green",
- help="flame graph color scheme",
- choices=["blue-green", "orange"])
- parser.add_argument("-i", "--input",
- help=argparse.SUPPRESS)
- parser.add_argument("--allow-download",
- default=False,
- action="store_true",
- help="allow unprompted downloading of HTML template")
- parser.add_argument("-e", "--event",
- default="",
- dest="event_name",
- type=str,
- help="specify the event to generate flamegraph for")
-
- cli_args = parser.parse_args()
- cli = FlameGraphCLI(cli_args)
-
- process_event = cli.process_event
- trace_end = cli.trace_end