cmogstored 1.8.1 - use default system stack size
[cmogstored.git] / maxconns.c
blob5060af7fe88b792469fe8b0290d118969e3f37b3
1 /*
2 * Copyright (C) 2012-2020 all contributors <cmogstored-public@yhbt.net>
3 * License: GPL-3.0+ <https://www.gnu.org/licenses/gpl-3.0.txt>
4 */
5 #include "cmogstored.h"
6 #include <sys/time.h>
7 #include <sys/resource.h>
9 #ifndef RLIM_INFINITY
10 # define RLIM_INFINITY ((rlim_t)(-1))
11 #endif
13 void mog_set_maxconns(unsigned long maxconns)
15 struct rlimit r;
16 rlim_t want;
17 struct rlimit orig;
19 if (getrlimit(RLIMIT_NOFILE, &r) != 0)
20 die_errno("getrlimit(RLIMIT_NOFILE) failed");
22 memcpy(&orig, &r, sizeof(struct rlimit));
24 if (maxconns == 0)
25 maxconns = MOG_DEFAULT_MAXCONNS;
26 want = maxconns;
28 if ((int)want < 0 || want > MOG_FD_MAX)
29 want = MOG_FD_MAX; /* LOL :D */
30 if (r.rlim_cur >= want)
31 return;
33 if (r.rlim_max == RLIM_INFINITY || r.rlim_cur == RLIM_INFINITY) {
34 /* insane? maybe... */
35 r.rlim_max = r.rlim_cur = want;
36 } else if (r.rlim_max == 0) {
37 warn("RLIMIT_NOFILE max=0, trying %ld anyways", (long)want);
38 r.rlim_max = r.rlim_cur = want;
39 } else if (r.rlim_max < want) {
40 warn("RLIMIT_NOFILE max=%ld less than wanted value=%ld",
41 (long)r.rlim_max, (long)want);
42 r.rlim_cur = r.rlim_max;
43 } else {
44 r.rlim_max = r.rlim_cur = want;
47 if (setrlimit(RLIMIT_NOFILE, &r) == 0) return;
49 warn("failed to set RLIMIT_NOFILE max=%ld cur=%ld (maxconns=%lu)",
50 (long)r.rlim_max, (long)r.rlim_cur, maxconns);
52 while ((want -= 64) >= maxconns) {
53 r.rlim_max = r.rlim_cur = want;
54 if (setrlimit(RLIMIT_NOFILE, &r) == 0)
55 goto eventual_success;
58 warn("RLIMIT_NOFILE stuck at max=%ld cur=%ld (maxconns=%lu)",
59 (long)orig.rlim_max, (long)orig.rlim_cur, maxconns);
60 return;
62 eventual_success:
63 warn("set RLIMIT_NOFILE max=%ld cur=%ld (maxconns=%lu)",
64 (long)r.rlim_max, (long)r.rlim_cur, maxconns);