Alexei Starovoitov | b6e43a2 | 2015-06-18 14:41:17 -0700 | [diff] [blame] | 1 | #!/usr/bin/python |
| 2 | # Copyright (c) PLUMgrid, Inc. |
| 3 | # Licensed under the Apache License, Version 2.0 (the "License") |
| 4 | |
Brenden Blanco | c35989d | 2015-09-02 18:04:07 -0700 | [diff] [blame] | 5 | from bcc import BPF |
Alexei Starovoitov | b6e43a2 | 2015-06-18 14:41:17 -0700 | [diff] [blame] | 6 | from time import sleep |
| 7 | |
Brendan Gregg | b79df7b | 2016-07-24 13:40:25 -0700 | [diff] [blame] | 8 | b = BPF(text=""" |
| 9 | #include <uapi/linux/ptrace.h> |
| 10 | #include <linux/sched.h> |
| 11 | |
| 12 | struct key_t { |
| 13 | u32 prev_pid; |
| 14 | u32 curr_pid; |
| 15 | }; |
| 16 | // map_type, key_type, leaf_type, table_name, num_entry |
Teng Qin | 7a3e5bc | 2017-03-29 13:39:17 -0700 | [diff] [blame] | 17 | BPF_HASH(stats, struct key_t, u64, 1024); |
Brendan Gregg | b79df7b | 2016-07-24 13:40:25 -0700 | [diff] [blame] | 18 | int 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 | |
| 25 | val = stats.lookup_or_init(&key, &zero); |
| 26 | (*val)++; |
| 27 | return 0; |
| 28 | } |
| 29 | """) |
Brenden Blanco | 5eef65e | 2015-08-19 15:39:19 -0700 | [diff] [blame] | 30 | b.attach_kprobe(event="finish_task_switch", fn_name="count_sched") |
Alexei Starovoitov | b6e43a2 | 2015-06-18 14:41:17 -0700 | [diff] [blame] | 31 | |
| 32 | # generate many schedule events |
| 33 | for i in range(0, 100): sleep(0.01) |
| 34 | |
Brenden Blanco | c8b6698 | 2015-08-28 23:15:19 -0700 | [diff] [blame] | 35 | for k, v in b["stats"].items(): |
Alexei Starovoitov | b6e43a2 | 2015-06-18 14:41:17 -0700 | [diff] [blame] | 36 | print("task_switch[%5d->%5d]=%u" % (k.prev_pid, k.curr_pid, v.value)) |