Back to home page

OSCL-LXR

 
 

    


0001 // SPDX-License-Identifier: GPL-2.0
0002 // Copyright (c) 2019 Facebook
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 #ifndef ARRAY_SIZE
0013 #define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))
0014 #endif
0015 
0016 /* tcp_mem sysctl has only 3 ints, but this test is doing TCP_MEM_LOOPS */
0017 #define TCP_MEM_LOOPS 28  /* because 30 doesn't fit into 512 bytes of stack */
0018 #define MAX_ULONG_STR_LEN 7
0019 #define MAX_VALUE_STR_LEN (TCP_MEM_LOOPS * MAX_ULONG_STR_LEN)
0020 
0021 const char tcp_mem_name[] = "net/ipv4/tcp_mem/very_very_very_very_long_pointless_string";
0022 static __always_inline int is_tcp_mem(struct bpf_sysctl *ctx)
0023 {
0024     unsigned char i;
0025     char name[sizeof(tcp_mem_name)];
0026     int ret;
0027 
0028     memset(name, 0, sizeof(name));
0029     ret = bpf_sysctl_get_name(ctx, name, sizeof(name), 0);
0030     if (ret < 0 || ret != sizeof(tcp_mem_name) - 1)
0031         return 0;
0032 
0033 #pragma clang loop unroll(disable)
0034     for (i = 0; i < sizeof(tcp_mem_name); ++i)
0035         if (name[i] != tcp_mem_name[i])
0036             return 0;
0037 
0038     return 1;
0039 }
0040 
0041 SEC("cgroup/sysctl")
0042 int sysctl_tcp_mem(struct bpf_sysctl *ctx)
0043 {
0044     unsigned long tcp_mem[TCP_MEM_LOOPS] = {};
0045     char value[MAX_VALUE_STR_LEN];
0046     unsigned char i, off = 0;
0047     /* a workaround to prevent compiler from generating
0048      * codes verifier cannot handle yet.
0049      */
0050     volatile int ret;
0051 
0052     if (ctx->write)
0053         return 0;
0054 
0055     if (!is_tcp_mem(ctx))
0056         return 0;
0057 
0058     ret = bpf_sysctl_get_current_value(ctx, value, MAX_VALUE_STR_LEN);
0059     if (ret < 0 || ret >= MAX_VALUE_STR_LEN)
0060         return 0;
0061 
0062 #pragma clang loop unroll(disable)
0063     for (i = 0; i < ARRAY_SIZE(tcp_mem); ++i) {
0064         ret = bpf_strtoul(value + off, MAX_ULONG_STR_LEN, 0,
0065                   tcp_mem + i);
0066         if (ret <= 0 || ret > MAX_ULONG_STR_LEN)
0067             return 0;
0068         off += ret & MAX_ULONG_STR_LEN;
0069     }
0070 
0071     return tcp_mem[0] < tcp_mem[1] && tcp_mem[1] < tcp_mem[2];
0072 }
0073 
0074 char _license[] SEC("license") = "GPL";