1 /*
2  * Copyright (C) 2013 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #define LOG_TAG "lowmemorykiller"
18 
19 #include <errno.h>
20 #include <inttypes.h>
21 #include <pwd.h>
22 #include <sched.h>
23 #include <stdbool.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <sys/cdefs.h>
27 #include <sys/epoll.h>
28 #include <sys/eventfd.h>
29 #include <sys/mman.h>
30 #include <sys/pidfd.h>
31 #include <sys/socket.h>
32 #include <sys/syscall.h>
33 #include <sys/sysinfo.h>
34 #include <time.h>
35 #include <unistd.h>
36 
37 #include <algorithm>
38 #include <array>
39 #include <memory>
40 #include <shared_mutex>
41 #include <vector>
42 
43 #include <BpfSyscallWrappers.h>
44 #include <android-base/unique_fd.h>
45 #include <bpf/WaitForProgsLoaded.h>
46 #include <cutils/properties.h>
47 #include <cutils/sockets.h>
48 #include <liblmkd_utils.h>
49 #include <lmkd.h>
50 #include <lmkd_hooks.h>
51 #include <log/log.h>
52 #include <log/log_event_list.h>
53 #include <log/log_time.h>
54 #include <memevents/memevents.h>
55 #include <private/android_filesystem_config.h>
56 #include <processgroup/processgroup.h>
57 #include <psi/psi.h>
58 
59 #include "reaper.h"
60 #include "statslog.h"
61 #include "watchdog.h"
62 
63 /*
64  * Define LMKD_TRACE_KILLS to record lmkd kills in kernel traces
65  * to profile and correlate with OOM kills
66  */
67 #ifdef LMKD_TRACE_KILLS
68 
69 #define ATRACE_TAG ATRACE_TAG_ALWAYS
70 #include <cutils/trace.h>
71 
trace_kill_start(const char * desc)72 static inline void trace_kill_start(const char *desc) {
73     ATRACE_BEGIN(desc);
74 }
75 
trace_kill_end()76 static inline void trace_kill_end() {
77     ATRACE_END();
78 }
79 
80 #else /* LMKD_TRACE_KILLS */
81 
trace_kill_start(const char *)82 static inline void trace_kill_start(const char *) {}
trace_kill_end()83 static inline void trace_kill_end() {}
84 
85 #endif /* LMKD_TRACE_KILLS */
86 
87 #ifndef __unused
88 #define __unused __attribute__((__unused__))
89 #endif
90 
91 #define ZONEINFO_PATH "/proc/zoneinfo"
92 #define MEMINFO_PATH "/proc/meminfo"
93 #define VMSTAT_PATH "/proc/vmstat"
94 #define PROC_STATUS_TGID_FIELD "Tgid:"
95 #define PROC_STATUS_RSS_FIELD "VmRSS:"
96 #define PROC_STATUS_SWAP_FIELD "VmSwap:"
97 #define NODE_STATS_MARKER "  per-node stats"
98 
99 #define PERCEPTIBLE_APP_ADJ 200
100 #define PREVIOUS_APP_ADJ 700
101 
102 /* Android Logger event logtags (see event.logtags) */
103 #define KILLINFO_LOG_TAG 10195355
104 
105 /* gid containing AID_SYSTEM required */
106 #define INKERNEL_MINFREE_PATH "/sys/module/lowmemorykiller/parameters/minfree"
107 #define INKERNEL_ADJ_PATH "/sys/module/lowmemorykiller/parameters/adj"
108 
109 #define EIGHT_MEGA (1 << 23)
110 
111 #define TARGET_UPDATE_MIN_INTERVAL_MS 1000
112 #define THRASHING_RESET_INTERVAL_MS 1000
113 
114 #define NS_PER_MS (NS_PER_SEC / MS_PER_SEC)
115 #define US_PER_MS (US_PER_SEC / MS_PER_SEC)
116 
117 /* Defined as ProcessList.SYSTEM_ADJ in ProcessList.java */
118 #define SYSTEM_ADJ (-900)
119 
120 #define STRINGIFY(x) STRINGIFY_INTERNAL(x)
121 #define STRINGIFY_INTERNAL(x) #x
122 
123 #define PROCFS_PATH_MAX 64
124 
125 /*
126  * Read lmk property with persist.device_config.lmkd_native.<name> overriding ro.lmk.<name>
127  * persist.device_config.lmkd_native.* properties are being set by experiments. If a new property
128  * can be controlled by an experiment then use GET_LMK_PROPERTY instead of property_get_xxx and
129  * add "on property" triggers in lmkd.rc to react to the experiment flag changes.
130  */
131 #define GET_LMK_PROPERTY(type, name, def) \
132     property_get_##type("persist.device_config.lmkd_native." name, \
133         property_get_##type("ro.lmk." name, def))
134 
135 /*
136  * PSI monitor tracking window size.
137  * PSI monitor generates events at most once per window,
138  * therefore we poll memory state for the duration of
139  * PSI_WINDOW_SIZE_MS after the event happens.
140  */
141 #define PSI_WINDOW_SIZE_MS 1000
142 /* Polling period after PSI signal when pressure is high */
143 #define PSI_POLL_PERIOD_SHORT_MS 10
144 /* Polling period after PSI signal when pressure is low */
145 #define PSI_POLL_PERIOD_LONG_MS 100
146 
147 #define FAIL_REPORT_RLIMIT_MS 1000
148 
149 /*
150  * System property defaults
151  */
152 /* ro.lmk.swap_free_low_percentage property defaults */
153 #define DEF_LOW_SWAP 10
154 /* ro.lmk.thrashing_limit property defaults */
155 #define DEF_THRASHING_LOWRAM 30
156 #define DEF_THRASHING 100
157 /* ro.lmk.thrashing_limit_decay property defaults */
158 #define DEF_THRASHING_DECAY_LOWRAM 50
159 #define DEF_THRASHING_DECAY 10
160 /* ro.lmk.psi_partial_stall_ms property defaults */
161 #define DEF_PARTIAL_STALL_LOWRAM 200
162 #define DEF_PARTIAL_STALL 70
163 /* ro.lmk.psi_complete_stall_ms property defaults */
164 #define DEF_COMPLETE_STALL 700
165 /* ro.lmk.direct_reclaim_threshold_ms property defaults */
166 #define DEF_DIRECT_RECL_THRESH_MS 0
167 /* ro.lmk.swap_compression_ratio property defaults */
168 #define DEF_SWAP_COMP_RATIO 1
169 /* ro.lmk.lowmem_min_oom_score defaults */
170 #define DEF_LOWMEM_MIN_SCORE (PREVIOUS_APP_ADJ + 1)
171 
172 #define LMKD_REINIT_PROP "lmkd.reinit"
173 
174 #define WATCHDOG_TIMEOUT_SEC 2
175 
176 /* default to old in-kernel interface if no memory pressure events */
177 static bool use_inkernel_interface = true;
178 static bool has_inkernel_module;
179 
180 /* memory pressure levels */
181 enum vmpressure_level {
182     VMPRESS_LEVEL_LOW = 0,
183     VMPRESS_LEVEL_MEDIUM,
184     VMPRESS_LEVEL_CRITICAL,
185     VMPRESS_LEVEL_COUNT
186 };
187 
188 static const char *level_name[] = {
189     "low",
190     "medium",
191     "critical"
192 };
193 
194 struct {
195     int64_t min_nr_free_pages; /* recorded but not used yet */
196     int64_t max_nr_free_pages;
197 } low_pressure_mem = { -1, -1 };
198 
199 struct psi_threshold {
200     enum psi_stall_type stall_type;
201     int threshold_ms;
202 };
203 
204 /* Listener for direct reclaim and kswapd state changes */
205 static std::unique_ptr<android::bpf::memevents::MemEventListener> memevent_listener(nullptr);
206 static struct timespec direct_reclaim_start_tm;
207 static struct timespec kswapd_start_tm;
208 
209 static int level_oomadj[VMPRESS_LEVEL_COUNT];
210 static int mpevfd[VMPRESS_LEVEL_COUNT] = { -1, -1, -1 };
211 static bool pidfd_supported;
212 static int last_kill_pid_or_fd = -1;
213 static struct timespec last_kill_tm;
214 enum vmpressure_level prev_level = VMPRESS_LEVEL_LOW;
215 static bool monitors_initialized;
216 static bool boot_completed_handled = false;
217 
218 /* lmkd configurable parameters */
219 static bool debug_process_killing;
220 static bool enable_pressure_upgrade;
221 static int64_t upgrade_pressure;
222 static int64_t downgrade_pressure;
223 static bool low_ram_device;
224 static bool kill_heaviest_task;
225 static unsigned long kill_timeout_ms;
226 static int pressure_after_kill_min_score;
227 static bool use_minfree_levels;
228 static bool per_app_memcg;
229 static int swap_free_low_percentage;
230 static int psi_partial_stall_ms;
231 static int psi_complete_stall_ms;
232 static int thrashing_limit_pct;
233 static int thrashing_limit_decay_pct;
234 static int thrashing_critical_pct;
235 static int swap_util_max;
236 static int64_t filecache_min_kb;
237 static int64_t stall_limit_critical;
238 static bool use_psi_monitors = false;
239 static int kpoll_fd;
240 static bool delay_monitors_until_boot;
241 static int direct_reclaim_threshold_ms;
242 static int swap_compression_ratio;
243 static int lowmem_min_oom_score;
244 static struct psi_threshold psi_thresholds[VMPRESS_LEVEL_COUNT] = {
245     { PSI_SOME, 70 },    /* 70ms out of 1sec for partial stall */
246     { PSI_SOME, 100 },   /* 100ms out of 1sec for partial stall */
247     { PSI_FULL, 70 },    /* 70ms out of 1sec for complete stall */
248 };
249 
250 static uint64_t mp_event_count;
251 
252 static android_log_context ctx;
253 static Reaper reaper;
254 static int reaper_comm_fd[2];
255 
256 enum polling_update {
257     POLLING_DO_NOT_CHANGE,
258     POLLING_START,
259     POLLING_PAUSE,
260     POLLING_RESUME,
261 };
262 
263 /*
264  * Data used for periodic polling for the memory state of the device.
265  * Note that when system is not polling poll_handler is set to NULL,
266  * when polling starts poll_handler gets set and is reset back to
267  * NULL when polling stops.
268  */
269 struct polling_params {
270     struct event_handler_info* poll_handler;
271     struct event_handler_info* paused_handler;
272     struct timespec poll_start_tm;
273     struct timespec last_poll_tm;
274     int polling_interval_ms;
275     enum polling_update update;
276 };
277 
278 /* data required to handle events */
279 struct event_handler_info {
280     int data;
281     void (*handler)(int data, uint32_t events, struct polling_params *poll_params);
282 };
283 
284 /* data required to handle socket events */
285 struct sock_event_handler_info {
286     int sock;
287     pid_t pid;
288     uint32_t async_event_mask;
289     struct event_handler_info handler_info;
290 };
291 
292 /* max supported number of data connections (AMS, init, tests) */
293 #define MAX_DATA_CONN 3
294 
295 /* socket event handler data */
296 static struct sock_event_handler_info ctrl_sock;
297 static struct sock_event_handler_info data_sock[MAX_DATA_CONN];
298 
299 /* vmpressure event handler data */
300 static struct event_handler_info vmpressure_hinfo[VMPRESS_LEVEL_COUNT];
301 
302 /*
303  * 1 ctrl listen socket, 3 ctrl data socket, 3 memory pressure levels,
304  * 1 lmk events + 1 fd to wait for process death + 1 fd to receive kill failure notifications
305  * + 1 fd to receive memevent_listener notifications
306  */
307 #define MAX_EPOLL_EVENTS (1 + MAX_DATA_CONN + VMPRESS_LEVEL_COUNT + 1 + 1 + 1 + 1)
308 static int epollfd;
309 static int maxevents;
310 
311 /* OOM score values used by both kernel and framework */
312 #define OOM_SCORE_ADJ_MIN       (-1000)
313 #define OOM_SCORE_ADJ_MAX       1000
314 
315 static std::array<int, MAX_TARGETS> lowmem_adj;
316 static std::array<int, MAX_TARGETS> lowmem_minfree;
317 static int lowmem_targets_size;
318 
319 /* Fields to parse in /proc/zoneinfo */
320 /* zoneinfo per-zone fields */
321 enum zoneinfo_zone_field {
322     ZI_ZONE_NR_FREE_PAGES = 0,
323     ZI_ZONE_MIN,
324     ZI_ZONE_LOW,
325     ZI_ZONE_HIGH,
326     ZI_ZONE_PRESENT,
327     ZI_ZONE_NR_FREE_CMA,
328     ZI_ZONE_FIELD_COUNT
329 };
330 
331 static const char* const zoneinfo_zone_field_names[ZI_ZONE_FIELD_COUNT] = {
332     "nr_free_pages",
333     "min",
334     "low",
335     "high",
336     "present",
337     "nr_free_cma",
338 };
339 
340 /* zoneinfo per-zone special fields */
341 enum zoneinfo_zone_spec_field {
342     ZI_ZONE_SPEC_PROTECTION = 0,
343     ZI_ZONE_SPEC_PAGESETS,
344     ZI_ZONE_SPEC_FIELD_COUNT,
345 };
346 
347 static const char* const zoneinfo_zone_spec_field_names[ZI_ZONE_SPEC_FIELD_COUNT] = {
348     "protection:",
349     "pagesets",
350 };
351 
352 /* see __MAX_NR_ZONES definition in kernel mmzone.h */
353 #define MAX_NR_ZONES 6
354 
355 union zoneinfo_zone_fields {
356     struct {
357         int64_t nr_free_pages;
358         int64_t min;
359         int64_t low;
360         int64_t high;
361         int64_t present;
362         int64_t nr_free_cma;
363     } field;
364     int64_t arr[ZI_ZONE_FIELD_COUNT];
365 };
366 
367 struct zoneinfo_zone {
368     union zoneinfo_zone_fields fields;
369     int64_t protection[MAX_NR_ZONES];
370     int64_t max_protection;
371 };
372 
373 /* zoneinfo per-node fields */
374 enum zoneinfo_node_field {
375     ZI_NODE_NR_INACTIVE_FILE = 0,
376     ZI_NODE_NR_ACTIVE_FILE,
377     ZI_NODE_FIELD_COUNT
378 };
379 
380 static const char* const zoneinfo_node_field_names[ZI_NODE_FIELD_COUNT] = {
381     "nr_inactive_file",
382     "nr_active_file",
383 };
384 
385 union zoneinfo_node_fields {
386     struct {
387         int64_t nr_inactive_file;
388         int64_t nr_active_file;
389     } field;
390     int64_t arr[ZI_NODE_FIELD_COUNT];
391 };
392 
393 struct zoneinfo_node {
394     int id;
395     int zone_count;
396     struct zoneinfo_zone zones[MAX_NR_ZONES];
397     union zoneinfo_node_fields fields;
398 };
399 
400 /* for now two memory nodes is more than enough */
401 #define MAX_NR_NODES 2
402 
403 struct zoneinfo {
404     int node_count;
405     struct zoneinfo_node nodes[MAX_NR_NODES];
406     int64_t totalreserve_pages;
407     int64_t total_inactive_file;
408     int64_t total_active_file;
409 };
410 
411 /* Fields to parse in /proc/meminfo */
412 enum meminfo_field {
413     MI_NR_FREE_PAGES = 0,
414     MI_CACHED,
415     MI_SWAP_CACHED,
416     MI_BUFFERS,
417     MI_SHMEM,
418     MI_UNEVICTABLE,
419     MI_TOTAL_SWAP,
420     MI_FREE_SWAP,
421     MI_ACTIVE_ANON,
422     MI_INACTIVE_ANON,
423     MI_ACTIVE_FILE,
424     MI_INACTIVE_FILE,
425     MI_SRECLAIMABLE,
426     MI_SUNRECLAIM,
427     MI_KERNEL_STACK,
428     MI_PAGE_TABLES,
429     MI_ION_HELP,
430     MI_ION_HELP_POOL,
431     MI_CMA_FREE,
432     MI_FIELD_COUNT
433 };
434 
435 static const char* const meminfo_field_names[MI_FIELD_COUNT] = {
436     "MemFree:",
437     "Cached:",
438     "SwapCached:",
439     "Buffers:",
440     "Shmem:",
441     "Unevictable:",
442     "SwapTotal:",
443     "SwapFree:",
444     "Active(anon):",
445     "Inactive(anon):",
446     "Active(file):",
447     "Inactive(file):",
448     "SReclaimable:",
449     "SUnreclaim:",
450     "KernelStack:",
451     "PageTables:",
452     "ION_heap:",
453     "ION_heap_pool:",
454     "CmaFree:",
455 };
456 
457 union meminfo {
458     struct {
459         int64_t nr_free_pages;
460         int64_t cached;
461         int64_t swap_cached;
462         int64_t buffers;
463         int64_t shmem;
464         int64_t unevictable;
465         int64_t total_swap;
466         int64_t free_swap;
467         int64_t active_anon;
468         int64_t inactive_anon;
469         int64_t active_file;
470         int64_t inactive_file;
471         int64_t sreclaimable;
472         int64_t sunreclaimable;
473         int64_t kernel_stack;
474         int64_t page_tables;
475         int64_t ion_heap;
476         int64_t ion_heap_pool;
477         int64_t cma_free;
478         /* fields below are calculated rather than read from the file */
479         int64_t nr_file_pages;
480         int64_t total_gpu_kb;
481         int64_t easy_available;
482     } field;
483     int64_t arr[MI_FIELD_COUNT];
484 };
485 
486 /* Fields to parse in /proc/vmstat */
487 enum vmstat_field {
488     VS_FREE_PAGES,
489     VS_INACTIVE_FILE,
490     VS_ACTIVE_FILE,
491     VS_WORKINGSET_REFAULT,
492     VS_WORKINGSET_REFAULT_FILE,
493     VS_PGSCAN_KSWAPD,
494     VS_PGSCAN_DIRECT,
495     VS_PGSCAN_DIRECT_THROTTLE,
496     VS_PGREFILL,
497     VS_FIELD_COUNT
498 };
499 
500 static const char* const vmstat_field_names[VS_FIELD_COUNT] = {
501     "nr_free_pages",
502     "nr_inactive_file",
503     "nr_active_file",
504     "workingset_refault",
505     "workingset_refault_file",
506     "pgscan_kswapd",
507     "pgscan_direct",
508     "pgscan_direct_throttle",
509     "pgrefill",
510 };
511 
512 union vmstat {
513     struct {
514         int64_t nr_free_pages;
515         int64_t nr_inactive_file;
516         int64_t nr_active_file;
517         int64_t workingset_refault;
518         int64_t workingset_refault_file;
519         int64_t pgscan_kswapd;
520         int64_t pgscan_direct;
521         int64_t pgscan_direct_throttle;
522         int64_t pgrefill;
523     } field;
524     int64_t arr[VS_FIELD_COUNT];
525 };
526 
527 enum field_match_result {
528     NO_MATCH,
529     PARSE_FAIL,
530     PARSE_SUCCESS
531 };
532 
533 struct adjslot_list {
534     struct adjslot_list *next;
535     struct adjslot_list *prev;
536 };
537 
538 struct proc {
539     struct adjslot_list asl;
540     int pid;
541     int pidfd;
542     uid_t uid;
543     int oomadj;
544     pid_t reg_pid; /* PID of the process that registered this record */
545     bool valid;
546     struct proc *pidhash_next;
547 };
548 
549 struct reread_data {
550     const char* const filename;
551     int fd;
552 };
553 
554 #define PIDHASH_SZ 1024
555 static struct proc *pidhash[PIDHASH_SZ];
556 #define pid_hashfn(x) ((((x) >> 8) ^ (x)) & (PIDHASH_SZ - 1))
557 
558 #define ADJTOSLOT(adj) ((adj) + -OOM_SCORE_ADJ_MIN)
559 #define ADJTOSLOT_COUNT (ADJTOSLOT(OOM_SCORE_ADJ_MAX) + 1)
560 
561 // protects procadjslot_list from concurrent access
562 static std::shared_mutex adjslot_list_lock;
563 // procadjslot_list should be modified only from the main thread while exclusively holding
564 // adjslot_list_lock. Readers from non-main threads should hold adjslot_list_lock shared lock.
565 static struct adjslot_list procadjslot_list[ADJTOSLOT_COUNT];
566 
567 #define MAX_DISTINCT_OOM_ADJ 32
568 #define KILLCNT_INVALID_IDX 0xFF
569 /*
570  * Because killcnt array is sparse a two-level indirection is used
571  * to keep the size small. killcnt_idx stores index of the element in
572  * killcnt array. Index KILLCNT_INVALID_IDX indicates an unused slot.
573  */
574 static uint8_t killcnt_idx[ADJTOSLOT_COUNT];
575 static uint16_t killcnt[MAX_DISTINCT_OOM_ADJ];
576 static int killcnt_free_idx = 0;
577 static uint32_t killcnt_total = 0;
578 
579 static int pagesize;
580 static long page_k; /* page size in kB */
581 
582 static bool update_props();
583 static bool init_monitors();
584 static void destroy_monitors();
585 static bool init_memevent_listener_monitoring();
586 
clamp(int low,int high,int value)587 static int clamp(int low, int high, int value) {
588     return std::max(std::min(value, high), low);
589 }
590 
parse_int64(const char * str,int64_t * ret)591 static bool parse_int64(const char* str, int64_t* ret) {
592     char* endptr;
593     long long val = strtoll(str, &endptr, 10);
594     if (str == endptr || val > INT64_MAX) {
595         return false;
596     }
597     *ret = (int64_t)val;
598     return true;
599 }
600 
find_field(const char * name,const char * const field_names[],int field_count)601 static int find_field(const char* name, const char* const field_names[], int field_count) {
602     for (int i = 0; i < field_count; i++) {
603         if (!strcmp(name, field_names[i])) {
604             return i;
605         }
606     }
607     return -1;
608 }
609 
match_field(const char * cp,const char * ap,const char * const field_names[],int field_count,int64_t * field,int * field_idx)610 static enum field_match_result match_field(const char* cp, const char* ap,
611                                    const char* const field_names[],
612                                    int field_count, int64_t* field,
613                                    int *field_idx) {
614     int i = find_field(cp, field_names, field_count);
615     if (i < 0) {
616         return NO_MATCH;
617     }
618     *field_idx = i;
619     return parse_int64(ap, field) ? PARSE_SUCCESS : PARSE_FAIL;
620 }
621 
622 /*
623  * Read file content from the beginning up to max_len bytes or EOF
624  * whichever happens first.
625  */
read_all(int fd,char * buf,size_t max_len)626 static ssize_t read_all(int fd, char *buf, size_t max_len)
627 {
628     ssize_t ret = 0;
629     off_t offset = 0;
630 
631     while (max_len > 0) {
632         ssize_t r = TEMP_FAILURE_RETRY(pread(fd, buf, max_len, offset));
633         if (r == 0) {
634             break;
635         }
636         if (r == -1) {
637             return -1;
638         }
639         ret += r;
640         buf += r;
641         offset += r;
642         max_len -= r;
643     }
644 
645     return ret;
646 }
647 
648 /*
649  * Read a new or already opened file from the beginning.
650  * If the file has not been opened yet data->fd should be set to -1.
651  * To be used with files which are read often and possibly during high
652  * memory pressure to minimize file opening which by itself requires kernel
653  * memory allocation and might result in a stall on memory stressed system.
654  */
reread_file(struct reread_data * data)655 static char *reread_file(struct reread_data *data) {
656     /* start with page-size buffer and increase if needed */
657     static ssize_t buf_size = pagesize;
658     static char *new_buf, *buf = NULL;
659     ssize_t size;
660 
661     if (data->fd == -1) {
662         /* First-time buffer initialization */
663         if (!buf && (buf = static_cast<char*>(malloc(buf_size))) == nullptr) {
664             return NULL;
665         }
666 
667         data->fd = TEMP_FAILURE_RETRY(open(data->filename, O_RDONLY | O_CLOEXEC));
668         if (data->fd < 0) {
669             ALOGE("%s open: %s", data->filename, strerror(errno));
670             return NULL;
671         }
672     }
673 
674     while (true) {
675         size = read_all(data->fd, buf, buf_size - 1);
676         if (size < 0) {
677             ALOGE("%s read: %s", data->filename, strerror(errno));
678             close(data->fd);
679             data->fd = -1;
680             return NULL;
681         }
682         if (size < buf_size - 1) {
683             break;
684         }
685         /*
686          * Since we are reading /proc files we can't use fstat to find out
687          * the real size of the file. Double the buffer size and keep retrying.
688          */
689         if ((new_buf = static_cast<char*>(realloc(buf, buf_size * 2))) == nullptr) {
690             errno = ENOMEM;
691             return NULL;
692         }
693         buf = new_buf;
694         buf_size *= 2;
695     }
696     buf[size] = 0;
697 
698     return buf;
699 }
700 
claim_record(struct proc * procp,pid_t pid)701 static bool claim_record(struct proc* procp, pid_t pid) {
702     if (procp->reg_pid == pid) {
703         /* Record already belongs to the registrant */
704         return true;
705     }
706     if (procp->reg_pid == 0) {
707         /* Old registrant is gone, claim the record */
708         procp->reg_pid = pid;
709         return true;
710     }
711     /* The record is owned by another registrant */
712     return false;
713 }
714 
remove_claims(pid_t pid)715 static void remove_claims(pid_t pid) {
716     int i;
717 
718     for (i = 0; i < PIDHASH_SZ; i++) {
719         struct proc* procp = pidhash[i];
720         while (procp) {
721             if (procp->reg_pid == pid) {
722                 procp->reg_pid = 0;
723             }
724             procp = procp->pidhash_next;
725         }
726     }
727 }
728 
ctrl_data_close(int dsock_idx)729 static void ctrl_data_close(int dsock_idx) {
730     struct epoll_event epev;
731 
732     ALOGI("closing lmkd data connection");
733     if (epoll_ctl(epollfd, EPOLL_CTL_DEL, data_sock[dsock_idx].sock, &epev) == -1) {
734         // Log a warning and keep going
735         ALOGW("epoll_ctl for data connection socket failed; errno=%d", errno);
736     }
737     maxevents--;
738 
739     close(data_sock[dsock_idx].sock);
740     data_sock[dsock_idx].sock = -1;
741 
742     /* Mark all records of the old registrant as unclaimed */
743     remove_claims(data_sock[dsock_idx].pid);
744 }
745 
ctrl_data_read(int dsock_idx,char * buf,size_t bufsz,struct ucred * sender_cred)746 static ssize_t ctrl_data_read(int dsock_idx, char* buf, size_t bufsz, struct ucred* sender_cred) {
747     struct iovec iov = {buf, bufsz};
748     char control[CMSG_SPACE(sizeof(struct ucred))];
749     struct msghdr hdr = {
750             NULL, 0, &iov, 1, control, sizeof(control), 0,
751     };
752     ssize_t ret;
753     ret = TEMP_FAILURE_RETRY(recvmsg(data_sock[dsock_idx].sock, &hdr, 0));
754     if (ret == -1) {
755         ALOGE("control data socket read failed; %s", strerror(errno));
756         return -1;
757     }
758     if (ret == 0) {
759         ALOGE("Got EOF on control data socket");
760         return -1;
761     }
762 
763     struct ucred* cred = NULL;
764     struct cmsghdr* cmsg = CMSG_FIRSTHDR(&hdr);
765     while (cmsg != NULL) {
766         if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_CREDENTIALS) {
767             cred = (struct ucred*)CMSG_DATA(cmsg);
768             break;
769         }
770         cmsg = CMSG_NXTHDR(&hdr, cmsg);
771     }
772 
773     if (cred == NULL) {
774         ALOGE("Failed to retrieve sender credentials");
775         /* Close the connection */
776         ctrl_data_close(dsock_idx);
777         return -1;
778     }
779 
780     memcpy(sender_cred, cred, sizeof(struct ucred));
781 
782     /* Store PID of the peer */
783     data_sock[dsock_idx].pid = cred->pid;
784 
785     return ret;
786 }
787 
ctrl_data_write(int dsock_idx,char * buf,size_t bufsz)788 static int ctrl_data_write(int dsock_idx, char* buf, size_t bufsz) {
789     int ret = 0;
790 
791     ret = TEMP_FAILURE_RETRY(write(data_sock[dsock_idx].sock, buf, bufsz));
792 
793     if (ret == -1) {
794         ALOGE("control data socket write failed; errno=%d", errno);
795     } else if (ret == 0) {
796         ALOGE("Got EOF on control data socket");
797         ret = -1;
798     }
799 
800     return ret;
801 }
802 
803 /*
804  * Write the pid/uid pair over the data socket, note: all active clients
805  * will receive this unsolicited notification.
806  */
ctrl_data_write_lmk_kill_occurred(pid_t pid,uid_t uid,int64_t rss_kb)807 static void ctrl_data_write_lmk_kill_occurred(pid_t pid, uid_t uid, int64_t rss_kb) {
808     LMKD_CTRL_PACKET packet;
809     size_t len = lmkd_pack_set_prockills(packet, pid, uid, static_cast<int>(rss_kb));
810 
811     for (int i = 0; i < MAX_DATA_CONN; i++) {
812         if (data_sock[i].sock >= 0 && data_sock[i].async_event_mask & 1 << LMK_ASYNC_EVENT_KILL) {
813             ctrl_data_write(i, (char*)packet, len);
814         }
815     }
816 }
817 
818 /*
819  * Write the kill_stat/memory_stat over the data socket to be propagated via AMS to statsd
820  */
stats_write_lmk_kill_occurred(struct kill_stat * kill_st,struct memory_stat * mem_st)821 static void stats_write_lmk_kill_occurred(struct kill_stat *kill_st,
822                                           struct memory_stat *mem_st) {
823     LMK_KILL_OCCURRED_PACKET packet;
824     const size_t len = lmkd_pack_set_kill_occurred(packet, kill_st, mem_st);
825     if (len == 0) {
826         return;
827     }
828 
829     for (int i = 0; i < MAX_DATA_CONN; i++) {
830         if (data_sock[i].sock >= 0 && data_sock[i].async_event_mask & 1 << LMK_ASYNC_EVENT_STAT) {
831             ctrl_data_write(i, packet, len);
832         }
833     }
834 
835 }
836 
stats_write_lmk_kill_occurred_pid(int pid,struct kill_stat * kill_st,struct memory_stat * mem_st)837 static void stats_write_lmk_kill_occurred_pid(int pid, struct kill_stat *kill_st,
838                                               struct memory_stat *mem_st) {
839     kill_st->taskname = stats_get_task_name(pid);
840     if (kill_st->taskname != NULL) {
841         stats_write_lmk_kill_occurred(kill_st, mem_st);
842     }
843 }
844 
poll_kernel(int poll_fd)845 static void poll_kernel(int poll_fd) {
846     if (poll_fd == -1) {
847         // not waiting
848         return;
849     }
850 
851     while (1) {
852         char rd_buf[256];
853         int bytes_read = TEMP_FAILURE_RETRY(pread(poll_fd, (void*)rd_buf, sizeof(rd_buf) - 1, 0));
854         if (bytes_read <= 0) break;
855         rd_buf[bytes_read] = '\0';
856 
857         int64_t pid;
858         int64_t uid;
859         int64_t group_leader_pid;
860         int64_t rss_in_pages;
861         struct memory_stat mem_st = {};
862         int16_t oom_score_adj;
863         int16_t min_score_adj;
864         int64_t starttime;
865         char* taskname = 0;
866         int64_t rss_kb;
867 
868         int fields_read =
869                 sscanf(rd_buf,
870                        "%" SCNd64 " %" SCNd64 " %" SCNd64 " %" SCNd64 " %" SCNd64 " %" SCNd64
871                        " %" SCNd16 " %" SCNd16 " %" SCNd64 "\n%m[^\n]",
872                        &pid, &uid, &group_leader_pid, &mem_st.pgfault, &mem_st.pgmajfault,
873                        &rss_in_pages, &oom_score_adj, &min_score_adj, &starttime, &taskname);
874 
875         /* only the death of the group leader process is logged */
876         if (fields_read == 10 && group_leader_pid == pid) {
877             mem_st.rss_in_bytes = rss_in_pages * pagesize;
878             rss_kb = mem_st.rss_in_bytes >> 10;
879             ctrl_data_write_lmk_kill_occurred((pid_t)pid, (uid_t)uid, rss_kb);
880             mem_st.process_start_time_ns = starttime * (NS_PER_SEC / sysconf(_SC_CLK_TCK));
881 
882             struct kill_stat kill_st = {
883                 .uid = static_cast<int32_t>(uid),
884                 .kill_reason = NONE,
885                 .oom_score = oom_score_adj,
886                 .min_oom_score = min_score_adj,
887                 .free_mem_kb = 0,
888                 .free_swap_kb = 0,
889             };
890             stats_write_lmk_kill_occurred_pid(pid, &kill_st, &mem_st);
891         }
892 
893         free(taskname);
894     }
895 }
896 
init_poll_kernel()897 static bool init_poll_kernel() {
898     kpoll_fd = TEMP_FAILURE_RETRY(open("/proc/lowmemorykiller", O_RDONLY | O_NONBLOCK | O_CLOEXEC));
899 
900     if (kpoll_fd < 0) {
901         ALOGE("kernel lmk event file could not be opened; errno=%d", errno);
902         return false;
903     }
904 
905     return true;
906 }
907 
pid_lookup(int pid)908 static struct proc *pid_lookup(int pid) {
909     struct proc *procp;
910 
911     for (procp = pidhash[pid_hashfn(pid)]; procp && procp->pid != pid;
912          procp = procp->pidhash_next)
913             ;
914 
915     return procp;
916 }
917 
adjslot_insert(struct adjslot_list * head,struct adjslot_list * new_element)918 static void adjslot_insert(struct adjslot_list *head, struct adjslot_list *new_element)
919 {
920     struct adjslot_list *next = head->next;
921     new_element->prev = head;
922     new_element->next = next;
923     next->prev = new_element;
924     head->next = new_element;
925 }
926 
adjslot_remove(struct adjslot_list * old)927 static void adjslot_remove(struct adjslot_list *old)
928 {
929     struct adjslot_list *prev = old->prev;
930     struct adjslot_list *next = old->next;
931     next->prev = prev;
932     prev->next = next;
933 }
934 
adjslot_tail(struct adjslot_list * head)935 static struct adjslot_list *adjslot_tail(struct adjslot_list *head) {
936     struct adjslot_list *asl = head->prev;
937 
938     return asl == head ? NULL : asl;
939 }
940 
941 // Should be modified only from the main thread.
proc_slot(struct proc * procp)942 static void proc_slot(struct proc *procp) {
943     int adjslot = ADJTOSLOT(procp->oomadj);
944     std::scoped_lock lock(adjslot_list_lock);
945 
946     adjslot_insert(&procadjslot_list[adjslot], &procp->asl);
947 }
948 
949 // Should be modified only from the main thread.
proc_unslot(struct proc * procp)950 static void proc_unslot(struct proc *procp) {
951     std::scoped_lock lock(adjslot_list_lock);
952 
953     adjslot_remove(&procp->asl);
954 }
955 
proc_insert(struct proc * procp)956 static void proc_insert(struct proc *procp) {
957     int hval = pid_hashfn(procp->pid);
958 
959     procp->pidhash_next = pidhash[hval];
960     pidhash[hval] = procp;
961     proc_slot(procp);
962 }
963 
964 // Can be called only from the main thread.
pid_remove(int pid)965 static int pid_remove(int pid) {
966     int hval = pid_hashfn(pid);
967     struct proc *procp;
968     struct proc *prevp;
969 
970     for (procp = pidhash[hval], prevp = NULL; procp && procp->pid != pid;
971          procp = procp->pidhash_next)
972             prevp = procp;
973 
974     if (!procp)
975         return -1;
976 
977     if (!prevp)
978         pidhash[hval] = procp->pidhash_next;
979     else
980         prevp->pidhash_next = procp->pidhash_next;
981 
982     proc_unslot(procp);
983     /*
984      * Close pidfd here if we are not waiting for corresponding process to die,
985      * in which case stop_wait_for_proc_kill() will close the pidfd later
986      */
987     if (procp->pidfd >= 0 && procp->pidfd != last_kill_pid_or_fd) {
988         close(procp->pidfd);
989     }
990     free(procp);
991     return 0;
992 }
993 
pid_invalidate(int pid)994 static void pid_invalidate(int pid) {
995     std::shared_lock lock(adjslot_list_lock);
996     struct proc *procp = pid_lookup(pid);
997 
998     if (procp) {
999         procp->valid = false;
1000     }
1001 }
1002 
1003 /*
1004  * Write a string to a file.
1005  * Returns false if the file does not exist.
1006  */
writefilestring(const char * path,const char * s,bool err_if_missing)1007 static bool writefilestring(const char *path, const char *s,
1008                             bool err_if_missing) {
1009     int fd = open(path, O_WRONLY | O_CLOEXEC);
1010     ssize_t len = strlen(s);
1011     ssize_t ret;
1012 
1013     if (fd < 0) {
1014         if (err_if_missing) {
1015             ALOGE("Error opening %s; errno=%d", path, errno);
1016         }
1017         return false;
1018     }
1019 
1020     ret = TEMP_FAILURE_RETRY(write(fd, s, len));
1021     if (ret < 0) {
1022         ALOGE("Error writing %s; errno=%d", path, errno);
1023     } else if (ret < len) {
1024         ALOGE("Short write on %s; length=%zd", path, ret);
1025     }
1026 
1027     close(fd);
1028     return true;
1029 }
1030 
get_time_diff_ms(struct timespec * from,struct timespec * to)1031 static inline long get_time_diff_ms(struct timespec *from,
1032                                     struct timespec *to) {
1033     return (to->tv_sec - from->tv_sec) * (long)MS_PER_SEC +
1034            (to->tv_nsec - from->tv_nsec) / (long)NS_PER_MS;
1035 }
1036 
1037 /* Reads /proc/pid/status into buf. */
read_proc_status(int pid,char * buf,size_t buf_sz)1038 static bool read_proc_status(int pid, char *buf, size_t buf_sz) {
1039     char path[PROCFS_PATH_MAX];
1040     int fd;
1041     ssize_t size;
1042 
1043     snprintf(path, PROCFS_PATH_MAX, "/proc/%d/status", pid);
1044     fd = open(path, O_RDONLY | O_CLOEXEC);
1045     if (fd < 0) {
1046         return false;
1047     }
1048 
1049     size = read_all(fd, buf, buf_sz - 1);
1050     close(fd);
1051     if (size <= 0) {
1052         return false;
1053     }
1054     buf[size] = 0;
1055     return true;
1056 }
1057 
1058 /* Looks for tag in buf and parses the first integer */
parse_status_tag(char * buf,const char * tag,int64_t * out)1059 static bool parse_status_tag(char *buf, const char *tag, int64_t *out) {
1060     char *pos = buf;
1061     while (true) {
1062         pos = strstr(pos, tag);
1063         /* Stop if tag not found or found at the line beginning */
1064         if (pos == NULL || pos == buf || pos[-1] == '\n') {
1065             break;
1066         }
1067         pos++;
1068     }
1069 
1070     if (pos == NULL) {
1071         return false;
1072     }
1073 
1074     pos += strlen(tag);
1075     while (*pos == ' ') ++pos;
1076     return parse_int64(pos, out);
1077 }
1078 
proc_get_size(int pid)1079 static int proc_get_size(int pid) {
1080     char path[PROCFS_PATH_MAX];
1081     char line[LINE_MAX];
1082     int fd;
1083     int rss = 0;
1084     int total;
1085     ssize_t ret;
1086 
1087     /* gid containing AID_READPROC required */
1088     snprintf(path, PROCFS_PATH_MAX, "/proc/%d/statm", pid);
1089     fd = open(path, O_RDONLY | O_CLOEXEC);
1090     if (fd == -1)
1091         return -1;
1092 
1093     ret = read_all(fd, line, sizeof(line) - 1);
1094     if (ret < 0) {
1095         close(fd);
1096         return -1;
1097     }
1098     line[ret] = '\0';
1099 
1100     sscanf(line, "%d %d ", &total, &rss);
1101     close(fd);
1102     return rss;
1103 }
1104 
proc_get_name(int pid,char * buf,size_t buf_size)1105 static char *proc_get_name(int pid, char *buf, size_t buf_size) {
1106     char path[PROCFS_PATH_MAX];
1107     int fd;
1108     char *cp;
1109     ssize_t ret;
1110 
1111     /* gid containing AID_READPROC required */
1112     snprintf(path, PROCFS_PATH_MAX, "/proc/%d/cmdline", pid);
1113     fd = open(path, O_RDONLY | O_CLOEXEC);
1114     if (fd == -1) {
1115         return NULL;
1116     }
1117     ret = read_all(fd, buf, buf_size - 1);
1118     close(fd);
1119     if (ret <= 0) {
1120         return NULL;
1121     }
1122     buf[ret] = '\0';
1123 
1124     cp = strchr(buf, ' ');
1125     if (cp) {
1126         *cp = '\0';
1127     }
1128 
1129     return buf;
1130 }
1131 
register_oom_adj_proc(const struct lmk_procprio & proc,struct ucred * cred)1132 static void register_oom_adj_proc(const struct lmk_procprio& proc, struct ucred* cred) {
1133     char val[20];
1134     int soft_limit_mult;
1135     bool is_system_server;
1136     struct passwd *pwdrec;
1137     struct proc* procp;
1138     int oom_adj_score = proc.oomadj;
1139 
1140     /* lmkd should not change soft limits for services */
1141     if (proc.ptype == PROC_TYPE_APP && per_app_memcg) {
1142         if (proc.oomadj >= 900) {
1143             soft_limit_mult = 0;
1144         } else if (proc.oomadj >= 800) {
1145             soft_limit_mult = 0;
1146         } else if (proc.oomadj >= 700) {
1147             soft_limit_mult = 0;
1148         } else if (proc.oomadj >= 600) {
1149             // Launcher should be perceptible, don't kill it.
1150             oom_adj_score = 200;
1151             soft_limit_mult = 1;
1152         } else if (proc.oomadj >= 500) {
1153             soft_limit_mult = 0;
1154         } else if (proc.oomadj >= 400) {
1155             soft_limit_mult = 0;
1156         } else if (proc.oomadj >= 300) {
1157             soft_limit_mult = 1;
1158         } else if (proc.oomadj >= 200) {
1159             soft_limit_mult = 8;
1160         } else if (proc.oomadj >= 100) {
1161             soft_limit_mult = 10;
1162         } else if (proc.oomadj >= 0) {
1163             soft_limit_mult = 20;
1164         } else {
1165             // Persistent processes will have a large
1166             // soft limit 512MB.
1167             soft_limit_mult = 64;
1168         }
1169 
1170         std::string soft_limit_path;
1171         if (!CgroupGetAttributePathForTask("MemSoftLimit", proc.pid, &soft_limit_path)) {
1172             ALOGE("Querying MemSoftLimit path failed");
1173             return;
1174         }
1175 
1176         snprintf(val, sizeof(val), "%d", soft_limit_mult * EIGHT_MEGA);
1177 
1178         /*
1179          * system_server process has no memcg under /dev/memcg/apps but should be
1180          * registered with lmkd. This is the best way so far to identify it.
1181          */
1182         is_system_server = (oom_adj_score == SYSTEM_ADJ && (pwdrec = getpwnam("system")) != NULL &&
1183                             proc.uid == pwdrec->pw_uid);
1184         writefilestring(soft_limit_path.c_str(), val, !is_system_server);
1185     }
1186 
1187     procp = pid_lookup(proc.pid);
1188     if (!procp) {
1189         int pidfd = -1;
1190 
1191         if (pidfd_supported) {
1192             pidfd = TEMP_FAILURE_RETRY(pidfd_open(proc.pid, 0));
1193             if (pidfd < 0) {
1194                 ALOGE("pidfd_open for pid %d failed; errno=%d", proc.pid, errno);
1195                 return;
1196             }
1197         }
1198 
1199         procp = static_cast<struct proc*>(calloc(1, sizeof(struct proc)));
1200         if (!procp) {
1201             // Oh, the irony.  May need to rebuild our state.
1202             return;
1203         }
1204 
1205         procp->pid = proc.pid;
1206         procp->pidfd = pidfd;
1207         procp->uid = proc.uid;
1208         procp->reg_pid = cred->pid;
1209         procp->oomadj = oom_adj_score;
1210         procp->valid = true;
1211         proc_insert(procp);
1212     } else {
1213         if (!claim_record(procp, cred->pid)) {
1214             char buf[LINE_MAX];
1215             char *taskname = proc_get_name(cred->pid, buf, sizeof(buf));
1216             /* Only registrant of the record can remove it */
1217             ALOGE("%s (%d, %d) attempts to modify a process registered by another client",
1218                 taskname ? taskname : "A process ", cred->uid, cred->pid);
1219             return;
1220         }
1221         proc_unslot(procp);
1222         procp->oomadj = oom_adj_score;
1223         proc_slot(procp);
1224     }
1225 }
1226 
apply_proc_prio(const struct lmk_procprio & params,struct ucred * cred)1227 static void apply_proc_prio(const struct lmk_procprio& params, struct ucred* cred) {
1228     char path[PROCFS_PATH_MAX];
1229     char val[20];
1230     int64_t tgid;
1231     char buf[pagesize];
1232 
1233     if (params.oomadj < OOM_SCORE_ADJ_MIN || params.oomadj > OOM_SCORE_ADJ_MAX) {
1234         ALOGE("Invalid PROCPRIO oomadj argument %d", params.oomadj);
1235         return;
1236     }
1237 
1238     if (params.ptype < PROC_TYPE_FIRST || params.ptype >= PROC_TYPE_COUNT) {
1239         ALOGE("Invalid PROCPRIO process type argument %d", params.ptype);
1240         return;
1241     }
1242 
1243     /* Check if registered process is a thread group leader */
1244     if (read_proc_status(params.pid, buf, sizeof(buf))) {
1245         if (parse_status_tag(buf, PROC_STATUS_TGID_FIELD, &tgid) && tgid != params.pid) {
1246             ALOGE("Attempt to register a task that is not a thread group leader "
1247                   "(tid %d, tgid %" PRId64 ")",
1248                   params.pid, tgid);
1249             return;
1250         }
1251     }
1252 
1253     /* gid containing AID_READPROC required */
1254     /* CAP_SYS_RESOURCE required */
1255     /* CAP_DAC_OVERRIDE required */
1256     snprintf(path, sizeof(path), "/proc/%d/oom_score_adj", params.pid);
1257     snprintf(val, sizeof(val), "%d", params.oomadj);
1258     if (!writefilestring(path, val, false)) {
1259         ALOGW("Failed to open %s; errno=%d: process %d might have been killed", path, errno,
1260               params.pid);
1261         /* If this file does not exist the process is dead. */
1262         return;
1263     }
1264 
1265     if (use_inkernel_interface) {
1266         stats_store_taskname(params.pid, proc_get_name(params.pid, path, sizeof(path)));
1267         return;
1268     }
1269 
1270     register_oom_adj_proc(params, cred);
1271 }
1272 
cmd_procprio(LMKD_CTRL_PACKET packet,int field_count,struct ucred * cred)1273 static void cmd_procprio(LMKD_CTRL_PACKET packet, int field_count, struct ucred* cred) {
1274     struct lmk_procprio proc_prio;
1275 
1276     lmkd_pack_get_procprio(packet, field_count, &proc_prio);
1277     apply_proc_prio(proc_prio, cred);
1278 }
1279 
cmd_procremove(LMKD_CTRL_PACKET packet,struct ucred * cred)1280 static void cmd_procremove(LMKD_CTRL_PACKET packet, struct ucred *cred) {
1281     struct lmk_procremove params;
1282     struct proc *procp;
1283 
1284     lmkd_pack_get_procremove(packet, &params);
1285 
1286     if (use_inkernel_interface) {
1287         /*
1288          * Perform an extra check before the pid is removed, after which it
1289          * will be impossible for poll_kernel to get the taskname. poll_kernel()
1290          * is potentially a long-running blocking function; however this method
1291          * handles AMS requests but does not block AMS.
1292          */
1293         poll_kernel(kpoll_fd);
1294 
1295         stats_remove_taskname(params.pid);
1296         return;
1297     }
1298 
1299     procp = pid_lookup(params.pid);
1300     if (!procp) {
1301         return;
1302     }
1303 
1304     if (!claim_record(procp, cred->pid)) {
1305         char buf[LINE_MAX];
1306         char *taskname = proc_get_name(cred->pid, buf, sizeof(buf));
1307         /* Only registrant of the record can remove it */
1308         ALOGE("%s (%d, %d) attempts to unregister a process registered by another client",
1309             taskname ? taskname : "A process ", cred->uid, cred->pid);
1310         return;
1311     }
1312 
1313     /*
1314      * WARNING: After pid_remove() procp is freed and can't be used!
1315      * Therefore placed at the end of the function.
1316      */
1317     pid_remove(params.pid);
1318 }
1319 
cmd_procpurge(struct ucred * cred)1320 static void cmd_procpurge(struct ucred *cred) {
1321     int i;
1322     struct proc *procp;
1323     struct proc *next;
1324 
1325     if (use_inkernel_interface) {
1326         stats_purge_tasknames();
1327         return;
1328     }
1329 
1330     for (i = 0; i < PIDHASH_SZ; i++) {
1331         procp = pidhash[i];
1332         while (procp) {
1333             next = procp->pidhash_next;
1334             /* Purge only records created by the requestor */
1335             if (claim_record(procp, cred->pid)) {
1336                 pid_remove(procp->pid);
1337             }
1338             procp = next;
1339         }
1340     }
1341 }
1342 
cmd_subscribe(int dsock_idx,LMKD_CTRL_PACKET packet)1343 static void cmd_subscribe(int dsock_idx, LMKD_CTRL_PACKET packet) {
1344     struct lmk_subscribe params;
1345 
1346     lmkd_pack_get_subscribe(packet, &params);
1347     data_sock[dsock_idx].async_event_mask |= 1 << params.evt_type;
1348 }
1349 
inc_killcnt(int oomadj)1350 static void inc_killcnt(int oomadj) {
1351     int slot = ADJTOSLOT(oomadj);
1352     uint8_t idx = killcnt_idx[slot];
1353 
1354     if (idx == KILLCNT_INVALID_IDX) {
1355         /* index is not assigned for this oomadj */
1356         if (killcnt_free_idx < MAX_DISTINCT_OOM_ADJ) {
1357             killcnt_idx[slot] = killcnt_free_idx;
1358             killcnt[killcnt_free_idx] = 1;
1359             killcnt_free_idx++;
1360         } else {
1361             ALOGW("Number of distinct oomadj levels exceeds %d",
1362                 MAX_DISTINCT_OOM_ADJ);
1363         }
1364     } else {
1365         /*
1366          * wraparound is highly unlikely and is detectable using total
1367          * counter because it has to be equal to the sum of all counters
1368          */
1369         killcnt[idx]++;
1370     }
1371     /* increment total kill counter */
1372     killcnt_total++;
1373 }
1374 
get_killcnt(int min_oomadj,int max_oomadj)1375 static int get_killcnt(int min_oomadj, int max_oomadj) {
1376     int slot;
1377     int count = 0;
1378 
1379     if (min_oomadj > max_oomadj)
1380         return 0;
1381 
1382     /* special case to get total kill count */
1383     if (min_oomadj > OOM_SCORE_ADJ_MAX)
1384         return killcnt_total;
1385 
1386     while (min_oomadj <= max_oomadj &&
1387            (slot = ADJTOSLOT(min_oomadj)) < ADJTOSLOT_COUNT) {
1388         uint8_t idx = killcnt_idx[slot];
1389         if (idx != KILLCNT_INVALID_IDX) {
1390             count += killcnt[idx];
1391         }
1392         min_oomadj++;
1393     }
1394 
1395     return count;
1396 }
1397 
cmd_getkillcnt(LMKD_CTRL_PACKET packet)1398 static int cmd_getkillcnt(LMKD_CTRL_PACKET packet) {
1399     struct lmk_getkillcnt params;
1400 
1401     if (use_inkernel_interface) {
1402         /* kernel driver does not expose this information */
1403         return 0;
1404     }
1405 
1406     lmkd_pack_get_getkillcnt(packet, &params);
1407 
1408     return get_killcnt(params.min_oomadj, params.max_oomadj);
1409 }
1410 
cmd_target(int ntargets,LMKD_CTRL_PACKET packet)1411 static void cmd_target(int ntargets, LMKD_CTRL_PACKET packet) {
1412     int i;
1413     struct lmk_target target;
1414     char minfree_str[PROPERTY_VALUE_MAX];
1415     char *pstr = minfree_str;
1416     char *pend = minfree_str + sizeof(minfree_str);
1417     static struct timespec last_req_tm;
1418     struct timespec curr_tm;
1419 
1420     if (ntargets < 1 || ntargets > (int)lowmem_adj.size()) {
1421         return;
1422     }
1423 
1424     /*
1425      * Ratelimit minfree updates to once per TARGET_UPDATE_MIN_INTERVAL_MS
1426      * to prevent DoS attacks
1427      */
1428     if (clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm) != 0) {
1429         ALOGE("Failed to get current time");
1430         return;
1431     }
1432 
1433     if (get_time_diff_ms(&last_req_tm, &curr_tm) <
1434         TARGET_UPDATE_MIN_INTERVAL_MS) {
1435         ALOGE("Ignoring frequent updated to lmkd limits");
1436         return;
1437     }
1438 
1439     last_req_tm = curr_tm;
1440 
1441     for (i = 0; i < ntargets; i++) {
1442         lmkd_pack_get_target(packet, i, &target);
1443         lowmem_minfree[i] = target.minfree;
1444         lowmem_adj[i] = target.oom_adj_score;
1445 
1446         pstr += snprintf(pstr, pend - pstr, "%d:%d,", target.minfree,
1447             target.oom_adj_score);
1448         if (pstr >= pend) {
1449             /* if no more space in the buffer then terminate the loop */
1450             pstr = pend;
1451             break;
1452         }
1453     }
1454 
1455     lowmem_targets_size = ntargets;
1456 
1457     /* Override the last extra comma */
1458     pstr[-1] = '\0';
1459     property_set("sys.lmk.minfree_levels", minfree_str);
1460 
1461     if (has_inkernel_module) {
1462         char minfreestr[128];
1463         char killpriostr[128];
1464 
1465         minfreestr[0] = '\0';
1466         killpriostr[0] = '\0';
1467 
1468         for (i = 0; i < lowmem_targets_size; i++) {
1469             char val[40];
1470 
1471             if (i) {
1472                 strlcat(minfreestr, ",", sizeof(minfreestr));
1473                 strlcat(killpriostr, ",", sizeof(killpriostr));
1474             }
1475 
1476             snprintf(val, sizeof(val), "%d", use_inkernel_interface ? lowmem_minfree[i] : 0);
1477             strlcat(minfreestr, val, sizeof(minfreestr));
1478             snprintf(val, sizeof(val), "%d", use_inkernel_interface ? lowmem_adj[i] : 0);
1479             strlcat(killpriostr, val, sizeof(killpriostr));
1480         }
1481 
1482         writefilestring(INKERNEL_MINFREE_PATH, minfreestr, true);
1483         writefilestring(INKERNEL_ADJ_PATH, killpriostr, true);
1484     }
1485 }
1486 
cmd_procs_prio(LMKD_CTRL_PACKET packet,const int field_count,struct ucred * cred)1487 static void cmd_procs_prio(LMKD_CTRL_PACKET packet, const int field_count, struct ucred* cred) {
1488     struct lmk_procs_prio params;
1489 
1490     const int procs_count = lmkd_pack_get_procs_prio(packet, &params, field_count);
1491     if (procs_count < 0) {
1492         ALOGE("LMK_PROCS_PRIO received invalid packet format");
1493         return;
1494     }
1495 
1496     for (int i = 0; i < procs_count; i++) {
1497         apply_proc_prio(params.procs[i], cred);
1498     }
1499 }
1500 
ctrl_command_handler(int dsock_idx)1501 static void ctrl_command_handler(int dsock_idx) {
1502     LMKD_CTRL_PACKET packet;
1503     struct ucred cred;
1504     int len;
1505     enum lmk_cmd cmd;
1506     int nargs;
1507     int targets;
1508     int kill_cnt;
1509     int result;
1510 
1511     len = ctrl_data_read(dsock_idx, (char *)packet, CTRL_PACKET_MAX_SIZE, &cred);
1512     if (len <= 0)
1513         return;
1514 
1515     if (len < (int)sizeof(int)) {
1516         ALOGE("Wrong control socket read length len=%d", len);
1517         return;
1518     }
1519 
1520     cmd = lmkd_pack_get_cmd(packet);
1521     nargs = len / sizeof(int) - 1;
1522     if (nargs < 0)
1523         goto wronglen;
1524 
1525     switch(cmd) {
1526     case LMK_TARGET:
1527         targets = nargs / 2;
1528         if (nargs & 0x1 || targets > (int)lowmem_adj.size()) {
1529             goto wronglen;
1530         }
1531         cmd_target(targets, packet);
1532         break;
1533     case LMK_PROCPRIO:
1534         /* process type field is optional for backward compatibility */
1535         if (nargs < 3 || nargs > 4)
1536             goto wronglen;
1537         cmd_procprio(packet, nargs, &cred);
1538         break;
1539     case LMK_PROCREMOVE:
1540         if (nargs != 1)
1541             goto wronglen;
1542         cmd_procremove(packet, &cred);
1543         break;
1544     case LMK_PROCPURGE:
1545         if (nargs != 0)
1546             goto wronglen;
1547         cmd_procpurge(&cred);
1548         break;
1549     case LMK_GETKILLCNT:
1550         if (nargs != 2)
1551             goto wronglen;
1552         kill_cnt = cmd_getkillcnt(packet);
1553         len = lmkd_pack_set_getkillcnt_repl(packet, kill_cnt);
1554         if (ctrl_data_write(dsock_idx, (char *)packet, len) != len)
1555             return;
1556         break;
1557     case LMK_SUBSCRIBE:
1558         if (nargs != 1)
1559             goto wronglen;
1560         cmd_subscribe(dsock_idx, packet);
1561         break;
1562     case LMK_PROCKILL:
1563         /* This command code is NOT expected at all */
1564         ALOGE("Received unexpected command code %d", cmd);
1565         break;
1566     case LMK_UPDATE_PROPS:
1567         if (nargs != 0)
1568             goto wronglen;
1569         result = -1;
1570         if (update_props()) {
1571             if (!use_inkernel_interface && monitors_initialized) {
1572                 /* Reinitialize monitors to apply new settings */
1573                 destroy_monitors();
1574                 if (init_monitors()) {
1575                     result = 0;
1576                 }
1577             } else {
1578                 result = 0;
1579             }
1580 
1581             if (direct_reclaim_threshold_ms > 0 && !memevent_listener) {
1582                 ALOGW("Kernel support for direct_reclaim_threshold_ms is not found");
1583                 direct_reclaim_threshold_ms = 0;
1584             }
1585         }
1586 
1587         len = lmkd_pack_set_update_props_repl(packet, result);
1588         if (ctrl_data_write(dsock_idx, (char *)packet, len) != len) {
1589             ALOGE("Failed to report operation results");
1590         }
1591         if (!result) {
1592             ALOGI("Properties reinitilized");
1593         } else {
1594             /* New settings can't be supported, crash to be restarted */
1595             ALOGE("New configuration is not supported. Exiting...");
1596             exit(1);
1597         }
1598         break;
1599     case LMK_START_MONITORING:
1600         if (nargs != 0)
1601             goto wronglen;
1602         // Registration is needed only if it was skipped earlier.
1603         if (monitors_initialized)
1604             return;
1605         if (!property_get_bool("sys.boot_completed", false)) {
1606             ALOGE("LMK_START_MONITORING cannot be handled before boot completed");
1607             return;
1608         }
1609 
1610         if (!init_monitors()) {
1611             /* Failure to start psi monitoring, crash to be restarted */
1612             ALOGE("Failure to initialize monitoring. Exiting...");
1613             exit(1);
1614         }
1615         ALOGI("Initialized monitors after boot completed.");
1616         break;
1617     case LMK_BOOT_COMPLETED:
1618         if (nargs != 0) goto wronglen;
1619 
1620         if (boot_completed_handled) {
1621             /* Notify we have already handled post boot-up operations */
1622             result = 1;
1623         } else if (!property_get_bool("sys.boot_completed", false)) {
1624             ALOGE("LMK_BOOT_COMPLETED cannot be handled before boot completed");
1625             result = -1;
1626         } else {
1627             /*
1628              * Initialize the memevent listener after boot is completed to prevent
1629              * waiting, during boot-up, for BPF programs to be loaded.
1630              */
1631             if (init_memevent_listener_monitoring()) {
1632                 ALOGI("Using memevents for direct reclaim and kswapd detection");
1633             } else {
1634                 ALOGI("Using vmstats for direct reclaim and kswapd detection");
1635                 if (direct_reclaim_threshold_ms > 0) {
1636                     ALOGW("Kernel support for direct_reclaim_threshold_ms is not found");
1637                     direct_reclaim_threshold_ms = 0;
1638                 }
1639             }
1640             result = 0;
1641             boot_completed_handled = true;
1642         }
1643 
1644         len = lmkd_pack_set_boot_completed_notif_repl(packet, result);
1645         if (ctrl_data_write(dsock_idx, (char*)packet, len) != len) {
1646             ALOGE("Failed to report boot-completed operation results");
1647         }
1648         break;
1649     case LMK_PROCS_PRIO:
1650         cmd_procs_prio(packet, nargs, &cred);
1651         break;
1652     default:
1653         ALOGE("Received unknown command code %d", cmd);
1654         return;
1655     }
1656 
1657     return;
1658 
1659 wronglen:
1660     ALOGE("Wrong control socket read length cmd=%d len=%d", cmd, len);
1661 }
1662 
ctrl_data_handler(int data,uint32_t events,struct polling_params * poll_params __unused)1663 static void ctrl_data_handler(int data, uint32_t events,
1664                               struct polling_params *poll_params __unused) {
1665     if (events & EPOLLIN) {
1666         ctrl_command_handler(data);
1667     }
1668 }
1669 
get_free_dsock()1670 static int get_free_dsock() {
1671     for (int i = 0; i < MAX_DATA_CONN; i++) {
1672         if (data_sock[i].sock < 0) {
1673             return i;
1674         }
1675     }
1676     return -1;
1677 }
1678 
ctrl_connect_handler(int data __unused,uint32_t events __unused,struct polling_params * poll_params __unused)1679 static void ctrl_connect_handler(int data __unused, uint32_t events __unused,
1680                                  struct polling_params *poll_params __unused) {
1681     struct epoll_event epev;
1682     int free_dscock_idx = get_free_dsock();
1683 
1684     if (free_dscock_idx < 0) {
1685         /*
1686          * Number of data connections exceeded max supported. This should not
1687          * happen but if it does we drop all existing connections and accept
1688          * the new one. This prevents inactive connections from monopolizing
1689          * data socket and if we drop ActivityManager connection it will
1690          * immediately reconnect.
1691          */
1692         for (int i = 0; i < MAX_DATA_CONN; i++) {
1693             ctrl_data_close(i);
1694         }
1695         free_dscock_idx = 0;
1696     }
1697 
1698     data_sock[free_dscock_idx].sock = accept(ctrl_sock.sock, NULL, NULL);
1699     if (data_sock[free_dscock_idx].sock < 0) {
1700         ALOGE("lmkd control socket accept failed; errno=%d", errno);
1701         return;
1702     }
1703 
1704     ALOGI("lmkd data connection established");
1705     /* use data to store data connection idx */
1706     data_sock[free_dscock_idx].handler_info.data = free_dscock_idx;
1707     data_sock[free_dscock_idx].handler_info.handler = ctrl_data_handler;
1708     data_sock[free_dscock_idx].async_event_mask = 0;
1709     epev.events = EPOLLIN;
1710     epev.data.ptr = (void *)&(data_sock[free_dscock_idx].handler_info);
1711     if (epoll_ctl(epollfd, EPOLL_CTL_ADD, data_sock[free_dscock_idx].sock, &epev) == -1) {
1712         ALOGE("epoll_ctl for data connection socket failed; errno=%d", errno);
1713         ctrl_data_close(free_dscock_idx);
1714         return;
1715     }
1716     maxevents++;
1717 }
1718 
1719 /*
1720  * /proc/zoneinfo parsing routines
1721  * Expected file format is:
1722  *
1723  *   Node <node_id>, zone   <zone_name>
1724  *   (
1725  *    per-node stats
1726  *       (<per-node field name> <value>)+
1727  *   )?
1728  *   (pages free     <value>
1729  *       (<per-zone field name> <value>)+
1730  *    pagesets
1731  *       (<unused fields>)*
1732  *   )+
1733  *   ...
1734  */
zoneinfo_parse_protection(char * buf,struct zoneinfo_zone * zone)1735 static void zoneinfo_parse_protection(char *buf, struct zoneinfo_zone *zone) {
1736     int zone_idx;
1737     int64_t max = 0;
1738     char *save_ptr;
1739 
1740     for (buf = strtok_r(buf, "(), ", &save_ptr), zone_idx = 0;
1741          buf && zone_idx < MAX_NR_ZONES;
1742          buf = strtok_r(NULL, "), ", &save_ptr), zone_idx++) {
1743         long long zoneval = strtoll(buf, &buf, 0);
1744         if (zoneval > max) {
1745             max = (zoneval > INT64_MAX) ? INT64_MAX : zoneval;
1746         }
1747         zone->protection[zone_idx] = zoneval;
1748     }
1749     zone->max_protection = max;
1750 }
1751 
zoneinfo_parse_zone(char ** buf,struct zoneinfo_zone * zone)1752 static int zoneinfo_parse_zone(char **buf, struct zoneinfo_zone *zone) {
1753     for (char *line = strtok_r(NULL, "\n", buf); line;
1754          line = strtok_r(NULL, "\n", buf)) {
1755         char *cp;
1756         char *ap;
1757         char *save_ptr;
1758         int64_t val;
1759         int field_idx;
1760         enum field_match_result match_res;
1761 
1762         cp = strtok_r(line, " ", &save_ptr);
1763         if (!cp) {
1764             return false;
1765         }
1766 
1767         field_idx = find_field(cp, zoneinfo_zone_spec_field_names, ZI_ZONE_SPEC_FIELD_COUNT);
1768         if (field_idx >= 0) {
1769             /* special field */
1770             if (field_idx == ZI_ZONE_SPEC_PAGESETS) {
1771                 /* no mode fields we are interested in */
1772                 return true;
1773             }
1774 
1775             /* protection field */
1776             ap = strtok_r(NULL, ")", &save_ptr);
1777             if (ap) {
1778                 zoneinfo_parse_protection(ap, zone);
1779             }
1780             continue;
1781         }
1782 
1783         ap = strtok_r(NULL, " ", &save_ptr);
1784         if (!ap) {
1785             continue;
1786         }
1787 
1788         match_res = match_field(cp, ap, zoneinfo_zone_field_names, ZI_ZONE_FIELD_COUNT,
1789             &val, &field_idx);
1790         if (match_res == PARSE_FAIL) {
1791             return false;
1792         }
1793         if (match_res == PARSE_SUCCESS) {
1794             zone->fields.arr[field_idx] = val;
1795         }
1796         if (field_idx == ZI_ZONE_PRESENT && val == 0) {
1797             /* zone is not populated, stop parsing it */
1798             return true;
1799         }
1800     }
1801     return false;
1802 }
1803 
zoneinfo_parse_node(char ** buf,struct zoneinfo_node * node)1804 static int zoneinfo_parse_node(char **buf, struct zoneinfo_node *node) {
1805     int fields_to_match = ZI_NODE_FIELD_COUNT;
1806 
1807     for (char *line = strtok_r(NULL, "\n", buf); line;
1808          line = strtok_r(NULL, "\n", buf)) {
1809         char *cp;
1810         char *ap;
1811         char *save_ptr;
1812         int64_t val;
1813         int field_idx;
1814         enum field_match_result match_res;
1815 
1816         cp = strtok_r(line, " ", &save_ptr);
1817         if (!cp) {
1818             return false;
1819         }
1820 
1821         ap = strtok_r(NULL, " ", &save_ptr);
1822         if (!ap) {
1823             return false;
1824         }
1825 
1826         match_res = match_field(cp, ap, zoneinfo_node_field_names, ZI_NODE_FIELD_COUNT,
1827             &val, &field_idx);
1828         if (match_res == PARSE_FAIL) {
1829             return false;
1830         }
1831         if (match_res == PARSE_SUCCESS) {
1832             node->fields.arr[field_idx] = val;
1833             fields_to_match--;
1834             if (!fields_to_match) {
1835                 return true;
1836             }
1837         }
1838     }
1839     return false;
1840 }
1841 
zoneinfo_parse(struct zoneinfo * zi)1842 static int zoneinfo_parse(struct zoneinfo *zi) {
1843     static struct reread_data file_data = {
1844         .filename = ZONEINFO_PATH,
1845         .fd = -1,
1846     };
1847     char *buf;
1848     char *save_ptr;
1849     char *line;
1850     char zone_name[LINE_MAX + 1];
1851     struct zoneinfo_node *node = NULL;
1852     int node_idx = 0;
1853     int zone_idx = 0;
1854 
1855     memset(zi, 0, sizeof(struct zoneinfo));
1856 
1857     if ((buf = reread_file(&file_data)) == NULL) {
1858         return -1;
1859     }
1860 
1861     for (line = strtok_r(buf, "\n", &save_ptr); line;
1862          line = strtok_r(NULL, "\n", &save_ptr)) {
1863         int node_id;
1864         if (sscanf(line, "Node %d, zone %" STRINGIFY(LINE_MAX) "s", &node_id, zone_name) == 2) {
1865             if (!node || node->id != node_id) {
1866                 line = strtok_r(NULL, "\n", &save_ptr);
1867                 if (strncmp(line, NODE_STATS_MARKER, strlen(NODE_STATS_MARKER)) != 0) {
1868                     /*
1869                      * per-node stats are only present in the first non-empty zone of
1870                      * the node.
1871                      */
1872                     continue;
1873                 }
1874 
1875                 /* new node is found */
1876                 if (node) {
1877                     node->zone_count = zone_idx + 1;
1878                     node_idx++;
1879                     if (node_idx == MAX_NR_NODES) {
1880                         /* max node count exceeded */
1881                         ALOGE("%s parse error", file_data.filename);
1882                         return -1;
1883                     }
1884                 }
1885                 node = &zi->nodes[node_idx];
1886                 node->id = node_id;
1887                 zone_idx = 0;
1888                 if (!zoneinfo_parse_node(&save_ptr, node)) {
1889                     ALOGE("%s parse error", file_data.filename);
1890                     return -1;
1891                 }
1892             } else {
1893                 /* new zone is found */
1894                 zone_idx++;
1895             }
1896             if (!zoneinfo_parse_zone(&save_ptr, &node->zones[zone_idx])) {
1897                 ALOGE("%s parse error", file_data.filename);
1898                 return -1;
1899             }
1900         }
1901     }
1902     if (!node) {
1903         ALOGE("%s parse error", file_data.filename);
1904         return -1;
1905     }
1906     node->zone_count = zone_idx + 1;
1907     zi->node_count = node_idx + 1;
1908 
1909     /* calculate totals fields */
1910     for (node_idx = 0; node_idx < zi->node_count; node_idx++) {
1911         node = &zi->nodes[node_idx];
1912         for (zone_idx = 0; zone_idx < node->zone_count; zone_idx++) {
1913             struct zoneinfo_zone *zone = &zi->nodes[node_idx].zones[zone_idx];
1914             zi->totalreserve_pages += zone->max_protection + zone->fields.field.high;
1915         }
1916         zi->total_inactive_file += node->fields.field.nr_inactive_file;
1917         zi->total_active_file += node->fields.field.nr_active_file;
1918     }
1919     return 0;
1920 }
1921 
1922 /* /proc/meminfo parsing routines */
meminfo_parse_line(char * line,union meminfo * mi)1923 static bool meminfo_parse_line(char *line, union meminfo *mi) {
1924     char *cp = line;
1925     char *ap;
1926     char *save_ptr;
1927     int64_t val;
1928     int field_idx;
1929     enum field_match_result match_res;
1930 
1931     cp = strtok_r(line, " ", &save_ptr);
1932     if (!cp) {
1933         return false;
1934     }
1935 
1936     ap = strtok_r(NULL, " ", &save_ptr);
1937     if (!ap) {
1938         return false;
1939     }
1940 
1941     match_res = match_field(cp, ap, meminfo_field_names, MI_FIELD_COUNT,
1942         &val, &field_idx);
1943     if (match_res == PARSE_SUCCESS) {
1944         mi->arr[field_idx] = val / page_k;
1945     }
1946     return (match_res != PARSE_FAIL);
1947 }
1948 
read_gpu_total_kb()1949 static int64_t read_gpu_total_kb() {
1950     static android::base::unique_fd fd(
1951             android::bpf::mapRetrieveRO("/sys/fs/bpf/map_gpuMem_gpu_mem_total_map"));
1952     static constexpr uint64_t kBpfKeyGpuTotalUsage = 0;
1953     uint64_t value;
1954 
1955     if (!fd.ok()) {
1956         return 0;
1957     }
1958 
1959     return android::bpf::findMapEntry(fd, &kBpfKeyGpuTotalUsage, &value)
1960             ? 0
1961             : (int32_t)(value / 1024);
1962 }
1963 
meminfo_parse(union meminfo * mi)1964 static int meminfo_parse(union meminfo *mi) {
1965     static struct reread_data file_data = {
1966         .filename = MEMINFO_PATH,
1967         .fd = -1,
1968     };
1969     char *buf;
1970     char *save_ptr;
1971     char *line;
1972 
1973     memset(mi, 0, sizeof(union meminfo));
1974 
1975     if ((buf = reread_file(&file_data)) == NULL) {
1976         return -1;
1977     }
1978 
1979     for (line = strtok_r(buf, "\n", &save_ptr); line;
1980          line = strtok_r(NULL, "\n", &save_ptr)) {
1981         if (!meminfo_parse_line(line, mi)) {
1982             ALOGE("%s parse error", file_data.filename);
1983             return -1;
1984         }
1985     }
1986     mi->field.nr_file_pages = mi->field.cached + mi->field.swap_cached +
1987         mi->field.buffers;
1988     mi->field.total_gpu_kb = read_gpu_total_kb();
1989     mi->field.easy_available = mi->field.nr_free_pages + mi->field.inactive_file;
1990 
1991     return 0;
1992 }
1993 
1994 // In the case of ZRAM, mi->field.free_swap can't be used directly because swap space is taken
1995 // from the free memory or reclaimed. Use the lowest of free_swap and easily available memory to
1996 // measure free swap because they represent how much swap space the system will consider to use
1997 // and how much it can actually use.
1998 // Swap compression ratio in the calculation can be adjusted using swap_compression_ratio tunable.
1999 // By setting swap_compression_ratio to 0, available memory can be ignored.
get_free_swap(union meminfo * mi)2000 static inline int64_t get_free_swap(union meminfo *mi) {
2001     if (swap_compression_ratio)
2002         return std::min(mi->field.free_swap, mi->field.easy_available * swap_compression_ratio);
2003     return mi->field.free_swap;
2004 }
2005 
2006 /* /proc/vmstat parsing routines */
vmstat_parse_line(char * line,union vmstat * vs)2007 static bool vmstat_parse_line(char *line, union vmstat *vs) {
2008     char *cp;
2009     char *ap;
2010     char *save_ptr;
2011     int64_t val;
2012     int field_idx;
2013     enum field_match_result match_res;
2014 
2015     cp = strtok_r(line, " ", &save_ptr);
2016     if (!cp) {
2017         return false;
2018     }
2019 
2020     ap = strtok_r(NULL, " ", &save_ptr);
2021     if (!ap) {
2022         return false;
2023     }
2024 
2025     match_res = match_field(cp, ap, vmstat_field_names, VS_FIELD_COUNT,
2026         &val, &field_idx);
2027     if (match_res == PARSE_SUCCESS) {
2028         vs->arr[field_idx] = val;
2029     }
2030     return (match_res != PARSE_FAIL);
2031 }
2032 
vmstat_parse(union vmstat * vs)2033 static int vmstat_parse(union vmstat *vs) {
2034     static struct reread_data file_data = {
2035         .filename = VMSTAT_PATH,
2036         .fd = -1,
2037     };
2038     char *buf;
2039     char *save_ptr;
2040     char *line;
2041 
2042     memset(vs, 0, sizeof(union vmstat));
2043 
2044     if ((buf = reread_file(&file_data)) == NULL) {
2045         return -1;
2046     }
2047 
2048     for (line = strtok_r(buf, "\n", &save_ptr); line;
2049          line = strtok_r(NULL, "\n", &save_ptr)) {
2050         if (!vmstat_parse_line(line, vs)) {
2051             ALOGE("%s parse error", file_data.filename);
2052             return -1;
2053         }
2054     }
2055 
2056     return 0;
2057 }
2058 
psi_parse(struct reread_data * file_data,struct psi_stats stats[],bool full)2059 static int psi_parse(struct reread_data *file_data, struct psi_stats stats[], bool full) {
2060     char *buf;
2061     char *save_ptr;
2062     char *line;
2063 
2064     if ((buf = reread_file(file_data)) == NULL) {
2065         return -1;
2066     }
2067 
2068     line = strtok_r(buf, "\n", &save_ptr);
2069     if (parse_psi_line(line, PSI_SOME, stats)) {
2070         return -1;
2071     }
2072     if (full) {
2073         line = strtok_r(NULL, "\n", &save_ptr);
2074         if (parse_psi_line(line, PSI_FULL, stats)) {
2075             return -1;
2076         }
2077     }
2078 
2079     return 0;
2080 }
2081 
psi_parse_mem(struct psi_data * psi_data)2082 static int psi_parse_mem(struct psi_data *psi_data) {
2083     static struct reread_data file_data = {
2084             .filename = psi_resource_file[PSI_MEMORY],
2085             .fd = -1,
2086     };
2087     return psi_parse(&file_data, psi_data->mem_stats, true);
2088 }
2089 
psi_parse_io(struct psi_data * psi_data)2090 static int psi_parse_io(struct psi_data *psi_data) {
2091     static struct reread_data file_data = {
2092             .filename = psi_resource_file[PSI_IO],
2093             .fd = -1,
2094     };
2095     return psi_parse(&file_data, psi_data->io_stats, true);
2096 }
2097 
psi_parse_cpu(struct psi_data * psi_data)2098 static int psi_parse_cpu(struct psi_data *psi_data) {
2099     static struct reread_data file_data = {
2100             .filename = psi_resource_file[PSI_CPU],
2101             .fd = -1,
2102     };
2103     return psi_parse(&file_data, psi_data->cpu_stats, false);
2104 }
2105 
2106 enum wakeup_reason {
2107     Event,
2108     Polling
2109 };
2110 
2111 struct wakeup_info {
2112     struct timespec wakeup_tm;
2113     struct timespec prev_wakeup_tm;
2114     struct timespec last_event_tm;
2115     int wakeups_since_event;
2116     int skipped_wakeups;
2117 };
2118 
2119 /*
2120  * After the initial memory pressure event is received lmkd schedules periodic wakeups to check
2121  * the memory conditions and kill if needed (polling). This is done because pressure events are
2122  * rate-limited and memory conditions can change in between events. Therefore after the initial
2123  * event there might be multiple wakeups. This function records the wakeup information such as the
2124  * timestamps of the last event and the last wakeup, the number of wakeups since the last event
2125  * and how many of those wakeups were skipped (some wakeups are skipped if previously killed
2126  * process is still freeing its memory).
2127  */
record_wakeup_time(struct timespec * tm,enum wakeup_reason reason,struct wakeup_info * wi)2128 static void record_wakeup_time(struct timespec *tm, enum wakeup_reason reason,
2129                                struct wakeup_info *wi) {
2130     wi->prev_wakeup_tm = wi->wakeup_tm;
2131     wi->wakeup_tm = *tm;
2132     if (reason == Event) {
2133         wi->last_event_tm = *tm;
2134         wi->wakeups_since_event = 0;
2135         wi->skipped_wakeups = 0;
2136     } else {
2137         wi->wakeups_since_event++;
2138     }
2139 }
2140 
2141 struct kill_info {
2142     enum kill_reasons kill_reason;
2143     const char *kill_desc;
2144     int thrashing;
2145     int max_thrashing;
2146 };
2147 
killinfo_log(struct proc * procp,int min_oom_score,int rss_kb,int swap_kb,struct kill_info * ki,union meminfo * mi,struct wakeup_info * wi,struct timespec * tm,struct psi_data * pd)2148 static void killinfo_log(struct proc* procp, int min_oom_score, int rss_kb,
2149                          int swap_kb, struct kill_info *ki, union meminfo *mi,
2150                          struct wakeup_info *wi, struct timespec *tm, struct psi_data *pd) {
2151     /* log process information */
2152     android_log_write_int32(ctx, procp->pid);
2153     android_log_write_int32(ctx, procp->uid);
2154     android_log_write_int32(ctx, procp->oomadj);
2155     android_log_write_int32(ctx, min_oom_score);
2156     android_log_write_int32(ctx, std::min(rss_kb, (int)INT32_MAX));
2157     android_log_write_int32(ctx, ki ? ki->kill_reason : NONE);
2158 
2159     /* log meminfo fields */
2160     for (int field_idx = 0; field_idx < MI_FIELD_COUNT; field_idx++) {
2161         android_log_write_int32(ctx,
2162                                 mi ? std::min(mi->arr[field_idx] * page_k, (int64_t)INT32_MAX) : 0);
2163     }
2164 
2165     /* log lmkd wakeup information */
2166     if (wi) {
2167         android_log_write_int32(ctx, (int32_t)get_time_diff_ms(&wi->last_event_tm, tm));
2168         android_log_write_int32(ctx, (int32_t)get_time_diff_ms(&wi->prev_wakeup_tm, tm));
2169         android_log_write_int32(ctx, wi->wakeups_since_event);
2170         android_log_write_int32(ctx, wi->skipped_wakeups);
2171     } else {
2172         android_log_write_int32(ctx, 0);
2173         android_log_write_int32(ctx, 0);
2174         android_log_write_int32(ctx, 0);
2175         android_log_write_int32(ctx, 0);
2176     }
2177 
2178     android_log_write_int32(ctx, std::min(swap_kb, (int)INT32_MAX));
2179     android_log_write_int32(ctx, mi ? (int32_t)mi->field.total_gpu_kb : 0);
2180     if (ki) {
2181         android_log_write_int32(ctx, ki->thrashing);
2182         android_log_write_int32(ctx, ki->max_thrashing);
2183     } else {
2184         android_log_write_int32(ctx, 0);
2185         android_log_write_int32(ctx, 0);
2186     }
2187 
2188     if (pd) {
2189         android_log_write_float32(ctx, pd->mem_stats[PSI_SOME].avg10);
2190         android_log_write_float32(ctx, pd->mem_stats[PSI_FULL].avg10);
2191         android_log_write_float32(ctx, pd->io_stats[PSI_SOME].avg10);
2192         android_log_write_float32(ctx, pd->io_stats[PSI_FULL].avg10);
2193         android_log_write_float32(ctx, pd->cpu_stats[PSI_SOME].avg10);
2194     } else {
2195         for (int i = 0; i < 5; i++) {
2196             android_log_write_float32(ctx, 0);
2197         }
2198     }
2199 
2200     android_log_write_list(ctx, LOG_ID_EVENTS);
2201     android_log_reset(ctx);
2202 }
2203 
2204 // Note: returned entry is only an anchor and does not hold a valid process info.
2205 // When called from a non-main thread, adjslot_list_lock read lock should be taken.
proc_adj_head(int oomadj)2206 static struct proc *proc_adj_head(int oomadj) {
2207     return (struct proc *)&procadjslot_list[ADJTOSLOT(oomadj)];
2208 }
2209 
2210 // When called from a non-main thread, adjslot_list_lock read lock should be taken.
proc_adj_tail(int oomadj)2211 static struct proc *proc_adj_tail(int oomadj) {
2212     return (struct proc *)adjslot_tail(&procadjslot_list[ADJTOSLOT(oomadj)]);
2213 }
2214 
2215 // When called from a non-main thread, adjslot_list_lock read lock should be taken.
proc_adj_prev(int oomadj,int pid)2216 static struct proc *proc_adj_prev(int oomadj, int pid) {
2217     struct adjslot_list *head = &procadjslot_list[ADJTOSLOT(oomadj)];
2218     struct adjslot_list *curr = adjslot_tail(&procadjslot_list[ADJTOSLOT(oomadj)]);
2219 
2220     while (curr != head) {
2221         if (((struct proc *)curr)->pid == pid) {
2222             return (struct proc *)curr->prev;
2223         }
2224         curr = curr->prev;
2225     }
2226 
2227     return NULL;
2228 }
2229 
2230 // Can be called only from the main thread.
proc_get_heaviest(int oomadj)2231 static struct proc *proc_get_heaviest(int oomadj) {
2232     struct adjslot_list *head = &procadjslot_list[ADJTOSLOT(oomadj)];
2233     struct adjslot_list *curr = head->next;
2234     struct proc *maxprocp = NULL;
2235     int maxsize = 0;
2236     while (curr != head) {
2237         int pid = ((struct proc *)curr)->pid;
2238         int tasksize = proc_get_size(pid);
2239         if (tasksize < 0) {
2240             struct adjslot_list *next = curr->next;
2241             pid_remove(pid);
2242             curr = next;
2243         } else {
2244             if (tasksize > maxsize) {
2245                 maxsize = tasksize;
2246                 maxprocp = (struct proc *)curr;
2247             }
2248             curr = curr->next;
2249         }
2250     }
2251     return maxprocp;
2252 }
2253 
find_victim(int oom_score,int prev_pid,struct proc & target_proc)2254 static bool find_victim(int oom_score, int prev_pid, struct proc &target_proc) {
2255     struct proc *procp;
2256     std::shared_lock lock(adjslot_list_lock);
2257 
2258     if (!prev_pid) {
2259         procp = proc_adj_tail(oom_score);
2260     } else {
2261         procp = proc_adj_prev(oom_score, prev_pid);
2262         if (!procp) {
2263             // pid was removed, restart at the tail
2264             procp = proc_adj_tail(oom_score);
2265         }
2266     }
2267 
2268     // the list is empty at this oom_score or we looped through it
2269     if (!procp || procp == proc_adj_head(oom_score)) {
2270         return false;
2271     }
2272 
2273     // make a copy because original might be destroyed after adjslot_list_lock is released
2274     target_proc = *procp;
2275 
2276     return true;
2277 }
2278 
watchdog_callback()2279 static void watchdog_callback() {
2280     int prev_pid = 0;
2281 
2282     ALOGW("lmkd watchdog timed out!");
2283     for (int oom_score = OOM_SCORE_ADJ_MAX; oom_score >= 0;) {
2284         struct proc target;
2285 
2286         if (!find_victim(oom_score, prev_pid, target)) {
2287             oom_score--;
2288             prev_pid = 0;
2289             continue;
2290         }
2291 
2292         if (target.valid && reaper.kill({ target.pidfd, target.pid, target.uid }, true) == 0) {
2293             ALOGW("lmkd watchdog killed process %d, oom_score_adj %d", target.pid, oom_score);
2294             killinfo_log(&target, 0, 0, 0, NULL, NULL, NULL, NULL, NULL);
2295             // Can't call pid_remove() from non-main thread, therefore just invalidate the record
2296             pid_invalidate(target.pid);
2297             break;
2298         }
2299         prev_pid = target.pid;
2300     }
2301 }
2302 
2303 static Watchdog watchdog(WATCHDOG_TIMEOUT_SEC, watchdog_callback);
2304 
is_kill_pending(void)2305 static bool is_kill_pending(void) {
2306     char buf[24];
2307 
2308     if (last_kill_pid_or_fd < 0) {
2309         return false;
2310     }
2311 
2312     if (pidfd_supported) {
2313         return true;
2314     }
2315 
2316     /* when pidfd is not supported base the decision on /proc/<pid> existence */
2317     snprintf(buf, sizeof(buf), "/proc/%d/", last_kill_pid_or_fd);
2318     if (access(buf, F_OK) == 0) {
2319         return true;
2320     }
2321 
2322     return false;
2323 }
2324 
is_waiting_for_kill(void)2325 static bool is_waiting_for_kill(void) {
2326     return pidfd_supported && last_kill_pid_or_fd >= 0;
2327 }
2328 
stop_wait_for_proc_kill(bool finished)2329 static void stop_wait_for_proc_kill(bool finished) {
2330     struct epoll_event epev;
2331 
2332     if (last_kill_pid_or_fd < 0) {
2333         return;
2334     }
2335 
2336     if (debug_process_killing) {
2337         struct timespec curr_tm;
2338 
2339         if (clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm) != 0) {
2340             /*
2341              * curr_tm is used here merely to report kill duration, so this failure is not fatal.
2342              * Log an error and continue.
2343              */
2344             ALOGE("Failed to get current time");
2345         }
2346 
2347         if (finished) {
2348             ALOGI("Process got killed in %ldms",
2349                 get_time_diff_ms(&last_kill_tm, &curr_tm));
2350         } else {
2351             ALOGI("Stop waiting for process kill after %ldms",
2352                 get_time_diff_ms(&last_kill_tm, &curr_tm));
2353         }
2354     }
2355 
2356     if (pidfd_supported) {
2357         /* unregister fd */
2358         if (epoll_ctl(epollfd, EPOLL_CTL_DEL, last_kill_pid_or_fd, &epev)) {
2359             // Log an error and keep going
2360             ALOGE("epoll_ctl for last killed process failed; errno=%d", errno);
2361         }
2362         maxevents--;
2363         close(last_kill_pid_or_fd);
2364     }
2365 
2366     last_kill_pid_or_fd = -1;
2367 }
2368 
kill_done_handler(int data __unused,uint32_t events __unused,struct polling_params * poll_params)2369 static void kill_done_handler(int data __unused, uint32_t events __unused,
2370                               struct polling_params *poll_params) {
2371     stop_wait_for_proc_kill(true);
2372     poll_params->update = POLLING_RESUME;
2373 }
2374 
kill_fail_handler(int data __unused,uint32_t events __unused,struct polling_params * poll_params)2375 static void kill_fail_handler(int data __unused, uint32_t events __unused,
2376                               struct polling_params *poll_params) {
2377     int pid;
2378 
2379     // Extract pid from the communication pipe. Clearing the pipe this way allows further
2380     // epoll_wait calls to sleep until the next event.
2381     if (TEMP_FAILURE_RETRY(read(reaper_comm_fd[0], &pid, sizeof(pid))) != sizeof(pid)) {
2382         ALOGE("thread communication read failed: %s", strerror(errno));
2383     }
2384     stop_wait_for_proc_kill(false);
2385     poll_params->update = POLLING_RESUME;
2386 }
2387 
start_wait_for_proc_kill(int pid_or_fd)2388 static void start_wait_for_proc_kill(int pid_or_fd) {
2389     static struct event_handler_info kill_done_hinfo = { 0, kill_done_handler };
2390     struct epoll_event epev;
2391 
2392     if (last_kill_pid_or_fd >= 0) {
2393         /* Should not happen but if it does we should stop previous wait */
2394         ALOGE("Attempt to wait for a kill while another wait is in progress");
2395         stop_wait_for_proc_kill(false);
2396     }
2397 
2398     last_kill_pid_or_fd = pid_or_fd;
2399 
2400     if (!pidfd_supported) {
2401         /* If pidfd is not supported just store PID and exit */
2402         return;
2403     }
2404 
2405     epev.events = EPOLLIN;
2406     epev.data.ptr = (void *)&kill_done_hinfo;
2407     if (epoll_ctl(epollfd, EPOLL_CTL_ADD, last_kill_pid_or_fd, &epev) != 0) {
2408         ALOGE("epoll_ctl for last kill failed; errno=%d", errno);
2409         close(last_kill_pid_or_fd);
2410         last_kill_pid_or_fd = -1;
2411         return;
2412     }
2413     maxevents++;
2414 }
2415 
2416 /* Kill one process specified by procp.  Returns the size (in pages) of the process killed */
kill_one_process(struct proc * procp,int min_oom_score,struct kill_info * ki,union meminfo * mi,struct wakeup_info * wi,struct timespec * tm,struct psi_data * pd)2417 static int kill_one_process(struct proc* procp, int min_oom_score, struct kill_info *ki,
2418                             union meminfo *mi, struct wakeup_info *wi, struct timespec *tm,
2419                             struct psi_data *pd) {
2420     int pid = procp->pid;
2421     int pidfd = procp->pidfd;
2422     uid_t uid = procp->uid;
2423     char *taskname;
2424     int kill_result;
2425     int result = -1;
2426     struct memory_stat *mem_st;
2427     struct kill_stat kill_st;
2428     int64_t tgid;
2429     int64_t rss_kb;
2430     int64_t swap_kb;
2431     char buf[pagesize];
2432     char desc[LINE_MAX];
2433 
2434     if (!procp->valid || !read_proc_status(pid, buf, sizeof(buf))) {
2435         goto out;
2436     }
2437     if (!parse_status_tag(buf, PROC_STATUS_TGID_FIELD, &tgid)) {
2438         ALOGE("Unable to parse tgid from /proc/%d/status", pid);
2439         goto out;
2440     }
2441     if (tgid != pid) {
2442         ALOGE("Possible pid reuse detected (pid %d, tgid %" PRId64 ")!", pid, tgid);
2443         goto out;
2444     }
2445     // Zombie processes will not have RSS / Swap fields.
2446     if (!parse_status_tag(buf, PROC_STATUS_RSS_FIELD, &rss_kb)) {
2447         goto out;
2448     }
2449     if (!parse_status_tag(buf, PROC_STATUS_SWAP_FIELD, &swap_kb)) {
2450         goto out;
2451     }
2452 
2453     taskname = proc_get_name(pid, buf, sizeof(buf));
2454     // taskname will point inside buf, do not reuse buf onwards.
2455     if (!taskname) {
2456         goto out;
2457     }
2458 
2459     mem_st = stats_read_memory_stat(per_app_memcg, pid, uid, rss_kb * 1024, swap_kb * 1024);
2460 
2461     snprintf(desc, sizeof(desc), "lmk,%d,%d,%d,%d,%d", pid, ki ? (int)ki->kill_reason : -1,
2462              procp->oomadj, min_oom_score, ki ? ki->max_thrashing : -1);
2463 
2464     result = lmkd_free_memory_before_kill_hook(procp, rss_kb / page_k, procp->oomadj,
2465                                                ki ? (int)ki->kill_reason : -1);
2466     if (result > 0) {
2467       /*
2468        * Memory was freed elsewhere; no need to kill. Note: intentionally do not
2469        * pid_remove(pid) since it was not killed.
2470        */
2471       ALOGI("Skipping kill; %ld kB freed elsewhere.", result * page_k);
2472       return result;
2473     }
2474 
2475     trace_kill_start(desc);
2476 
2477     start_wait_for_proc_kill(pidfd < 0 ? pid : pidfd);
2478     kill_result = reaper.kill({ pidfd, pid, uid }, false);
2479 
2480     trace_kill_end();
2481 
2482     if (kill_result) {
2483         stop_wait_for_proc_kill(false);
2484         ALOGE("kill(%d): errno=%d", pid, errno);
2485         /* Delete process record even when we fail to kill so that we don't get stuck on it */
2486         goto out;
2487     }
2488 
2489     last_kill_tm = *tm;
2490 
2491     inc_killcnt(procp->oomadj);
2492 
2493     if (ki) {
2494         kill_st.kill_reason = ki->kill_reason;
2495         kill_st.thrashing = ki->thrashing;
2496         kill_st.max_thrashing = ki->max_thrashing;
2497         ALOGI("Kill '%s' (%d), uid %d, oom_score_adj %d to free %" PRId64 "kB rss, %" PRId64
2498               "kB swap; reason: %s", taskname, pid, uid, procp->oomadj, rss_kb, swap_kb,
2499               ki->kill_desc);
2500     } else {
2501         kill_st.kill_reason = NONE;
2502         kill_st.thrashing = 0;
2503         kill_st.max_thrashing = 0;
2504         ALOGI("Kill '%s' (%d), uid %d, oom_score_adj %d to free %" PRId64 "kB rss, %" PRId64
2505               "kb swap", taskname, pid, uid, procp->oomadj, rss_kb, swap_kb);
2506     }
2507     killinfo_log(procp, min_oom_score, rss_kb, swap_kb, ki, mi, wi, tm, pd);
2508 
2509     kill_st.uid = static_cast<int32_t>(uid);
2510     kill_st.taskname = taskname;
2511     kill_st.oom_score = procp->oomadj;
2512     kill_st.min_oom_score = min_oom_score;
2513     kill_st.free_mem_kb = mi->field.nr_free_pages * page_k;
2514     kill_st.free_swap_kb = get_free_swap(mi) * page_k;
2515     stats_write_lmk_kill_occurred(&kill_st, mem_st);
2516 
2517     ctrl_data_write_lmk_kill_occurred((pid_t)pid, uid, rss_kb);
2518 
2519     result = rss_kb / page_k;
2520 
2521 out:
2522     /*
2523      * WARNING: After pid_remove() procp is freed and can't be used!
2524      * Therefore placed at the end of the function.
2525      */
2526     pid_remove(pid);
2527     return result;
2528 }
2529 
2530 /*
2531  * Find one process to kill at or above the given oom_score_adj level.
2532  * Returns size of the killed process.
2533  */
find_and_kill_process(int min_score_adj,struct kill_info * ki,union meminfo * mi,struct wakeup_info * wi,struct timespec * tm,struct psi_data * pd)2534 static int find_and_kill_process(int min_score_adj, struct kill_info *ki, union meminfo *mi,
2535                                  struct wakeup_info *wi, struct timespec *tm,
2536                                  struct psi_data *pd) {
2537     int i;
2538     int killed_size = 0;
2539     bool choose_heaviest_task = kill_heaviest_task;
2540 
2541     for (i = OOM_SCORE_ADJ_MAX; i >= min_score_adj; i--) {
2542         struct proc *procp;
2543 
2544         if (!choose_heaviest_task && i <= PERCEPTIBLE_APP_ADJ) {
2545             /*
2546              * If we have to choose a perceptible process, choose the heaviest one to
2547              * hopefully minimize the number of victims.
2548              */
2549             choose_heaviest_task = true;
2550         }
2551 
2552         while (true) {
2553             procp = choose_heaviest_task ?
2554                 proc_get_heaviest(i) : proc_adj_tail(i);
2555 
2556             if (!procp)
2557                 break;
2558 
2559             killed_size = kill_one_process(procp, min_score_adj, ki, mi, wi, tm, pd);
2560             if (killed_size >= 0) {
2561                 break;
2562             }
2563         }
2564         if (killed_size) {
2565             break;
2566         }
2567     }
2568 
2569     return killed_size;
2570 }
2571 
get_memory_usage(struct reread_data * file_data)2572 static int64_t get_memory_usage(struct reread_data *file_data) {
2573     int64_t mem_usage;
2574     char *buf;
2575 
2576     if ((buf = reread_file(file_data)) == NULL) {
2577         return -1;
2578     }
2579 
2580     if (!parse_int64(buf, &mem_usage)) {
2581         ALOGE("%s parse error", file_data->filename);
2582         return -1;
2583     }
2584     if (mem_usage == 0) {
2585         ALOGE("No memory!");
2586         return -1;
2587     }
2588     return mem_usage;
2589 }
2590 
record_low_pressure_levels(union meminfo * mi)2591 void record_low_pressure_levels(union meminfo *mi) {
2592     if (low_pressure_mem.min_nr_free_pages == -1 ||
2593         low_pressure_mem.min_nr_free_pages > mi->field.nr_free_pages) {
2594         if (debug_process_killing) {
2595             ALOGI("Low pressure min memory update from %" PRId64 " to %" PRId64,
2596                 low_pressure_mem.min_nr_free_pages, mi->field.nr_free_pages);
2597         }
2598         low_pressure_mem.min_nr_free_pages = mi->field.nr_free_pages;
2599     }
2600     /*
2601      * Free memory at low vmpressure events occasionally gets spikes,
2602      * possibly a stale low vmpressure event with memory already
2603      * freed up (no memory pressure should have been reported).
2604      * Ignore large jumps in max_nr_free_pages that would mess up our stats.
2605      */
2606     if (low_pressure_mem.max_nr_free_pages == -1 ||
2607         (low_pressure_mem.max_nr_free_pages < mi->field.nr_free_pages &&
2608          mi->field.nr_free_pages - low_pressure_mem.max_nr_free_pages <
2609          low_pressure_mem.max_nr_free_pages * 0.1)) {
2610         if (debug_process_killing) {
2611             ALOGI("Low pressure max memory update from %" PRId64 " to %" PRId64,
2612                 low_pressure_mem.max_nr_free_pages, mi->field.nr_free_pages);
2613         }
2614         low_pressure_mem.max_nr_free_pages = mi->field.nr_free_pages;
2615     }
2616 }
2617 
upgrade_level(enum vmpressure_level level)2618 enum vmpressure_level upgrade_level(enum vmpressure_level level) {
2619     return (enum vmpressure_level)((level < VMPRESS_LEVEL_CRITICAL) ?
2620         level + 1 : level);
2621 }
2622 
downgrade_level(enum vmpressure_level level)2623 enum vmpressure_level downgrade_level(enum vmpressure_level level) {
2624     return (enum vmpressure_level)((level > VMPRESS_LEVEL_LOW) ?
2625         level - 1 : level);
2626 }
2627 
2628 enum zone_watermark {
2629     WMARK_MIN = 0,
2630     WMARK_LOW,
2631     WMARK_HIGH,
2632     WMARK_NONE
2633 };
2634 
2635 struct zone_watermarks {
2636     long high_wmark;
2637     long low_wmark;
2638     long min_wmark;
2639 };
2640 
2641 /*
2642  * Returns lowest breached watermark or WMARK_NONE.
2643  */
get_lowest_watermark(union meminfo * mi,struct zone_watermarks * watermarks)2644 static enum zone_watermark get_lowest_watermark(union meminfo *mi,
2645                                                 struct zone_watermarks *watermarks)
2646 {
2647     int64_t nr_free_pages = mi->field.nr_free_pages - mi->field.cma_free;
2648 
2649     if (nr_free_pages < watermarks->min_wmark) {
2650         return WMARK_MIN;
2651     }
2652     if (nr_free_pages < watermarks->low_wmark) {
2653         return WMARK_LOW;
2654     }
2655     if (nr_free_pages < watermarks->high_wmark) {
2656         return WMARK_HIGH;
2657     }
2658     return WMARK_NONE;
2659 }
2660 
calc_zone_watermarks(struct zoneinfo * zi,struct zone_watermarks * watermarks)2661 void calc_zone_watermarks(struct zoneinfo *zi, struct zone_watermarks *watermarks) {
2662     memset(watermarks, 0, sizeof(struct zone_watermarks));
2663 
2664     for (int node_idx = 0; node_idx < zi->node_count; node_idx++) {
2665         struct zoneinfo_node *node = &zi->nodes[node_idx];
2666         for (int zone_idx = 0; zone_idx < node->zone_count; zone_idx++) {
2667             struct zoneinfo_zone *zone = &node->zones[zone_idx];
2668 
2669             if (!zone->fields.field.present) {
2670                 continue;
2671             }
2672 
2673             watermarks->high_wmark += zone->max_protection + zone->fields.field.high;
2674             watermarks->low_wmark += zone->max_protection + zone->fields.field.low;
2675             watermarks->min_wmark += zone->max_protection + zone->fields.field.min;
2676         }
2677     }
2678 }
2679 
calc_swap_utilization(union meminfo * mi)2680 static int calc_swap_utilization(union meminfo *mi) {
2681     int64_t swap_used = mi->field.total_swap - get_free_swap(mi);
2682     int64_t total_swappable = mi->field.active_anon + mi->field.inactive_anon +
2683                               mi->field.shmem + swap_used;
2684     return total_swappable > 0 ? (swap_used * 100) / total_swappable : 0;
2685 }
2686 
mp_event_psi(int data,uint32_t events,struct polling_params * poll_params)2687 static void mp_event_psi(int data, uint32_t events, struct polling_params *poll_params) {
2688     enum reclaim_state {
2689         NO_RECLAIM = 0,
2690         KSWAPD_RECLAIM,
2691         DIRECT_RECLAIM,
2692     };
2693     static int64_t init_ws_refault;
2694     static int64_t prev_workingset_refault;
2695     static int64_t base_file_lru;
2696     static int64_t init_pgscan_kswapd;
2697     static int64_t init_pgscan_direct;
2698     static int64_t init_pgrefill;
2699     static bool killing;
2700     static int thrashing_limit = thrashing_limit_pct;
2701     static struct zone_watermarks watermarks;
2702     static struct timespec wmark_update_tm;
2703     static struct wakeup_info wi;
2704     static struct timespec thrashing_reset_tm;
2705     static int64_t prev_thrash_growth = 0;
2706     static bool check_filecache = false;
2707     static int max_thrashing = 0;
2708 
2709     union meminfo mi;
2710     union vmstat vs;
2711     struct psi_data psi_data;
2712     struct timespec curr_tm;
2713     int64_t thrashing = 0;
2714     bool swap_is_low = false;
2715     enum vmpressure_level level = (enum vmpressure_level)data;
2716     enum kill_reasons kill_reason = NONE;
2717     bool cycle_after_kill = false;
2718     enum reclaim_state reclaim = NO_RECLAIM;
2719     enum zone_watermark wmark = WMARK_NONE;
2720     char kill_desc[LINE_MAX];
2721     bool cut_thrashing_limit = false;
2722     int min_score_adj = 0;
2723     int swap_util = 0;
2724     int64_t swap_low_threshold;
2725     long since_thrashing_reset_ms;
2726     int64_t workingset_refault_file;
2727     bool critical_stall = false;
2728     bool in_direct_reclaim;
2729     long direct_reclaim_duration_ms;
2730     bool in_kswapd_reclaim;
2731 
2732     mp_event_count++;
2733     if (debug_process_killing) {
2734         ALOGI("%s memory pressure event #%" PRIu64 " is triggered",
2735               level_name[level], mp_event_count);
2736     }
2737 
2738     if (clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm) != 0) {
2739         ALOGE("Failed to get current time");
2740         return;
2741     }
2742 
2743     if (events > 0 ) {
2744         /* Ignore a lower event within the first polling window. */
2745         if (level < prev_level) {
2746             if (debug_process_killing)
2747                 ALOGI("Ignoring %s pressure event; occurred too soon.",
2748                        level_name[level]);
2749             return;
2750         }
2751         prev_level = level;
2752     } else {
2753         /* Reset event level after the first polling window. */
2754         prev_level = VMPRESS_LEVEL_LOW;
2755     }
2756 
2757     record_wakeup_time(&curr_tm, events ? Event : Polling, &wi);
2758 
2759     bool kill_pending = is_kill_pending();
2760     if (kill_pending && (kill_timeout_ms == 0 ||
2761         get_time_diff_ms(&last_kill_tm, &curr_tm) < static_cast<long>(kill_timeout_ms))) {
2762         /* Skip while still killing a process */
2763         wi.skipped_wakeups++;
2764         goto no_kill;
2765     }
2766     /*
2767      * Process is dead or kill timeout is over, stop waiting. This has no effect if pidfds are
2768      * supported and death notification already caused waiting to stop.
2769      */
2770     stop_wait_for_proc_kill(!kill_pending);
2771 
2772     if (vmstat_parse(&vs) < 0) {
2773         ALOGE("Failed to parse vmstat!");
2774         return;
2775     }
2776     /* Starting 5.9 kernel workingset_refault vmstat field was renamed workingset_refault_file */
2777     workingset_refault_file = vs.field.workingset_refault ? : vs.field.workingset_refault_file;
2778 
2779     if (meminfo_parse(&mi) < 0) {
2780         ALOGE("Failed to parse meminfo!");
2781         return;
2782     }
2783 
2784     /* Reset states after process got killed */
2785     if (killing) {
2786         killing = false;
2787         cycle_after_kill = true;
2788         /* Reset file-backed pagecache size and refault amounts after a kill */
2789         base_file_lru = vs.field.nr_inactive_file + vs.field.nr_active_file;
2790         init_ws_refault = workingset_refault_file;
2791         thrashing_reset_tm = curr_tm;
2792         prev_thrash_growth = 0;
2793     }
2794 
2795     /* Check free swap levels */
2796     if (swap_free_low_percentage) {
2797         swap_low_threshold = mi.field.total_swap * swap_free_low_percentage / 100;
2798         swap_is_low = get_free_swap(&mi) < swap_low_threshold;
2799     } else {
2800         swap_low_threshold = 0;
2801     }
2802 
2803     if (memevent_listener) {
2804         in_direct_reclaim =
2805                 direct_reclaim_start_tm.tv_sec != 0 || direct_reclaim_start_tm.tv_nsec != 0;
2806         in_kswapd_reclaim = kswapd_start_tm.tv_sec != 0 || kswapd_start_tm.tv_nsec != 0;
2807     } else {
2808         in_direct_reclaim = vs.field.pgscan_direct != init_pgscan_direct;
2809         in_kswapd_reclaim = (vs.field.pgscan_kswapd != init_pgscan_kswapd) ||
2810                             (vs.field.pgrefill != init_pgrefill);
2811     }
2812 
2813     /* Identify reclaim state */
2814     if (in_direct_reclaim) {
2815         init_pgscan_direct = vs.field.pgscan_direct;
2816         init_pgscan_kswapd = vs.field.pgscan_kswapd;
2817         init_pgrefill = vs.field.pgrefill;
2818         direct_reclaim_duration_ms = get_time_diff_ms(&direct_reclaim_start_tm, &curr_tm);
2819         reclaim = DIRECT_RECLAIM;
2820     } else if (in_kswapd_reclaim) {
2821         init_pgscan_kswapd = vs.field.pgscan_kswapd;
2822         init_pgrefill = vs.field.pgrefill;
2823         reclaim = KSWAPD_RECLAIM;
2824     } else if (workingset_refault_file == prev_workingset_refault) {
2825         /*
2826          * Device is not thrashing and not reclaiming, bail out early until we see these stats
2827          * changing
2828          */
2829         goto no_kill;
2830     }
2831 
2832     prev_workingset_refault = workingset_refault_file;
2833 
2834      /*
2835      * It's possible we fail to find an eligible process to kill (ex. no process is
2836      * above oom_adj_min). When this happens, we should retry to find a new process
2837      * for a kill whenever a new eligible process is available. This is especially
2838      * important for a slow growing refault case. While retrying, we should keep
2839      * monitoring new thrashing counter as someone could release the memory to mitigate
2840      * the thrashing. Thus, when thrashing reset window comes, we decay the prev thrashing
2841      * counter by window counts. If the counter is still greater than thrashing limit,
2842      * we preserve the current prev_thrash counter so we will retry kill again. Otherwise,
2843      * we reset the prev_thrash counter so we will stop retrying.
2844      */
2845     since_thrashing_reset_ms = get_time_diff_ms(&thrashing_reset_tm, &curr_tm);
2846     if (since_thrashing_reset_ms > THRASHING_RESET_INTERVAL_MS) {
2847         long windows_passed;
2848         /* Calculate prev_thrash_growth if we crossed THRASHING_RESET_INTERVAL_MS */
2849         prev_thrash_growth = (workingset_refault_file - init_ws_refault) * 100
2850                             / (base_file_lru + 1);
2851         windows_passed = (since_thrashing_reset_ms / THRASHING_RESET_INTERVAL_MS);
2852         /*
2853          * Decay prev_thrashing unless over-the-limit thrashing was registered in the window we
2854          * just crossed, which means there were no eligible processes to kill. We preserve the
2855          * counter in that case to ensure a kill if a new eligible process appears.
2856          */
2857         if (windows_passed > 1 || prev_thrash_growth < thrashing_limit) {
2858             prev_thrash_growth >>= windows_passed;
2859         }
2860 
2861         /* Record file-backed pagecache size when crossing THRASHING_RESET_INTERVAL_MS */
2862         base_file_lru = vs.field.nr_inactive_file + vs.field.nr_active_file;
2863         init_ws_refault = workingset_refault_file;
2864         thrashing_reset_tm = curr_tm;
2865         thrashing_limit = thrashing_limit_pct;
2866     } else {
2867         /* Calculate what % of the file-backed pagecache refaulted so far */
2868         thrashing = (workingset_refault_file - init_ws_refault) * 100 / (base_file_lru + 1);
2869     }
2870     /* Add previous cycle's decayed thrashing amount */
2871     thrashing += prev_thrash_growth;
2872     if (max_thrashing < thrashing) {
2873         max_thrashing = thrashing;
2874     }
2875 
2876 update_watermarks:
2877     /*
2878      * Refresh watermarks once per min in case user updated one of the margins.
2879      * TODO: b/140521024 replace this periodic update with an API for AMS to notify LMKD
2880      * that zone watermarks were changed by the system software.
2881      */
2882     if (watermarks.high_wmark == 0 || get_time_diff_ms(&wmark_update_tm, &curr_tm) > 60000) {
2883         struct zoneinfo zi;
2884 
2885         if (zoneinfo_parse(&zi) < 0) {
2886             ALOGE("Failed to parse zoneinfo!");
2887             return;
2888         }
2889 
2890         calc_zone_watermarks(&zi, &watermarks);
2891         wmark_update_tm = curr_tm;
2892     }
2893 
2894     /* Find out which watermark is breached if any */
2895     wmark = get_lowest_watermark(&mi, &watermarks);
2896 
2897     if (!psi_parse_mem(&psi_data)) {
2898         critical_stall = psi_data.mem_stats[PSI_FULL].avg10 > (float)stall_limit_critical;
2899     }
2900     /*
2901      * TODO: move this logic into a separate function
2902      * Decide if killing a process is necessary and record the reason
2903      */
2904     if (cycle_after_kill && wmark < WMARK_LOW) {
2905         /*
2906          * Prevent kills not freeing enough memory which might lead to OOM kill.
2907          * This might happen when a process is consuming memory faster than reclaim can
2908          * free even after a kill. Mostly happens when running memory stress tests.
2909          */
2910         min_score_adj = pressure_after_kill_min_score;
2911         kill_reason = PRESSURE_AFTER_KILL;
2912         strncpy(kill_desc, "min watermark is breached even after kill", sizeof(kill_desc));
2913     } else if (level == VMPRESS_LEVEL_CRITICAL && events != 0) {
2914         /*
2915          * Device is too busy reclaiming memory which might lead to ANR.
2916          * Critical level is triggered when PSI complete stall (all tasks are blocked because
2917          * of the memory congestion) breaches the configured threshold.
2918          */
2919         kill_reason = NOT_RESPONDING;
2920         strncpy(kill_desc, "device is not responding", sizeof(kill_desc));
2921     } else if (swap_is_low && thrashing > thrashing_limit_pct) {
2922         /* Page cache is thrashing while swap is low */
2923         kill_reason = LOW_SWAP_AND_THRASHING;
2924         snprintf(kill_desc, sizeof(kill_desc), "device is low on swap (%" PRId64
2925             "kB < %" PRId64 "kB) and thrashing (%" PRId64 "%%)",
2926             get_free_swap(&mi) * page_k, swap_low_threshold * page_k, thrashing);
2927         /* Do not kill perceptible apps unless below min watermark or heavily thrashing */
2928         if (wmark > WMARK_MIN && thrashing < thrashing_critical_pct) {
2929             min_score_adj = PERCEPTIBLE_APP_ADJ + 1;
2930         }
2931         check_filecache = true;
2932     } else if (swap_is_low && wmark < WMARK_HIGH) {
2933         /* Both free memory and swap are low */
2934         kill_reason = LOW_MEM_AND_SWAP;
2935         snprintf(kill_desc, sizeof(kill_desc), "%s watermark is breached and swap is low (%"
2936             PRId64 "kB < %" PRId64 "kB)", wmark < WMARK_LOW ? "min" : "low",
2937             get_free_swap(&mi) * page_k, swap_low_threshold * page_k);
2938         /* Do not kill perceptible apps unless below min watermark or heavily thrashing */
2939         if (wmark > WMARK_MIN && thrashing < thrashing_critical_pct) {
2940             min_score_adj = PERCEPTIBLE_APP_ADJ + 1;
2941         }
2942     } else if (wmark < WMARK_HIGH && swap_util_max < 100 &&
2943                (swap_util = calc_swap_utilization(&mi)) > swap_util_max) {
2944         /*
2945          * Too much anon memory is swapped out but swap is not low.
2946          * Non-swappable allocations created memory pressure.
2947          */
2948         kill_reason = LOW_MEM_AND_SWAP_UTIL;
2949         snprintf(kill_desc, sizeof(kill_desc), "%s watermark is breached and swap utilization"
2950             " is high (%d%% > %d%%)", wmark < WMARK_LOW ? "min" : "low",
2951             swap_util, swap_util_max);
2952     } else if (wmark < WMARK_HIGH && thrashing > thrashing_limit) {
2953         /* Page cache is thrashing while memory is low */
2954         kill_reason = LOW_MEM_AND_THRASHING;
2955         snprintf(kill_desc, sizeof(kill_desc), "%s watermark is breached and thrashing (%"
2956             PRId64 "%%)", wmark < WMARK_LOW ? "min" : "low", thrashing);
2957         cut_thrashing_limit = true;
2958         /* Do not kill perceptible apps unless thrashing at critical levels */
2959         if (thrashing < thrashing_critical_pct) {
2960             min_score_adj = PERCEPTIBLE_APP_ADJ + 1;
2961         }
2962         check_filecache = true;
2963     } else if (reclaim == DIRECT_RECLAIM && thrashing > thrashing_limit) {
2964         /* Page cache is thrashing while in direct reclaim (mostly happens on lowram devices) */
2965         kill_reason = DIRECT_RECL_AND_THRASHING;
2966         snprintf(kill_desc, sizeof(kill_desc), "device is in direct reclaim and thrashing (%"
2967             PRId64 "%%)", thrashing);
2968         cut_thrashing_limit = true;
2969         /* Do not kill perceptible apps unless thrashing at critical levels */
2970         if (thrashing < thrashing_critical_pct) {
2971             min_score_adj = PERCEPTIBLE_APP_ADJ + 1;
2972         }
2973         check_filecache = true;
2974     } else if (reclaim == DIRECT_RECLAIM && direct_reclaim_threshold_ms > 0 &&
2975                direct_reclaim_duration_ms > direct_reclaim_threshold_ms) {
2976         kill_reason = DIRECT_RECL_STUCK;
2977         snprintf(kill_desc, sizeof(kill_desc), "device is stuck in direct reclaim (%ldms > %dms)",
2978                  direct_reclaim_duration_ms, direct_reclaim_threshold_ms);
2979     } else if (check_filecache) {
2980         int64_t file_lru_kb = (vs.field.nr_inactive_file + vs.field.nr_active_file) * page_k;
2981 
2982         if (file_lru_kb < filecache_min_kb) {
2983             /* File cache is too low after thrashing, keep killing background processes */
2984             kill_reason = LOW_FILECACHE_AFTER_THRASHING;
2985             snprintf(kill_desc, sizeof(kill_desc),
2986                 "filecache is low (%" PRId64 "kB < %" PRId64 "kB) after thrashing",
2987                 file_lru_kb, filecache_min_kb);
2988             min_score_adj = PERCEPTIBLE_APP_ADJ + 1;
2989         } else {
2990             /* File cache is big enough, stop checking */
2991             check_filecache = false;
2992         }
2993     }
2994 
2995     /* Check if a cached app should be killed */
2996     if (kill_reason == NONE && wmark < WMARK_HIGH) {
2997         kill_reason = LOW_MEM;
2998         snprintf(kill_desc, sizeof(kill_desc), "%s watermark is breached",
2999             wmark < WMARK_LOW ? "min" : "low");
3000         min_score_adj = lowmem_min_oom_score;
3001     }
3002 
3003     /* Kill a process if necessary */
3004     if (kill_reason != NONE) {
3005         struct kill_info ki = {
3006             .kill_reason = kill_reason,
3007             .kill_desc = kill_desc,
3008             .thrashing = (int)thrashing,
3009             .max_thrashing = max_thrashing,
3010         };
3011         static bool first_kill = true;
3012 
3013         /* Make sure watermarks are correct before the first kill */
3014         if (first_kill) {
3015             first_kill = false;
3016             watermarks.high_wmark = 0;  // force recomputation
3017             goto update_watermarks;
3018         }
3019 
3020         /* Allow killing perceptible apps if the system is stalled */
3021         if (critical_stall) {
3022             min_score_adj = 0;
3023         }
3024         psi_parse_io(&psi_data);
3025         psi_parse_cpu(&psi_data);
3026         int pages_freed = find_and_kill_process(min_score_adj, &ki, &mi, &wi, &curr_tm, &psi_data);
3027         if (pages_freed > 0) {
3028             killing = true;
3029             max_thrashing = 0;
3030             if (cut_thrashing_limit) {
3031                 /*
3032                  * Cut thrasing limit by thrashing_limit_decay_pct percentage of the current
3033                  * thrashing limit until the system stops thrashing.
3034                  */
3035                 thrashing_limit = (thrashing_limit * (100 - thrashing_limit_decay_pct)) / 100;
3036             }
3037         }
3038     }
3039 
3040 no_kill:
3041     /* Do not poll if kernel supports pidfd waiting */
3042     if (is_waiting_for_kill()) {
3043         /* Pause polling if we are waiting for process death notification */
3044         poll_params->update = POLLING_PAUSE;
3045         return;
3046     }
3047 
3048     /*
3049      * Start polling after initial PSI event;
3050      * extend polling while device is in direct reclaim or process is being killed;
3051      * do not extend when kswapd reclaims because that might go on for a long time
3052      * without causing memory pressure
3053      */
3054     if (events || killing || reclaim == DIRECT_RECLAIM) {
3055         poll_params->update = POLLING_START;
3056     }
3057 
3058     /* Decide the polling interval */
3059     if (swap_is_low || killing) {
3060         /* Fast polling during and after a kill or when swap is low */
3061         poll_params->polling_interval_ms = PSI_POLL_PERIOD_SHORT_MS;
3062     } else {
3063         /* By default use long intervals */
3064         poll_params->polling_interval_ms = PSI_POLL_PERIOD_LONG_MS;
3065     }
3066 }
3067 
GetCgroupAttributePath(const char * attr)3068 static std::string GetCgroupAttributePath(const char* attr) {
3069     std::string path;
3070     if (!CgroupGetAttributePath(attr, &path)) {
3071         ALOGE("Unknown cgroup attribute %s", attr);
3072     }
3073     return path;
3074 }
3075 
3076 // The implementation of this function relies on memcg statistics that are only available in the
3077 // v1 cgroup hierarchy.
mp_event_common(int data,uint32_t events,struct polling_params * poll_params)3078 static void mp_event_common(int data, uint32_t events, struct polling_params *poll_params) {
3079     unsigned long long evcount;
3080     int64_t mem_usage, memsw_usage;
3081     int64_t mem_pressure;
3082     union meminfo mi;
3083     struct zoneinfo zi;
3084     struct timespec curr_tm;
3085     static unsigned long kill_skip_count = 0;
3086     enum vmpressure_level level = (enum vmpressure_level)data;
3087     long other_free = 0, other_file = 0;
3088     int min_score_adj;
3089     int minfree = 0;
3090     static const std::string mem_usage_path = GetCgroupAttributePath("MemUsage");
3091     static struct reread_data mem_usage_file_data = {
3092         .filename = mem_usage_path.c_str(),
3093         .fd = -1,
3094     };
3095     static const std::string memsw_usage_path = GetCgroupAttributePath("MemAndSwapUsage");
3096     static struct reread_data memsw_usage_file_data = {
3097         .filename = memsw_usage_path.c_str(),
3098         .fd = -1,
3099     };
3100     static struct wakeup_info wi;
3101 
3102     mp_event_count++;
3103     if (debug_process_killing) {
3104         ALOGI("%s memory pressure event #%" PRIu64 " is triggered",
3105               level_name[level], mp_event_count);
3106     }
3107 
3108     if (!use_psi_monitors) {
3109         /*
3110          * Check all event counters from low to critical
3111          * and upgrade to the highest priority one. By reading
3112          * eventfd we also reset the event counters.
3113          */
3114         for (int lvl = VMPRESS_LEVEL_LOW; lvl < VMPRESS_LEVEL_COUNT; lvl++) {
3115             if (mpevfd[lvl] != -1 &&
3116                 TEMP_FAILURE_RETRY(read(mpevfd[lvl],
3117                                    &evcount, sizeof(evcount))) > 0 &&
3118                 evcount > 0 && lvl > level) {
3119                 level = static_cast<vmpressure_level>(lvl);
3120             }
3121         }
3122     }
3123 
3124     /* Start polling after initial PSI event */
3125     if (use_psi_monitors && events) {
3126         /* Override polling params only if current event is more critical */
3127         if (!poll_params->poll_handler || data > poll_params->poll_handler->data) {
3128             poll_params->polling_interval_ms = PSI_POLL_PERIOD_SHORT_MS;
3129             poll_params->update = POLLING_START;
3130         }
3131     }
3132 
3133     if (clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm) != 0) {
3134         ALOGE("Failed to get current time");
3135         return;
3136     }
3137 
3138     record_wakeup_time(&curr_tm, events ? Event : Polling, &wi);
3139 
3140     if (kill_timeout_ms &&
3141         get_time_diff_ms(&last_kill_tm, &curr_tm) < static_cast<long>(kill_timeout_ms)) {
3142         /*
3143          * If we're within the no-kill timeout, see if there's pending reclaim work
3144          * from the last killed process. If so, skip killing for now.
3145          */
3146         if (is_kill_pending()) {
3147             kill_skip_count++;
3148             wi.skipped_wakeups++;
3149             return;
3150         }
3151         /*
3152          * Process is dead, stop waiting. This has no effect if pidfds are supported and
3153          * death notification already caused waiting to stop.
3154          */
3155         stop_wait_for_proc_kill(true);
3156     } else {
3157         /*
3158          * Killing took longer than no-kill timeout. Stop waiting for the last process
3159          * to die because we are ready to kill again.
3160          */
3161         stop_wait_for_proc_kill(false);
3162     }
3163 
3164     if (kill_skip_count > 0) {
3165         ALOGI("%lu memory pressure events were skipped after a kill!",
3166               kill_skip_count);
3167         kill_skip_count = 0;
3168     }
3169 
3170     if (meminfo_parse(&mi) < 0 || zoneinfo_parse(&zi) < 0) {
3171         ALOGE("Failed to get free memory!");
3172         return;
3173     }
3174 
3175     if (use_minfree_levels) {
3176         int i;
3177 
3178         other_free = mi.field.nr_free_pages - zi.totalreserve_pages;
3179         if (mi.field.nr_file_pages > (mi.field.shmem + mi.field.unevictable + mi.field.swap_cached)) {
3180             other_file = (mi.field.nr_file_pages - mi.field.shmem -
3181                           mi.field.unevictable - mi.field.swap_cached);
3182         } else {
3183             other_file = 0;
3184         }
3185 
3186         min_score_adj = OOM_SCORE_ADJ_MAX + 1;
3187         for (i = 0; i < lowmem_targets_size; i++) {
3188             minfree = lowmem_minfree[i];
3189             if (other_free < minfree && other_file < minfree) {
3190                 min_score_adj = lowmem_adj[i];
3191                 break;
3192             }
3193         }
3194 
3195         if (min_score_adj == OOM_SCORE_ADJ_MAX + 1) {
3196             if (debug_process_killing && lowmem_targets_size) {
3197                 ALOGI("Ignore %s memory pressure event "
3198                       "(free memory=%ldkB, cache=%ldkB, limit=%ldkB)",
3199                       level_name[level], other_free * page_k, other_file * page_k,
3200                       (long)lowmem_minfree[lowmem_targets_size - 1] * page_k);
3201             }
3202             return;
3203         }
3204 
3205         goto do_kill;
3206     }
3207 
3208     if (level == VMPRESS_LEVEL_LOW) {
3209         record_low_pressure_levels(&mi);
3210     }
3211 
3212     if (level_oomadj[level] > OOM_SCORE_ADJ_MAX) {
3213         /* Do not monitor this pressure level */
3214         return;
3215     }
3216 
3217     if ((mem_usage = get_memory_usage(&mem_usage_file_data)) < 0) {
3218         goto do_kill;
3219     }
3220     if ((memsw_usage = get_memory_usage(&memsw_usage_file_data)) < 0) {
3221         goto do_kill;
3222     }
3223 
3224     // Calculate percent for swappinness.
3225     mem_pressure = (mem_usage * 100) / memsw_usage;
3226 
3227     if (enable_pressure_upgrade && level != VMPRESS_LEVEL_CRITICAL) {
3228         // We are swapping too much.
3229         if (mem_pressure < upgrade_pressure) {
3230             level = upgrade_level(level);
3231             if (debug_process_killing) {
3232                 ALOGI("Event upgraded to %s", level_name[level]);
3233             }
3234         }
3235     }
3236 
3237     // If we still have enough swap space available, check if we want to
3238     // ignore/downgrade pressure events.
3239     if (get_free_swap(&mi) >=
3240         mi.field.total_swap * swap_free_low_percentage / 100) {
3241         // If the pressure is larger than downgrade_pressure lmk will not
3242         // kill any process, since enough memory is available.
3243         if (mem_pressure > downgrade_pressure) {
3244             if (debug_process_killing) {
3245                 ALOGI("Ignore %s memory pressure", level_name[level]);
3246             }
3247             return;
3248         } else if (level == VMPRESS_LEVEL_CRITICAL && mem_pressure > upgrade_pressure) {
3249             if (debug_process_killing) {
3250                 ALOGI("Downgrade critical memory pressure");
3251             }
3252             // Downgrade event, since enough memory available.
3253             level = downgrade_level(level);
3254         }
3255     }
3256 
3257 do_kill:
3258     if (low_ram_device) {
3259         /* For Go devices kill only one task */
3260         if (find_and_kill_process(use_minfree_levels ? min_score_adj : level_oomadj[level],
3261                                   NULL, &mi, &wi, &curr_tm, NULL) == 0) {
3262             if (debug_process_killing) {
3263                 ALOGI("Nothing to kill");
3264             }
3265         }
3266     } else {
3267         int pages_freed;
3268         static struct timespec last_report_tm;
3269         static unsigned long report_skip_count = 0;
3270 
3271         if (!use_minfree_levels) {
3272             /* Free up enough memory to downgrate the memory pressure to low level */
3273             if (mi.field.nr_free_pages >= low_pressure_mem.max_nr_free_pages) {
3274                 if (debug_process_killing) {
3275                     ALOGI("Ignoring pressure since more memory is "
3276                         "available (%" PRId64 ") than watermark (%" PRId64 ")",
3277                         mi.field.nr_free_pages, low_pressure_mem.max_nr_free_pages);
3278                 }
3279                 return;
3280             }
3281             min_score_adj = level_oomadj[level];
3282         }
3283 
3284         pages_freed = find_and_kill_process(min_score_adj, NULL, &mi, &wi, &curr_tm, NULL);
3285 
3286         if (pages_freed == 0 && min_score_adj == 0) {
3287             lmkd_no_kill_candidates_hook();
3288         }
3289 
3290         if (pages_freed == 0) {
3291             /* Rate limit kill reports when nothing was reclaimed */
3292             if (get_time_diff_ms(&last_report_tm, &curr_tm) < FAIL_REPORT_RLIMIT_MS) {
3293                 report_skip_count++;
3294                 return;
3295             }
3296         }
3297 
3298         /* Log whenever we kill or when report rate limit allows */
3299         if (use_minfree_levels) {
3300             ALOGI("Reclaimed %ldkB, cache(%ldkB) and free(%" PRId64 "kB)-reserved(%" PRId64 "kB) "
3301                 "below min(%ldkB) for oom_score_adj %d",
3302                 pages_freed * page_k,
3303                 other_file * page_k, mi.field.nr_free_pages * page_k,
3304                 zi.totalreserve_pages * page_k,
3305                 minfree * page_k, min_score_adj);
3306         } else {
3307             ALOGI("Reclaimed %ldkB at oom_score_adj %d", pages_freed * page_k, min_score_adj);
3308         }
3309 
3310         if (report_skip_count > 0) {
3311             ALOGI("Suppressed %lu failed kill reports", report_skip_count);
3312             report_skip_count = 0;
3313         }
3314 
3315         last_report_tm = curr_tm;
3316     }
3317     if (is_waiting_for_kill()) {
3318         /* pause polling if we are waiting for process death notification */
3319         poll_params->update = POLLING_PAUSE;
3320     }
3321 }
3322 
init_mp_psi(enum vmpressure_level level,bool use_new_strategy)3323 static bool init_mp_psi(enum vmpressure_level level, bool use_new_strategy) {
3324     int fd;
3325 
3326     /* Do not register a handler if threshold_ms is not set */
3327     if (!psi_thresholds[level].threshold_ms) {
3328         return true;
3329     }
3330 
3331     fd = init_psi_monitor(psi_thresholds[level].stall_type,
3332         psi_thresholds[level].threshold_ms * US_PER_MS,
3333         PSI_WINDOW_SIZE_MS * US_PER_MS);
3334 
3335     if (fd < 0) {
3336         return false;
3337     }
3338 
3339     vmpressure_hinfo[level].handler = use_new_strategy ? mp_event_psi : mp_event_common;
3340     vmpressure_hinfo[level].data = level;
3341     if (register_psi_monitor(epollfd, fd, &vmpressure_hinfo[level]) < 0) {
3342         destroy_psi_monitor(fd);
3343         return false;
3344     }
3345     maxevents++;
3346     mpevfd[level] = fd;
3347 
3348     return true;
3349 }
3350 
destroy_mp_psi(enum vmpressure_level level)3351 static void destroy_mp_psi(enum vmpressure_level level) {
3352     int fd = mpevfd[level];
3353 
3354     if (fd < 0) {
3355         return;
3356     }
3357 
3358     if (unregister_psi_monitor(epollfd, fd) < 0) {
3359         ALOGE("Failed to unregister psi monitor for %s memory pressure; errno=%d",
3360             level_name[level], errno);
3361     }
3362     maxevents--;
3363     destroy_psi_monitor(fd);
3364     mpevfd[level] = -1;
3365 }
3366 
3367 enum class MemcgVersion {
3368     kNotFound,
3369     kV1,
3370     kV2,
3371 };
3372 
__memcg_version()3373 static MemcgVersion __memcg_version() {
3374     std::string cgroupv2_path, memcg_path;
3375 
3376     if (!CgroupGetControllerPath("memory", &memcg_path)) {
3377         return MemcgVersion::kNotFound;
3378     }
3379     return CgroupGetControllerPath(CGROUPV2_HIERARCHY_NAME, &cgroupv2_path) &&
3380                            cgroupv2_path == memcg_path
3381                    ? MemcgVersion::kV2
3382                    : MemcgVersion::kV1;
3383 }
3384 
memcg_version()3385 static MemcgVersion memcg_version() {
3386     static MemcgVersion version = __memcg_version();
3387 
3388     return version;
3389 }
3390 
memevent_listener_notification(int data __unused,uint32_t events __unused,struct polling_params * poll_params __unused)3391 static void memevent_listener_notification(int data __unused, uint32_t events __unused,
3392                                            struct polling_params* poll_params __unused) {
3393     struct timespec curr_tm;
3394     std::vector<mem_event_t> mem_events;
3395 
3396     if (clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm) != 0) {
3397         direct_reclaim_start_tm.tv_sec = 0;
3398         direct_reclaim_start_tm.tv_nsec = 0;
3399         ALOGE("Failed to get current time for memevent listener notification.");
3400         return;
3401     }
3402 
3403     if (!memevent_listener->getMemEvents(mem_events)) {
3404         direct_reclaim_start_tm.tv_sec = 0;
3405         direct_reclaim_start_tm.tv_nsec = 0;
3406         ALOGE("Failed fetching memory listener events.");
3407         return;
3408     }
3409 
3410     for (const mem_event_t& mem_event : mem_events) {
3411         switch (mem_event.type) {
3412             /* Direct Reclaim */
3413             case MEM_EVENT_DIRECT_RECLAIM_BEGIN:
3414                 direct_reclaim_start_tm = curr_tm;
3415                 break;
3416             case MEM_EVENT_DIRECT_RECLAIM_END:
3417                 direct_reclaim_start_tm.tv_sec = 0;
3418                 direct_reclaim_start_tm.tv_nsec = 0;
3419                 break;
3420 
3421             /* kswapd */
3422             case MEM_EVENT_KSWAPD_WAKE:
3423                 kswapd_start_tm = curr_tm;
3424                 break;
3425             case MEM_EVENT_KSWAPD_SLEEP:
3426                 kswapd_start_tm.tv_sec = 0;
3427                 kswapd_start_tm.tv_nsec = 0;
3428                 break;
3429         }
3430     }
3431 }
3432 
init_memevent_listener_monitoring()3433 static bool init_memevent_listener_monitoring() {
3434     static struct event_handler_info direct_reclaim_poll_hinfo = {0,
3435                                                                   memevent_listener_notification};
3436 
3437     if (memevent_listener) return true;
3438 
3439     // Make sure bpf programs are loaded, else we'll wait until they are loaded
3440     android::bpf::waitForProgsLoaded();
3441     memevent_listener = std::make_unique<android::bpf::memevents::MemEventListener>(
3442             android::bpf::memevents::MemEventClient::LMKD);
3443 
3444     if (!memevent_listener->ok()) {
3445         ALOGE("Failed to initialize memevents listener");
3446         memevent_listener.reset();
3447         return false;
3448     }
3449 
3450     if (!memevent_listener->registerEvent(MEM_EVENT_DIRECT_RECLAIM_BEGIN) ||
3451         !memevent_listener->registerEvent(MEM_EVENT_DIRECT_RECLAIM_END)) {
3452         ALOGE("Failed to register direct reclaim memevents");
3453         memevent_listener.reset();
3454         return false;
3455     }
3456     if (!memevent_listener->registerEvent(MEM_EVENT_KSWAPD_WAKE) ||
3457         !memevent_listener->registerEvent(MEM_EVENT_KSWAPD_SLEEP)) {
3458         ALOGE("Failed to register kswapd memevents");
3459         memevent_listener.reset();
3460         return false;
3461     }
3462 
3463     int memevent_listener_fd = memevent_listener->getRingBufferFd();
3464     if (memevent_listener_fd < 0) {
3465         memevent_listener.reset();
3466         ALOGE("Invalid memevent_listener fd: %d", memevent_listener_fd);
3467         return false;
3468     }
3469 
3470     struct epoll_event epev;
3471     epev.events = EPOLLIN;
3472     epev.data.ptr = (void*)&direct_reclaim_poll_hinfo;
3473     if (epoll_ctl(epollfd, EPOLL_CTL_ADD, memevent_listener_fd, &epev) < 0) {
3474         ALOGE("Failed registering memevent_listener fd: %d; errno=%d", memevent_listener_fd, errno);
3475         memevent_listener.reset();
3476         return false;
3477     }
3478 
3479     direct_reclaim_start_tm.tv_sec = 0;
3480     direct_reclaim_start_tm.tv_nsec = 0;
3481 
3482     maxevents++;
3483     return true;
3484 }
3485 
init_psi_monitors()3486 static bool init_psi_monitors() {
3487     /*
3488      * When PSI is used on low-ram devices or on high-end devices without memfree levels
3489      * use new kill strategy based on zone watermarks, free swap and thrashing stats.
3490      * Also use the new strategy if memcg has not been mounted in the v1 cgroups hiearchy since
3491      * the old strategy relies on memcg attributes that are available only in the v1 cgroups
3492      * hiearchy.
3493      */
3494     bool use_new_strategy =
3495         GET_LMK_PROPERTY(bool, "use_new_strategy", low_ram_device || !use_minfree_levels);
3496     if (!use_new_strategy && memcg_version() != MemcgVersion::kV1) {
3497         ALOGE("Old kill strategy can only be used with v1 cgroup hierarchy");
3498         return false;
3499     }
3500     /* In default PSI mode override stall amounts using system properties */
3501     if (use_new_strategy) {
3502         /* Do not use low pressure level */
3503         psi_thresholds[VMPRESS_LEVEL_LOW].threshold_ms = 0;
3504         psi_thresholds[VMPRESS_LEVEL_MEDIUM].threshold_ms = psi_partial_stall_ms;
3505         psi_thresholds[VMPRESS_LEVEL_CRITICAL].threshold_ms = psi_complete_stall_ms;
3506     }
3507 
3508     if (!init_mp_psi(VMPRESS_LEVEL_LOW, use_new_strategy)) {
3509         return false;
3510     }
3511     if (!init_mp_psi(VMPRESS_LEVEL_MEDIUM, use_new_strategy)) {
3512         destroy_mp_psi(VMPRESS_LEVEL_LOW);
3513         return false;
3514     }
3515     if (!init_mp_psi(VMPRESS_LEVEL_CRITICAL, use_new_strategy)) {
3516         destroy_mp_psi(VMPRESS_LEVEL_MEDIUM);
3517         destroy_mp_psi(VMPRESS_LEVEL_LOW);
3518         return false;
3519     }
3520     return true;
3521 }
3522 
init_mp_common(enum vmpressure_level level)3523 static bool init_mp_common(enum vmpressure_level level) {
3524     // The implementation of this function relies on memcg statistics that are only available in the
3525     // v1 cgroup hierarchy.
3526     if (memcg_version() != MemcgVersion::kV1) {
3527         ALOGE("%s: global monitoring is only available for the v1 cgroup hierarchy", __func__);
3528         return false;
3529     }
3530 
3531     int mpfd;
3532     int evfd;
3533     int evctlfd;
3534     char buf[256];
3535     struct epoll_event epev;
3536     int ret;
3537     int level_idx = (int)level;
3538     const char *levelstr = level_name[level_idx];
3539 
3540     /* gid containing AID_SYSTEM required */
3541     mpfd = open(GetCgroupAttributePath("MemPressureLevel").c_str(), O_RDONLY | O_CLOEXEC);
3542     if (mpfd < 0) {
3543         ALOGI("No kernel memory.pressure_level support (errno=%d)", errno);
3544         goto err_open_mpfd;
3545     }
3546 
3547     evctlfd = open(GetCgroupAttributePath("MemCgroupEventControl").c_str(), O_WRONLY | O_CLOEXEC);
3548     if (evctlfd < 0) {
3549         ALOGI("No kernel memory cgroup event control (errno=%d)", errno);
3550         goto err_open_evctlfd;
3551     }
3552 
3553     evfd = eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC);
3554     if (evfd < 0) {
3555         ALOGE("eventfd failed for level %s; errno=%d", levelstr, errno);
3556         goto err_eventfd;
3557     }
3558 
3559     ret = snprintf(buf, sizeof(buf), "%d %d %s", evfd, mpfd, levelstr);
3560     if (ret >= (ssize_t)sizeof(buf)) {
3561         ALOGE("cgroup.event_control line overflow for level %s", levelstr);
3562         goto err;
3563     }
3564 
3565     ret = TEMP_FAILURE_RETRY(write(evctlfd, buf, strlen(buf) + 1));
3566     if (ret == -1) {
3567         ALOGE("cgroup.event_control write failed for level %s; errno=%d",
3568               levelstr, errno);
3569         goto err;
3570     }
3571 
3572     epev.events = EPOLLIN;
3573     /* use data to store event level */
3574     vmpressure_hinfo[level_idx].data = level_idx;
3575     vmpressure_hinfo[level_idx].handler = mp_event_common;
3576     epev.data.ptr = (void *)&vmpressure_hinfo[level_idx];
3577     ret = epoll_ctl(epollfd, EPOLL_CTL_ADD, evfd, &epev);
3578     if (ret == -1) {
3579         ALOGE("epoll_ctl for level %s failed; errno=%d", levelstr, errno);
3580         goto err;
3581     }
3582     maxevents++;
3583     mpevfd[level] = evfd;
3584     close(evctlfd);
3585     return true;
3586 
3587 err:
3588     close(evfd);
3589 err_eventfd:
3590     close(evctlfd);
3591 err_open_evctlfd:
3592     close(mpfd);
3593 err_open_mpfd:
3594     return false;
3595 }
3596 
destroy_mp_common(enum vmpressure_level level)3597 static void destroy_mp_common(enum vmpressure_level level) {
3598     struct epoll_event epev;
3599     int fd = mpevfd[level];
3600 
3601     if (fd < 0) {
3602         return;
3603     }
3604 
3605     if (epoll_ctl(epollfd, EPOLL_CTL_DEL, fd, &epev)) {
3606         // Log an error and keep going
3607         ALOGE("epoll_ctl for level %s failed; errno=%d", level_name[level], errno);
3608     }
3609     maxevents--;
3610     close(fd);
3611     mpevfd[level] = -1;
3612 }
3613 
kernel_event_handler(int data __unused,uint32_t events __unused,struct polling_params * poll_params __unused)3614 static void kernel_event_handler(int data __unused, uint32_t events __unused,
3615                                  struct polling_params *poll_params __unused) {
3616     poll_kernel(kpoll_fd);
3617 }
3618 
init_monitors()3619 static bool init_monitors() {
3620     ALOGI("Wakeup counter is reset from %" PRIu64 " to 0", mp_event_count);
3621     mp_event_count = 0;
3622     /* Try to use psi monitor first if kernel has it */
3623     use_psi_monitors = GET_LMK_PROPERTY(bool, "use_psi", true) &&
3624         init_psi_monitors();
3625     /* Fall back to vmpressure */
3626     if (!use_psi_monitors &&
3627         (!init_mp_common(VMPRESS_LEVEL_LOW) ||
3628         !init_mp_common(VMPRESS_LEVEL_MEDIUM) ||
3629         !init_mp_common(VMPRESS_LEVEL_CRITICAL))) {
3630         ALOGE("Kernel does not support memory pressure events or in-kernel low memory killer");
3631         return false;
3632     }
3633     if (use_psi_monitors) {
3634         ALOGI("Using psi monitors for memory pressure detection");
3635     } else {
3636         ALOGI("Using vmpressure for memory pressure detection");
3637     }
3638 
3639     monitors_initialized = true;
3640     return true;
3641 }
3642 
destroy_monitors()3643 static void destroy_monitors() {
3644     if (use_psi_monitors) {
3645         destroy_mp_psi(VMPRESS_LEVEL_CRITICAL);
3646         destroy_mp_psi(VMPRESS_LEVEL_MEDIUM);
3647         destroy_mp_psi(VMPRESS_LEVEL_LOW);
3648     } else {
3649         destroy_mp_common(VMPRESS_LEVEL_CRITICAL);
3650         destroy_mp_common(VMPRESS_LEVEL_MEDIUM);
3651         destroy_mp_common(VMPRESS_LEVEL_LOW);
3652     }
3653 }
3654 
drop_reaper_comm()3655 static void drop_reaper_comm() {
3656     close(reaper_comm_fd[0]);
3657     close(reaper_comm_fd[1]);
3658 }
3659 
setup_reaper_comm()3660 static bool setup_reaper_comm() {
3661     if (pipe(reaper_comm_fd)) {
3662         ALOGE("pipe failed: %s", strerror(errno));
3663         return false;
3664     }
3665 
3666     // Ensure main thread never blocks on read
3667     int flags = fcntl(reaper_comm_fd[0], F_GETFL);
3668     if (fcntl(reaper_comm_fd[0], F_SETFL, flags | O_NONBLOCK)) {
3669         ALOGE("fcntl failed: %s", strerror(errno));
3670         drop_reaper_comm();
3671         return false;
3672     }
3673 
3674     return true;
3675 }
3676 
init_reaper()3677 static bool init_reaper() {
3678     if (!reaper.is_reaping_supported()) {
3679         ALOGI("Process reaping is not supported");
3680         return false;
3681     }
3682 
3683     if (!setup_reaper_comm()) {
3684         ALOGE("Failed to create thread communication channel");
3685         return false;
3686     }
3687 
3688     // Setup epoll handler
3689     struct epoll_event epev;
3690     static struct event_handler_info kill_failed_hinfo = { 0, kill_fail_handler };
3691     epev.events = EPOLLIN;
3692     epev.data.ptr = (void *)&kill_failed_hinfo;
3693     if (epoll_ctl(epollfd, EPOLL_CTL_ADD, reaper_comm_fd[0], &epev)) {
3694         ALOGE("epoll_ctl failed: %s", strerror(errno));
3695         drop_reaper_comm();
3696         return false;
3697     }
3698 
3699     if (!reaper.init(reaper_comm_fd[1])) {
3700         ALOGE("Failed to initialize reaper object");
3701         if (epoll_ctl(epollfd, EPOLL_CTL_DEL, reaper_comm_fd[0], &epev)) {
3702             ALOGE("epoll_ctl failed: %s", strerror(errno));
3703         }
3704         drop_reaper_comm();
3705         return false;
3706     }
3707     maxevents++;
3708 
3709     return true;
3710 }
3711 
init(void)3712 static int init(void) {
3713     static struct event_handler_info kernel_poll_hinfo = { 0, kernel_event_handler };
3714     struct reread_data file_data = {
3715         .filename = ZONEINFO_PATH,
3716         .fd = -1,
3717     };
3718     struct epoll_event epev;
3719     int pidfd;
3720     int i;
3721     int ret;
3722 
3723     // Initialize page size
3724     pagesize = getpagesize();
3725     page_k = pagesize / 1024;
3726 
3727     epollfd = epoll_create(MAX_EPOLL_EVENTS);
3728     if (epollfd == -1) {
3729         ALOGE("epoll_create failed (errno=%d)", errno);
3730         return -1;
3731     }
3732 
3733     // mark data connections as not connected
3734     for (int i = 0; i < MAX_DATA_CONN; i++) {
3735         data_sock[i].sock = -1;
3736     }
3737 
3738     ctrl_sock.sock = android_get_control_socket("lmkd");
3739     if (ctrl_sock.sock < 0) {
3740         ALOGE("get lmkd control socket failed");
3741         return -1;
3742     }
3743 
3744     ret = listen(ctrl_sock.sock, MAX_DATA_CONN);
3745     if (ret < 0) {
3746         ALOGE("lmkd control socket listen failed (errno=%d)", errno);
3747         return -1;
3748     }
3749 
3750     epev.events = EPOLLIN;
3751     ctrl_sock.handler_info.handler = ctrl_connect_handler;
3752     epev.data.ptr = (void *)&(ctrl_sock.handler_info);
3753     if (epoll_ctl(epollfd, EPOLL_CTL_ADD, ctrl_sock.sock, &epev) == -1) {
3754         ALOGE("epoll_ctl for lmkd control socket failed (errno=%d)", errno);
3755         return -1;
3756     }
3757     maxevents++;
3758 
3759     has_inkernel_module = !access(INKERNEL_MINFREE_PATH, W_OK);
3760     use_inkernel_interface = has_inkernel_module;
3761 
3762     if (use_inkernel_interface) {
3763         ALOGI("Using in-kernel low memory killer interface");
3764         if (init_poll_kernel()) {
3765             epev.events = EPOLLIN;
3766             epev.data.ptr = (void*)&kernel_poll_hinfo;
3767             if (epoll_ctl(epollfd, EPOLL_CTL_ADD, kpoll_fd, &epev) != 0) {
3768                 ALOGE("epoll_ctl for lmk events failed (errno=%d)", errno);
3769                 close(kpoll_fd);
3770                 kpoll_fd = -1;
3771             } else {
3772                 maxevents++;
3773                 /* let the others know it does support reporting kills */
3774                 property_set("sys.lmk.reportkills", "1");
3775             }
3776         }
3777     } else {
3778         // Do not register monitors until boot completed for devices configured
3779         // for delaying monitors. This is done to save CPU cycles for low
3780         // resource devices during boot up.
3781         if (!delay_monitors_until_boot || property_get_bool("sys.boot_completed", false)) {
3782             if (!init_monitors()) {
3783                 return -1;
3784             }
3785         }
3786         /* let the others know it does support reporting kills */
3787         property_set("sys.lmk.reportkills", "1");
3788     }
3789 
3790     for (i = 0; i <= ADJTOSLOT(OOM_SCORE_ADJ_MAX); i++) {
3791         procadjslot_list[i].next = &procadjslot_list[i];
3792         procadjslot_list[i].prev = &procadjslot_list[i];
3793     }
3794 
3795     memset(killcnt_idx, KILLCNT_INVALID_IDX, sizeof(killcnt_idx));
3796 
3797     /*
3798      * Read zoneinfo as the biggest file we read to create and size the initial
3799      * read buffer and avoid memory re-allocations during memory pressure
3800      */
3801     if (reread_file(&file_data) == NULL) {
3802         ALOGE("Failed to read %s: %s", file_data.filename, strerror(errno));
3803     }
3804 
3805     /* check if kernel supports pidfd_open syscall */
3806     pidfd = TEMP_FAILURE_RETRY(pidfd_open(getpid(), 0));
3807     if (pidfd < 0) {
3808         pidfd_supported = (errno != ENOSYS);
3809     } else {
3810         pidfd_supported = true;
3811         close(pidfd);
3812     }
3813     ALOGI("Process polling is %s", pidfd_supported ? "supported" : "not supported" );
3814 
3815     if (!lmkd_init_hook()) {
3816         ALOGE("Failed to initialize LMKD hooks.");
3817         return -1;
3818     }
3819 
3820     return 0;
3821 }
3822 
polling_paused(struct polling_params * poll_params)3823 static bool polling_paused(struct polling_params *poll_params) {
3824     return poll_params->paused_handler != NULL;
3825 }
3826 
resume_polling(struct polling_params * poll_params,struct timespec curr_tm)3827 static void resume_polling(struct polling_params *poll_params, struct timespec curr_tm) {
3828     poll_params->poll_start_tm = curr_tm;
3829     poll_params->poll_handler = poll_params->paused_handler;
3830     poll_params->polling_interval_ms = PSI_POLL_PERIOD_SHORT_MS;
3831     poll_params->paused_handler = NULL;
3832 }
3833 
call_handler(struct event_handler_info * handler_info,struct polling_params * poll_params,uint32_t events)3834 static void call_handler(struct event_handler_info* handler_info,
3835                          struct polling_params *poll_params, uint32_t events) {
3836     struct timespec curr_tm;
3837 
3838     watchdog.start();
3839     poll_params->update = POLLING_DO_NOT_CHANGE;
3840     handler_info->handler(handler_info->data, events, poll_params);
3841     clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm);
3842     if (poll_params->poll_handler == handler_info) {
3843         poll_params->last_poll_tm = curr_tm;
3844     }
3845 
3846     switch (poll_params->update) {
3847     case POLLING_START:
3848         /*
3849          * Poll for the duration of PSI_WINDOW_SIZE_MS after the
3850          * initial PSI event because psi events are rate-limited
3851          * at one per sec.
3852          */
3853         poll_params->poll_start_tm = curr_tm;
3854         poll_params->poll_handler = handler_info;
3855         poll_params->last_poll_tm = curr_tm;
3856         break;
3857     case POLLING_PAUSE:
3858         poll_params->paused_handler = handler_info;
3859         poll_params->poll_handler = NULL;
3860         break;
3861     case POLLING_RESUME:
3862         resume_polling(poll_params, curr_tm);
3863         break;
3864     case POLLING_DO_NOT_CHANGE:
3865         if (poll_params->poll_handler &&
3866             get_time_diff_ms(&poll_params->poll_start_tm, &curr_tm) > PSI_WINDOW_SIZE_MS) {
3867             /* Polled for the duration of PSI window, time to stop */
3868             poll_params->poll_handler = NULL;
3869         }
3870         break;
3871     }
3872     watchdog.stop();
3873 }
3874 
mainloop(void)3875 static void mainloop(void) {
3876     struct event_handler_info* handler_info;
3877     struct polling_params poll_params;
3878     struct timespec curr_tm;
3879     struct epoll_event *evt;
3880     long delay = -1;
3881 
3882     poll_params.poll_handler = NULL;
3883     poll_params.paused_handler = NULL;
3884 
3885     while (1) {
3886         struct epoll_event events[MAX_EPOLL_EVENTS];
3887         int nevents;
3888         int i;
3889 
3890         if (poll_params.poll_handler) {
3891             bool poll_now;
3892 
3893             clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm);
3894             if (poll_params.update == POLLING_RESUME) {
3895                 /* Just transitioned into POLLING_RESUME, poll immediately. */
3896                 poll_now = true;
3897                 nevents = 0;
3898             } else {
3899                 /* Calculate next timeout */
3900                 delay = get_time_diff_ms(&poll_params.last_poll_tm, &curr_tm);
3901                 delay = (delay < poll_params.polling_interval_ms) ?
3902                     poll_params.polling_interval_ms - delay : poll_params.polling_interval_ms;
3903 
3904                 /* Wait for events until the next polling timeout */
3905                 nevents = epoll_wait(epollfd, events, maxevents, delay);
3906 
3907                 /* Update current time after wait */
3908                 clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm);
3909                 poll_now = (get_time_diff_ms(&poll_params.last_poll_tm, &curr_tm) >=
3910                     poll_params.polling_interval_ms);
3911             }
3912             if (poll_now) {
3913                 call_handler(poll_params.poll_handler, &poll_params, 0);
3914             }
3915         } else {
3916             if (kill_timeout_ms && is_waiting_for_kill()) {
3917                 clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm);
3918                 delay = kill_timeout_ms - get_time_diff_ms(&last_kill_tm, &curr_tm);
3919                 /* Wait for pidfds notification or kill timeout to expire */
3920                 nevents = (delay > 0) ? epoll_wait(epollfd, events, maxevents, delay) : 0;
3921                 if (nevents == 0) {
3922                     /* Kill notification timed out */
3923                     stop_wait_for_proc_kill(false);
3924                     if (polling_paused(&poll_params)) {
3925                         clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm);
3926                         poll_params.update = POLLING_RESUME;
3927                         resume_polling(&poll_params, curr_tm);
3928                     }
3929                 }
3930             } else {
3931                 /* Wait for events with no timeout */
3932                 nevents = epoll_wait(epollfd, events, maxevents, -1);
3933             }
3934         }
3935 
3936         if (nevents == -1) {
3937             if (errno == EINTR)
3938                 continue;
3939             ALOGE("epoll_wait failed (errno=%d)", errno);
3940             continue;
3941         }
3942 
3943         /*
3944          * First pass to see if any data socket connections were dropped.
3945          * Dropped connection should be handled before any other events
3946          * to deallocate data connection and correctly handle cases when
3947          * connection gets dropped and reestablished in the same epoll cycle.
3948          * In such cases it's essential to handle connection closures first.
3949          */
3950         for (i = 0, evt = &events[0]; i < nevents; ++i, evt++) {
3951             if ((evt->events & EPOLLHUP) && evt->data.ptr) {
3952                 handler_info = (struct event_handler_info*)evt->data.ptr;
3953                 if (handler_info->handler == kill_done_handler) {
3954                     call_handler(handler_info, &poll_params, evt->events);
3955                 } else {
3956                     ALOGI("lmkd data connection dropped");
3957                     watchdog.start();
3958                     ctrl_data_close(handler_info->data);
3959                     watchdog.stop();
3960                 }
3961             }
3962         }
3963 
3964         /* Second pass to handle all other events */
3965         for (i = 0, evt = &events[0]; i < nevents; ++i, evt++) {
3966             if (evt->events & EPOLLERR) {
3967                 ALOGD("EPOLLERR on event #%d", i);
3968             }
3969             if (evt->events & EPOLLHUP) {
3970                 /* This case was handled in the first pass */
3971                 continue;
3972             }
3973             if (evt->data.ptr) {
3974                 handler_info = (struct event_handler_info*)evt->data.ptr;
3975                 call_handler(handler_info, &poll_params, evt->events);
3976             }
3977         }
3978     }
3979 }
3980 
issue_reinit()3981 int issue_reinit() {
3982     int sock;
3983 
3984     sock = lmkd_connect();
3985     if (sock < 0) {
3986         ALOGE("failed to connect to lmkd: %s", strerror(errno));
3987         return -1;
3988     }
3989 
3990     enum update_props_result res = lmkd_update_props(sock);
3991     switch (res) {
3992     case UPDATE_PROPS_SUCCESS:
3993         ALOGI("lmkd updated properties successfully");
3994         break;
3995     case UPDATE_PROPS_SEND_ERR:
3996         ALOGE("failed to send lmkd request: %s", strerror(errno));
3997         break;
3998     case UPDATE_PROPS_RECV_ERR:
3999         ALOGE("failed to receive lmkd reply: %s", strerror(errno));
4000         break;
4001     case UPDATE_PROPS_FORMAT_ERR:
4002         ALOGE("lmkd reply is invalid");
4003         break;
4004     case UPDATE_PROPS_FAIL:
4005         ALOGE("lmkd failed to update its properties");
4006         break;
4007     }
4008 
4009     close(sock);
4010     return res == UPDATE_PROPS_SUCCESS ? 0 : -1;
4011 }
4012 
on_boot_completed()4013 static int on_boot_completed() {
4014     int sock;
4015 
4016     sock = lmkd_connect();
4017     if (sock < 0) {
4018         ALOGE("failed to connect to lmkd: %s", strerror(errno));
4019         return -1;
4020     }
4021 
4022     enum boot_completed_notification_result res = lmkd_notify_boot_completed(sock);
4023 
4024     switch (res) {
4025         case BOOT_COMPLETED_NOTIF_SUCCESS:
4026             break;
4027         case BOOT_COMPLETED_NOTIF_ALREADY_HANDLED:
4028             ALOGW("lmkd already handled boot-completed operations");
4029             break;
4030         case BOOT_COMPLETED_NOTIF_SEND_ERR:
4031             ALOGE("failed to send lmkd request: %m");
4032             break;
4033         case BOOT_COMPLETED_NOTIF_RECV_ERR:
4034             ALOGE("failed to receive request: %m");
4035             break;
4036         case BOOT_COMPLETED_NOTIF_FORMAT_ERR:
4037             ALOGE("lmkd reply is invalid");
4038             break;
4039         case BOOT_COMPLETED_NOTIF_FAILS:
4040             ALOGE("lmkd failed to receive boot-completed notification");
4041             break;
4042     }
4043 
4044     close(sock);
4045     return res == BOOT_COMPLETED_NOTIF_SUCCESS ? 0 : -1;
4046 }
4047 
update_props()4048 static bool update_props() {
4049     /* By default disable low level vmpressure events */
4050     level_oomadj[VMPRESS_LEVEL_LOW] =
4051         GET_LMK_PROPERTY(int32, "low", OOM_SCORE_ADJ_MAX + 1);
4052     level_oomadj[VMPRESS_LEVEL_MEDIUM] =
4053         GET_LMK_PROPERTY(int32, "medium", 800);
4054     level_oomadj[VMPRESS_LEVEL_CRITICAL] =
4055         GET_LMK_PROPERTY(int32, "critical", 0);
4056     debug_process_killing = GET_LMK_PROPERTY(bool, "debug", false);
4057 
4058     /* By default disable upgrade/downgrade logic */
4059     enable_pressure_upgrade =
4060         GET_LMK_PROPERTY(bool, "critical_upgrade", false);
4061     upgrade_pressure =
4062         (int64_t)GET_LMK_PROPERTY(int32, "upgrade_pressure", 100);
4063     downgrade_pressure =
4064         (int64_t)GET_LMK_PROPERTY(int32, "downgrade_pressure", 100);
4065     kill_heaviest_task =
4066         GET_LMK_PROPERTY(bool, "kill_heaviest_task", false);
4067     low_ram_device = property_get_bool("ro.config.low_ram", false);
4068     kill_timeout_ms =
4069         (unsigned long)GET_LMK_PROPERTY(int32, "kill_timeout_ms", 100);
4070     pressure_after_kill_min_score =
4071         (unsigned long)GET_LMK_PROPERTY(int32, "pressure_after_kill_min_score", 0);
4072     use_minfree_levels =
4073         GET_LMK_PROPERTY(bool, "use_minfree_levels", false);
4074     per_app_memcg =
4075         property_get_bool("ro.config.per_app_memcg", low_ram_device);
4076     swap_free_low_percentage = clamp(0, 100, GET_LMK_PROPERTY(int32, "swap_free_low_percentage",
4077         DEF_LOW_SWAP));
4078     psi_partial_stall_ms = GET_LMK_PROPERTY(int32, "psi_partial_stall_ms",
4079         low_ram_device ? DEF_PARTIAL_STALL_LOWRAM : DEF_PARTIAL_STALL);
4080     psi_complete_stall_ms = GET_LMK_PROPERTY(int32, "psi_complete_stall_ms",
4081         DEF_COMPLETE_STALL);
4082     thrashing_limit_pct =
4083             std::max(0, GET_LMK_PROPERTY(int32, "thrashing_limit",
4084                                          low_ram_device ? DEF_THRASHING_LOWRAM : DEF_THRASHING));
4085     thrashing_limit_decay_pct = clamp(0, 100, GET_LMK_PROPERTY(int32, "thrashing_limit_decay",
4086         low_ram_device ? DEF_THRASHING_DECAY_LOWRAM : DEF_THRASHING_DECAY));
4087     thrashing_critical_pct = std::max(
4088             0, GET_LMK_PROPERTY(int32, "thrashing_limit_critical", thrashing_limit_pct * 3));
4089     swap_util_max = clamp(0, 100, GET_LMK_PROPERTY(int32, "swap_util_max", 100));
4090     filecache_min_kb = GET_LMK_PROPERTY(int64, "filecache_min_kb", 0);
4091     stall_limit_critical = GET_LMK_PROPERTY(int64, "stall_limit_critical", 100);
4092     delay_monitors_until_boot = GET_LMK_PROPERTY(bool, "delay_monitors_until_boot", false);
4093     direct_reclaim_threshold_ms =
4094             GET_LMK_PROPERTY(int64, "direct_reclaim_threshold_ms", DEF_DIRECT_RECL_THRESH_MS);
4095     swap_compression_ratio =
4096             GET_LMK_PROPERTY(int64, "swap_compression_ratio", DEF_SWAP_COMP_RATIO);
4097     lowmem_min_oom_score =
4098             std::max(PERCEPTIBLE_APP_ADJ + 1,
4099                      GET_LMK_PROPERTY(int32, "lowmem_min_oom_score", DEF_LOWMEM_MIN_SCORE));
4100 
4101     reaper.enable_debug(debug_process_killing);
4102 
4103     /* Call the update props hook */
4104     if (!lmkd_update_props_hook()) {
4105         ALOGE("Failed to update LMKD hook props.");
4106         return false;
4107     }
4108 
4109     return true;
4110 }
4111 
main(int argc,char ** argv)4112 int main(int argc, char **argv) {
4113     if ((argc > 1) && argv[1]) {
4114         if (!strcmp(argv[1], "--reinit")) {
4115             if (property_set(LMKD_REINIT_PROP, "")) {
4116                 ALOGE("Failed to reset " LMKD_REINIT_PROP " property");
4117             }
4118             return issue_reinit();
4119         } else if (!strcmp(argv[1], "--boot_completed")) {
4120             return on_boot_completed();
4121         }
4122     }
4123 
4124     if (!update_props()) {
4125         ALOGE("Failed to initialize props, exiting.");
4126         return -1;
4127     }
4128 
4129     ctx = create_android_logger(KILLINFO_LOG_TAG);
4130 
4131     if (!init()) {
4132         if (!use_inkernel_interface) {
4133             /*
4134              * MCL_ONFAULT pins pages as they fault instead of loading
4135              * everything immediately all at once. (Which would be bad,
4136              * because as of this writing, we have a lot of mapped pages we
4137              * never use.) Old kernels will see MCL_ONFAULT and fail with
4138              * EINVAL; we ignore this failure.
4139              *
4140              * N.B. read the man page for mlockall. MCL_CURRENT | MCL_ONFAULT
4141              * pins ⊆ MCL_CURRENT, converging to just MCL_CURRENT as we fault
4142              * in pages.
4143              */
4144             /* CAP_IPC_LOCK required */
4145             if (mlockall(MCL_CURRENT | MCL_FUTURE | MCL_ONFAULT) && (errno != EINVAL)) {
4146                 ALOGW("mlockall failed %s", strerror(errno));
4147             }
4148 
4149             /* CAP_NICE required */
4150             struct sched_param param = {
4151                     .sched_priority = 1,
4152             };
4153             if (sched_setscheduler(0, SCHED_FIFO, &param)) {
4154                 ALOGW("set SCHED_FIFO failed %s", strerror(errno));
4155             }
4156         }
4157 
4158         if (init_reaper()) {
4159             ALOGI("Process reaper initialized with %d threads in the pool",
4160                 reaper.thread_cnt());
4161         }
4162 
4163         if (!watchdog.init()) {
4164             ALOGE("Failed to initialize the watchdog");
4165         }
4166 
4167         mainloop();
4168     }
4169 
4170     android_log_destroy(&ctx);
4171 
4172     ALOGI("exiting");
4173     return 0;
4174 }
4175