From 74792bf37cd511453acd88e45b752c0ca13ea22e Mon Sep 17 00:00:00 2001
From: Petr Baudis <pasky@ucw.cz>
Date: Fri, 16 Mar 2012 05:27:35 +0100
Subject: [PATCH] cgroup_set_mem_limit(): Fix increasing the memory limit

---
 cgroup.c | 30 +++++++++++++++++++++---------
 1 file changed, 21 insertions(+), 9 deletions(-)

diff --git a/cgroup.c b/cgroup.c
index ab09b65..0892afd 100644
--- a/cgroup.c
+++ b/cgroup.c
@@ -141,7 +141,7 @@ cgroup_get_mem_limit(const char *chier, const char *cgroup)
 	return nlimit;
 }
 
-int
+static int
 cgroup_set_mem_limit_do(const char *chier, const char *cgroup, size_t nlimit, char *memsw)
 {
 	char limitfile[PATH_MAX];
@@ -163,21 +163,33 @@ cgroup_set_mem_limit_do(const char *chier, const char *cgroup, size_t nlimit, ch
 	return 1;
 }
 
-int
-cgroup_set_mem_limit(const char *chier, const char *cgroup, size_t nlimit)
+static int
+cgroup_set_mem_limit_twice(const char *chier, const char *cgroup, size_t nlimit, char *memsw1, char *memsw2)
 {
-	/* We need to set both the "normal" and memsw limits, normal first,
-	 * since normal <= memsw must hold. */
-	int ret = cgroup_set_mem_limit_do(chier, cgroup, nlimit, "");
-#if SWAP_LIMIT
+	int ret = cgroup_set_mem_limit_do(chier, cgroup, nlimit, memsw1);
 	if (ret >= 0) {
-		int ret2 = cgroup_set_mem_limit_do(chier, cgroup, nlimit, MEMSW);
+		int ret2 = cgroup_set_mem_limit_do(chier, cgroup, nlimit, memsw2);
 		ret = ret2 < 0 ? ret2 : (ret || ret2);
 	}
-#endif
 	return ret;
 }
 
+int
+cgroup_set_mem_limit(const char *chier, const char *cgroup, size_t nlimit)
+{
+#if SWAP_LIMIT
+	/* We need to set both the "normal" and memsw limits, but in such
+	 * order that normal <= memsw always holds. */
+	size_t curlimit = cgroup_get_mem_limit(chier, cgroup);
+	if (nlimit < curlimit)
+		return cgroup_set_mem_limit_twice(chier, cgroup, nlimit, "", MEMSW);
+	else
+		return cgroup_set_mem_limit_twice(chier, cgroup, nlimit, MEMSW, "");
+#else
+	return cgroup_set_mem_limit_do(chier, cgroup, nlimit, "");
+#endif
+}
+
 size_t
 cgroup_get_mem_usage(const char *chier, const char *cgroup)
 {
-- 
GitLab