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