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 20  /* 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_to_stress_byte_loop";
0022 static __attribute__((noinline)) 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 
0042 SEC("cgroup/sysctl")
0043 int sysctl_tcp_mem(struct bpf_sysctl *ctx)
0044 {
0045     unsigned long tcp_mem[TCP_MEM_LOOPS] = {};
0046     char value[MAX_VALUE_STR_LEN];
0047     unsigned char i, off = 0;
0048     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(disable)
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     return tcp_mem[0] < tcp_mem[1] && tcp_mem[1] < tcp_mem[2];
0070 }
0071 
0072 char _license[] SEC("license") = "GPL";