[LTP] [PATCH v2 1/3] lib: add functions to adjust oom score
Li Wang
liwang@redhat.com
Fri Dec 17 12:37:48 CET 2021
This introduces function to LTP for adjusting the oom_score_adj of
target process, which may be helpful in OOM tests to prevent kernel
killing the main or lib process during test running.
The exported global tst_enable_oom_protection function can be used
at anywhere you want to protect, but please remember that if you
do enable protection on a process($PID) that all the children will
inherit its score and be ignored by OOM Killer as well. So that's
why tst_cancel_oom_protection is recommended to combination in use.
Signed-off-by: Li Wang <liwang@redhat.com>
Reviewed-by: Petr Vorel <pvorel@suse.cz>
---
Notes:
Changes v1->v2:
* Move commit messages to source code comment
* correct typos
include/tst_memutils.h | 19 +++++++++++++++++++
lib/tst_memutils.c | 29 +++++++++++++++++++++++++++++
2 files changed, 48 insertions(+)
diff --git a/include/tst_memutils.h b/include/tst_memutils.h
index f605f544e..dc18df6d2 100644
--- a/include/tst_memutils.h
+++ b/include/tst_memutils.h
@@ -25,4 +25,23 @@ void tst_pollute_memory(size_t maxsize, int fillchar);
*/
long long tst_available_mem(void);
+/*
+ * Enable OOM protection to prevent process($PID) being killed by OOM Killer.
+ * echo -1000 >/proc/$PID/oom_score_adj
+ *
+ * Note:
+ * This exported tst_enable_oom_protection function can be used at anywhere
+ * you want to protect, but please remember that if you do enable protection
+ * on a process($PID) that all the children will inherit its score and be
+ * ignored by OOM Killer as well. So that's why tst_cancel_oom_protection is
+ * recommended to combination in use.
+ */
+void tst_enable_oom_protection(pid_t pid);
+
+/*
+ * Cancel the OOM protection for the process($PID).
+ * echo 0 >/proc/$PID/oom_score_adj
+ */
+void tst_cancel_oom_protection(pid_t pid);
+
#endif /* TST_MEMUTILS_H__ */
diff --git a/lib/tst_memutils.c b/lib/tst_memutils.c
index bd09cf6fa..d97b35007 100644
--- a/lib/tst_memutils.c
+++ b/lib/tst_memutils.c
@@ -3,6 +3,7 @@
* Copyright (c) 2020 SUSE LLC <mdoucha@suse.cz>
*/
+#include <stdio.h>
#include <unistd.h>
#include <limits.h>
#include <sys/sysinfo.h>
@@ -91,3 +92,31 @@ long long tst_available_mem(void)
return mem_available;
}
+
+static void set_oom_score_adj(pid_t pid, int value)
+{
+ int val;
+ char score_path[64];
+
+ if (access("/proc/self/oom_score_adj", F_OK) == -1) {
+ tst_res(TINFO, "Warning: oom_score_adj does not exist");
+ return;
+ }
+
+ sprintf(score_path, "/proc/%d/oom_score_adj", pid);
+ SAFE_FILE_PRINTF(score_path, "%d", value);
+
+ SAFE_FILE_SCANF(score_path, "%d", &val);
+ if (val != value)
+ tst_brk(TBROK, "oom_score_adj = %d, but expect %d.", val, value);
+}
+
+void tst_enable_oom_protection(pid_t pid)
+{
+ set_oom_score_adj(pid, -1000);
+}
+
+void tst_cancel_oom_protection(pid_t pid)
+{
+ set_oom_score_adj(pid, 0);
+}
--
2.31.1
More information about the ltp
mailing list