xref: /aosp_15_r20/external/bcc/tools/old/profile.py (revision 387f9dfdfa2baef462e92476d413c7bc2470293e)
1#!/usr/bin/python
2# @lint-avoid-python-3-compatibility-imports
3#
4# profile  Profile CPU usage by sampling stack traces at a timed interval.
5#          For Linux, uses BCC, BPF, perf_events. Embedded C.
6#
7# This is an efficient profiler, as stack traces are frequency counted in
8# kernel context, rather than passing every stack to user space for frequency
9# counting there. Only the unique stacks and counts are passed to user space
10# at the end of the profile, greatly reducing the kernel<->user transfer.
11#
12# This uses perf_event_open to setup a timer which is instrumented by BPF,
13# and for efficiency it does not initialize the perf ring buffer, so the
14# redundant perf samples are not collected.
15#
16# Kernel stacks are post-process in user-land to skip the interrupt framework
17# frames. You can improve efficiency a little by specifying the exact number
18# of frames to skip with -s, provided you know what that is. If you get -s
19# wrong, note that the first line is the IP, and then the (skipped) stack.
20#
21# Note: if another perf-based sampling session is active, the output may become
22# polluted with their events. On older kernels, the output may also become
23# polluted with tracing sessions (when the kprobe is used instead of the
24# tracepoint). If this becomes a problem, logic can be added to filter events.
25#
26# REQUIRES: Linux 4.6+ (BPF_MAP_TYPE_STACK_TRACE support), and the
27# perf_misc_flags() function symbol to exist. The latter may or may not
28# exist depending on your kernel build. Linux 4.9 provides a proper solution
29# to this (this tool will be updated).
30#
31# Copyright 2016 Netflix, Inc.
32# Licensed under the Apache License, Version 2.0 (the "License")
33#
34# THANKS: Sasha Goldshtein, Andrew Birchall, and Evgeny Vereshchagin, who wrote
35# much of the code here, borrowed from tracepoint.py and offcputime.py.
36#
37# 15-Jul-2016   Brendan Gregg   Created this.
38
39from __future__ import print_function
40from bcc import BPF, Perf
41from sys import stderr
42from time import sleep
43import argparse
44import signal
45import os
46import errno
47import multiprocessing
48import ctypes as ct
49
50#
51# Process Arguments
52#
53
54# arg validation
55def positive_int(val):
56    try:
57        ival = int(val)
58    except ValueError:
59        raise argparse.ArgumentTypeError("must be an integer")
60
61    if ival < 0:
62        raise argparse.ArgumentTypeError("must be positive")
63    return ival
64
65def positive_nonzero_int(val):
66    ival = positive_int(val)
67    if ival == 0:
68        raise argparse.ArgumentTypeError("must be nonzero")
69    return ival
70
71# arguments
72examples = """examples:
73    ./profile             # profile stack traces at 49 Hertz until Ctrl-C
74    ./profile -F 99       # profile stack traces at 99 Hertz
75    ./profile 5           # profile at 49 Hertz for 5 seconds only
76    ./profile -f 5        # output in folded format for flame graphs
77    ./profile -p 185      # only profile threads for PID 185
78    ./profile -U          # only show user space stacks (no kernel)
79    ./profile -K          # only show kernel space stacks (no user)
80    ./profile -S 11       # always skip 11 frames of kernel stack
81"""
82parser = argparse.ArgumentParser(
83    description="Profile CPU stack traces at a timed interval",
84    formatter_class=argparse.RawDescriptionHelpFormatter,
85    epilog=examples)
86thread_group = parser.add_mutually_exclusive_group()
87thread_group.add_argument("-p", "--pid", type=positive_int,
88    help="profile this PID only")
89# TODO: add options for user/kernel threads only
90stack_group = parser.add_mutually_exclusive_group()
91stack_group.add_argument("-U", "--user-stacks-only", action="store_true",
92    help="show stacks from user space only (no kernel space stacks)")
93stack_group.add_argument("-K", "--kernel-stacks-only", action="store_true",
94    help="show stacks from kernel space only (no user space stacks)")
95parser.add_argument("-F", "--frequency", type=positive_int, default=49,
96    help="sample frequency, Hertz (default 49)")
97parser.add_argument("-d", "--delimited", action="store_true",
98    help="insert delimiter between kernel/user stacks")
99parser.add_argument("-a", "--annotations", action="store_true",
100    help="add _[k] annotations to kernel frames")
101parser.add_argument("-f", "--folded", action="store_true",
102    help="output folded format, one line per stack (for flame graphs)")
103parser.add_argument("--stack-storage-size", default=2048,
104    type=positive_nonzero_int,
105    help="the number of unique stack traces that can be stored and "
106        "displayed (default 2048)")
107parser.add_argument("-S", "--kernel-skip", type=positive_int, default=0,
108    help="skip this many kernel frames (default 3)")
109parser.add_argument("duration", nargs="?", default=99999999,
110    type=positive_nonzero_int,
111    help="duration of trace, in seconds")
112
113# option logic
114args = parser.parse_args()
115skip = args.kernel_skip
116pid = int(args.pid) if args.pid is not None else -1
117duration = int(args.duration)
118debug = 0
119need_delimiter = args.delimited and not (args.kernel_stacks_only or
120    args.user_stacks_only)
121# TODO: add stack depth, and interval
122
123#
124# Setup BPF
125#
126
127# define BPF program
128bpf_text = """
129#include <uapi/linux/ptrace.h>
130#include <linux/sched.h>
131
132struct key_t {
133    u32 pid;
134    u64 kernel_ip;
135    u64 kernel_ret_ip;
136    int user_stack_id;
137    int kernel_stack_id;
138    char name[TASK_COMM_LEN];
139};
140BPF_HASH(counts, struct key_t);
141BPF_HASH(start, u32);
142BPF_STACK_TRACE(stack_traces, STACK_STORAGE_SIZE);
143
144// This code gets a bit complex. Probably not suitable for casual hacking.
145
146PERF_TRACE_EVENT {
147    u32 pid = bpf_get_current_pid_tgid();
148    if (!(THREAD_FILTER))
149        return 0;
150
151    // create map key
152    u64 zero = 0, *val;
153    struct key_t key = {.pid = pid};
154    bpf_get_current_comm(&key.name, sizeof(key.name));
155
156    // get stacks
157    key.user_stack_id = USER_STACK_GET;
158    key.kernel_stack_id = KERNEL_STACK_GET;
159
160    if (key.kernel_stack_id >= 0) {
161        // populate extras to fix the kernel stack
162        struct pt_regs regs = {};
163        bpf_probe_read(&regs, sizeof(regs), (void *)REGS_LOCATION);
164        u64 ip = PT_REGS_IP(&regs);
165
166        // if ip isn't sane, leave key ips as zero for later checking
167#ifdef CONFIG_RANDOMIZE_MEMORY
168        if (ip > __PAGE_OFFSET_BASE) {
169#else
170        if (ip > PAGE_OFFSET) {
171#endif
172            key.kernel_ip = ip;
173            if (DO_KERNEL_RIP) {
174                /*
175                 * User didn't specify a skip value (-s), so we will figure
176                 * out how many interrupt framework frames to skip by recording
177                 * the kernel rip, then later scanning for it on the stack.
178                 * This is likely x86_64 specific; can use -s as a workaround
179                 * until this supports your architecture.
180                 */
181                bpf_probe_read(&key.kernel_ret_ip, sizeof(key.kernel_ret_ip),
182                (void *)(regs.bp + 8));
183            }
184        }
185    }
186
187    val = counts.lookup_or_init(&key, &zero);
188    if (val) {
189        (*val)++;
190    }
191    return 0;
192}
193"""
194
195# set thread filter
196thread_context = ""
197perf_filter = "-a"
198if args.pid is not None:
199    thread_context = "PID %s" % args.pid
200    thread_filter = 'pid == %s' % args.pid
201    perf_filter = '-p %s' % args.pid
202else:
203    thread_context = "all threads"
204    thread_filter = '1'
205bpf_text = bpf_text.replace('THREAD_FILTER', thread_filter)
206
207# set stack storage size
208bpf_text = bpf_text.replace('STACK_STORAGE_SIZE', str(args.stack_storage_size))
209
210# handle stack args
211kernel_stack_get = "stack_traces.get_stackid(args, " \
212    "%d)" % skip
213user_stack_get = \
214    "stack_traces.get_stackid(args, BPF_F_USER_STACK)"
215stack_context = ""
216if args.user_stacks_only:
217    stack_context = "user"
218    kernel_stack_get = "-1"
219elif args.kernel_stacks_only:
220    stack_context = "kernel"
221    user_stack_get = "-1"
222else:
223    stack_context = "user + kernel"
224bpf_text = bpf_text.replace('USER_STACK_GET', user_stack_get)
225bpf_text = bpf_text.replace('KERNEL_STACK_GET', kernel_stack_get)
226if skip:
227    # don't record the rip, as we won't use it
228    bpf_text = bpf_text.replace('DO_KERNEL_RIP', '0')
229else:
230    # rip is used to skip interrupt infrastructure frames
231    bpf_text = bpf_text.replace('DO_KERNEL_RIP', '1')
232
233# header
234if not args.folded:
235    print("Sampling at %d Hertz of %s by %s stack" %
236        (args.frequency, thread_context, stack_context), end="")
237    if duration < 99999999:
238        print(" for %d secs." % duration)
239    else:
240        print("... Hit Ctrl-C to end.")
241
242# kprobe perf_misc_flags()
243bpf_text = bpf_text.replace('PERF_TRACE_EVENT',
244    'int kprobe__perf_misc_flags(struct pt_regs *args)')
245bpf_text = bpf_text.replace('REGS_LOCATION', 'PT_REGS_PARM1(args)')
246if debug:
247    print(bpf_text)
248
249# initialize BPF
250try:
251    b = BPF(text=bpf_text)
252except:
253    print("BPF initialization failed. perf_misc_flags() may be inlined in " +
254        "your kernel build.\nThis tool will be updated in the future to " +
255        "support Linux 4.9, which has reliable profiling support. Exiting.")
256    exit()
257
258# signal handler
259def signal_ignore(signal, frame):
260    print()
261
262#
263# Setup perf_events
264#
265
266# use perf_events to sample
267try:
268    Perf.perf_event_open(0, pid=-1, ptype=Perf.PERF_TYPE_SOFTWARE,
269        freq=args.frequency)
270except:
271    print("ERROR: initializing perf_events for sampling.\n"
272        "To debug this, try running the following command:\n"
273        "    perf record -F 49 -e cpu-clock %s -- sleep 1\n"
274        "If that also doesn't work, fix it first." % perf_filter, file=stderr)
275    exit(0)
276
277#
278# Output Report
279#
280
281# collect samples
282try:
283    sleep(duration)
284except KeyboardInterrupt:
285    # as cleanup can take some time, trap Ctrl-C:
286    signal.signal(signal.SIGINT, signal_ignore)
287
288if not args.folded:
289    print()
290
291def aksym(addr):
292    if args.annotations:
293        return b.ksym(addr) + "_[k]"
294    else:
295        return b.ksym(addr)
296
297# output stacks
298missing_stacks = 0
299has_enomem = False
300counts = b.get_table("counts")
301stack_traces = b.get_table("stack_traces")
302for k, v in sorted(counts.items(), key=lambda counts: counts[1].value):
303    # handle get_stackid errors
304    if (not args.user_stacks_only and k.kernel_stack_id < 0 and
305            k.kernel_stack_id != -errno.EFAULT) or \
306            (not args.kernel_stacks_only and k.user_stack_id < 0 and
307            k.user_stack_id != -errno.EFAULT):
308        missing_stacks += 1
309        # check for an ENOMEM error
310        if k.kernel_stack_id == -errno.ENOMEM or \
311                k.user_stack_id == -errno.ENOMEM:
312            has_enomem = True
313
314    user_stack = [] if k.user_stack_id < 0 else \
315        stack_traces.walk(k.user_stack_id)
316    kernel_tmp = [] if k.kernel_stack_id < 0 else \
317        stack_traces.walk(k.kernel_stack_id)
318
319    # fix kernel stack
320    kernel_stack = []
321    if k.kernel_stack_id >= 0:
322        if skip:
323            # fixed skip
324            for addr in kernel_tmp:
325                kernel_stack.append(addr)
326            kernel_stack = kernel_stack[skip:]
327        else:
328            # skip the interrupt framework stack by searching for our RIP
329            skipping = 1
330            for addr in kernel_tmp:
331                if k.kernel_ret_ip == addr:
332                    skipping = 0
333                if not skipping:
334                    kernel_stack.append(addr)
335        if k.kernel_ip:
336            kernel_stack.insert(0, k.kernel_ip)
337
338    do_delimiter = need_delimiter and kernel_stack
339
340    if args.folded:
341        # print folded stack output
342        user_stack = list(user_stack)
343        kernel_stack = list(kernel_stack)
344        line = [k.name.decode('utf-8', 'replace')] + \
345            [b.sym(addr, k.pid) for addr in reversed(user_stack)] + \
346            (do_delimiter and ["-"] or []) + \
347            [aksym(addr) for addr in reversed(kernel_stack)]
348        print("%s %d" % (";".join(line), v.value))
349    else:
350        # print default multi-line stack output.
351        for addr in kernel_stack:
352            print("    %s" % aksym(addr))
353        if do_delimiter:
354            print("    --")
355        for addr in user_stack:
356            print("    %s" % b.sym(addr, k.pid))
357        print("    %-16s %s (%d)" % ("-", k.name, k.pid))
358        print("        %d\n" % v.value)
359
360# check missing
361if missing_stacks > 0:
362    enomem_str = "" if not has_enomem else \
363        " Consider increasing --stack-storage-size."
364    print("WARNING: %d stack traces could not be displayed.%s" %
365        (missing_stacks, enomem_str),
366        file=stderr)
367