1 // SPDX-License-Identifier: GPL-2.0
2 /* Copyright (c) 2022 Meta Platforms, Inc. and affiliates. */
3 #include "vmlinux.h"
4 #include <bpf/bpf_helpers.h>
5 #include <bpf/bpf_tracing.h>
6 #include <bpf/bpf_core_read.h>
7 
8 struct {
9 	__uint(type, BPF_MAP_TYPE_TASK_STORAGE);
10 	__uint(map_flags, BPF_F_NO_PREALLOC);
11 	__type(key, int);
12 	__type(value, long);
13 } enter_id SEC(".maps");
14 
15 #define	IFNAMSIZ 16
16 
17 int ifindex, ingress_ifindex;
18 char name[IFNAMSIZ];
19 unsigned int inum;
20 unsigned int meta_len, frag0_len, kskb_len, kskb2_len;
21 
22 void *bpf_cast_to_kern_ctx(void *) __ksym;
23 void *bpf_rdonly_cast(void *, __u32) __ksym;
24 
25 SEC("?xdp")
md_xdp(struct xdp_md * ctx)26 int md_xdp(struct xdp_md *ctx)
27 {
28 	struct xdp_buff *kctx = bpf_cast_to_kern_ctx(ctx);
29 	struct net_device *dev;
30 
31 	dev = kctx->rxq->dev;
32 	ifindex = dev->ifindex;
33 	inum = dev->nd_net.net->ns.inum;
34 	__builtin_memcpy(name, dev->name, IFNAMSIZ);
35 	ingress_ifindex = ctx->ingress_ifindex;
36 	return XDP_PASS;
37 }
38 
39 SEC("?tc")
md_skb(struct __sk_buff * skb)40 int md_skb(struct __sk_buff *skb)
41 {
42 	struct sk_buff *kskb = bpf_cast_to_kern_ctx(skb);
43 	struct skb_shared_info *shared_info;
44 	struct sk_buff *kskb2;
45 
46 	kskb_len = kskb->len;
47 
48 	/* Simulate the following kernel macro:
49 	 *   #define skb_shinfo(SKB) ((struct skb_shared_info *)(skb_end_pointer(SKB)))
50 	 */
51 	shared_info = bpf_rdonly_cast(kskb->head + kskb->end,
52 		bpf_core_type_id_kernel(struct skb_shared_info));
53 	meta_len = shared_info->meta_len;
54 	frag0_len = shared_info->frag_list->len;
55 
56 	/* kskb2 should be equal to kskb */
57 	kskb2 = bpf_rdonly_cast(kskb, bpf_core_type_id_kernel(struct sk_buff));
58 	kskb2_len = kskb2->len;
59 	return 0;
60 }
61 
62 SEC("?tp_btf/sys_enter")
BPF_PROG(untrusted_ptr,struct pt_regs * regs,long id)63 int BPF_PROG(untrusted_ptr, struct pt_regs *regs, long id)
64 {
65 	struct task_struct *task, *task_dup;
66 
67 	task = bpf_get_current_task_btf();
68 	task_dup = bpf_rdonly_cast(task, bpf_core_type_id_kernel(struct task_struct));
69 	(void)bpf_task_storage_get(&enter_id, task_dup, 0, 0);
70 	return 0;
71 }
72 
73 SEC("?tracepoint/syscalls/sys_enter_nanosleep")
kctx_u64(void * ctx)74 int kctx_u64(void *ctx)
75 {
76 	u64 *kctx = bpf_rdonly_cast(ctx, bpf_core_type_id_kernel(u64));
77 
78 	(void)kctx;
79 	return 0;
80 }
81 
82 char _license[] SEC("license") = "GPL";
83