Back to home page

OSCL-LXR

 
 

    


0001 // SPDX-License-Identifier: GPL-2.0
0002 // Copyright (c) 2020 Facebook
0003 
0004 #include <linux/bpf.h>
0005 #include <bpf/bpf_helpers.h>
0006 #include "bpf_misc.h"
0007 
0008 char _license[] SEC("license") = "GPL";
0009 
0010 struct sample {
0011     int pid;
0012     int seq;
0013     long value;
0014     char comm[16];
0015 };
0016 
0017 struct {
0018     __uint(type, BPF_MAP_TYPE_RINGBUF);
0019 } ringbuf SEC(".maps");
0020 
0021 /* inputs */
0022 int pid = 0;
0023 long value = 0;
0024 long flags = 0;
0025 
0026 /* outputs */
0027 long total = 0;
0028 long discarded = 0;
0029 long dropped = 0;
0030 
0031 long avail_data = 0;
0032 long ring_size = 0;
0033 long cons_pos = 0;
0034 long prod_pos = 0;
0035 
0036 /* inner state */
0037 long seq = 0;
0038 
0039 SEC("fentry/" SYS_PREFIX "sys_getpgid")
0040 int test_ringbuf(void *ctx)
0041 {
0042     int cur_pid = bpf_get_current_pid_tgid() >> 32;
0043     struct sample *sample;
0044     int zero = 0;
0045 
0046     if (cur_pid != pid)
0047         return 0;
0048 
0049     sample = bpf_ringbuf_reserve(&ringbuf, sizeof(*sample), 0);
0050     if (!sample) {
0051         __sync_fetch_and_add(&dropped, 1);
0052         return 0;
0053     }
0054 
0055     sample->pid = pid;
0056     bpf_get_current_comm(sample->comm, sizeof(sample->comm));
0057     sample->value = value;
0058 
0059     sample->seq = seq++;
0060     __sync_fetch_and_add(&total, 1);
0061 
0062     if (sample->seq & 1) {
0063         /* copy from reserved sample to a new one... */
0064         bpf_ringbuf_output(&ringbuf, sample, sizeof(*sample), flags);
0065         /* ...and then discard reserved sample */
0066         bpf_ringbuf_discard(sample, flags);
0067         __sync_fetch_and_add(&discarded, 1);
0068     } else {
0069         bpf_ringbuf_submit(sample, flags);
0070     }
0071 
0072     avail_data = bpf_ringbuf_query(&ringbuf, BPF_RB_AVAIL_DATA);
0073     ring_size = bpf_ringbuf_query(&ringbuf, BPF_RB_RING_SIZE);
0074     cons_pos = bpf_ringbuf_query(&ringbuf, BPF_RB_CONS_POS);
0075     prod_pos = bpf_ringbuf_query(&ringbuf, BPF_RB_PROD_POS);
0076 
0077     return 0;
0078 }