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