Back to home page

OSCL-LXR

 
 

    


0001 // SPDX-License-Identifier: GPL-2.0
0002 #include <linux/bpf.h>
0003 #include <linux/version.h>
0004 
0005 #include <bpf/bpf_helpers.h>
0006 #include "netcnt_common.h"
0007 
0008 #define MAX_BPS (3 * 1024 * 1024)
0009 
0010 #define REFRESH_TIME_NS 100000000
0011 #define NS_PER_SEC  1000000000
0012 
0013 struct {
0014     __uint(type, BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
0015     __type(key, struct bpf_cgroup_storage_key);
0016     __type(value, union percpu_net_cnt);
0017 } percpu_netcnt SEC(".maps");
0018 
0019 struct {
0020     __uint(type, BPF_MAP_TYPE_CGROUP_STORAGE);
0021     __type(key, struct bpf_cgroup_storage_key);
0022     __type(value, union net_cnt);
0023 } netcnt SEC(".maps");
0024 
0025 SEC("cgroup/skb")
0026 int bpf_nextcnt(struct __sk_buff *skb)
0027 {
0028     union percpu_net_cnt *percpu_cnt;
0029     char fmt[] = "%d %llu %llu\n";
0030     union net_cnt *cnt;
0031     __u64 ts, dt;
0032     int ret;
0033 
0034     cnt = bpf_get_local_storage(&netcnt, 0);
0035     percpu_cnt = bpf_get_local_storage(&percpu_netcnt, 0);
0036 
0037     percpu_cnt->packets++;
0038     percpu_cnt->bytes += skb->len;
0039 
0040     if (percpu_cnt->packets > MAX_PERCPU_PACKETS) {
0041         __sync_fetch_and_add(&cnt->packets,
0042                      percpu_cnt->packets);
0043         percpu_cnt->packets = 0;
0044 
0045         __sync_fetch_and_add(&cnt->bytes,
0046                      percpu_cnt->bytes);
0047         percpu_cnt->bytes = 0;
0048     }
0049 
0050     ts = bpf_ktime_get_ns();
0051     dt = ts - percpu_cnt->prev_ts;
0052 
0053     dt *= MAX_BPS;
0054     dt /= NS_PER_SEC;
0055 
0056     if (cnt->bytes + percpu_cnt->bytes - percpu_cnt->prev_bytes < dt)
0057         ret = 1;
0058     else
0059         ret = 0;
0060 
0061     if (dt > REFRESH_TIME_NS) {
0062         percpu_cnt->prev_ts = ts;
0063         percpu_cnt->prev_packets = cnt->packets;
0064         percpu_cnt->prev_bytes = cnt->bytes;
0065     }
0066 
0067     return !!ret;
0068 }
0069 
0070 char _license[] SEC("license") = "GPL";