0001
0002
0003
0004 #include <stdint.h>
0005 #include <string.h>
0006
0007 #include <linux/stddef.h>
0008 #include <linux/bpf.h>
0009
0010 #include <bpf/bpf_helpers.h>
0011
0012
0013 #define MAX_ULONG_STR_LEN 0xF
0014
0015
0016 #define MAX_VALUE_STR_LEN 0x40
0017
0018 #ifndef ARRAY_SIZE
0019 #define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))
0020 #endif
0021
0022 const char tcp_mem_name[] = "net/ipv4/tcp_mem";
0023 static __always_inline int is_tcp_mem(struct bpf_sysctl *ctx)
0024 {
0025 unsigned char i;
0026 char name[sizeof(tcp_mem_name)];
0027 int ret;
0028
0029 memset(name, 0, sizeof(name));
0030 ret = bpf_sysctl_get_name(ctx, name, sizeof(name), 0);
0031 if (ret < 0 || ret != sizeof(tcp_mem_name) - 1)
0032 return 0;
0033
0034 #pragma clang loop unroll(full)
0035 for (i = 0; i < sizeof(tcp_mem_name); ++i)
0036 if (name[i] != tcp_mem_name[i])
0037 return 0;
0038
0039 return 1;
0040 }
0041
0042 SEC("cgroup/sysctl")
0043 int sysctl_tcp_mem(struct bpf_sysctl *ctx)
0044 {
0045 unsigned long tcp_mem[3] = {0, 0, 0};
0046 char value[MAX_VALUE_STR_LEN];
0047 unsigned char i, off = 0;
0048 volatile int ret;
0049
0050 if (ctx->write)
0051 return 0;
0052
0053 if (!is_tcp_mem(ctx))
0054 return 0;
0055
0056 ret = bpf_sysctl_get_current_value(ctx, value, MAX_VALUE_STR_LEN);
0057 if (ret < 0 || ret >= MAX_VALUE_STR_LEN)
0058 return 0;
0059
0060 #pragma clang loop unroll(full)
0061 for (i = 0; i < ARRAY_SIZE(tcp_mem); ++i) {
0062 ret = bpf_strtoul(value + off, MAX_ULONG_STR_LEN, 0,
0063 tcp_mem + i);
0064 if (ret <= 0 || ret > MAX_ULONG_STR_LEN)
0065 return 0;
0066 off += ret & MAX_ULONG_STR_LEN;
0067 }
0068
0069
0070 return tcp_mem[0] < tcp_mem[1] && tcp_mem[1] < tcp_mem[2];
0071 }
0072
0073 char _license[] SEC("license") = "GPL";