From d8cf2ac79b524d7784bccb428295ebc9c5e8548c Mon Sep 17 00:00:00 2001 From: Lennart Poettering Date: Wed, 8 Jun 2016 20:45:32 +0200 Subject: util: introduce physical_memory_scale() to unify how we scale by physical memory The various bits of code did the scaling all different, let's unify this, given that the code is not trivial. --- src/basic/util.c | 27 +++++++++++++++++++++++++++ src/basic/util.h | 1 + 2 files changed, 28 insertions(+) (limited to 'src/basic') diff --git a/src/basic/util.c b/src/basic/util.c index 88d58cd94a..09d16697b7 100644 --- a/src/basic/util.c +++ b/src/basic/util.c @@ -805,6 +805,33 @@ uint64_t physical_memory(void) { return MIN(mem, lim); } +uint64_t physical_memory_scale(uint64_t v, uint64_t max) { + uint64_t p, m, ps, r; + + assert(max > 0); + + /* Returns the physical memory size, multiplied by v divided by max. Returns UINT64_MAX on overflow. On success + * the result is a multiple of the page size (rounds down). */ + + ps = page_size(); + assert(ps > 0); + + p = physical_memory() / ps; + assert(p > 0); + + m = p * v; + if (m / p != v) + return UINT64_MAX; + + m /= max; + + r = m * ps; + if (r / ps != m) + return UINT64_MAX; + + return r; +} + int update_reboot_parameter_and_warn(const char *param) { int r; diff --git a/src/basic/util.h b/src/basic/util.h index 9e6df19ef1..db105197e8 100644 --- a/src/basic/util.h +++ b/src/basic/util.h @@ -184,6 +184,7 @@ int namespace_open(pid_t pid, int *pidns_fd, int *mntns_fd, int *netns_fd, int * int namespace_enter(int pidns_fd, int mntns_fd, int netns_fd, int userns_fd, int root_fd); uint64_t physical_memory(void); +uint64_t physical_memory_scale(uint64_t v, uint64_t max); int update_reboot_parameter_and_warn(const char *param); -- cgit v1.2.3-54-g00ecf