xdp_sample_pkts_kern.c 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. // SPDX-License-Identifier: GPL-2.0
  2. #include <linux/ptrace.h>
  3. #include <linux/version.h>
  4. #include <uapi/linux/bpf.h>
  5. #include <bpf/bpf_helpers.h>
  6. #define SAMPLE_SIZE 64ul
  7. struct {
  8. __uint(type, BPF_MAP_TYPE_PERF_EVENT_ARRAY);
  9. __uint(key_size, sizeof(int));
  10. __uint(value_size, sizeof(u32));
  11. } my_map SEC(".maps");
  12. SEC("xdp_sample")
  13. int xdp_sample_prog(struct xdp_md *ctx)
  14. {
  15. void *data_end = (void *)(long)ctx->data_end;
  16. void *data = (void *)(long)ctx->data;
  17. /* Metadata will be in the perf event before the packet data. */
  18. struct S {
  19. u16 cookie;
  20. u16 pkt_len;
  21. } __packed metadata;
  22. if (data < data_end) {
  23. /* The XDP perf_event_output handler will use the upper 32 bits
  24. * of the flags argument as a number of bytes to include of the
  25. * packet payload in the event data. If the size is too big, the
  26. * call to bpf_perf_event_output will fail and return -EFAULT.
  27. *
  28. * See bpf_xdp_event_output in net/core/filter.c.
  29. *
  30. * The BPF_F_CURRENT_CPU flag means that the event output fd
  31. * will be indexed by the CPU number in the event map.
  32. */
  33. u64 flags = BPF_F_CURRENT_CPU;
  34. u16 sample_size;
  35. int ret;
  36. metadata.cookie = 0xdead;
  37. metadata.pkt_len = (u16)(data_end - data);
  38. sample_size = min(metadata.pkt_len, SAMPLE_SIZE);
  39. flags |= (u64)sample_size << 32;
  40. ret = bpf_perf_event_output(ctx, &my_map, flags,
  41. &metadata, sizeof(metadata));
  42. if (ret)
  43. bpf_printk("perf_event_output failed: %d\n", ret);
  44. }
  45. return XDP_PASS;
  46. }
  47. char _license[] SEC("license") = "GPL";
  48. u32 _version SEC("version") = LINUX_VERSION_CODE;