lmkd: Detect the highest level of vmpressure when event is detected

lmkd checks for vmpressure events using epoll_wait() with eventfds of
all registered events. It's possible that multiple events of different
priorities happen before epoll_wait() returns. For these cases we
use conservative approach by assuming that the system is under the
highest registered vmpressure levels. This speeds up lmkd response time
to high memory pressure by not responding to possibly stale low pressure
levels when vmpressure rises quickly.

Bug: 63631020
Test: alloc-stress

Change-Id: I79a85c3342e7e1b3a3be82945266b2cc60b437cf
Signed-off-by: Suren Baghdasaryan <surenb@google.com>
diff --git a/lmkd/lmkd.c b/lmkd/lmkd.c
index 6def5f4..1b8fed3 100644
--- a/lmkd/lmkd.c
+++ b/lmkd/lmkd.c
@@ -102,7 +102,7 @@
 };
 
 static int level_oomadj[VMPRESS_LEVEL_COUNT];
-static int mpevfd[VMPRESS_LEVEL_COUNT];
+static int mpevfd[VMPRESS_LEVEL_COUNT] = { -1, -1, -1 };
 static bool debug_process_killing;
 static bool enable_pressure_upgrade;
 static int64_t upgrade_pressure;
@@ -745,11 +745,20 @@
     unsigned long long evcount;
     int64_t mem_usage, memsw_usage;
     int64_t mem_pressure;
+    enum vmpressure_level lvl;
 
-    ret = read(mpevfd[level], &evcount, sizeof(evcount));
-    if (ret < 0)
-        ALOGE("Error reading memory pressure event fd; errno=%d",
-              errno);
+    /*
+     * Check all event counters from low to critical
+     * and upgrade to the highest priority one. By reading
+     * eventfd we also reset the event counters.
+     */
+    for (lvl = VMPRESS_LEVEL_LOW; lvl < VMPRESS_LEVEL_COUNT; lvl++) {
+        if (mpevfd[lvl] != -1 &&
+            read(mpevfd[lvl], &evcount, sizeof(evcount)) > 0 &&
+            evcount > 0 && lvl > level) {
+            level = lvl;
+        }
+    }
 
     mem_usage = get_memory_usage(MEMCG_MEMORY_USAGE);
     memsw_usage = get_memory_usage(MEMCG_MEMORYSW_USAGE);