1// SPDX-License-Identifier: GPL-2.0
2// Copyright (c) 2019 Facebook
3
4#include <stdint.h>
5#include <string.h>
6
7#include <linux/stddef.h>
8#include <linux/bpf.h>
9
10#include <bpf/bpf_helpers.h>
11
12#include "bpf_compiler.h"
13
14/* Max supported length of a string with unsigned long in base 10 (pow2 - 1). */
15#define MAX_ULONG_STR_LEN 0xF
16
17/* Max supported length of sysctl value string (pow2). */
18#define MAX_VALUE_STR_LEN 0x40
19
20#ifndef ARRAY_SIZE
21#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))
22#endif
23
24const char tcp_mem_name[] = "net/ipv4/tcp_mem";
25static __always_inline int is_tcp_mem(struct bpf_sysctl *ctx)
26{
27	unsigned char i;
28	char name[sizeof(tcp_mem_name)];
29	int ret;
30
31	memset(name, 0, sizeof(name));
32	ret = bpf_sysctl_get_name(ctx, name, sizeof(name), 0);
33	if (ret < 0 || ret != sizeof(tcp_mem_name) - 1)
34		return 0;
35
36	__pragma_loop_unroll_full
37	for (i = 0; i < sizeof(tcp_mem_name); ++i)
38		if (name[i] != tcp_mem_name[i])
39			return 0;
40
41	return 1;
42}
43
44SEC("cgroup/sysctl")
45int sysctl_tcp_mem(struct bpf_sysctl *ctx)
46{
47	unsigned long tcp_mem[3] = {0, 0, 0};
48	char value[MAX_VALUE_STR_LEN];
49	unsigned char i, off = 0;
50	volatile int ret;
51
52	if (ctx->write)
53		return 0;
54
55	if (!is_tcp_mem(ctx))
56		return 0;
57
58	ret = bpf_sysctl_get_current_value(ctx, value, MAX_VALUE_STR_LEN);
59	if (ret < 0 || ret >= MAX_VALUE_STR_LEN)
60		return 0;
61
62	__pragma_loop_unroll_full
63	for (i = 0; i < ARRAY_SIZE(tcp_mem); ++i) {
64		ret = bpf_strtoul(value + off, MAX_ULONG_STR_LEN, 0,
65				  tcp_mem + i);
66		if (ret <= 0 || ret > MAX_ULONG_STR_LEN)
67			return 0;
68		off += ret & MAX_ULONG_STR_LEN;
69	}
70
71
72	return tcp_mem[0] < tcp_mem[1] && tcp_mem[1] < tcp_mem[2];
73}
74
75char _license[] SEC("license") = "GPL";
76