Alexei Starovoitov | b896c4f | 2015-03-25 12:49:23 -0700 | [diff] [blame] | 1 | /* Copyright (c) 2013-2015 PLUMgrid, http://plumgrid.com |
| 2 | * |
| 3 | * This program is free software; you can redistribute it and/or |
| 4 | * modify it under the terms of version 2 of the GNU General Public |
| 5 | * License as published by the Free Software Foundation. |
| 6 | */ |
| 7 | #include <linux/skbuff.h> |
| 8 | #include <linux/netdevice.h> |
| 9 | #include <uapi/linux/bpf.h> |
| 10 | #include <linux/version.h> |
Toke Høiland-Jørgensen | 7cf245a | 2020-01-20 14:06:49 +0100 | [diff] [blame] | 11 | #include <bpf/bpf_helpers.h> |
| 12 | #include <bpf/bpf_tracing.h> |
Alexei Starovoitov | b896c4f | 2015-03-25 12:49:23 -0700 | [diff] [blame] | 13 | |
Ilya Leoshkevich | e4d9c23 | 2020-07-20 13:48:06 +0200 | [diff] [blame] | 14 | #define _(P) \ |
| 15 | ({ \ |
| 16 | typeof(P) val = 0; \ |
| 17 | bpf_probe_read_kernel(&val, sizeof(val), &(P)); \ |
| 18 | val; \ |
| 19 | }) |
Alexei Starovoitov | b896c4f | 2015-03-25 12:49:23 -0700 | [diff] [blame] | 20 | |
| 21 | /* kprobe is NOT a stable ABI |
| 22 | * kernel functions can be removed, renamed or completely change semantics. |
| 23 | * Number of arguments and their positions can change, etc. |
| 24 | * In such case this bpf+kprobe example will no longer be meaningful |
| 25 | */ |
| 26 | SEC("kprobe/__netif_receive_skb_core") |
| 27 | int bpf_prog1(struct pt_regs *ctx) |
| 28 | { |
Yaqi Chen | 137733d | 2021-04-16 23:48:03 +0800 | [diff] [blame] | 29 | /* attaches to kprobe __netif_receive_skb_core, |
Alexei Starovoitov | b896c4f | 2015-03-25 12:49:23 -0700 | [diff] [blame] | 30 | * looks for packets on loobpack device and prints them |
| 31 | */ |
Daniel Borkmann | 02413ca | 2016-04-13 00:10:53 +0200 | [diff] [blame] | 32 | char devname[IFNAMSIZ]; |
Alexei Starovoitov | b896c4f | 2015-03-25 12:49:23 -0700 | [diff] [blame] | 33 | struct net_device *dev; |
| 34 | struct sk_buff *skb; |
| 35 | int len; |
| 36 | |
| 37 | /* non-portable! works for the given kernel only */ |
Yaqi Chen | 137733d | 2021-04-16 23:48:03 +0800 | [diff] [blame] | 38 | bpf_probe_read_kernel(&skb, sizeof(skb), (void *)PT_REGS_PARM1(ctx)); |
Alexei Starovoitov | b896c4f | 2015-03-25 12:49:23 -0700 | [diff] [blame] | 39 | dev = _(skb->dev); |
Alexei Starovoitov | b896c4f | 2015-03-25 12:49:23 -0700 | [diff] [blame] | 40 | len = _(skb->len); |
| 41 | |
Ilya Leoshkevich | e4d9c23 | 2020-07-20 13:48:06 +0200 | [diff] [blame] | 42 | bpf_probe_read_kernel(devname, sizeof(devname), dev->name); |
Alexei Starovoitov | b896c4f | 2015-03-25 12:49:23 -0700 | [diff] [blame] | 43 | |
| 44 | if (devname[0] == 'l' && devname[1] == 'o') { |
| 45 | char fmt[] = "skb %p len %d\n"; |
| 46 | /* using bpf_trace_printk() for DEBUG ONLY */ |
| 47 | bpf_trace_printk(fmt, sizeof(fmt), skb, len); |
| 48 | } |
| 49 | |
| 50 | return 0; |
| 51 | } |
| 52 | |
| 53 | char _license[] SEC("license") = "GPL"; |
| 54 | u32 _version SEC("version") = LINUX_VERSION_CODE; |