xref: /linux/tools/testing/selftests/bpf/progs/cgroup_ancestor.c (revision 3a39d672e7f48b8d6b91a09afa4b55352773b4b5)
1 // SPDX-License-Identifier: GPL-2.0
2 // Copyright (c) 2018 Facebook
3 
4 #include <vmlinux.h>
5 #include <bpf/bpf_helpers.h>
6 #include <bpf/bpf_core_read.h>
7 #include "bpf_tracing_net.h"
8 #define NUM_CGROUP_LEVELS	4
9 
10 __u64 cgroup_ids[NUM_CGROUP_LEVELS];
11 __u16 dport;
12 
log_nth_level(struct __sk_buff * skb,__u32 level)13 static __always_inline void log_nth_level(struct __sk_buff *skb, __u32 level)
14 {
15 	/* [1] &level passed to external function that may change it, it's
16 	 *     incompatible with loop unroll.
17 	 */
18 	cgroup_ids[level] = bpf_skb_ancestor_cgroup_id(skb, level);
19 }
20 
21 SEC("tc")
log_cgroup_id(struct __sk_buff * skb)22 int log_cgroup_id(struct __sk_buff *skb)
23 {
24 	struct sock *sk = (void *)skb->sk;
25 
26 	if (!sk)
27 		return TC_ACT_OK;
28 
29 	sk = bpf_core_cast(sk, struct sock);
30 	if (sk->sk_protocol == IPPROTO_UDP && sk->sk_dport == dport) {
31 		log_nth_level(skb, 0);
32 		log_nth_level(skb, 1);
33 		log_nth_level(skb, 2);
34 		log_nth_level(skb, 3);
35 	}
36 
37 	return TC_ACT_OK;
38 }
39 
40 char _license[] SEC("license") = "GPL";
41