Path: blob/master/tools/bpf/runqslower/runqslower.bpf.c
26292 views
// SPDX-License-Identifier: GPL-2.01// Copyright (c) 2019 Facebook2#include "vmlinux.h"3#include <bpf/bpf_helpers.h>4#include "runqslower.h"56#define TASK_RUNNING 07#define BPF_F_CURRENT_CPU 0xffffffffULL89const volatile __u64 min_us = 0;10const volatile pid_t targ_pid = 0;1112struct {13__uint(type, BPF_MAP_TYPE_TASK_STORAGE);14__uint(map_flags, BPF_F_NO_PREALLOC);15__type(key, int);16__type(value, u64);17} start SEC(".maps");1819struct {20__uint(type, BPF_MAP_TYPE_PERF_EVENT_ARRAY);21__uint(key_size, sizeof(u32));22__uint(value_size, sizeof(u32));23} events SEC(".maps");2425/* record enqueue timestamp */26__always_inline27static int trace_enqueue(struct task_struct *t)28{29u32 pid = t->pid;30u64 *ptr;3132if (!pid || (targ_pid && targ_pid != pid))33return 0;3435ptr = bpf_task_storage_get(&start, t, 0,36BPF_LOCAL_STORAGE_GET_F_CREATE);37if (!ptr)38return 0;3940*ptr = bpf_ktime_get_ns();41return 0;42}4344SEC("tp_btf/sched_wakeup")45int handle__sched_wakeup(u64 *ctx)46{47/* TP_PROTO(struct task_struct *p) */48struct task_struct *p = (void *)ctx[0];4950return trace_enqueue(p);51}5253SEC("tp_btf/sched_wakeup_new")54int handle__sched_wakeup_new(u64 *ctx)55{56/* TP_PROTO(struct task_struct *p) */57struct task_struct *p = (void *)ctx[0];5859return trace_enqueue(p);60}6162SEC("tp_btf/sched_switch")63int handle__sched_switch(u64 *ctx)64{65/* TP_PROTO(bool preempt, struct task_struct *prev,66* struct task_struct *next)67*/68struct task_struct *prev = (struct task_struct *)ctx[1];69struct task_struct *next = (struct task_struct *)ctx[2];70struct runq_event event = {};71u64 *tsp, delta_us;72u32 pid;7374/* ivcsw: treat like an enqueue event and store timestamp */75if (prev->__state == TASK_RUNNING)76trace_enqueue(prev);7778pid = next->pid;7980/* For pid mismatch, save a bpf_task_storage_get */81if (!pid || (targ_pid && targ_pid != pid))82return 0;8384/* fetch timestamp and calculate delta */85tsp = bpf_task_storage_get(&start, next, 0, 0);86if (!tsp)87return 0; /* missed enqueue */8889delta_us = (bpf_ktime_get_ns() - *tsp) / 1000;90if (min_us && delta_us <= min_us)91return 0;9293event.pid = pid;94event.delta_us = delta_us;95bpf_get_current_comm(&event.task, sizeof(event.task));9697/* output */98bpf_perf_event_output(ctx, &events, BPF_F_CURRENT_CPU,99&event, sizeof(event));100101bpf_task_storage_delete(&start, next);102return 0;103}104105char LICENSE[] SEC("license") = "GPL";106107108