example that shows usages of maps, probe_read, get_current_pid helpers
authorAlexei Starovoitov <ast@plumgrid.com>
Thu, 18 Jun 2015 21:41:17 +0000 (14:41 -0700)
committerAlexei Starovoitov <ast@plumgrid.com>
Thu, 18 Jun 2015 21:41:17 +0000 (14:41 -0700)
$ ./task_switch.py

task_switch[ 2379->    0]=4
task_switch[ 3914->    0]=2
task_switch[ 3133->    0]=5
task_switch[10903->    0]=100  <-- 100 times python process switched into idle
task_switch[  116->    0]=1
task_switch[    0->   14]=1
task_switch[10803->    0]=1
task_switch[22292->    0]=1
task_switch[    0->22292]=1
task_switch[    0->10803]=1
task_switch[   30->    0]=1
task_switch[    0->10903]=100  <-- 100 times back into python

Signed-off-by: Alexei Starovoitov <ast@plumgrid.com>
examples/task_switch.c [new file with mode: 0644]
examples/task_switch.py [new file with mode: 0755]

diff --git a/examples/task_switch.c b/examples/task_switch.c
new file mode 100644 (file)
index 0000000..e6e66ed
--- /dev/null
@@ -0,0 +1,22 @@
+#include <uapi/linux/ptrace.h>
+#include <linux/sched.h>
+
+struct key_t {
+  u32 prev_pid;
+  u32 curr_pid;
+};
+// map_type, key_type, leaf_type, table_name, num_entry
+BPF_TABLE("hash", struct key_t, u64, stats, 1024);
+int count_sched(struct pt_regs *ctx) {
+  struct key_t key = {};
+  u64 zero = 0, *val;
+
+  key.curr_pid = bpf_get_current_pid_tgid();
+  bpf_probe_read(&key.prev_pid, 4,
+                (void *)ctx->di + offsetof(struct task_struct, pid));
+
+  val = stats.lookup_or_init(&key, &zero);
+  (*val)++;
+  return 0;
+}
+
diff --git a/examples/task_switch.py b/examples/task_switch.py
new file mode 100755 (executable)
index 0000000..f25913f
--- /dev/null
@@ -0,0 +1,17 @@
+#!/usr/bin/python
+# Copyright (c) PLUMgrid, Inc.
+# Licensed under the Apache License, Version 2.0 (the "License")
+
+from bpf import BPF
+from time import sleep
+
+b = BPF(src_file="task_switch.c")
+fn = b.load_func("count_sched", BPF.KPROBE)
+stats = b.get_table("stats")
+BPF.attach_kprobe(fn, "finish_task_switch")
+
+# generate many schedule events
+for i in range(0, 100): sleep(0.01)
+
+for k, v in stats.items():
+    print("task_switch[%5d->%5d]=%u" % (k.prev_pid, k.curr_pid, v.value))