From 160c9b63a25c30ebe6b3e8481003dac72fe35a4a Mon Sep 17 00:00:00 2001 From: Hengqi Chen Date: Wed, 5 Jan 2022 00:02:49 +0800 Subject: [PATCH] examples: Add local storage examples Add examples to demostrate BPF_{INODE, TASK}_STORAGE usage. $ sudo ./task_storage.py b' nc-668442 [000] d..21 1221279.139354: bpf_trace_printk: inet_listen entry: store timestamp 1221271907116757' b' nc-668442 [000] d..21 1221279.139375: bpf_trace_printk: inet_listen exit: cost 26us' Signed-off-by: Hengqi Chen --- examples/local_storage/inode_storage.py | 28 +++++++++++++++++ examples/local_storage/task_storage.py | 41 +++++++++++++++++++++++++ 2 files changed, 69 insertions(+) create mode 100755 examples/local_storage/inode_storage.py create mode 100755 examples/local_storage/task_storage.py diff --git a/examples/local_storage/inode_storage.py b/examples/local_storage/inode_storage.py new file mode 100755 index 00000000..fcc58c57 --- /dev/null +++ b/examples/local_storage/inode_storage.py @@ -0,0 +1,28 @@ +#!/usr/bin/python3 + +from bcc import BPF + +source = r""" +#include + +BPF_INODE_STORAGE(inode_storage_map, int); + +LSM_PROBE(inode_rename, struct inode *old_dir, struct dentry *old_dentry, + struct inode *new_dir, struct dentry *new_dentry, unsigned int flags) +{ + int *value; + + value = inode_storage_map.inode_storage_get(old_dentry->d_inode, 0, BPF_LOCAL_STORAGE_GET_F_CREATE); + if (!value) + return 0; + + bpf_trace_printk("%d", *value); + return 0; +} +""" + +b = BPF(text=source) +try: + b.trace_print() +except KeyboardInterrupt: + pass diff --git a/examples/local_storage/task_storage.py b/examples/local_storage/task_storage.py new file mode 100755 index 00000000..ee9e9b72 --- /dev/null +++ b/examples/local_storage/task_storage.py @@ -0,0 +1,41 @@ +#!/usr/bin/python3 + +from bcc import BPF + +source = r""" +BPF_TASK_STORAGE(task_storage_map, __u64); + +KFUNC_PROBE(inet_listen) +{ + __u64 ts = bpf_ktime_get_ns(); + + /* save timestamp to local storage on function entry */ + task_storage_map.task_storage_get(bpf_get_current_task_btf(), &ts, BPF_LOCAL_STORAGE_GET_F_CREATE); + + bpf_trace_printk("inet_listen entry: store timestamp %lld", ts); + return 0; +} + +KRETFUNC_PROBE(inet_listen) +{ + __u64 *ts; + + /* retrieve timestamp stored at local storage on function exit */ + ts = task_storage_map.task_storage_get(bpf_get_current_task_btf(), 0, 0); + if (!ts) + return 0; + + /* delete timestamp from local storage */ + task_storage_map.task_storage_delete(bpf_get_current_task_btf()); + + /* calculate latency */ + bpf_trace_printk("inet_listen exit: cost %lldus", (bpf_ktime_get_ns() - *ts) / 1000); + return 0; +} +""" + +b = BPF(text=source) +try: + b.trace_print() +except KeyboardInterrupt: + pass -- 2.34.1