blob: 46d43babf4798b276a286fcb643f5d167838d35c [file] [log] [blame]
Alexey Ivanov777e8022019-01-03 13:46:38 -08001#!/usr/bin/env python
Alexei Starovoitovb6e43a22015-06-18 14:41:17 -07002# Copyright (c) PLUMgrid, Inc.
3# Licensed under the Apache License, Version 2.0 (the "License")
4
Brenden Blancoc35989d2015-09-02 18:04:07 -07005from bcc import BPF
Alexei Starovoitovb6e43a22015-06-18 14:41:17 -07006from time import sleep
7
Brendan Greggb79df7b2016-07-24 13:40:25 -07008b = BPF(text="""
9#include <uapi/linux/ptrace.h>
10#include <linux/sched.h>
11
12struct key_t {
13 u32 prev_pid;
14 u32 curr_pid;
15};
16// map_type, key_type, leaf_type, table_name, num_entry
Teng Qin7a3e5bc2017-03-29 13:39:17 -070017BPF_HASH(stats, struct key_t, u64, 1024);
Brendan Greggb79df7b2016-07-24 13:40:25 -070018int count_sched(struct pt_regs *ctx, struct task_struct *prev) {
19 struct key_t key = {};
20 u64 zero = 0, *val;
21
22 key.curr_pid = bpf_get_current_pid_tgid();
23 key.prev_pid = prev->pid;
24
Javier Honduvilla Coto64bf9652018-08-01 06:50:19 +020025 // could also use `stats.increment(key);`
Brendan Greggb79df7b2016-07-24 13:40:25 -070026 val = stats.lookup_or_init(&key, &zero);
27 (*val)++;
28 return 0;
29}
30""")
Brenden Blanco5eef65e2015-08-19 15:39:19 -070031b.attach_kprobe(event="finish_task_switch", fn_name="count_sched")
Alexei Starovoitovb6e43a22015-06-18 14:41:17 -070032
33# generate many schedule events
34for i in range(0, 100): sleep(0.01)
35
Brenden Blancoc8b66982015-08-28 23:15:19 -070036for k, v in b["stats"].items():
Alexei Starovoitovb6e43a22015-06-18 14:41:17 -070037 print("task_switch[%5d->%5d]=%u" % (k.prev_pid, k.curr_pid, v.value))