From bd0d7d1f67b5a4f7ba2eeb94224a10f949517c1a Mon Sep 17 00:00:00 2001
From: "Carlos R. Mafra" <crmafra@gmail.com>
Date: Sat, 12 Jan 2019 21:55:02 +0000
Subject: [PATCH] wmmemload: Use MemAvailable from kernel > v3.14 to display
 memory usage

After the introduction of MemAvailable in the kernel v3.14 one can
estimate how much RAM memory is being "used" by how much it is left
before the system starts swapping.

That is the reason why I want to monitor memory usage, to know
how close the system is to swapping. Therefore I propose to
use MemAvailable to compute the percentage of "used" memory.
Theoretically, after this patch a 100% memory usage is a more
accurate description of "yeah, we need to swap from now on".

See https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=34e431b0ae398fc54ea69ff85ec700722c9da773
---
 wmmemload/src/mem_linux.c | 10 +++++++---
 1 file changed, 7 insertions(+), 3 deletions(-)

diff --git a/wmmemload/src/mem_linux.c b/wmmemload/src/mem_linux.c
index ab6e01b..1c645c3 100644
--- a/wmmemload/src/mem_linux.c
+++ b/wmmemload/src/mem_linux.c
@@ -94,7 +94,7 @@ void mem_getusage(int *per_mem, int *per_swap, const struct mem_options *opts)
 {
 	char buffer[BUFSIZ], *p;
 	int fd, len, i;
-	u_int64_t mtotal, mused, mfree, mbuffer, mcached;
+	u_int64_t mtotal, mused, mfree, mbuffer, mcached, mavail;
 	u_int64_t stotal, sused, sfree, scached = 0;
 
 	/* read /proc/meminfo */
@@ -141,8 +141,8 @@ void mem_getusage(int *per_mem, int *per_swap, const struct mem_options *opts)
 		p = skip_token(p);
 		/* examine each line of file */
 		mtotal  = strtoul(p, &p, 0); p = skip_multiple_token(p, 2);
-		mfree   = strtoul(p, &p, 0);
-		p = skip_multiple_token(p, 5); /* skip MemAvailable line */
+		mfree   = strtoul(p, &p, 0); p = skip_multiple_token(p, 2);
+		mavail  = strtoul(p, &p, 0); p = skip_multiple_token(p, 2);
 		mbuffer = strtoul(p, &p, 0); p = skip_multiple_token(p, 2);
 		mcached = strtoul(p, &p, 0); p = skip_multiple_token(p, 2);
 		scached = strtoul(p, &p, 0);
@@ -162,6 +162,9 @@ void mem_getusage(int *per_mem, int *per_swap, const struct mem_options *opts)
 	stotal = strtoul(p, &p, 0); p = skip_multiple_token(p, 2);
 	sfree  = strtoul(p, &p, 0);
 
+	if (format == AFTER_3_14) {
+		*per_mem = 100 * (double) (mtotal - mavail) / (double) mtotal;
+	} else {
 	/* calculate memory usage in percent */
 	mused = mtotal - mfree;
 	if (opts->ignore_buffers)
@@ -169,6 +172,7 @@ void mem_getusage(int *per_mem, int *per_swap, const struct mem_options *opts)
 	if (opts->ignore_cached)
 		mused -= mcached;
 	*per_mem = 100 * (double) mused / (double) mtotal;
+	}
 
 	/* calculate swap usage in percent */
 	sused = stotal - sfree;