xdp_sample_pkts_kern.c 1.7 KB

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