This helper obtains the active namespace from current and returns pid, tgid, device and namespace id as seen from that namespace, allowing to instrument a process inside a container. Device is read from /proc/self/ns/pid, as in the future it's possible that different pid_ns files may belong to different devices, according to the discussion between Eric Biederman and Yonghong in 2017 linux plumbers conference. Currently bpf_get_current_pid_tgid(), is used to do pid filtering in bcc's scripts but this helper returns the pid as seen by the root namespace which is fine when a bcc script is not executed inside a container. When the process of interest is inside a container, pid filtering will not work if bpf_get_current_pid_tgid() is used. This helper addresses this limitation returning the pid as it's seen by the current namespace where the script is executing. This helper has the same use cases as bpf_get_current_pid_tgid() as it can be used to do pid filtering even inside a container. For example a bcc script using bpf_get_current_pid_tgid() (tools/funccount.py): u32 pid = bpf_get_current_pid_tgid() >> 32; if (pid != <pid_arg_passed_in>) return 0; Could be modified to use bpf_get_current_pidns_info() as follows: struct bpf_pidns pidns; bpf_get_current_pidns_info(&pidns, sizeof(struct bpf_pidns)); u32 pid = pidns.tgid; u32 nsid = pidns.nsid; if ((pid != <pid_arg_passed_in>) && (nsid != <nsid_arg_passed_in>)) return 0; To find out the name PID namespace id of a process, you could use this command: $ ps -h -o pidns -p <pid_of_interest> Or this other command: $ ls -Li /proc/<pid_of_interest>/ns/pid Signed-off-by: Carlos Neira <cneirabustos@xxxxxxxxx> Carlos Neira (3): bpf: new helper to obtain namespace data from current task samples/bpf: added sample code for bpf_get_current_pidns_info. tools/testing/selftests/bpf: Add self-tests for new helper. fs/internal.h | 2 - fs/namei.c | 1 - include/linux/bpf.h | 1 + include/linux/namei.h | 4 + include/uapi/linux/bpf.h | 31 ++++- kernel/bpf/core.c | 1 + kernel/bpf/helpers.c | 64 ++++++++++ kernel/trace/bpf_trace.c | 2 + samples/bpf/Makefile | 3 + samples/bpf/trace_ns_info_user.c | 35 ++++++ samples/bpf/trace_ns_info_user_kern.c | 44 +++++++ tools/include/uapi/linux/bpf.h | 31 ++++- tools/testing/selftests/bpf/Makefile | 2 +- tools/testing/selftests/bpf/bpf_helpers.h | 3 + .../testing/selftests/bpf/progs/test_pidns_kern.c | 51 ++++++++ tools/testing/selftests/bpf/test_pidns.c | 138 +++++++++++++++++++++ 16 files changed, 407 insertions(+), 6 deletions(-) create mode 100644 samples/bpf/trace_ns_info_user.c create mode 100644 samples/bpf/trace_ns_info_user_kern.c create mode 100644 tools/testing/selftests/bpf/progs/test_pidns_kern.c create mode 100644 tools/testing/selftests/bpf/test_pidns.c -- 2.11.0