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 <dirent.h>
20 #include <errno.h>
21 #include <inttypes.h>
22 #include <pwd.h>
23 #include <sched.h>
24 #include <signal.h>
25 #include <statslog_lmkd.h>
26 #include <stdbool.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include <sys/cdefs.h>
30 #include <sys/epoll.h>
31 #include <sys/eventfd.h>
32 #include <sys/mman.h>
33 #include <sys/resource.h>
34 #include <sys/socket.h>
35 #include <sys/syscall.h>
36 #include <sys/sysinfo.h>
37 #include <sys/time.h>
38 #include <sys/types.h>
39 #include <time.h>
40 #include <unistd.h>
41 
42 #include <cutils/properties.h>
43 #include <cutils/sched_policy.h>
44 #include <cutils/sockets.h>
45 #include <liblmkd_utils.h>
46 #include <lmkd.h>
47 #include <log/log.h>
48 #include <log/log_event_list.h>
49 #include <log/log_time.h>
50 #include <private/android_filesystem_config.h>
51 #include <psi/psi.h>
52 #include <system/thread_defs.h>
53 
54 #include "statslog.h"
55 
56 /*
57  * Define LMKD_TRACE_KILLS to record lmkd kills in kernel traces
58  * to profile and correlate with OOM kills
59  */
60 #ifdef LMKD_TRACE_KILLS
61 
62 #define ATRACE_TAG ATRACE_TAG_ALWAYS
63 #include <cutils/trace.h>
64 
65 #define TRACE_KILL_START(pid) ATRACE_INT(__FUNCTION__, pid);
66 #define TRACE_KILL_END()      ATRACE_INT(__FUNCTION__, 0);
67 
68 #else /* LMKD_TRACE_KILLS */
69 
70 #define TRACE_KILL_START(pid) ((void)(pid))
71 #define TRACE_KILL_END() ((void)0)
72 
73 #endif /* LMKD_TRACE_KILLS */
74 
75 #ifndef __unused
76 #define __unused __attribute__((__unused__))
77 #endif
78 
79 #define MEMCG_SYSFS_PATH "/dev/memcg/"
80 #define MEMCG_MEMORY_USAGE "/dev/memcg/memory.usage_in_bytes"
81 #define MEMCG_MEMORYSW_USAGE "/dev/memcg/memory.memsw.usage_in_bytes"
82 #define ZONEINFO_PATH "/proc/zoneinfo"
83 #define MEMINFO_PATH "/proc/meminfo"
84 #define VMSTAT_PATH "/proc/vmstat"
85 #define PROC_STATUS_TGID_FIELD "Tgid:"
86 #define LINE_MAX 128
87 
88 #define PERCEPTIBLE_APP_ADJ 200
89 
90 /* Android Logger event logtags (see event.logtags) */
91 #define KILLINFO_LOG_TAG 10195355
92 
93 /* gid containing AID_SYSTEM required */
94 #define INKERNEL_MINFREE_PATH "/sys/module/lowmemorykiller/parameters/minfree"
95 #define INKERNEL_ADJ_PATH "/sys/module/lowmemorykiller/parameters/adj"
96 
97 #define ARRAY_SIZE(x)   (sizeof(x) / sizeof(*(x)))
98 #define EIGHT_MEGA (1 << 23)
99 
100 #define TARGET_UPDATE_MIN_INTERVAL_MS 1000
101 
102 #define NS_PER_MS (NS_PER_SEC / MS_PER_SEC)
103 #define US_PER_MS (US_PER_SEC / MS_PER_SEC)
104 
105 /* Defined as ProcessList.SYSTEM_ADJ in ProcessList.java */
106 #define SYSTEM_ADJ (-900)
107 
108 #define STRINGIFY(x) STRINGIFY_INTERNAL(x)
109 #define STRINGIFY_INTERNAL(x) #x
110 
111 /*
112  * PSI monitor tracking window size.
113  * PSI monitor generates events at most once per window,
114  * therefore we poll memory state for the duration of
115  * PSI_WINDOW_SIZE_MS after the event happens.
116  */
117 #define PSI_WINDOW_SIZE_MS 1000
118 /* Polling period after PSI signal when pressure is high */
119 #define PSI_POLL_PERIOD_SHORT_MS 10
120 /* Polling period after PSI signal when pressure is low */
121 #define PSI_POLL_PERIOD_LONG_MS 100
122 
123 #define min(a, b) (((a) < (b)) ? (a) : (b))
124 #define max(a, b) (((a) > (b)) ? (a) : (b))
125 
126 #define FAIL_REPORT_RLIMIT_MS 1000
127 
128 /*
129  * System property defaults
130  */
131 /* ro.lmk.swap_free_low_percentage property defaults */
132 #define DEF_LOW_SWAP 10
133 /* ro.lmk.thrashing_limit property defaults */
134 #define DEF_THRASHING_LOWRAM 30
135 #define DEF_THRASHING 100
136 /* ro.lmk.thrashing_limit_decay property defaults */
137 #define DEF_THRASHING_DECAY_LOWRAM 50
138 #define DEF_THRASHING_DECAY 10
139 /* ro.lmk.psi_partial_stall_ms property defaults */
140 #define DEF_PARTIAL_STALL_LOWRAM 200
141 #define DEF_PARTIAL_STALL 70
142 /* ro.lmk.psi_complete_stall_ms property defaults */
143 #define DEF_COMPLETE_STALL 700
144 
145 #define LMKD_REINIT_PROP "lmkd.reinit"
146 
sys_pidfd_open(pid_t pid,unsigned int flags)147 static inline int sys_pidfd_open(pid_t pid, unsigned int flags) {
148     return syscall(__NR_pidfd_open, pid, flags);
149 }
150 
sys_pidfd_send_signal(int pidfd,int sig,siginfo_t * info,unsigned int flags)151 static inline int sys_pidfd_send_signal(int pidfd, int sig, siginfo_t *info,
152                                         unsigned int flags) {
153     return syscall(__NR_pidfd_send_signal, pidfd, sig, info, flags);
154 }
155 
156 /* default to old in-kernel interface if no memory pressure events */
157 static bool use_inkernel_interface = true;
158 static bool has_inkernel_module;
159 
160 /* memory pressure levels */
161 enum vmpressure_level {
162     VMPRESS_LEVEL_LOW = 0,
163     VMPRESS_LEVEL_MEDIUM,
164     VMPRESS_LEVEL_CRITICAL,
165     VMPRESS_LEVEL_COUNT
166 };
167 
168 static const char *level_name[] = {
169     "low",
170     "medium",
171     "critical"
172 };
173 
174 struct {
175     int64_t min_nr_free_pages; /* recorded but not used yet */
176     int64_t max_nr_free_pages;
177 } low_pressure_mem = { -1, -1 };
178 
179 struct psi_threshold {
180     enum psi_stall_type stall_type;
181     int threshold_ms;
182 };
183 
184 static int level_oomadj[VMPRESS_LEVEL_COUNT];
185 static int mpevfd[VMPRESS_LEVEL_COUNT] = { -1, -1, -1 };
186 static bool pidfd_supported;
187 static int last_kill_pid_or_fd = -1;
188 static struct timespec last_kill_tm;
189 
190 /* lmkd configurable parameters */
191 static bool debug_process_killing;
192 static bool enable_pressure_upgrade;
193 static int64_t upgrade_pressure;
194 static int64_t downgrade_pressure;
195 static bool low_ram_device;
196 static bool kill_heaviest_task;
197 static unsigned long kill_timeout_ms;
198 static bool use_minfree_levels;
199 static bool per_app_memcg;
200 static int swap_free_low_percentage;
201 static int psi_partial_stall_ms;
202 static int psi_complete_stall_ms;
203 static int thrashing_limit_pct;
204 static int thrashing_limit_decay_pct;
205 static int swap_util_max;
206 static bool use_psi_monitors = false;
207 static int kpoll_fd;
208 static struct psi_threshold psi_thresholds[VMPRESS_LEVEL_COUNT] = {
209     { PSI_SOME, 70 },    /* 70ms out of 1sec for partial stall */
210     { PSI_SOME, 100 },   /* 100ms out of 1sec for partial stall */
211     { PSI_FULL, 70 },    /* 70ms out of 1sec for complete stall */
212 };
213 
214 static android_log_context ctx;
215 
216 enum polling_update {
217     POLLING_DO_NOT_CHANGE,
218     POLLING_START,
219     POLLING_PAUSE,
220     POLLING_RESUME,
221 };
222 
223 /*
224  * Data used for periodic polling for the memory state of the device.
225  * Note that when system is not polling poll_handler is set to NULL,
226  * when polling starts poll_handler gets set and is reset back to
227  * NULL when polling stops.
228  */
229 struct polling_params {
230     struct event_handler_info* poll_handler;
231     struct event_handler_info* paused_handler;
232     struct timespec poll_start_tm;
233     struct timespec last_poll_tm;
234     int polling_interval_ms;
235     enum polling_update update;
236 };
237 
238 /* data required to handle events */
239 struct event_handler_info {
240     int data;
241     void (*handler)(int data, uint32_t events, struct polling_params *poll_params);
242 };
243 
244 /* data required to handle socket events */
245 struct sock_event_handler_info {
246     int sock;
247     pid_t pid;
248     uint32_t async_event_mask;
249     struct event_handler_info handler_info;
250 };
251 
252 /* max supported number of data connections (AMS, init, tests) */
253 #define MAX_DATA_CONN 3
254 
255 /* socket event handler data */
256 static struct sock_event_handler_info ctrl_sock;
257 static struct sock_event_handler_info data_sock[MAX_DATA_CONN];
258 
259 /* vmpressure event handler data */
260 static struct event_handler_info vmpressure_hinfo[VMPRESS_LEVEL_COUNT];
261 
262 /*
263  * 1 ctrl listen socket, 3 ctrl data socket, 3 memory pressure levels,
264  * 1 lmk events + 1 fd to wait for process death
265  */
266 #define MAX_EPOLL_EVENTS (1 + MAX_DATA_CONN + VMPRESS_LEVEL_COUNT + 1 + 1)
267 static int epollfd;
268 static int maxevents;
269 
270 /* OOM score values used by both kernel and framework */
271 #define OOM_SCORE_ADJ_MIN       (-1000)
272 #define OOM_SCORE_ADJ_MAX       1000
273 
274 static int lowmem_adj[MAX_TARGETS];
275 static int lowmem_minfree[MAX_TARGETS];
276 static int lowmem_targets_size;
277 
278 /* Fields to parse in /proc/zoneinfo */
279 /* zoneinfo per-zone fields */
280 enum zoneinfo_zone_field {
281     ZI_ZONE_NR_FREE_PAGES = 0,
282     ZI_ZONE_MIN,
283     ZI_ZONE_LOW,
284     ZI_ZONE_HIGH,
285     ZI_ZONE_PRESENT,
286     ZI_ZONE_NR_FREE_CMA,
287     ZI_ZONE_FIELD_COUNT
288 };
289 
290 static const char* const zoneinfo_zone_field_names[ZI_ZONE_FIELD_COUNT] = {
291     "nr_free_pages",
292     "min",
293     "low",
294     "high",
295     "present",
296     "nr_free_cma",
297 };
298 
299 /* zoneinfo per-zone special fields */
300 enum zoneinfo_zone_spec_field {
301     ZI_ZONE_SPEC_PROTECTION = 0,
302     ZI_ZONE_SPEC_PAGESETS,
303     ZI_ZONE_SPEC_FIELD_COUNT,
304 };
305 
306 static const char* const zoneinfo_zone_spec_field_names[ZI_ZONE_SPEC_FIELD_COUNT] = {
307     "protection:",
308     "pagesets",
309 };
310 
311 /* see __MAX_NR_ZONES definition in kernel mmzone.h */
312 #define MAX_NR_ZONES 6
313 
314 union zoneinfo_zone_fields {
315     struct {
316         int64_t nr_free_pages;
317         int64_t min;
318         int64_t low;
319         int64_t high;
320         int64_t present;
321         int64_t nr_free_cma;
322     } field;
323     int64_t arr[ZI_ZONE_FIELD_COUNT];
324 };
325 
326 struct zoneinfo_zone {
327     union zoneinfo_zone_fields fields;
328     int64_t protection[MAX_NR_ZONES];
329     int64_t max_protection;
330 };
331 
332 /* zoneinfo per-node fields */
333 enum zoneinfo_node_field {
334     ZI_NODE_NR_INACTIVE_FILE = 0,
335     ZI_NODE_NR_ACTIVE_FILE,
336     ZI_NODE_WORKINGSET_REFAULT,
337     ZI_NODE_FIELD_COUNT
338 };
339 
340 static const char* const zoneinfo_node_field_names[ZI_NODE_FIELD_COUNT] = {
341     "nr_inactive_file",
342     "nr_active_file",
343     "workingset_refault",
344 };
345 
346 union zoneinfo_node_fields {
347     struct {
348         int64_t nr_inactive_file;
349         int64_t nr_active_file;
350         int64_t workingset_refault;
351     } field;
352     int64_t arr[ZI_NODE_FIELD_COUNT];
353 };
354 
355 struct zoneinfo_node {
356     int id;
357     int zone_count;
358     struct zoneinfo_zone zones[MAX_NR_ZONES];
359     union zoneinfo_node_fields fields;
360 };
361 
362 /* for now two memory nodes is more than enough */
363 #define MAX_NR_NODES 2
364 
365 struct zoneinfo {
366     int node_count;
367     struct zoneinfo_node nodes[MAX_NR_NODES];
368     int64_t totalreserve_pages;
369     int64_t total_inactive_file;
370     int64_t total_active_file;
371     int64_t total_workingset_refault;
372 };
373 
374 /* Fields to parse in /proc/meminfo */
375 enum meminfo_field {
376     MI_NR_FREE_PAGES = 0,
377     MI_CACHED,
378     MI_SWAP_CACHED,
379     MI_BUFFERS,
380     MI_SHMEM,
381     MI_UNEVICTABLE,
382     MI_TOTAL_SWAP,
383     MI_FREE_SWAP,
384     MI_ACTIVE_ANON,
385     MI_INACTIVE_ANON,
386     MI_ACTIVE_FILE,
387     MI_INACTIVE_FILE,
388     MI_SRECLAIMABLE,
389     MI_SUNRECLAIM,
390     MI_KERNEL_STACK,
391     MI_PAGE_TABLES,
392     MI_ION_HELP,
393     MI_ION_HELP_POOL,
394     MI_CMA_FREE,
395     MI_FIELD_COUNT
396 };
397 
398 static const char* const meminfo_field_names[MI_FIELD_COUNT] = {
399     "MemFree:",
400     "Cached:",
401     "SwapCached:",
402     "Buffers:",
403     "Shmem:",
404     "Unevictable:",
405     "SwapTotal:",
406     "SwapFree:",
407     "Active(anon):",
408     "Inactive(anon):",
409     "Active(file):",
410     "Inactive(file):",
411     "SReclaimable:",
412     "SUnreclaim:",
413     "KernelStack:",
414     "PageTables:",
415     "ION_heap:",
416     "ION_heap_pool:",
417     "CmaFree:",
418 };
419 
420 union meminfo {
421     struct {
422         int64_t nr_free_pages;
423         int64_t cached;
424         int64_t swap_cached;
425         int64_t buffers;
426         int64_t shmem;
427         int64_t unevictable;
428         int64_t total_swap;
429         int64_t free_swap;
430         int64_t active_anon;
431         int64_t inactive_anon;
432         int64_t active_file;
433         int64_t inactive_file;
434         int64_t sreclaimable;
435         int64_t sunreclaimable;
436         int64_t kernel_stack;
437         int64_t page_tables;
438         int64_t ion_heap;
439         int64_t ion_heap_pool;
440         int64_t cma_free;
441         /* fields below are calculated rather than read from the file */
442         int64_t nr_file_pages;
443     } field;
444     int64_t arr[MI_FIELD_COUNT];
445 };
446 
447 /* Fields to parse in /proc/vmstat */
448 enum vmstat_field {
449     VS_FREE_PAGES,
450     VS_INACTIVE_FILE,
451     VS_ACTIVE_FILE,
452     VS_WORKINGSET_REFAULT,
453     VS_PGSCAN_KSWAPD,
454     VS_PGSCAN_DIRECT,
455     VS_PGSCAN_DIRECT_THROTTLE,
456     VS_FIELD_COUNT
457 };
458 
459 static const char* const vmstat_field_names[MI_FIELD_COUNT] = {
460     "nr_free_pages",
461     "nr_inactive_file",
462     "nr_active_file",
463     "workingset_refault",
464     "pgscan_kswapd",
465     "pgscan_direct",
466     "pgscan_direct_throttle",
467 };
468 
469 union vmstat {
470     struct {
471         int64_t nr_free_pages;
472         int64_t nr_inactive_file;
473         int64_t nr_active_file;
474         int64_t workingset_refault;
475         int64_t pgscan_kswapd;
476         int64_t pgscan_direct;
477         int64_t pgscan_direct_throttle;
478     } field;
479     int64_t arr[VS_FIELD_COUNT];
480 };
481 
482 enum field_match_result {
483     NO_MATCH,
484     PARSE_FAIL,
485     PARSE_SUCCESS
486 };
487 
488 struct adjslot_list {
489     struct adjslot_list *next;
490     struct adjslot_list *prev;
491 };
492 
493 struct proc {
494     struct adjslot_list asl;
495     int pid;
496     int pidfd;
497     uid_t uid;
498     int oomadj;
499     pid_t reg_pid; /* PID of the process that registered this record */
500     struct proc *pidhash_next;
501 };
502 
503 struct reread_data {
504     const char* const filename;
505     int fd;
506 };
507 
508 #define PIDHASH_SZ 1024
509 static struct proc *pidhash[PIDHASH_SZ];
510 #define pid_hashfn(x) ((((x) >> 8) ^ (x)) & (PIDHASH_SZ - 1))
511 
512 #define ADJTOSLOT(adj) ((adj) + -OOM_SCORE_ADJ_MIN)
513 #define ADJTOSLOT_COUNT (ADJTOSLOT(OOM_SCORE_ADJ_MAX) + 1)
514 static struct adjslot_list procadjslot_list[ADJTOSLOT_COUNT];
515 
516 #define MAX_DISTINCT_OOM_ADJ 32
517 #define KILLCNT_INVALID_IDX 0xFF
518 /*
519  * Because killcnt array is sparse a two-level indirection is used
520  * to keep the size small. killcnt_idx stores index of the element in
521  * killcnt array. Index KILLCNT_INVALID_IDX indicates an unused slot.
522  */
523 static uint8_t killcnt_idx[ADJTOSLOT_COUNT];
524 static uint16_t killcnt[MAX_DISTINCT_OOM_ADJ];
525 static int killcnt_free_idx = 0;
526 static uint32_t killcnt_total = 0;
527 
528 /* PAGE_SIZE / 1024 */
529 static long page_k;
530 
531 static void update_props();
532 static bool init_monitors();
533 static void destroy_monitors();
534 
clamp(int low,int high,int value)535 static int clamp(int low, int high, int value) {
536     return max(min(value, high), low);
537 }
538 
parse_int64(const char * str,int64_t * ret)539 static bool parse_int64(const char* str, int64_t* ret) {
540     char* endptr;
541     long long val = strtoll(str, &endptr, 10);
542     if (str == endptr || val > INT64_MAX) {
543         return false;
544     }
545     *ret = (int64_t)val;
546     return true;
547 }
548 
find_field(const char * name,const char * const field_names[],int field_count)549 static int find_field(const char* name, const char* const field_names[], int field_count) {
550     for (int i = 0; i < field_count; i++) {
551         if (!strcmp(name, field_names[i])) {
552             return i;
553         }
554     }
555     return -1;
556 }
557 
match_field(const char * cp,const char * ap,const char * const field_names[],int field_count,int64_t * field,int * field_idx)558 static enum field_match_result match_field(const char* cp, const char* ap,
559                                    const char* const field_names[],
560                                    int field_count, int64_t* field,
561                                    int *field_idx) {
562     int i = find_field(cp, field_names, field_count);
563     if (i < 0) {
564         return NO_MATCH;
565     }
566     *field_idx = i;
567     return parse_int64(ap, field) ? PARSE_SUCCESS : PARSE_FAIL;
568 }
569 
570 /*
571  * Read file content from the beginning up to max_len bytes or EOF
572  * whichever happens first.
573  */
read_all(int fd,char * buf,size_t max_len)574 static ssize_t read_all(int fd, char *buf, size_t max_len)
575 {
576     ssize_t ret = 0;
577     off_t offset = 0;
578 
579     while (max_len > 0) {
580         ssize_t r = TEMP_FAILURE_RETRY(pread(fd, buf, max_len, offset));
581         if (r == 0) {
582             break;
583         }
584         if (r == -1) {
585             return -1;
586         }
587         ret += r;
588         buf += r;
589         offset += r;
590         max_len -= r;
591     }
592 
593     return ret;
594 }
595 
596 /*
597  * Read a new or already opened file from the beginning.
598  * If the file has not been opened yet data->fd should be set to -1.
599  * To be used with files which are read often and possibly during high
600  * memory pressure to minimize file opening which by itself requires kernel
601  * memory allocation and might result in a stall on memory stressed system.
602  */
reread_file(struct reread_data * data)603 static char *reread_file(struct reread_data *data) {
604     /* start with page-size buffer and increase if needed */
605     static ssize_t buf_size = PAGE_SIZE;
606     static char *new_buf, *buf = NULL;
607     ssize_t size;
608 
609     if (data->fd == -1) {
610         /* First-time buffer initialization */
611         if (!buf && (buf = static_cast<char*>(malloc(buf_size))) == nullptr) {
612             return NULL;
613         }
614 
615         data->fd = TEMP_FAILURE_RETRY(open(data->filename, O_RDONLY | O_CLOEXEC));
616         if (data->fd < 0) {
617             ALOGE("%s open: %s", data->filename, strerror(errno));
618             return NULL;
619         }
620     }
621 
622     while (true) {
623         size = read_all(data->fd, buf, buf_size - 1);
624         if (size < 0) {
625             ALOGE("%s read: %s", data->filename, strerror(errno));
626             close(data->fd);
627             data->fd = -1;
628             return NULL;
629         }
630         if (size < buf_size - 1) {
631             break;
632         }
633         /*
634          * Since we are reading /proc files we can't use fstat to find out
635          * the real size of the file. Double the buffer size and keep retrying.
636          */
637         if ((new_buf = static_cast<char*>(realloc(buf, buf_size * 2))) == nullptr) {
638             errno = ENOMEM;
639             return NULL;
640         }
641         buf = new_buf;
642         buf_size *= 2;
643     }
644     buf[size] = 0;
645 
646     return buf;
647 }
648 
claim_record(struct proc * procp,pid_t pid)649 static bool claim_record(struct proc* procp, pid_t pid) {
650     if (procp->reg_pid == pid) {
651         /* Record already belongs to the registrant */
652         return true;
653     }
654     if (procp->reg_pid == 0) {
655         /* Old registrant is gone, claim the record */
656         procp->reg_pid = pid;
657         return true;
658     }
659     /* The record is owned by another registrant */
660     return false;
661 }
662 
remove_claims(pid_t pid)663 static void remove_claims(pid_t pid) {
664     int i;
665 
666     for (i = 0; i < PIDHASH_SZ; i++) {
667         struct proc* procp = pidhash[i];
668         while (procp) {
669             if (procp->reg_pid == pid) {
670                 procp->reg_pid = 0;
671             }
672             procp = procp->pidhash_next;
673         }
674     }
675 }
676 
ctrl_data_close(int dsock_idx)677 static void ctrl_data_close(int dsock_idx) {
678     struct epoll_event epev;
679 
680     ALOGI("closing lmkd data connection");
681     if (epoll_ctl(epollfd, EPOLL_CTL_DEL, data_sock[dsock_idx].sock, &epev) == -1) {
682         // Log a warning and keep going
683         ALOGW("epoll_ctl for data connection socket failed; errno=%d", errno);
684     }
685     maxevents--;
686 
687     close(data_sock[dsock_idx].sock);
688     data_sock[dsock_idx].sock = -1;
689 
690     /* Mark all records of the old registrant as unclaimed */
691     remove_claims(data_sock[dsock_idx].pid);
692 }
693 
ctrl_data_read(int dsock_idx,char * buf,size_t bufsz,struct ucred * sender_cred)694 static ssize_t ctrl_data_read(int dsock_idx, char* buf, size_t bufsz, struct ucred* sender_cred) {
695     struct iovec iov = {buf, bufsz};
696     char control[CMSG_SPACE(sizeof(struct ucred))];
697     struct msghdr hdr = {
698             NULL, 0, &iov, 1, control, sizeof(control), 0,
699     };
700     ssize_t ret;
701     ret = TEMP_FAILURE_RETRY(recvmsg(data_sock[dsock_idx].sock, &hdr, 0));
702     if (ret == -1) {
703         ALOGE("control data socket read failed; %s", strerror(errno));
704         return -1;
705     }
706     if (ret == 0) {
707         ALOGE("Got EOF on control data socket");
708         return -1;
709     }
710 
711     struct ucred* cred = NULL;
712     struct cmsghdr* cmsg = CMSG_FIRSTHDR(&hdr);
713     while (cmsg != NULL) {
714         if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_CREDENTIALS) {
715             cred = (struct ucred*)CMSG_DATA(cmsg);
716             break;
717         }
718         cmsg = CMSG_NXTHDR(&hdr, cmsg);
719     }
720 
721     if (cred == NULL) {
722         ALOGE("Failed to retrieve sender credentials");
723         /* Close the connection */
724         ctrl_data_close(dsock_idx);
725         return -1;
726     }
727 
728     memcpy(sender_cred, cred, sizeof(struct ucred));
729 
730     /* Store PID of the peer */
731     data_sock[dsock_idx].pid = cred->pid;
732 
733     return ret;
734 }
735 
ctrl_data_write(int dsock_idx,char * buf,size_t bufsz)736 static int ctrl_data_write(int dsock_idx, char* buf, size_t bufsz) {
737     int ret = 0;
738 
739     ret = TEMP_FAILURE_RETRY(write(data_sock[dsock_idx].sock, buf, bufsz));
740 
741     if (ret == -1) {
742         ALOGE("control data socket write failed; errno=%d", errno);
743     } else if (ret == 0) {
744         ALOGE("Got EOF on control data socket");
745         ret = -1;
746     }
747 
748     return ret;
749 }
750 
751 /*
752  * Write the pid/uid pair over the data socket, note: all active clients
753  * will receive this unsolicited notification.
754  */
ctrl_data_write_lmk_kill_occurred(pid_t pid,uid_t uid)755 static void ctrl_data_write_lmk_kill_occurred(pid_t pid, uid_t uid) {
756     LMKD_CTRL_PACKET packet;
757     size_t len = lmkd_pack_set_prockills(packet, pid, uid);
758 
759     for (int i = 0; i < MAX_DATA_CONN; i++) {
760         if (data_sock[i].sock >= 0 && data_sock[i].async_event_mask & 1 << LMK_ASYNC_EVENT_KILL) {
761             ctrl_data_write(i, (char*)packet, len);
762         }
763     }
764 }
765 
poll_kernel(int poll_fd)766 static void poll_kernel(int poll_fd) {
767     if (poll_fd == -1) {
768         // not waiting
769         return;
770     }
771 
772     while (1) {
773         char rd_buf[256];
774         int bytes_read = TEMP_FAILURE_RETRY(pread(poll_fd, (void*)rd_buf, sizeof(rd_buf), 0));
775         if (bytes_read <= 0) break;
776         rd_buf[bytes_read] = '\0';
777 
778         int64_t pid;
779         int64_t uid;
780         int64_t group_leader_pid;
781         int64_t rss_in_pages;
782         struct memory_stat mem_st = {};
783         int16_t oom_score_adj;
784         int16_t min_score_adj;
785         int64_t starttime;
786         char* taskname = 0;
787 
788         int fields_read =
789                 sscanf(rd_buf,
790                        "%" SCNd64 " %" SCNd64 " %" SCNd64 " %" SCNd64 " %" SCNd64 " %" SCNd64
791                        " %" SCNd16 " %" SCNd16 " %" SCNd64 "\n%m[^\n]",
792                        &pid, &uid, &group_leader_pid, &mem_st.pgfault, &mem_st.pgmajfault,
793                        &rss_in_pages, &oom_score_adj, &min_score_adj, &starttime, &taskname);
794 
795         /* only the death of the group leader process is logged */
796         if (fields_read == 10 && group_leader_pid == pid) {
797             ctrl_data_write_lmk_kill_occurred((pid_t)pid, (uid_t)uid);
798             mem_st.process_start_time_ns = starttime * (NS_PER_SEC / sysconf(_SC_CLK_TCK));
799             mem_st.rss_in_bytes = rss_in_pages * PAGE_SIZE;
800             stats_write_lmk_kill_occurred_pid(uid, pid, oom_score_adj,
801                                               min_score_adj, 0, &mem_st);
802         }
803 
804         free(taskname);
805     }
806 }
807 
init_poll_kernel()808 static bool init_poll_kernel() {
809     kpoll_fd = TEMP_FAILURE_RETRY(open("/proc/lowmemorykiller", O_RDONLY | O_NONBLOCK | O_CLOEXEC));
810 
811     if (kpoll_fd < 0) {
812         ALOGE("kernel lmk event file could not be opened; errno=%d", errno);
813         return false;
814     }
815 
816     return true;
817 }
818 
pid_lookup(int pid)819 static struct proc *pid_lookup(int pid) {
820     struct proc *procp;
821 
822     for (procp = pidhash[pid_hashfn(pid)]; procp && procp->pid != pid;
823          procp = procp->pidhash_next)
824             ;
825 
826     return procp;
827 }
828 
adjslot_insert(struct adjslot_list * head,struct adjslot_list * new_element)829 static void adjslot_insert(struct adjslot_list *head, struct adjslot_list *new_element)
830 {
831     struct adjslot_list *next = head->next;
832     new_element->prev = head;
833     new_element->next = next;
834     next->prev = new_element;
835     head->next = new_element;
836 }
837 
adjslot_remove(struct adjslot_list * old)838 static void adjslot_remove(struct adjslot_list *old)
839 {
840     struct adjslot_list *prev = old->prev;
841     struct adjslot_list *next = old->next;
842     next->prev = prev;
843     prev->next = next;
844 }
845 
adjslot_tail(struct adjslot_list * head)846 static struct adjslot_list *adjslot_tail(struct adjslot_list *head) {
847     struct adjslot_list *asl = head->prev;
848 
849     return asl == head ? NULL : asl;
850 }
851 
proc_slot(struct proc * procp)852 static void proc_slot(struct proc *procp) {
853     int adjslot = ADJTOSLOT(procp->oomadj);
854 
855     adjslot_insert(&procadjslot_list[adjslot], &procp->asl);
856 }
857 
proc_unslot(struct proc * procp)858 static void proc_unslot(struct proc *procp) {
859     adjslot_remove(&procp->asl);
860 }
861 
proc_insert(struct proc * procp)862 static void proc_insert(struct proc *procp) {
863     int hval = pid_hashfn(procp->pid);
864 
865     procp->pidhash_next = pidhash[hval];
866     pidhash[hval] = procp;
867     proc_slot(procp);
868 }
869 
pid_remove(int pid)870 static int pid_remove(int pid) {
871     int hval = pid_hashfn(pid);
872     struct proc *procp;
873     struct proc *prevp;
874 
875     for (procp = pidhash[hval], prevp = NULL; procp && procp->pid != pid;
876          procp = procp->pidhash_next)
877             prevp = procp;
878 
879     if (!procp)
880         return -1;
881 
882     if (!prevp)
883         pidhash[hval] = procp->pidhash_next;
884     else
885         prevp->pidhash_next = procp->pidhash_next;
886 
887     proc_unslot(procp);
888     /*
889      * Close pidfd here if we are not waiting for corresponding process to die,
890      * in which case stop_wait_for_proc_kill() will close the pidfd later
891      */
892     if (procp->pidfd >= 0 && procp->pidfd != last_kill_pid_or_fd) {
893         close(procp->pidfd);
894     }
895     free(procp);
896     return 0;
897 }
898 
899 /*
900  * Write a string to a file.
901  * Returns false if the file does not exist.
902  */
writefilestring(const char * path,const char * s,bool err_if_missing)903 static bool writefilestring(const char *path, const char *s,
904                             bool err_if_missing) {
905     int fd = open(path, O_WRONLY | O_CLOEXEC);
906     ssize_t len = strlen(s);
907     ssize_t ret;
908 
909     if (fd < 0) {
910         if (err_if_missing) {
911             ALOGE("Error opening %s; errno=%d", path, errno);
912         }
913         return false;
914     }
915 
916     ret = TEMP_FAILURE_RETRY(write(fd, s, len));
917     if (ret < 0) {
918         ALOGE("Error writing %s; errno=%d", path, errno);
919     } else if (ret < len) {
920         ALOGE("Short write on %s; length=%zd", path, ret);
921     }
922 
923     close(fd);
924     return true;
925 }
926 
get_time_diff_ms(struct timespec * from,struct timespec * to)927 static inline long get_time_diff_ms(struct timespec *from,
928                                     struct timespec *to) {
929     return (to->tv_sec - from->tv_sec) * (long)MS_PER_SEC +
930            (to->tv_nsec - from->tv_nsec) / (long)NS_PER_MS;
931 }
932 
proc_get_tgid(int pid)933 static int proc_get_tgid(int pid) {
934     char path[PATH_MAX];
935     char buf[PAGE_SIZE];
936     int fd;
937     ssize_t size;
938     char *pos;
939     int64_t tgid = -1;
940 
941     snprintf(path, PATH_MAX, "/proc/%d/status", pid);
942     fd = open(path, O_RDONLY | O_CLOEXEC);
943     if (fd < 0) {
944         return -1;
945     }
946 
947     size = read_all(fd, buf, sizeof(buf) - 1);
948     if (size < 0) {
949         goto out;
950     }
951     buf[size] = 0;
952 
953     pos = buf;
954     while (true) {
955         pos = strstr(pos, PROC_STATUS_TGID_FIELD);
956         /* Stop if TGID tag not found or found at the line beginning */
957         if (pos == NULL || pos == buf || pos[-1] == '\n') {
958             break;
959         }
960         pos++;
961     }
962 
963     if (pos == NULL) {
964         goto out;
965     }
966 
967     pos += strlen(PROC_STATUS_TGID_FIELD);
968     while (*pos == ' ') pos++;
969     parse_int64(pos, &tgid);
970 
971 out:
972     close(fd);
973     return (int)tgid;
974 }
975 
proc_get_size(int pid)976 static int proc_get_size(int pid) {
977     char path[PATH_MAX];
978     char line[LINE_MAX];
979     int fd;
980     int rss = 0;
981     int total;
982     ssize_t ret;
983 
984     /* gid containing AID_READPROC required */
985     snprintf(path, PATH_MAX, "/proc/%d/statm", pid);
986     fd = open(path, O_RDONLY | O_CLOEXEC);
987     if (fd == -1)
988         return -1;
989 
990     ret = read_all(fd, line, sizeof(line) - 1);
991     if (ret < 0) {
992         close(fd);
993         return -1;
994     }
995     line[ret] = '\0';
996 
997     sscanf(line, "%d %d ", &total, &rss);
998     close(fd);
999     return rss;
1000 }
1001 
proc_get_name(int pid,char * buf,size_t buf_size)1002 static char *proc_get_name(int pid, char *buf, size_t buf_size) {
1003     char path[PATH_MAX];
1004     int fd;
1005     char *cp;
1006     ssize_t ret;
1007 
1008     /* gid containing AID_READPROC required */
1009     snprintf(path, PATH_MAX, "/proc/%d/cmdline", pid);
1010     fd = open(path, O_RDONLY | O_CLOEXEC);
1011     if (fd == -1) {
1012         return NULL;
1013     }
1014     ret = read_all(fd, buf, buf_size - 1);
1015     close(fd);
1016     if (ret < 0) {
1017         return NULL;
1018     }
1019     buf[ret] = '\0';
1020 
1021     cp = strchr(buf, ' ');
1022     if (cp) {
1023         *cp = '\0';
1024     }
1025 
1026     return buf;
1027 }
1028 
cmd_procprio(LMKD_CTRL_PACKET packet,int field_count,struct ucred * cred)1029 static void cmd_procprio(LMKD_CTRL_PACKET packet, int field_count, struct ucred *cred) {
1030     struct proc *procp;
1031     char path[LINE_MAX];
1032     char val[20];
1033     int soft_limit_mult;
1034     struct lmk_procprio params;
1035     bool is_system_server;
1036     struct passwd *pwdrec;
1037     int tgid;
1038 
1039     lmkd_pack_get_procprio(packet, field_count, &params);
1040 
1041     if (params.oomadj < OOM_SCORE_ADJ_MIN ||
1042         params.oomadj > OOM_SCORE_ADJ_MAX) {
1043         ALOGE("Invalid PROCPRIO oomadj argument %d", params.oomadj);
1044         return;
1045     }
1046 
1047     if (params.ptype < PROC_TYPE_FIRST || params.ptype >= PROC_TYPE_COUNT) {
1048         ALOGE("Invalid PROCPRIO process type argument %d", params.ptype);
1049         return;
1050     }
1051 
1052     /* Check if registered process is a thread group leader */
1053     tgid = proc_get_tgid(params.pid);
1054     if (tgid >= 0 && tgid != params.pid) {
1055         ALOGE("Attempt to register a task that is not a thread group leader (tid %d, tgid %d)",
1056             params.pid, tgid);
1057         return;
1058     }
1059 
1060     /* gid containing AID_READPROC required */
1061     /* CAP_SYS_RESOURCE required */
1062     /* CAP_DAC_OVERRIDE required */
1063     snprintf(path, sizeof(path), "/proc/%d/oom_score_adj", params.pid);
1064     snprintf(val, sizeof(val), "%d", params.oomadj);
1065     if (!writefilestring(path, val, false)) {
1066         ALOGW("Failed to open %s; errno=%d: process %d might have been killed",
1067               path, errno, params.pid);
1068         /* If this file does not exist the process is dead. */
1069         return;
1070     }
1071 
1072     if (use_inkernel_interface) {
1073         stats_store_taskname(params.pid, proc_get_name(params.pid, path, sizeof(path)));
1074         return;
1075     }
1076 
1077     /* lmkd should not change soft limits for services */
1078     if (params.ptype == PROC_TYPE_APP && per_app_memcg) {
1079         if (params.oomadj >= 900) {
1080             soft_limit_mult = 0;
1081         } else if (params.oomadj >= 800) {
1082             soft_limit_mult = 0;
1083         } else if (params.oomadj >= 700) {
1084             soft_limit_mult = 0;
1085         } else if (params.oomadj >= 600) {
1086             // Launcher should be perceptible, don't kill it.
1087             params.oomadj = 200;
1088             soft_limit_mult = 1;
1089         } else if (params.oomadj >= 500) {
1090             soft_limit_mult = 0;
1091         } else if (params.oomadj >= 400) {
1092             soft_limit_mult = 0;
1093         } else if (params.oomadj >= 300) {
1094             soft_limit_mult = 1;
1095         } else if (params.oomadj >= 200) {
1096             soft_limit_mult = 8;
1097         } else if (params.oomadj >= 100) {
1098             soft_limit_mult = 10;
1099         } else if (params.oomadj >=   0) {
1100             soft_limit_mult = 20;
1101         } else {
1102             // Persistent processes will have a large
1103             // soft limit 512MB.
1104             soft_limit_mult = 64;
1105         }
1106 
1107         snprintf(path, sizeof(path), MEMCG_SYSFS_PATH
1108                  "apps/uid_%d/pid_%d/memory.soft_limit_in_bytes",
1109                  params.uid, params.pid);
1110         snprintf(val, sizeof(val), "%d", soft_limit_mult * EIGHT_MEGA);
1111 
1112         /*
1113          * system_server process has no memcg under /dev/memcg/apps but should be
1114          * registered with lmkd. This is the best way so far to identify it.
1115          */
1116         is_system_server = (params.oomadj == SYSTEM_ADJ &&
1117                             (pwdrec = getpwnam("system")) != NULL &&
1118                             params.uid == pwdrec->pw_uid);
1119         writefilestring(path, val, !is_system_server);
1120     }
1121 
1122     procp = pid_lookup(params.pid);
1123     if (!procp) {
1124         int pidfd = -1;
1125 
1126         if (pidfd_supported) {
1127             pidfd = TEMP_FAILURE_RETRY(sys_pidfd_open(params.pid, 0));
1128             if (pidfd < 0) {
1129                 ALOGE("pidfd_open for pid %d failed; errno=%d", params.pid, errno);
1130                 return;
1131             }
1132         }
1133 
1134         procp = static_cast<struct proc*>(calloc(1, sizeof(struct proc)));
1135         if (!procp) {
1136             // Oh, the irony.  May need to rebuild our state.
1137             return;
1138         }
1139 
1140         procp->pid = params.pid;
1141         procp->pidfd = pidfd;
1142         procp->uid = params.uid;
1143         procp->reg_pid = cred->pid;
1144         procp->oomadj = params.oomadj;
1145         proc_insert(procp);
1146     } else {
1147         if (!claim_record(procp, cred->pid)) {
1148             char buf[LINE_MAX];
1149             /* Only registrant of the record can remove it */
1150             ALOGE("%s (%d, %d) attempts to modify a process registered by another client",
1151                 proc_get_name(cred->pid, buf, sizeof(buf)), cred->uid, cred->pid);
1152             return;
1153         }
1154         proc_unslot(procp);
1155         procp->oomadj = params.oomadj;
1156         proc_slot(procp);
1157     }
1158 }
1159 
cmd_procremove(LMKD_CTRL_PACKET packet,struct ucred * cred)1160 static void cmd_procremove(LMKD_CTRL_PACKET packet, struct ucred *cred) {
1161     struct lmk_procremove params;
1162     struct proc *procp;
1163 
1164     lmkd_pack_get_procremove(packet, &params);
1165 
1166     if (use_inkernel_interface) {
1167         /*
1168          * Perform an extra check before the pid is removed, after which it
1169          * will be impossible for poll_kernel to get the taskname. poll_kernel()
1170          * is potentially a long-running blocking function; however this method
1171          * handles AMS requests but does not block AMS.
1172          */
1173         poll_kernel(kpoll_fd);
1174 
1175         stats_remove_taskname(params.pid);
1176         return;
1177     }
1178 
1179     procp = pid_lookup(params.pid);
1180     if (!procp) {
1181         return;
1182     }
1183 
1184     if (!claim_record(procp, cred->pid)) {
1185         char buf[LINE_MAX];
1186         /* Only registrant of the record can remove it */
1187         ALOGE("%s (%d, %d) attempts to unregister a process registered by another client",
1188             proc_get_name(cred->pid, buf, sizeof(buf)), cred->uid, cred->pid);
1189         return;
1190     }
1191 
1192     /*
1193      * WARNING: After pid_remove() procp is freed and can't be used!
1194      * Therefore placed at the end of the function.
1195      */
1196     pid_remove(params.pid);
1197 }
1198 
cmd_procpurge(struct ucred * cred)1199 static void cmd_procpurge(struct ucred *cred) {
1200     int i;
1201     struct proc *procp;
1202     struct proc *next;
1203 
1204     if (use_inkernel_interface) {
1205         stats_purge_tasknames();
1206         return;
1207     }
1208 
1209     for (i = 0; i < PIDHASH_SZ; i++) {
1210         procp = pidhash[i];
1211         while (procp) {
1212             next = procp->pidhash_next;
1213             /* Purge only records created by the requestor */
1214             if (claim_record(procp, cred->pid)) {
1215                 pid_remove(procp->pid);
1216             }
1217             procp = next;
1218         }
1219     }
1220 }
1221 
cmd_subscribe(int dsock_idx,LMKD_CTRL_PACKET packet)1222 static void cmd_subscribe(int dsock_idx, LMKD_CTRL_PACKET packet) {
1223     struct lmk_subscribe params;
1224 
1225     lmkd_pack_get_subscribe(packet, &params);
1226     data_sock[dsock_idx].async_event_mask |= 1 << params.evt_type;
1227 }
1228 
inc_killcnt(int oomadj)1229 static void inc_killcnt(int oomadj) {
1230     int slot = ADJTOSLOT(oomadj);
1231     uint8_t idx = killcnt_idx[slot];
1232 
1233     if (idx == KILLCNT_INVALID_IDX) {
1234         /* index is not assigned for this oomadj */
1235         if (killcnt_free_idx < MAX_DISTINCT_OOM_ADJ) {
1236             killcnt_idx[slot] = killcnt_free_idx;
1237             killcnt[killcnt_free_idx] = 1;
1238             killcnt_free_idx++;
1239         } else {
1240             ALOGW("Number of distinct oomadj levels exceeds %d",
1241                 MAX_DISTINCT_OOM_ADJ);
1242         }
1243     } else {
1244         /*
1245          * wraparound is highly unlikely and is detectable using total
1246          * counter because it has to be equal to the sum of all counters
1247          */
1248         killcnt[idx]++;
1249     }
1250     /* increment total kill counter */
1251     killcnt_total++;
1252 }
1253 
get_killcnt(int min_oomadj,int max_oomadj)1254 static int get_killcnt(int min_oomadj, int max_oomadj) {
1255     int slot;
1256     int count = 0;
1257 
1258     if (min_oomadj > max_oomadj)
1259         return 0;
1260 
1261     /* special case to get total kill count */
1262     if (min_oomadj > OOM_SCORE_ADJ_MAX)
1263         return killcnt_total;
1264 
1265     while (min_oomadj <= max_oomadj &&
1266            (slot = ADJTOSLOT(min_oomadj)) < ADJTOSLOT_COUNT) {
1267         uint8_t idx = killcnt_idx[slot];
1268         if (idx != KILLCNT_INVALID_IDX) {
1269             count += killcnt[idx];
1270         }
1271         min_oomadj++;
1272     }
1273 
1274     return count;
1275 }
1276 
cmd_getkillcnt(LMKD_CTRL_PACKET packet)1277 static int cmd_getkillcnt(LMKD_CTRL_PACKET packet) {
1278     struct lmk_getkillcnt params;
1279 
1280     if (use_inkernel_interface) {
1281         /* kernel driver does not expose this information */
1282         return 0;
1283     }
1284 
1285     lmkd_pack_get_getkillcnt(packet, &params);
1286 
1287     return get_killcnt(params.min_oomadj, params.max_oomadj);
1288 }
1289 
cmd_target(int ntargets,LMKD_CTRL_PACKET packet)1290 static void cmd_target(int ntargets, LMKD_CTRL_PACKET packet) {
1291     int i;
1292     struct lmk_target target;
1293     char minfree_str[PROPERTY_VALUE_MAX];
1294     char *pstr = minfree_str;
1295     char *pend = minfree_str + sizeof(minfree_str);
1296     static struct timespec last_req_tm;
1297     struct timespec curr_tm;
1298 
1299     if (ntargets < 1 || ntargets > (int)ARRAY_SIZE(lowmem_adj))
1300         return;
1301 
1302     /*
1303      * Ratelimit minfree updates to once per TARGET_UPDATE_MIN_INTERVAL_MS
1304      * to prevent DoS attacks
1305      */
1306     if (clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm) != 0) {
1307         ALOGE("Failed to get current time");
1308         return;
1309     }
1310 
1311     if (get_time_diff_ms(&last_req_tm, &curr_tm) <
1312         TARGET_UPDATE_MIN_INTERVAL_MS) {
1313         ALOGE("Ignoring frequent updated to lmkd limits");
1314         return;
1315     }
1316 
1317     last_req_tm = curr_tm;
1318 
1319     for (i = 0; i < ntargets; i++) {
1320         lmkd_pack_get_target(packet, i, &target);
1321         lowmem_minfree[i] = target.minfree;
1322         lowmem_adj[i] = target.oom_adj_score;
1323 
1324         pstr += snprintf(pstr, pend - pstr, "%d:%d,", target.minfree,
1325             target.oom_adj_score);
1326         if (pstr >= pend) {
1327             /* if no more space in the buffer then terminate the loop */
1328             pstr = pend;
1329             break;
1330         }
1331     }
1332 
1333     lowmem_targets_size = ntargets;
1334 
1335     /* Override the last extra comma */
1336     pstr[-1] = '\0';
1337     property_set("sys.lmk.minfree_levels", minfree_str);
1338 
1339     if (has_inkernel_module) {
1340         char minfreestr[128];
1341         char killpriostr[128];
1342 
1343         minfreestr[0] = '\0';
1344         killpriostr[0] = '\0';
1345 
1346         for (i = 0; i < lowmem_targets_size; i++) {
1347             char val[40];
1348 
1349             if (i) {
1350                 strlcat(minfreestr, ",", sizeof(minfreestr));
1351                 strlcat(killpriostr, ",", sizeof(killpriostr));
1352             }
1353 
1354             snprintf(val, sizeof(val), "%d", use_inkernel_interface ? lowmem_minfree[i] : 0);
1355             strlcat(minfreestr, val, sizeof(minfreestr));
1356             snprintf(val, sizeof(val), "%d", use_inkernel_interface ? lowmem_adj[i] : 0);
1357             strlcat(killpriostr, val, sizeof(killpriostr));
1358         }
1359 
1360         writefilestring(INKERNEL_MINFREE_PATH, minfreestr, true);
1361         writefilestring(INKERNEL_ADJ_PATH, killpriostr, true);
1362     }
1363 }
1364 
ctrl_command_handler(int dsock_idx)1365 static void ctrl_command_handler(int dsock_idx) {
1366     LMKD_CTRL_PACKET packet;
1367     struct ucred cred;
1368     int len;
1369     enum lmk_cmd cmd;
1370     int nargs;
1371     int targets;
1372     int kill_cnt;
1373     int result;
1374 
1375     len = ctrl_data_read(dsock_idx, (char *)packet, CTRL_PACKET_MAX_SIZE, &cred);
1376     if (len <= 0)
1377         return;
1378 
1379     if (len < (int)sizeof(int)) {
1380         ALOGE("Wrong control socket read length len=%d", len);
1381         return;
1382     }
1383 
1384     cmd = lmkd_pack_get_cmd(packet);
1385     nargs = len / sizeof(int) - 1;
1386     if (nargs < 0)
1387         goto wronglen;
1388 
1389     switch(cmd) {
1390     case LMK_TARGET:
1391         targets = nargs / 2;
1392         if (nargs & 0x1 || targets > (int)ARRAY_SIZE(lowmem_adj))
1393             goto wronglen;
1394         cmd_target(targets, packet);
1395         break;
1396     case LMK_PROCPRIO:
1397         /* process type field is optional for backward compatibility */
1398         if (nargs < 3 || nargs > 4)
1399             goto wronglen;
1400         cmd_procprio(packet, nargs, &cred);
1401         break;
1402     case LMK_PROCREMOVE:
1403         if (nargs != 1)
1404             goto wronglen;
1405         cmd_procremove(packet, &cred);
1406         break;
1407     case LMK_PROCPURGE:
1408         if (nargs != 0)
1409             goto wronglen;
1410         cmd_procpurge(&cred);
1411         break;
1412     case LMK_GETKILLCNT:
1413         if (nargs != 2)
1414             goto wronglen;
1415         kill_cnt = cmd_getkillcnt(packet);
1416         len = lmkd_pack_set_getkillcnt_repl(packet, kill_cnt);
1417         if (ctrl_data_write(dsock_idx, (char *)packet, len) != len)
1418             return;
1419         break;
1420     case LMK_SUBSCRIBE:
1421         if (nargs != 1)
1422             goto wronglen;
1423         cmd_subscribe(dsock_idx, packet);
1424         break;
1425     case LMK_PROCKILL:
1426         /* This command code is NOT expected at all */
1427         ALOGE("Received unexpected command code %d", cmd);
1428         break;
1429     case LMK_UPDATE_PROPS:
1430         if (nargs != 0)
1431             goto wronglen;
1432         update_props();
1433         if (!use_inkernel_interface) {
1434             /* Reinitialize monitors to apply new settings */
1435             destroy_monitors();
1436             result = init_monitors() ? 0 : -1;
1437         } else {
1438             result = 0;
1439         }
1440         len = lmkd_pack_set_update_props_repl(packet, result);
1441         if (ctrl_data_write(dsock_idx, (char *)packet, len) != len) {
1442             ALOGE("Failed to report operation results");
1443         }
1444         if (!result) {
1445             ALOGI("Properties reinitilized");
1446         } else {
1447             /* New settings can't be supported, crash to be restarted */
1448             ALOGE("New configuration is not supported. Exiting...");
1449             exit(1);
1450         }
1451         break;
1452     default:
1453         ALOGE("Received unknown command code %d", cmd);
1454         return;
1455     }
1456 
1457     return;
1458 
1459 wronglen:
1460     ALOGE("Wrong control socket read length cmd=%d len=%d", cmd, len);
1461 }
1462 
ctrl_data_handler(int data,uint32_t events,struct polling_params * poll_params __unused)1463 static void ctrl_data_handler(int data, uint32_t events,
1464                               struct polling_params *poll_params __unused) {
1465     if (events & EPOLLIN) {
1466         ctrl_command_handler(data);
1467     }
1468 }
1469 
get_free_dsock()1470 static int get_free_dsock() {
1471     for (int i = 0; i < MAX_DATA_CONN; i++) {
1472         if (data_sock[i].sock < 0) {
1473             return i;
1474         }
1475     }
1476     return -1;
1477 }
1478 
ctrl_connect_handler(int data __unused,uint32_t events __unused,struct polling_params * poll_params __unused)1479 static void ctrl_connect_handler(int data __unused, uint32_t events __unused,
1480                                  struct polling_params *poll_params __unused) {
1481     struct epoll_event epev;
1482     int free_dscock_idx = get_free_dsock();
1483 
1484     if (free_dscock_idx < 0) {
1485         /*
1486          * Number of data connections exceeded max supported. This should not
1487          * happen but if it does we drop all existing connections and accept
1488          * the new one. This prevents inactive connections from monopolizing
1489          * data socket and if we drop ActivityManager connection it will
1490          * immediately reconnect.
1491          */
1492         for (int i = 0; i < MAX_DATA_CONN; i++) {
1493             ctrl_data_close(i);
1494         }
1495         free_dscock_idx = 0;
1496     }
1497 
1498     data_sock[free_dscock_idx].sock = accept(ctrl_sock.sock, NULL, NULL);
1499     if (data_sock[free_dscock_idx].sock < 0) {
1500         ALOGE("lmkd control socket accept failed; errno=%d", errno);
1501         return;
1502     }
1503 
1504     ALOGI("lmkd data connection established");
1505     /* use data to store data connection idx */
1506     data_sock[free_dscock_idx].handler_info.data = free_dscock_idx;
1507     data_sock[free_dscock_idx].handler_info.handler = ctrl_data_handler;
1508     data_sock[free_dscock_idx].async_event_mask = 0;
1509     epev.events = EPOLLIN;
1510     epev.data.ptr = (void *)&(data_sock[free_dscock_idx].handler_info);
1511     if (epoll_ctl(epollfd, EPOLL_CTL_ADD, data_sock[free_dscock_idx].sock, &epev) == -1) {
1512         ALOGE("epoll_ctl for data connection socket failed; errno=%d", errno);
1513         ctrl_data_close(free_dscock_idx);
1514         return;
1515     }
1516     maxevents++;
1517 }
1518 
1519 /*
1520  * /proc/zoneinfo parsing routines
1521  * Expected file format is:
1522  *
1523  *   Node <node_id>, zone   <zone_name>
1524  *   (
1525  *    per-node stats
1526  *       (<per-node field name> <value>)+
1527  *   )?
1528  *   (pages free     <value>
1529  *       (<per-zone field name> <value>)+
1530  *    pagesets
1531  *       (<unused fields>)*
1532  *   )+
1533  *   ...
1534  */
zoneinfo_parse_protection(char * buf,struct zoneinfo_zone * zone)1535 static void zoneinfo_parse_protection(char *buf, struct zoneinfo_zone *zone) {
1536     int zone_idx;
1537     int64_t max = 0;
1538     char *save_ptr;
1539 
1540     for (buf = strtok_r(buf, "(), ", &save_ptr), zone_idx = 0;
1541          buf && zone_idx < MAX_NR_ZONES;
1542          buf = strtok_r(NULL, "), ", &save_ptr), zone_idx++) {
1543         long long zoneval = strtoll(buf, &buf, 0);
1544         if (zoneval > max) {
1545             max = (zoneval > INT64_MAX) ? INT64_MAX : zoneval;
1546         }
1547         zone->protection[zone_idx] = zoneval;
1548     }
1549     zone->max_protection = max;
1550 }
1551 
zoneinfo_parse_zone(char ** buf,struct zoneinfo_zone * zone)1552 static int zoneinfo_parse_zone(char **buf, struct zoneinfo_zone *zone) {
1553     for (char *line = strtok_r(NULL, "\n", buf); line;
1554          line = strtok_r(NULL, "\n", buf)) {
1555         char *cp;
1556         char *ap;
1557         char *save_ptr;
1558         int64_t val;
1559         int field_idx;
1560         enum field_match_result match_res;
1561 
1562         cp = strtok_r(line, " ", &save_ptr);
1563         if (!cp) {
1564             return false;
1565         }
1566 
1567         field_idx = find_field(cp, zoneinfo_zone_spec_field_names, ZI_ZONE_SPEC_FIELD_COUNT);
1568         if (field_idx >= 0) {
1569             /* special field */
1570             if (field_idx == ZI_ZONE_SPEC_PAGESETS) {
1571                 /* no mode fields we are interested in */
1572                 return true;
1573             }
1574 
1575             /* protection field */
1576             ap = strtok_r(NULL, ")", &save_ptr);
1577             if (ap) {
1578                 zoneinfo_parse_protection(ap, zone);
1579             }
1580             continue;
1581         }
1582 
1583         ap = strtok_r(NULL, " ", &save_ptr);
1584         if (!ap) {
1585             continue;
1586         }
1587 
1588         match_res = match_field(cp, ap, zoneinfo_zone_field_names, ZI_ZONE_FIELD_COUNT,
1589             &val, &field_idx);
1590         if (match_res == PARSE_FAIL) {
1591             return false;
1592         }
1593         if (match_res == PARSE_SUCCESS) {
1594             zone->fields.arr[field_idx] = val;
1595         }
1596         if (field_idx == ZI_ZONE_PRESENT && val == 0) {
1597             /* zone is not populated, stop parsing it */
1598             return true;
1599         }
1600     }
1601     return false;
1602 }
1603 
zoneinfo_parse_node(char ** buf,struct zoneinfo_node * node)1604 static int zoneinfo_parse_node(char **buf, struct zoneinfo_node *node) {
1605     int fields_to_match = ZI_NODE_FIELD_COUNT;
1606 
1607     for (char *line = strtok_r(NULL, "\n", buf); line;
1608          line = strtok_r(NULL, "\n", buf)) {
1609         char *cp;
1610         char *ap;
1611         char *save_ptr;
1612         int64_t val;
1613         int field_idx;
1614         enum field_match_result match_res;
1615 
1616         cp = strtok_r(line, " ", &save_ptr);
1617         if (!cp) {
1618             return false;
1619         }
1620 
1621         ap = strtok_r(NULL, " ", &save_ptr);
1622         if (!ap) {
1623             return false;
1624         }
1625 
1626         match_res = match_field(cp, ap, zoneinfo_node_field_names, ZI_NODE_FIELD_COUNT,
1627             &val, &field_idx);
1628         if (match_res == PARSE_FAIL) {
1629             return false;
1630         }
1631         if (match_res == PARSE_SUCCESS) {
1632             node->fields.arr[field_idx] = val;
1633             fields_to_match--;
1634             if (!fields_to_match) {
1635                 return true;
1636             }
1637         }
1638     }
1639     return false;
1640 }
1641 
zoneinfo_parse(struct zoneinfo * zi)1642 static int zoneinfo_parse(struct zoneinfo *zi) {
1643     static struct reread_data file_data = {
1644         .filename = ZONEINFO_PATH,
1645         .fd = -1,
1646     };
1647     char *buf;
1648     char *save_ptr;
1649     char *line;
1650     char zone_name[LINE_MAX + 1];
1651     struct zoneinfo_node *node = NULL;
1652     int node_idx = 0;
1653     int zone_idx = 0;
1654 
1655     memset(zi, 0, sizeof(struct zoneinfo));
1656 
1657     if ((buf = reread_file(&file_data)) == NULL) {
1658         return -1;
1659     }
1660 
1661     for (line = strtok_r(buf, "\n", &save_ptr); line;
1662          line = strtok_r(NULL, "\n", &save_ptr)) {
1663         int node_id;
1664         if (sscanf(line, "Node %d, zone %" STRINGIFY(LINE_MAX) "s", &node_id, zone_name) == 2) {
1665             if (!node || node->id != node_id) {
1666                 /* new node is found */
1667                 if (node) {
1668                     node->zone_count = zone_idx + 1;
1669                     node_idx++;
1670                     if (node_idx == MAX_NR_NODES) {
1671                         /* max node count exceeded */
1672                         ALOGE("%s parse error", file_data.filename);
1673                         return -1;
1674                     }
1675                 }
1676                 node = &zi->nodes[node_idx];
1677                 node->id = node_id;
1678                 zone_idx = 0;
1679                 if (!zoneinfo_parse_node(&save_ptr, node)) {
1680                     ALOGE("%s parse error", file_data.filename);
1681                     return -1;
1682                 }
1683             } else {
1684                 /* new zone is found */
1685                 zone_idx++;
1686             }
1687             if (!zoneinfo_parse_zone(&save_ptr, &node->zones[zone_idx])) {
1688                 ALOGE("%s parse error", file_data.filename);
1689                 return -1;
1690             }
1691         }
1692     }
1693     if (!node) {
1694         ALOGE("%s parse error", file_data.filename);
1695         return -1;
1696     }
1697     node->zone_count = zone_idx + 1;
1698     zi->node_count = node_idx + 1;
1699 
1700     /* calculate totals fields */
1701     for (node_idx = 0; node_idx < zi->node_count; node_idx++) {
1702         node = &zi->nodes[node_idx];
1703         for (zone_idx = 0; zone_idx < node->zone_count; zone_idx++) {
1704             struct zoneinfo_zone *zone = &zi->nodes[node_idx].zones[zone_idx];
1705             zi->totalreserve_pages += zone->max_protection + zone->fields.field.high;
1706         }
1707         zi->total_inactive_file += node->fields.field.nr_inactive_file;
1708         zi->total_active_file += node->fields.field.nr_active_file;
1709         zi->total_workingset_refault += node->fields.field.workingset_refault;
1710     }
1711     return 0;
1712 }
1713 
1714 /* /proc/meminfo parsing routines */
meminfo_parse_line(char * line,union meminfo * mi)1715 static bool meminfo_parse_line(char *line, union meminfo *mi) {
1716     char *cp = line;
1717     char *ap;
1718     char *save_ptr;
1719     int64_t val;
1720     int field_idx;
1721     enum field_match_result match_res;
1722 
1723     cp = strtok_r(line, " ", &save_ptr);
1724     if (!cp) {
1725         return false;
1726     }
1727 
1728     ap = strtok_r(NULL, " ", &save_ptr);
1729     if (!ap) {
1730         return false;
1731     }
1732 
1733     match_res = match_field(cp, ap, meminfo_field_names, MI_FIELD_COUNT,
1734         &val, &field_idx);
1735     if (match_res == PARSE_SUCCESS) {
1736         mi->arr[field_idx] = val / page_k;
1737     }
1738     return (match_res != PARSE_FAIL);
1739 }
1740 
meminfo_parse(union meminfo * mi)1741 static int meminfo_parse(union meminfo *mi) {
1742     static struct reread_data file_data = {
1743         .filename = MEMINFO_PATH,
1744         .fd = -1,
1745     };
1746     char *buf;
1747     char *save_ptr;
1748     char *line;
1749 
1750     memset(mi, 0, sizeof(union meminfo));
1751 
1752     if ((buf = reread_file(&file_data)) == NULL) {
1753         return -1;
1754     }
1755 
1756     for (line = strtok_r(buf, "\n", &save_ptr); line;
1757          line = strtok_r(NULL, "\n", &save_ptr)) {
1758         if (!meminfo_parse_line(line, mi)) {
1759             ALOGE("%s parse error", file_data.filename);
1760             return -1;
1761         }
1762     }
1763     mi->field.nr_file_pages = mi->field.cached + mi->field.swap_cached +
1764         mi->field.buffers;
1765 
1766     return 0;
1767 }
1768 
1769 /* /proc/vmstat parsing routines */
vmstat_parse_line(char * line,union vmstat * vs)1770 static bool vmstat_parse_line(char *line, union vmstat *vs) {
1771     char *cp;
1772     char *ap;
1773     char *save_ptr;
1774     int64_t val;
1775     int field_idx;
1776     enum field_match_result match_res;
1777 
1778     cp = strtok_r(line, " ", &save_ptr);
1779     if (!cp) {
1780         return false;
1781     }
1782 
1783     ap = strtok_r(NULL, " ", &save_ptr);
1784     if (!ap) {
1785         return false;
1786     }
1787 
1788     match_res = match_field(cp, ap, vmstat_field_names, VS_FIELD_COUNT,
1789         &val, &field_idx);
1790     if (match_res == PARSE_SUCCESS) {
1791         vs->arr[field_idx] = val;
1792     }
1793     return (match_res != PARSE_FAIL);
1794 }
1795 
vmstat_parse(union vmstat * vs)1796 static int vmstat_parse(union vmstat *vs) {
1797     static struct reread_data file_data = {
1798         .filename = VMSTAT_PATH,
1799         .fd = -1,
1800     };
1801     char *buf;
1802     char *save_ptr;
1803     char *line;
1804 
1805     memset(vs, 0, sizeof(union vmstat));
1806 
1807     if ((buf = reread_file(&file_data)) == NULL) {
1808         return -1;
1809     }
1810 
1811     for (line = strtok_r(buf, "\n", &save_ptr); line;
1812          line = strtok_r(NULL, "\n", &save_ptr)) {
1813         if (!vmstat_parse_line(line, vs)) {
1814             ALOGE("%s parse error", file_data.filename);
1815             return -1;
1816         }
1817     }
1818 
1819     return 0;
1820 }
1821 
1822 enum wakeup_reason {
1823     Event,
1824     Polling
1825 };
1826 
1827 struct wakeup_info {
1828     struct timespec wakeup_tm;
1829     struct timespec prev_wakeup_tm;
1830     struct timespec last_event_tm;
1831     int wakeups_since_event;
1832     int skipped_wakeups;
1833 };
1834 
1835 /*
1836  * After the initial memory pressure event is received lmkd schedules periodic wakeups to check
1837  * the memory conditions and kill if needed (polling). This is done because pressure events are
1838  * rate-limited and memory conditions can change in between events. Therefore after the initial
1839  * event there might be multiple wakeups. This function records the wakeup information such as the
1840  * timestamps of the last event and the last wakeup, the number of wakeups since the last event
1841  * and how many of those wakeups were skipped (some wakeups are skipped if previously killed
1842  * process is still freeing its memory).
1843  */
record_wakeup_time(struct timespec * tm,enum wakeup_reason reason,struct wakeup_info * wi)1844 static void record_wakeup_time(struct timespec *tm, enum wakeup_reason reason,
1845                                struct wakeup_info *wi) {
1846     wi->prev_wakeup_tm = wi->wakeup_tm;
1847     wi->wakeup_tm = *tm;
1848     if (reason == Event) {
1849         wi->last_event_tm = *tm;
1850         wi->wakeups_since_event = 0;
1851         wi->skipped_wakeups = 0;
1852     } else {
1853         wi->wakeups_since_event++;
1854     }
1855 }
1856 
killinfo_log(struct proc * procp,int min_oom_score,int tasksize,int kill_reason,union meminfo * mi,struct wakeup_info * wi,struct timespec * tm)1857 static void killinfo_log(struct proc* procp, int min_oom_score, int tasksize,
1858                          int kill_reason, union meminfo *mi,
1859                          struct wakeup_info *wi, struct timespec *tm) {
1860     /* log process information */
1861     android_log_write_int32(ctx, procp->pid);
1862     android_log_write_int32(ctx, procp->uid);
1863     android_log_write_int32(ctx, procp->oomadj);
1864     android_log_write_int32(ctx, min_oom_score);
1865     android_log_write_int32(ctx, (int32_t)min(tasksize * page_k, INT32_MAX));
1866     android_log_write_int32(ctx, kill_reason);
1867 
1868     /* log meminfo fields */
1869     for (int field_idx = 0; field_idx < MI_FIELD_COUNT; field_idx++) {
1870         android_log_write_int32(ctx, (int32_t)min(mi->arr[field_idx] * page_k, INT32_MAX));
1871     }
1872 
1873     /* log lmkd wakeup information */
1874     android_log_write_int32(ctx, (int32_t)get_time_diff_ms(&wi->last_event_tm, tm));
1875     android_log_write_int32(ctx, (int32_t)get_time_diff_ms(&wi->prev_wakeup_tm, tm));
1876     android_log_write_int32(ctx, wi->wakeups_since_event);
1877     android_log_write_int32(ctx, wi->skipped_wakeups);
1878 
1879     android_log_write_list(ctx, LOG_ID_EVENTS);
1880     android_log_reset(ctx);
1881 }
1882 
proc_adj_lru(int oomadj)1883 static struct proc *proc_adj_lru(int oomadj) {
1884     return (struct proc *)adjslot_tail(&procadjslot_list[ADJTOSLOT(oomadj)]);
1885 }
1886 
proc_get_heaviest(int oomadj)1887 static struct proc *proc_get_heaviest(int oomadj) {
1888     struct adjslot_list *head = &procadjslot_list[ADJTOSLOT(oomadj)];
1889     struct adjslot_list *curr = head->next;
1890     struct proc *maxprocp = NULL;
1891     int maxsize = 0;
1892     while (curr != head) {
1893         int pid = ((struct proc *)curr)->pid;
1894         int tasksize = proc_get_size(pid);
1895         if (tasksize <= 0) {
1896             struct adjslot_list *next = curr->next;
1897             pid_remove(pid);
1898             curr = next;
1899         } else {
1900             if (tasksize > maxsize) {
1901                 maxsize = tasksize;
1902                 maxprocp = (struct proc *)curr;
1903             }
1904             curr = curr->next;
1905         }
1906     }
1907     return maxprocp;
1908 }
1909 
set_process_group_and_prio(int pid,SchedPolicy sp,int prio)1910 static void set_process_group_and_prio(int pid, SchedPolicy sp, int prio) {
1911     DIR* d;
1912     char proc_path[PATH_MAX];
1913     struct dirent* de;
1914 
1915     snprintf(proc_path, sizeof(proc_path), "/proc/%d/task", pid);
1916     if (!(d = opendir(proc_path))) {
1917         ALOGW("Failed to open %s; errno=%d: process pid(%d) might have died", proc_path, errno,
1918               pid);
1919         return;
1920     }
1921 
1922     while ((de = readdir(d))) {
1923         int t_pid;
1924 
1925         if (de->d_name[0] == '.') continue;
1926         t_pid = atoi(de->d_name);
1927 
1928         if (!t_pid) {
1929             ALOGW("Failed to get t_pid for '%s' of pid(%d)", de->d_name, pid);
1930             continue;
1931         }
1932 
1933         if (setpriority(PRIO_PROCESS, t_pid, prio) && errno != ESRCH) {
1934             ALOGW("Unable to raise priority of killing t_pid (%d): errno=%d", t_pid, errno);
1935         }
1936 
1937         if (set_cpuset_policy(t_pid, sp)) {
1938             ALOGW("Failed to set_cpuset_policy on pid(%d) t_pid(%d) to %d", pid, t_pid, (int)sp);
1939             continue;
1940         }
1941     }
1942     closedir(d);
1943 }
1944 
is_kill_pending(void)1945 static bool is_kill_pending(void) {
1946     char buf[24];
1947 
1948     if (last_kill_pid_or_fd < 0) {
1949         return false;
1950     }
1951 
1952     if (pidfd_supported) {
1953         return true;
1954     }
1955 
1956     /* when pidfd is not supported base the decision on /proc/<pid> existence */
1957     snprintf(buf, sizeof(buf), "/proc/%d/", last_kill_pid_or_fd);
1958     if (access(buf, F_OK) == 0) {
1959         return true;
1960     }
1961 
1962     return false;
1963 }
1964 
is_waiting_for_kill(void)1965 static bool is_waiting_for_kill(void) {
1966     return pidfd_supported && last_kill_pid_or_fd >= 0;
1967 }
1968 
stop_wait_for_proc_kill(bool finished)1969 static void stop_wait_for_proc_kill(bool finished) {
1970     struct epoll_event epev;
1971 
1972     if (last_kill_pid_or_fd < 0) {
1973         return;
1974     }
1975 
1976     if (debug_process_killing) {
1977         struct timespec curr_tm;
1978 
1979         if (clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm) != 0) {
1980             /*
1981              * curr_tm is used here merely to report kill duration, so this failure is not fatal.
1982              * Log an error and continue.
1983              */
1984             ALOGE("Failed to get current time");
1985         }
1986 
1987         if (finished) {
1988             ALOGI("Process got killed in %ldms",
1989                 get_time_diff_ms(&last_kill_tm, &curr_tm));
1990         } else {
1991             ALOGI("Stop waiting for process kill after %ldms",
1992                 get_time_diff_ms(&last_kill_tm, &curr_tm));
1993         }
1994     }
1995 
1996     if (pidfd_supported) {
1997         /* unregister fd */
1998         if (epoll_ctl(epollfd, EPOLL_CTL_DEL, last_kill_pid_or_fd, &epev)) {
1999             // Log an error and keep going
2000             ALOGE("epoll_ctl for last killed process failed; errno=%d", errno);
2001         }
2002         maxevents--;
2003         close(last_kill_pid_or_fd);
2004     }
2005 
2006     last_kill_pid_or_fd = -1;
2007 }
2008 
kill_done_handler(int data __unused,uint32_t events __unused,struct polling_params * poll_params)2009 static void kill_done_handler(int data __unused, uint32_t events __unused,
2010                               struct polling_params *poll_params) {
2011     stop_wait_for_proc_kill(true);
2012     poll_params->update = POLLING_RESUME;
2013 }
2014 
start_wait_for_proc_kill(int pid_or_fd)2015 static void start_wait_for_proc_kill(int pid_or_fd) {
2016     static struct event_handler_info kill_done_hinfo = { 0, kill_done_handler };
2017     struct epoll_event epev;
2018 
2019     if (last_kill_pid_or_fd >= 0) {
2020         /* Should not happen but if it does we should stop previous wait */
2021         ALOGE("Attempt to wait for a kill while another wait is in progress");
2022         stop_wait_for_proc_kill(false);
2023     }
2024 
2025     last_kill_pid_or_fd = pid_or_fd;
2026 
2027     if (!pidfd_supported) {
2028         /* If pidfd is not supported just store PID and exit */
2029         return;
2030     }
2031 
2032     epev.events = EPOLLIN;
2033     epev.data.ptr = (void *)&kill_done_hinfo;
2034     if (epoll_ctl(epollfd, EPOLL_CTL_ADD, last_kill_pid_or_fd, &epev) != 0) {
2035         ALOGE("epoll_ctl for last kill failed; errno=%d", errno);
2036         close(last_kill_pid_or_fd);
2037         last_kill_pid_or_fd = -1;
2038         return;
2039     }
2040     maxevents++;
2041 }
2042 
2043 /* Kill one process specified by procp.  Returns the size of the process killed */
kill_one_process(struct proc * procp,int min_oom_score,int kill_reason,const char * kill_desc,union meminfo * mi,struct wakeup_info * wi,struct timespec * tm)2044 static int kill_one_process(struct proc* procp, int min_oom_score, int kill_reason,
2045                             const char *kill_desc, union meminfo *mi, struct wakeup_info *wi,
2046                             struct timespec *tm) {
2047     int pid = procp->pid;
2048     int pidfd = procp->pidfd;
2049     uid_t uid = procp->uid;
2050     int tgid;
2051     char *taskname;
2052     int tasksize;
2053     int r;
2054     int result = -1;
2055     struct memory_stat *mem_st;
2056     char buf[LINE_MAX];
2057 
2058     tgid = proc_get_tgid(pid);
2059     if (tgid >= 0 && tgid != pid) {
2060         ALOGE("Possible pid reuse detected (pid %d, tgid %d)!", pid, tgid);
2061         goto out;
2062     }
2063 
2064     taskname = proc_get_name(pid, buf, sizeof(buf));
2065     if (!taskname) {
2066         goto out;
2067     }
2068 
2069     tasksize = proc_get_size(pid);
2070     if (tasksize <= 0) {
2071         goto out;
2072     }
2073 
2074     mem_st = stats_read_memory_stat(per_app_memcg, pid, uid);
2075 
2076     TRACE_KILL_START(pid);
2077 
2078     /* CAP_KILL required */
2079     if (pidfd < 0) {
2080         start_wait_for_proc_kill(pid);
2081         r = kill(pid, SIGKILL);
2082     } else {
2083         start_wait_for_proc_kill(pidfd);
2084         r = sys_pidfd_send_signal(pidfd, SIGKILL, NULL, 0);
2085     }
2086 
2087     TRACE_KILL_END();
2088 
2089     if (r) {
2090         stop_wait_for_proc_kill(false);
2091         ALOGE("kill(%d): errno=%d", pid, errno);
2092         /* Delete process record even when we fail to kill so that we don't get stuck on it */
2093         goto out;
2094     }
2095 
2096     set_process_group_and_prio(pid, SP_FOREGROUND, ANDROID_PRIORITY_HIGHEST);
2097 
2098     last_kill_tm = *tm;
2099 
2100     inc_killcnt(procp->oomadj);
2101 
2102     killinfo_log(procp, min_oom_score, tasksize, kill_reason, mi, wi, tm);
2103 
2104     if (kill_desc) {
2105         ALOGI("Kill '%s' (%d), uid %d, oom_adj %d to free %ldkB; reason: %s", taskname, pid,
2106               uid, procp->oomadj, tasksize * page_k, kill_desc);
2107     } else {
2108         ALOGI("Kill '%s' (%d), uid %d, oom_adj %d to free %ldkB", taskname, pid,
2109               uid, procp->oomadj, tasksize * page_k);
2110     }
2111 
2112     stats_write_lmk_kill_occurred(uid, taskname, procp->oomadj, min_oom_score, tasksize, mem_st);
2113 
2114     ctrl_data_write_lmk_kill_occurred((pid_t)pid, uid);
2115 
2116     result = tasksize;
2117 
2118 out:
2119     /*
2120      * WARNING: After pid_remove() procp is freed and can't be used!
2121      * Therefore placed at the end of the function.
2122      */
2123     pid_remove(pid);
2124     return result;
2125 }
2126 
2127 /*
2128  * Find one process to kill at or above the given oom_adj level.
2129  * Returns size of the killed process.
2130  */
find_and_kill_process(int min_score_adj,int kill_reason,const char * kill_desc,union meminfo * mi,struct wakeup_info * wi,struct timespec * tm)2131 static int find_and_kill_process(int min_score_adj, int kill_reason, const char *kill_desc,
2132                                  union meminfo *mi, struct wakeup_info *wi, struct timespec *tm) {
2133     int i;
2134     int killed_size = 0;
2135     bool lmk_state_change_start = false;
2136 
2137     for (i = OOM_SCORE_ADJ_MAX; i >= min_score_adj; i--) {
2138         struct proc *procp;
2139 
2140         while (true) {
2141             procp = kill_heaviest_task ?
2142                 proc_get_heaviest(i) : proc_adj_lru(i);
2143 
2144             if (!procp)
2145                 break;
2146 
2147             killed_size = kill_one_process(procp, min_score_adj, kill_reason, kill_desc,
2148                                            mi, wi, tm);
2149             if (killed_size >= 0) {
2150                 if (!lmk_state_change_start) {
2151                     lmk_state_change_start = true;
2152                     stats_write_lmk_state_changed(
2153                             android::lmkd::stats::LMK_STATE_CHANGED__STATE__START);
2154                 }
2155                 break;
2156             }
2157         }
2158         if (killed_size) {
2159             break;
2160         }
2161     }
2162 
2163     if (lmk_state_change_start) {
2164         stats_write_lmk_state_changed(android::lmkd::stats::LMK_STATE_CHANGED__STATE__STOP);
2165     }
2166 
2167     return killed_size;
2168 }
2169 
get_memory_usage(struct reread_data * file_data)2170 static int64_t get_memory_usage(struct reread_data *file_data) {
2171     int64_t mem_usage;
2172     char *buf;
2173 
2174     if ((buf = reread_file(file_data)) == NULL) {
2175         return -1;
2176     }
2177 
2178     if (!parse_int64(buf, &mem_usage)) {
2179         ALOGE("%s parse error", file_data->filename);
2180         return -1;
2181     }
2182     if (mem_usage == 0) {
2183         ALOGE("No memory!");
2184         return -1;
2185     }
2186     return mem_usage;
2187 }
2188 
record_low_pressure_levels(union meminfo * mi)2189 void record_low_pressure_levels(union meminfo *mi) {
2190     if (low_pressure_mem.min_nr_free_pages == -1 ||
2191         low_pressure_mem.min_nr_free_pages > mi->field.nr_free_pages) {
2192         if (debug_process_killing) {
2193             ALOGI("Low pressure min memory update from %" PRId64 " to %" PRId64,
2194                 low_pressure_mem.min_nr_free_pages, mi->field.nr_free_pages);
2195         }
2196         low_pressure_mem.min_nr_free_pages = mi->field.nr_free_pages;
2197     }
2198     /*
2199      * Free memory at low vmpressure events occasionally gets spikes,
2200      * possibly a stale low vmpressure event with memory already
2201      * freed up (no memory pressure should have been reported).
2202      * Ignore large jumps in max_nr_free_pages that would mess up our stats.
2203      */
2204     if (low_pressure_mem.max_nr_free_pages == -1 ||
2205         (low_pressure_mem.max_nr_free_pages < mi->field.nr_free_pages &&
2206          mi->field.nr_free_pages - low_pressure_mem.max_nr_free_pages <
2207          low_pressure_mem.max_nr_free_pages * 0.1)) {
2208         if (debug_process_killing) {
2209             ALOGI("Low pressure max memory update from %" PRId64 " to %" PRId64,
2210                 low_pressure_mem.max_nr_free_pages, mi->field.nr_free_pages);
2211         }
2212         low_pressure_mem.max_nr_free_pages = mi->field.nr_free_pages;
2213     }
2214 }
2215 
upgrade_level(enum vmpressure_level level)2216 enum vmpressure_level upgrade_level(enum vmpressure_level level) {
2217     return (enum vmpressure_level)((level < VMPRESS_LEVEL_CRITICAL) ?
2218         level + 1 : level);
2219 }
2220 
downgrade_level(enum vmpressure_level level)2221 enum vmpressure_level downgrade_level(enum vmpressure_level level) {
2222     return (enum vmpressure_level)((level > VMPRESS_LEVEL_LOW) ?
2223         level - 1 : level);
2224 }
2225 
2226 enum zone_watermark {
2227     WMARK_MIN = 0,
2228     WMARK_LOW,
2229     WMARK_HIGH,
2230     WMARK_NONE
2231 };
2232 
2233 struct zone_watermarks {
2234     long high_wmark;
2235     long low_wmark;
2236     long min_wmark;
2237 };
2238 
2239 /*
2240  * Returns lowest breached watermark or WMARK_NONE.
2241  */
get_lowest_watermark(union meminfo * mi,struct zone_watermarks * watermarks)2242 static enum zone_watermark get_lowest_watermark(union meminfo *mi,
2243                                                 struct zone_watermarks *watermarks)
2244 {
2245     int64_t nr_free_pages = mi->field.nr_free_pages - mi->field.cma_free;
2246 
2247     if (nr_free_pages < watermarks->min_wmark) {
2248         return WMARK_MIN;
2249     }
2250     if (nr_free_pages < watermarks->low_wmark) {
2251         return WMARK_LOW;
2252     }
2253     if (nr_free_pages < watermarks->high_wmark) {
2254         return WMARK_HIGH;
2255     }
2256     return WMARK_NONE;
2257 }
2258 
calc_zone_watermarks(struct zoneinfo * zi,struct zone_watermarks * watermarks)2259 void calc_zone_watermarks(struct zoneinfo *zi, struct zone_watermarks *watermarks) {
2260     memset(watermarks, 0, sizeof(struct zone_watermarks));
2261 
2262     for (int node_idx = 0; node_idx < zi->node_count; node_idx++) {
2263         struct zoneinfo_node *node = &zi->nodes[node_idx];
2264         for (int zone_idx = 0; zone_idx < node->zone_count; zone_idx++) {
2265             struct zoneinfo_zone *zone = &node->zones[zone_idx];
2266 
2267             if (!zone->fields.field.present) {
2268                 continue;
2269             }
2270 
2271             watermarks->high_wmark += zone->max_protection + zone->fields.field.high;
2272             watermarks->low_wmark += zone->max_protection + zone->fields.field.low;
2273             watermarks->min_wmark += zone->max_protection + zone->fields.field.min;
2274         }
2275     }
2276 }
2277 
calc_swap_utilization(union meminfo * mi)2278 static int calc_swap_utilization(union meminfo *mi) {
2279     int64_t swap_used = mi->field.total_swap - mi->field.free_swap;
2280     int64_t total_swappable = mi->field.active_anon + mi->field.inactive_anon +
2281                               mi->field.shmem + swap_used;
2282     return total_swappable > 0 ? (swap_used * 100) / total_swappable : 0;
2283 }
2284 
mp_event_psi(int data,uint32_t events,struct polling_params * poll_params)2285 static void mp_event_psi(int data, uint32_t events, struct polling_params *poll_params) {
2286     enum kill_reasons {
2287         NONE = -1, /* To denote no kill condition */
2288         PRESSURE_AFTER_KILL = 0,
2289         NOT_RESPONDING,
2290         LOW_SWAP_AND_THRASHING,
2291         LOW_MEM_AND_SWAP,
2292         LOW_MEM_AND_THRASHING,
2293         DIRECT_RECL_AND_THRASHING,
2294         LOW_MEM_AND_SWAP_UTIL,
2295         KILL_REASON_COUNT
2296     };
2297     enum reclaim_state {
2298         NO_RECLAIM = 0,
2299         KSWAPD_RECLAIM,
2300         DIRECT_RECLAIM,
2301     };
2302     static int64_t init_ws_refault;
2303     static int64_t base_file_lru;
2304     static int64_t init_pgscan_kswapd;
2305     static int64_t init_pgscan_direct;
2306     static int64_t swap_low_threshold;
2307     static bool killing;
2308     static int thrashing_limit;
2309     static bool in_reclaim;
2310     static struct zone_watermarks watermarks;
2311     static struct timespec wmark_update_tm;
2312     static struct wakeup_info wi;
2313 
2314     union meminfo mi;
2315     union vmstat vs;
2316     struct timespec curr_tm;
2317     int64_t thrashing = 0;
2318     bool swap_is_low = false;
2319     enum vmpressure_level level = (enum vmpressure_level)data;
2320     enum kill_reasons kill_reason = NONE;
2321     bool cycle_after_kill = false;
2322     enum reclaim_state reclaim = NO_RECLAIM;
2323     enum zone_watermark wmark = WMARK_NONE;
2324     char kill_desc[LINE_MAX];
2325     bool cut_thrashing_limit = false;
2326     int min_score_adj = 0;
2327     int swap_util = 0;
2328 
2329     if (clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm) != 0) {
2330         ALOGE("Failed to get current time");
2331         return;
2332     }
2333 
2334     record_wakeup_time(&curr_tm, events ? Event : Polling, &wi);
2335 
2336     bool kill_pending = is_kill_pending();
2337     if (kill_pending && (kill_timeout_ms == 0 ||
2338         get_time_diff_ms(&last_kill_tm, &curr_tm) < static_cast<long>(kill_timeout_ms))) {
2339         /* Skip while still killing a process */
2340         wi.skipped_wakeups++;
2341         goto no_kill;
2342     }
2343     /*
2344      * Process is dead or kill timeout is over, stop waiting. This has no effect if pidfds are
2345      * supported and death notification already caused waiting to stop.
2346      */
2347     stop_wait_for_proc_kill(!kill_pending);
2348 
2349     if (vmstat_parse(&vs) < 0) {
2350         ALOGE("Failed to parse vmstat!");
2351         return;
2352     }
2353 
2354     if (meminfo_parse(&mi) < 0) {
2355         ALOGE("Failed to parse meminfo!");
2356         return;
2357     }
2358 
2359     /* Reset states after process got killed */
2360     if (killing) {
2361         killing = false;
2362         cycle_after_kill = true;
2363         /* Reset file-backed pagecache size and refault amounts after a kill */
2364         base_file_lru = vs.field.nr_inactive_file + vs.field.nr_active_file;
2365         init_ws_refault = vs.field.workingset_refault;
2366     }
2367 
2368     /* Check free swap levels */
2369     if (swap_free_low_percentage) {
2370         if (!swap_low_threshold) {
2371             swap_low_threshold = mi.field.total_swap * swap_free_low_percentage / 100;
2372         }
2373         swap_is_low = mi.field.free_swap < swap_low_threshold;
2374     }
2375 
2376     /* Identify reclaim state */
2377     if (vs.field.pgscan_direct > init_pgscan_direct) {
2378         init_pgscan_direct = vs.field.pgscan_direct;
2379         init_pgscan_kswapd = vs.field.pgscan_kswapd;
2380         reclaim = DIRECT_RECLAIM;
2381     } else if (vs.field.pgscan_kswapd > init_pgscan_kswapd) {
2382         init_pgscan_kswapd = vs.field.pgscan_kswapd;
2383         reclaim = KSWAPD_RECLAIM;
2384     } else {
2385         in_reclaim = false;
2386         /* Skip if system is not reclaiming */
2387         goto no_kill;
2388     }
2389 
2390     if (!in_reclaim) {
2391         /* Record file-backed pagecache size when entering reclaim cycle */
2392         base_file_lru = vs.field.nr_inactive_file + vs.field.nr_active_file;
2393         init_ws_refault = vs.field.workingset_refault;
2394         thrashing_limit = thrashing_limit_pct;
2395     } else {
2396         /* Calculate what % of the file-backed pagecache refaulted so far */
2397         thrashing = (vs.field.workingset_refault - init_ws_refault) * 100 / base_file_lru;
2398     }
2399     in_reclaim = true;
2400 
2401     /*
2402      * Refresh watermarks once per min in case user updated one of the margins.
2403      * TODO: b/140521024 replace this periodic update with an API for AMS to notify LMKD
2404      * that zone watermarks were changed by the system software.
2405      */
2406     if (watermarks.high_wmark == 0 || get_time_diff_ms(&wmark_update_tm, &curr_tm) > 60000) {
2407         struct zoneinfo zi;
2408 
2409         if (zoneinfo_parse(&zi) < 0) {
2410             ALOGE("Failed to parse zoneinfo!");
2411             return;
2412         }
2413 
2414         calc_zone_watermarks(&zi, &watermarks);
2415         wmark_update_tm = curr_tm;
2416      }
2417 
2418     /* Find out which watermark is breached if any */
2419     wmark = get_lowest_watermark(&mi, &watermarks);
2420 
2421     /*
2422      * TODO: move this logic into a separate function
2423      * Decide if killing a process is necessary and record the reason
2424      */
2425     if (cycle_after_kill && wmark < WMARK_LOW) {
2426         /*
2427          * Prevent kills not freeing enough memory which might lead to OOM kill.
2428          * This might happen when a process is consuming memory faster than reclaim can
2429          * free even after a kill. Mostly happens when running memory stress tests.
2430          */
2431         kill_reason = PRESSURE_AFTER_KILL;
2432         strncpy(kill_desc, "min watermark is breached even after kill", sizeof(kill_desc));
2433     } else if (level == VMPRESS_LEVEL_CRITICAL && events != 0) {
2434         /*
2435          * Device is too busy reclaiming memory which might lead to ANR.
2436          * Critical level is triggered when PSI complete stall (all tasks are blocked because
2437          * of the memory congestion) breaches the configured threshold.
2438          */
2439         kill_reason = NOT_RESPONDING;
2440         strncpy(kill_desc, "device is not responding", sizeof(kill_desc));
2441     } else if (swap_is_low && thrashing > thrashing_limit_pct) {
2442         /* Page cache is thrashing while swap is low */
2443         kill_reason = LOW_SWAP_AND_THRASHING;
2444         snprintf(kill_desc, sizeof(kill_desc), "device is low on swap (%" PRId64
2445             "kB < %" PRId64 "kB) and thrashing (%" PRId64 "%%)",
2446             mi.field.free_swap * page_k, swap_low_threshold * page_k, thrashing);
2447         /* Do not kill perceptible apps unless below min watermark */
2448         if (wmark > WMARK_MIN) {
2449             min_score_adj = PERCEPTIBLE_APP_ADJ + 1;
2450         }
2451     } else if (swap_is_low && wmark < WMARK_HIGH) {
2452         /* Both free memory and swap are low */
2453         kill_reason = LOW_MEM_AND_SWAP;
2454         snprintf(kill_desc, sizeof(kill_desc), "%s watermark is breached and swap is low (%"
2455             PRId64 "kB < %" PRId64 "kB)", wmark > WMARK_LOW ? "min" : "low",
2456             mi.field.free_swap * page_k, swap_low_threshold * page_k);
2457         /* Do not kill perceptible apps unless below min watermark */
2458         if (wmark > WMARK_MIN) {
2459             min_score_adj = PERCEPTIBLE_APP_ADJ + 1;
2460         }
2461     } else if (wmark < WMARK_HIGH && swap_util_max < 100 &&
2462                (swap_util = calc_swap_utilization(&mi)) > swap_util_max) {
2463         /*
2464          * Too much anon memory is swapped out but swap is not low.
2465          * Non-swappable allocations created memory pressure.
2466          */
2467         kill_reason = LOW_MEM_AND_SWAP_UTIL;
2468         snprintf(kill_desc, sizeof(kill_desc), "%s watermark is breached and swap utilization"
2469             " is high (%d%% > %d%%)", wmark > WMARK_LOW ? "min" : "low",
2470             swap_util, swap_util_max);
2471     } else if (wmark < WMARK_HIGH && thrashing > thrashing_limit) {
2472         /* Page cache is thrashing while memory is low */
2473         kill_reason = LOW_MEM_AND_THRASHING;
2474         snprintf(kill_desc, sizeof(kill_desc), "%s watermark is breached and thrashing (%"
2475             PRId64 "%%)", wmark > WMARK_LOW ? "min" : "low", thrashing);
2476         cut_thrashing_limit = true;
2477         /* Do not kill perceptible apps because of thrashing */
2478         min_score_adj = PERCEPTIBLE_APP_ADJ + 1;
2479     } else if (reclaim == DIRECT_RECLAIM && thrashing > thrashing_limit) {
2480         /* Page cache is thrashing while in direct reclaim (mostly happens on lowram devices) */
2481         kill_reason = DIRECT_RECL_AND_THRASHING;
2482         snprintf(kill_desc, sizeof(kill_desc), "device is in direct reclaim and thrashing (%"
2483             PRId64 "%%)", thrashing);
2484         cut_thrashing_limit = true;
2485         /* Do not kill perceptible apps because of thrashing */
2486         min_score_adj = PERCEPTIBLE_APP_ADJ + 1;
2487     }
2488 
2489     /* Kill a process if necessary */
2490     if (kill_reason != NONE) {
2491         int pages_freed = find_and_kill_process(min_score_adj, kill_reason, kill_desc, &mi,
2492                                                 &wi, &curr_tm);
2493         if (pages_freed > 0) {
2494             killing = true;
2495             if (cut_thrashing_limit) {
2496                 /*
2497                  * Cut thrasing limit by thrashing_limit_decay_pct percentage of the current
2498                  * thrashing limit until the system stops thrashing.
2499                  */
2500                 thrashing_limit = (thrashing_limit * (100 - thrashing_limit_decay_pct)) / 100;
2501             }
2502         }
2503     }
2504 
2505 no_kill:
2506     /* Do not poll if kernel supports pidfd waiting */
2507     if (is_waiting_for_kill()) {
2508         /* Pause polling if we are waiting for process death notification */
2509         poll_params->update = POLLING_PAUSE;
2510         return;
2511     }
2512 
2513     /*
2514      * Start polling after initial PSI event;
2515      * extend polling while device is in direct reclaim or process is being killed;
2516      * do not extend when kswapd reclaims because that might go on for a long time
2517      * without causing memory pressure
2518      */
2519     if (events || killing || reclaim == DIRECT_RECLAIM) {
2520         poll_params->update = POLLING_START;
2521     }
2522 
2523     /* Decide the polling interval */
2524     if (swap_is_low || killing) {
2525         /* Fast polling during and after a kill or when swap is low */
2526         poll_params->polling_interval_ms = PSI_POLL_PERIOD_SHORT_MS;
2527     } else {
2528         /* By default use long intervals */
2529         poll_params->polling_interval_ms = PSI_POLL_PERIOD_LONG_MS;
2530     }
2531 }
2532 
mp_event_common(int data,uint32_t events,struct polling_params * poll_params)2533 static void mp_event_common(int data, uint32_t events, struct polling_params *poll_params) {
2534     unsigned long long evcount;
2535     int64_t mem_usage, memsw_usage;
2536     int64_t mem_pressure;
2537     union meminfo mi;
2538     struct zoneinfo zi;
2539     struct timespec curr_tm;
2540     static unsigned long kill_skip_count = 0;
2541     enum vmpressure_level level = (enum vmpressure_level)data;
2542     long other_free = 0, other_file = 0;
2543     int min_score_adj;
2544     int minfree = 0;
2545     static struct reread_data mem_usage_file_data = {
2546         .filename = MEMCG_MEMORY_USAGE,
2547         .fd = -1,
2548     };
2549     static struct reread_data memsw_usage_file_data = {
2550         .filename = MEMCG_MEMORYSW_USAGE,
2551         .fd = -1,
2552     };
2553     static struct wakeup_info wi;
2554 
2555     if (debug_process_killing) {
2556         ALOGI("%s memory pressure event is triggered", level_name[level]);
2557     }
2558 
2559     if (!use_psi_monitors) {
2560         /*
2561          * Check all event counters from low to critical
2562          * and upgrade to the highest priority one. By reading
2563          * eventfd we also reset the event counters.
2564          */
2565         for (int lvl = VMPRESS_LEVEL_LOW; lvl < VMPRESS_LEVEL_COUNT; lvl++) {
2566             if (mpevfd[lvl] != -1 &&
2567                 TEMP_FAILURE_RETRY(read(mpevfd[lvl],
2568                                    &evcount, sizeof(evcount))) > 0 &&
2569                 evcount > 0 && lvl > level) {
2570                 level = static_cast<vmpressure_level>(lvl);
2571             }
2572         }
2573     }
2574 
2575     /* Start polling after initial PSI event */
2576     if (use_psi_monitors && events) {
2577         /* Override polling params only if current event is more critical */
2578         if (!poll_params->poll_handler || data > poll_params->poll_handler->data) {
2579             poll_params->polling_interval_ms = PSI_POLL_PERIOD_SHORT_MS;
2580             poll_params->update = POLLING_START;
2581         }
2582     }
2583 
2584     if (clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm) != 0) {
2585         ALOGE("Failed to get current time");
2586         return;
2587     }
2588 
2589     record_wakeup_time(&curr_tm, events ? Event : Polling, &wi);
2590 
2591     if (kill_timeout_ms &&
2592         get_time_diff_ms(&last_kill_tm, &curr_tm) < static_cast<long>(kill_timeout_ms)) {
2593         /*
2594          * If we're within the no-kill timeout, see if there's pending reclaim work
2595          * from the last killed process. If so, skip killing for now.
2596          */
2597         if (is_kill_pending()) {
2598             kill_skip_count++;
2599             wi.skipped_wakeups++;
2600             return;
2601         }
2602         /*
2603          * Process is dead, stop waiting. This has no effect if pidfds are supported and
2604          * death notification already caused waiting to stop.
2605          */
2606         stop_wait_for_proc_kill(true);
2607     } else {
2608         /*
2609          * Killing took longer than no-kill timeout. Stop waiting for the last process
2610          * to die because we are ready to kill again.
2611          */
2612         stop_wait_for_proc_kill(false);
2613     }
2614 
2615     if (kill_skip_count > 0) {
2616         ALOGI("%lu memory pressure events were skipped after a kill!",
2617               kill_skip_count);
2618         kill_skip_count = 0;
2619     }
2620 
2621     if (meminfo_parse(&mi) < 0 || zoneinfo_parse(&zi) < 0) {
2622         ALOGE("Failed to get free memory!");
2623         return;
2624     }
2625 
2626     if (use_minfree_levels) {
2627         int i;
2628 
2629         other_free = mi.field.nr_free_pages - zi.totalreserve_pages;
2630         if (mi.field.nr_file_pages > (mi.field.shmem + mi.field.unevictable + mi.field.swap_cached)) {
2631             other_file = (mi.field.nr_file_pages - mi.field.shmem -
2632                           mi.field.unevictable - mi.field.swap_cached);
2633         } else {
2634             other_file = 0;
2635         }
2636 
2637         min_score_adj = OOM_SCORE_ADJ_MAX + 1;
2638         for (i = 0; i < lowmem_targets_size; i++) {
2639             minfree = lowmem_minfree[i];
2640             if (other_free < minfree && other_file < minfree) {
2641                 min_score_adj = lowmem_adj[i];
2642                 break;
2643             }
2644         }
2645 
2646         if (min_score_adj == OOM_SCORE_ADJ_MAX + 1) {
2647             if (debug_process_killing) {
2648                 ALOGI("Ignore %s memory pressure event "
2649                       "(free memory=%ldkB, cache=%ldkB, limit=%ldkB)",
2650                       level_name[level], other_free * page_k, other_file * page_k,
2651                       (long)lowmem_minfree[lowmem_targets_size - 1] * page_k);
2652             }
2653             return;
2654         }
2655 
2656         goto do_kill;
2657     }
2658 
2659     if (level == VMPRESS_LEVEL_LOW) {
2660         record_low_pressure_levels(&mi);
2661     }
2662 
2663     if (level_oomadj[level] > OOM_SCORE_ADJ_MAX) {
2664         /* Do not monitor this pressure level */
2665         return;
2666     }
2667 
2668     if ((mem_usage = get_memory_usage(&mem_usage_file_data)) < 0) {
2669         goto do_kill;
2670     }
2671     if ((memsw_usage = get_memory_usage(&memsw_usage_file_data)) < 0) {
2672         goto do_kill;
2673     }
2674 
2675     // Calculate percent for swappinness.
2676     mem_pressure = (mem_usage * 100) / memsw_usage;
2677 
2678     if (enable_pressure_upgrade && level != VMPRESS_LEVEL_CRITICAL) {
2679         // We are swapping too much.
2680         if (mem_pressure < upgrade_pressure) {
2681             level = upgrade_level(level);
2682             if (debug_process_killing) {
2683                 ALOGI("Event upgraded to %s", level_name[level]);
2684             }
2685         }
2686     }
2687 
2688     // If we still have enough swap space available, check if we want to
2689     // ignore/downgrade pressure events.
2690     if (mi.field.free_swap >=
2691         mi.field.total_swap * swap_free_low_percentage / 100) {
2692         // If the pressure is larger than downgrade_pressure lmk will not
2693         // kill any process, since enough memory is available.
2694         if (mem_pressure > downgrade_pressure) {
2695             if (debug_process_killing) {
2696                 ALOGI("Ignore %s memory pressure", level_name[level]);
2697             }
2698             return;
2699         } else if (level == VMPRESS_LEVEL_CRITICAL && mem_pressure > upgrade_pressure) {
2700             if (debug_process_killing) {
2701                 ALOGI("Downgrade critical memory pressure");
2702             }
2703             // Downgrade event, since enough memory available.
2704             level = downgrade_level(level);
2705         }
2706     }
2707 
2708 do_kill:
2709     if (low_ram_device) {
2710         /* For Go devices kill only one task */
2711         if (find_and_kill_process(level_oomadj[level], -1, NULL, &mi, &wi, &curr_tm) == 0) {
2712             if (debug_process_killing) {
2713                 ALOGI("Nothing to kill");
2714             }
2715         }
2716     } else {
2717         int pages_freed;
2718         static struct timespec last_report_tm;
2719         static unsigned long report_skip_count = 0;
2720 
2721         if (!use_minfree_levels) {
2722             /* Free up enough memory to downgrate the memory pressure to low level */
2723             if (mi.field.nr_free_pages >= low_pressure_mem.max_nr_free_pages) {
2724                 if (debug_process_killing) {
2725                     ALOGI("Ignoring pressure since more memory is "
2726                         "available (%" PRId64 ") than watermark (%" PRId64 ")",
2727                         mi.field.nr_free_pages, low_pressure_mem.max_nr_free_pages);
2728                 }
2729                 return;
2730             }
2731             min_score_adj = level_oomadj[level];
2732         }
2733 
2734         pages_freed = find_and_kill_process(min_score_adj, -1, NULL, &mi, &wi, &curr_tm);
2735 
2736         if (pages_freed == 0) {
2737             /* Rate limit kill reports when nothing was reclaimed */
2738             if (get_time_diff_ms(&last_report_tm, &curr_tm) < FAIL_REPORT_RLIMIT_MS) {
2739                 report_skip_count++;
2740                 return;
2741             }
2742         }
2743 
2744         /* Log whenever we kill or when report rate limit allows */
2745         if (use_minfree_levels) {
2746             ALOGI("Reclaimed %ldkB, cache(%ldkB) and "
2747                 "free(%" PRId64 "kB)-reserved(%" PRId64 "kB) below min(%ldkB) for oom_adj %d",
2748                 pages_freed * page_k,
2749                 other_file * page_k, mi.field.nr_free_pages * page_k,
2750                 zi.totalreserve_pages * page_k,
2751                 minfree * page_k, min_score_adj);
2752         } else {
2753             ALOGI("Reclaimed %ldkB at oom_adj %d",
2754                 pages_freed * page_k, min_score_adj);
2755         }
2756 
2757         if (report_skip_count > 0) {
2758             ALOGI("Suppressed %lu failed kill reports", report_skip_count);
2759             report_skip_count = 0;
2760         }
2761 
2762         last_report_tm = curr_tm;
2763     }
2764     if (is_waiting_for_kill()) {
2765         /* pause polling if we are waiting for process death notification */
2766         poll_params->update = POLLING_PAUSE;
2767     }
2768 }
2769 
init_mp_psi(enum vmpressure_level level,bool use_new_strategy)2770 static bool init_mp_psi(enum vmpressure_level level, bool use_new_strategy) {
2771     int fd;
2772 
2773     /* Do not register a handler if threshold_ms is not set */
2774     if (!psi_thresholds[level].threshold_ms) {
2775         return true;
2776     }
2777 
2778     fd = init_psi_monitor(psi_thresholds[level].stall_type,
2779         psi_thresholds[level].threshold_ms * US_PER_MS,
2780         PSI_WINDOW_SIZE_MS * US_PER_MS);
2781 
2782     if (fd < 0) {
2783         return false;
2784     }
2785 
2786     vmpressure_hinfo[level].handler = use_new_strategy ? mp_event_psi : mp_event_common;
2787     vmpressure_hinfo[level].data = level;
2788     if (register_psi_monitor(epollfd, fd, &vmpressure_hinfo[level]) < 0) {
2789         destroy_psi_monitor(fd);
2790         return false;
2791     }
2792     maxevents++;
2793     mpevfd[level] = fd;
2794 
2795     return true;
2796 }
2797 
destroy_mp_psi(enum vmpressure_level level)2798 static void destroy_mp_psi(enum vmpressure_level level) {
2799     int fd = mpevfd[level];
2800 
2801     if (fd < 0) {
2802         return;
2803     }
2804 
2805     if (unregister_psi_monitor(epollfd, fd) < 0) {
2806         ALOGE("Failed to unregister psi monitor for %s memory pressure; errno=%d",
2807             level_name[level], errno);
2808     }
2809     maxevents--;
2810     destroy_psi_monitor(fd);
2811     mpevfd[level] = -1;
2812 }
2813 
init_psi_monitors()2814 static bool init_psi_monitors() {
2815     /*
2816      * When PSI is used on low-ram devices or on high-end devices without memfree levels
2817      * use new kill strategy based on zone watermarks, free swap and thrashing stats
2818      */
2819     bool use_new_strategy =
2820         property_get_bool("ro.lmk.use_new_strategy", low_ram_device || !use_minfree_levels);
2821 
2822     /* In default PSI mode override stall amounts using system properties */
2823     if (use_new_strategy) {
2824         /* Do not use low pressure level */
2825         psi_thresholds[VMPRESS_LEVEL_LOW].threshold_ms = 0;
2826         psi_thresholds[VMPRESS_LEVEL_MEDIUM].threshold_ms = psi_partial_stall_ms;
2827         psi_thresholds[VMPRESS_LEVEL_CRITICAL].threshold_ms = psi_complete_stall_ms;
2828     }
2829 
2830     if (!init_mp_psi(VMPRESS_LEVEL_LOW, use_new_strategy)) {
2831         return false;
2832     }
2833     if (!init_mp_psi(VMPRESS_LEVEL_MEDIUM, use_new_strategy)) {
2834         destroy_mp_psi(VMPRESS_LEVEL_LOW);
2835         return false;
2836     }
2837     if (!init_mp_psi(VMPRESS_LEVEL_CRITICAL, use_new_strategy)) {
2838         destroy_mp_psi(VMPRESS_LEVEL_MEDIUM);
2839         destroy_mp_psi(VMPRESS_LEVEL_LOW);
2840         return false;
2841     }
2842     return true;
2843 }
2844 
init_mp_common(enum vmpressure_level level)2845 static bool init_mp_common(enum vmpressure_level level) {
2846     int mpfd;
2847     int evfd;
2848     int evctlfd;
2849     char buf[256];
2850     struct epoll_event epev;
2851     int ret;
2852     int level_idx = (int)level;
2853     const char *levelstr = level_name[level_idx];
2854 
2855     /* gid containing AID_SYSTEM required */
2856     mpfd = open(MEMCG_SYSFS_PATH "memory.pressure_level", O_RDONLY | O_CLOEXEC);
2857     if (mpfd < 0) {
2858         ALOGI("No kernel memory.pressure_level support (errno=%d)", errno);
2859         goto err_open_mpfd;
2860     }
2861 
2862     evctlfd = open(MEMCG_SYSFS_PATH "cgroup.event_control", O_WRONLY | O_CLOEXEC);
2863     if (evctlfd < 0) {
2864         ALOGI("No kernel memory cgroup event control (errno=%d)", errno);
2865         goto err_open_evctlfd;
2866     }
2867 
2868     evfd = eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC);
2869     if (evfd < 0) {
2870         ALOGE("eventfd failed for level %s; errno=%d", levelstr, errno);
2871         goto err_eventfd;
2872     }
2873 
2874     ret = snprintf(buf, sizeof(buf), "%d %d %s", evfd, mpfd, levelstr);
2875     if (ret >= (ssize_t)sizeof(buf)) {
2876         ALOGE("cgroup.event_control line overflow for level %s", levelstr);
2877         goto err;
2878     }
2879 
2880     ret = TEMP_FAILURE_RETRY(write(evctlfd, buf, strlen(buf) + 1));
2881     if (ret == -1) {
2882         ALOGE("cgroup.event_control write failed for level %s; errno=%d",
2883               levelstr, errno);
2884         goto err;
2885     }
2886 
2887     epev.events = EPOLLIN;
2888     /* use data to store event level */
2889     vmpressure_hinfo[level_idx].data = level_idx;
2890     vmpressure_hinfo[level_idx].handler = mp_event_common;
2891     epev.data.ptr = (void *)&vmpressure_hinfo[level_idx];
2892     ret = epoll_ctl(epollfd, EPOLL_CTL_ADD, evfd, &epev);
2893     if (ret == -1) {
2894         ALOGE("epoll_ctl for level %s failed; errno=%d", levelstr, errno);
2895         goto err;
2896     }
2897     maxevents++;
2898     mpevfd[level] = evfd;
2899     close(evctlfd);
2900     return true;
2901 
2902 err:
2903     close(evfd);
2904 err_eventfd:
2905     close(evctlfd);
2906 err_open_evctlfd:
2907     close(mpfd);
2908 err_open_mpfd:
2909     return false;
2910 }
2911 
destroy_mp_common(enum vmpressure_level level)2912 static void destroy_mp_common(enum vmpressure_level level) {
2913     struct epoll_event epev;
2914     int fd = mpevfd[level];
2915 
2916     if (fd < 0) {
2917         return;
2918     }
2919 
2920     if (epoll_ctl(epollfd, EPOLL_CTL_DEL, fd, &epev)) {
2921         // Log an error and keep going
2922         ALOGE("epoll_ctl for level %s failed; errno=%d", level_name[level], errno);
2923     }
2924     maxevents--;
2925     close(fd);
2926     mpevfd[level] = -1;
2927 }
2928 
kernel_event_handler(int data __unused,uint32_t events __unused,struct polling_params * poll_params __unused)2929 static void kernel_event_handler(int data __unused, uint32_t events __unused,
2930                                  struct polling_params *poll_params __unused) {
2931     poll_kernel(kpoll_fd);
2932 }
2933 
init_monitors()2934 static bool init_monitors() {
2935     /* Try to use psi monitor first if kernel has it */
2936     use_psi_monitors = property_get_bool("ro.lmk.use_psi", true) &&
2937         init_psi_monitors();
2938     /* Fall back to vmpressure */
2939     if (!use_psi_monitors &&
2940         (!init_mp_common(VMPRESS_LEVEL_LOW) ||
2941         !init_mp_common(VMPRESS_LEVEL_MEDIUM) ||
2942         !init_mp_common(VMPRESS_LEVEL_CRITICAL))) {
2943         ALOGE("Kernel does not support memory pressure events or in-kernel low memory killer");
2944         return false;
2945     }
2946     if (use_psi_monitors) {
2947         ALOGI("Using psi monitors for memory pressure detection");
2948     } else {
2949         ALOGI("Using vmpressure for memory pressure detection");
2950     }
2951     return true;
2952 }
2953 
destroy_monitors()2954 static void destroy_monitors() {
2955     if (use_psi_monitors) {
2956         destroy_mp_psi(VMPRESS_LEVEL_CRITICAL);
2957         destroy_mp_psi(VMPRESS_LEVEL_MEDIUM);
2958         destroy_mp_psi(VMPRESS_LEVEL_LOW);
2959     } else {
2960         destroy_mp_common(VMPRESS_LEVEL_CRITICAL);
2961         destroy_mp_common(VMPRESS_LEVEL_MEDIUM);
2962         destroy_mp_common(VMPRESS_LEVEL_LOW);
2963     }
2964 }
2965 
init(void)2966 static int init(void) {
2967     static struct event_handler_info kernel_poll_hinfo = { 0, kernel_event_handler };
2968     struct reread_data file_data = {
2969         .filename = ZONEINFO_PATH,
2970         .fd = -1,
2971     };
2972     struct epoll_event epev;
2973     int pidfd;
2974     int i;
2975     int ret;
2976 
2977     page_k = sysconf(_SC_PAGESIZE);
2978     if (page_k == -1)
2979         page_k = PAGE_SIZE;
2980     page_k /= 1024;
2981 
2982     epollfd = epoll_create(MAX_EPOLL_EVENTS);
2983     if (epollfd == -1) {
2984         ALOGE("epoll_create failed (errno=%d)", errno);
2985         return -1;
2986     }
2987 
2988     // mark data connections as not connected
2989     for (int i = 0; i < MAX_DATA_CONN; i++) {
2990         data_sock[i].sock = -1;
2991     }
2992 
2993     ctrl_sock.sock = android_get_control_socket("lmkd");
2994     if (ctrl_sock.sock < 0) {
2995         ALOGE("get lmkd control socket failed");
2996         return -1;
2997     }
2998 
2999     ret = listen(ctrl_sock.sock, MAX_DATA_CONN);
3000     if (ret < 0) {
3001         ALOGE("lmkd control socket listen failed (errno=%d)", errno);
3002         return -1;
3003     }
3004 
3005     epev.events = EPOLLIN;
3006     ctrl_sock.handler_info.handler = ctrl_connect_handler;
3007     epev.data.ptr = (void *)&(ctrl_sock.handler_info);
3008     if (epoll_ctl(epollfd, EPOLL_CTL_ADD, ctrl_sock.sock, &epev) == -1) {
3009         ALOGE("epoll_ctl for lmkd control socket failed (errno=%d)", errno);
3010         return -1;
3011     }
3012     maxevents++;
3013 
3014     has_inkernel_module = !access(INKERNEL_MINFREE_PATH, W_OK);
3015     use_inkernel_interface = has_inkernel_module;
3016 
3017     if (use_inkernel_interface) {
3018         ALOGI("Using in-kernel low memory killer interface");
3019         if (init_poll_kernel()) {
3020             epev.events = EPOLLIN;
3021             epev.data.ptr = (void*)&kernel_poll_hinfo;
3022             if (epoll_ctl(epollfd, EPOLL_CTL_ADD, kpoll_fd, &epev) != 0) {
3023                 ALOGE("epoll_ctl for lmk events failed (errno=%d)", errno);
3024                 close(kpoll_fd);
3025                 kpoll_fd = -1;
3026             } else {
3027                 maxevents++;
3028                 /* let the others know it does support reporting kills */
3029                 property_set("sys.lmk.reportkills", "1");
3030             }
3031         }
3032     } else {
3033         if (!init_monitors()) {
3034             return -1;
3035         }
3036         /* let the others know it does support reporting kills */
3037         property_set("sys.lmk.reportkills", "1");
3038     }
3039 
3040     for (i = 0; i <= ADJTOSLOT(OOM_SCORE_ADJ_MAX); i++) {
3041         procadjslot_list[i].next = &procadjslot_list[i];
3042         procadjslot_list[i].prev = &procadjslot_list[i];
3043     }
3044 
3045     memset(killcnt_idx, KILLCNT_INVALID_IDX, sizeof(killcnt_idx));
3046 
3047     /*
3048      * Read zoneinfo as the biggest file we read to create and size the initial
3049      * read buffer and avoid memory re-allocations during memory pressure
3050      */
3051     if (reread_file(&file_data) == NULL) {
3052         ALOGE("Failed to read %s: %s", file_data.filename, strerror(errno));
3053     }
3054 
3055     /* check if kernel supports pidfd_open syscall */
3056     pidfd = TEMP_FAILURE_RETRY(sys_pidfd_open(getpid(), 0));
3057     if (pidfd < 0) {
3058         pidfd_supported = (errno != ENOSYS);
3059     } else {
3060         pidfd_supported = true;
3061         close(pidfd);
3062     }
3063     ALOGI("Process polling is %s", pidfd_supported ? "supported" : "not supported" );
3064 
3065     return 0;
3066 }
3067 
polling_paused(struct polling_params * poll_params)3068 static bool polling_paused(struct polling_params *poll_params) {
3069     return poll_params->paused_handler != NULL;
3070 }
3071 
resume_polling(struct polling_params * poll_params,struct timespec curr_tm)3072 static void resume_polling(struct polling_params *poll_params, struct timespec curr_tm) {
3073     poll_params->poll_start_tm = curr_tm;
3074     poll_params->poll_handler = poll_params->paused_handler;
3075 }
3076 
call_handler(struct event_handler_info * handler_info,struct polling_params * poll_params,uint32_t events)3077 static void call_handler(struct event_handler_info* handler_info,
3078                          struct polling_params *poll_params, uint32_t events) {
3079     struct timespec curr_tm;
3080 
3081     poll_params->update = POLLING_DO_NOT_CHANGE;
3082     handler_info->handler(handler_info->data, events, poll_params);
3083     clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm);
3084     if (poll_params->poll_handler == handler_info) {
3085         poll_params->last_poll_tm = curr_tm;
3086     }
3087 
3088     switch (poll_params->update) {
3089     case POLLING_START:
3090         /*
3091          * Poll for the duration of PSI_WINDOW_SIZE_MS after the
3092          * initial PSI event because psi events are rate-limited
3093          * at one per sec.
3094          */
3095         poll_params->poll_start_tm = curr_tm;
3096         poll_params->poll_handler = handler_info;
3097         break;
3098     case POLLING_PAUSE:
3099         poll_params->paused_handler = handler_info;
3100         poll_params->poll_handler = NULL;
3101         break;
3102     case POLLING_RESUME:
3103         resume_polling(poll_params, curr_tm);
3104         break;
3105     case POLLING_DO_NOT_CHANGE:
3106         if (get_time_diff_ms(&poll_params->poll_start_tm, &curr_tm) > PSI_WINDOW_SIZE_MS) {
3107             /* Polled for the duration of PSI window, time to stop */
3108             poll_params->poll_handler = NULL;
3109             poll_params->paused_handler = NULL;
3110         }
3111         break;
3112     }
3113 }
3114 
mainloop(void)3115 static void mainloop(void) {
3116     struct event_handler_info* handler_info;
3117     struct polling_params poll_params;
3118     struct timespec curr_tm;
3119     struct epoll_event *evt;
3120     long delay = -1;
3121 
3122     poll_params.poll_handler = NULL;
3123     poll_params.paused_handler = NULL;
3124 
3125     while (1) {
3126         struct epoll_event events[MAX_EPOLL_EVENTS];
3127         int nevents;
3128         int i;
3129 
3130         if (poll_params.poll_handler) {
3131             bool poll_now;
3132 
3133             clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm);
3134             if (poll_params.poll_handler == poll_params.paused_handler) {
3135                 /*
3136                  * Just transitioned into POLLING_RESUME. Reset paused_handler
3137                  * and poll immediately
3138                  */
3139                 poll_params.paused_handler = NULL;
3140                 poll_now = true;
3141                 nevents = 0;
3142             } else {
3143                 /* Calculate next timeout */
3144                 delay = get_time_diff_ms(&poll_params.last_poll_tm, &curr_tm);
3145                 delay = (delay < poll_params.polling_interval_ms) ?
3146                     poll_params.polling_interval_ms - delay : poll_params.polling_interval_ms;
3147 
3148                 /* Wait for events until the next polling timeout */
3149                 nevents = epoll_wait(epollfd, events, maxevents, delay);
3150 
3151                 /* Update current time after wait */
3152                 clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm);
3153                 poll_now = (get_time_diff_ms(&poll_params.last_poll_tm, &curr_tm) >=
3154                     poll_params.polling_interval_ms);
3155             }
3156             if (poll_now) {
3157                 call_handler(poll_params.poll_handler, &poll_params, 0);
3158             }
3159         } else {
3160             if (kill_timeout_ms && is_waiting_for_kill()) {
3161                 clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm);
3162                 delay = kill_timeout_ms - get_time_diff_ms(&last_kill_tm, &curr_tm);
3163                 /* Wait for pidfds notification or kill timeout to expire */
3164                 nevents = (delay > 0) ? epoll_wait(epollfd, events, maxevents, delay) : 0;
3165                 if (nevents == 0) {
3166                     /* Kill notification timed out */
3167                     stop_wait_for_proc_kill(false);
3168                     if (polling_paused(&poll_params)) {
3169                         clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm);
3170                         resume_polling(&poll_params, curr_tm);
3171                     }
3172                 }
3173             } else {
3174                 /* Wait for events with no timeout */
3175                 nevents = epoll_wait(epollfd, events, maxevents, -1);
3176             }
3177         }
3178 
3179         if (nevents == -1) {
3180             if (errno == EINTR)
3181                 continue;
3182             ALOGE("epoll_wait failed (errno=%d)", errno);
3183             continue;
3184         }
3185 
3186         /*
3187          * First pass to see if any data socket connections were dropped.
3188          * Dropped connection should be handled before any other events
3189          * to deallocate data connection and correctly handle cases when
3190          * connection gets dropped and reestablished in the same epoll cycle.
3191          * In such cases it's essential to handle connection closures first.
3192          */
3193         for (i = 0, evt = &events[0]; i < nevents; ++i, evt++) {
3194             if ((evt->events & EPOLLHUP) && evt->data.ptr) {
3195                 ALOGI("lmkd data connection dropped");
3196                 handler_info = (struct event_handler_info*)evt->data.ptr;
3197                 ctrl_data_close(handler_info->data);
3198             }
3199         }
3200 
3201         /* Second pass to handle all other events */
3202         for (i = 0, evt = &events[0]; i < nevents; ++i, evt++) {
3203             if (evt->events & EPOLLERR) {
3204                 ALOGD("EPOLLERR on event #%d", i);
3205             }
3206             if (evt->events & EPOLLHUP) {
3207                 /* This case was handled in the first pass */
3208                 continue;
3209             }
3210             if (evt->data.ptr) {
3211                 handler_info = (struct event_handler_info*)evt->data.ptr;
3212                 call_handler(handler_info, &poll_params, evt->events);
3213             }
3214         }
3215     }
3216 }
3217 
issue_reinit()3218 int issue_reinit() {
3219     int sock;
3220 
3221     sock = lmkd_connect();
3222     if (sock < 0) {
3223         ALOGE("failed to connect to lmkd: %s", strerror(errno));
3224         return -1;
3225     }
3226 
3227     enum update_props_result res = lmkd_update_props(sock);
3228     switch (res) {
3229     case UPDATE_PROPS_SUCCESS:
3230         ALOGI("lmkd updated properties successfully");
3231         break;
3232     case UPDATE_PROPS_SEND_ERR:
3233         ALOGE("failed to send lmkd request: %s", strerror(errno));
3234         break;
3235     case UPDATE_PROPS_RECV_ERR:
3236         ALOGE("failed to receive lmkd reply: %s", strerror(errno));
3237         break;
3238     case UPDATE_PROPS_FORMAT_ERR:
3239         ALOGE("lmkd reply is invalid");
3240         break;
3241     case UPDATE_PROPS_FAIL:
3242         ALOGE("lmkd failed to update its properties");
3243         break;
3244     }
3245 
3246     close(sock);
3247     return res == UPDATE_PROPS_SUCCESS ? 0 : -1;
3248 }
3249 
update_props()3250 static void update_props() {
3251     /* By default disable low level vmpressure events */
3252     level_oomadj[VMPRESS_LEVEL_LOW] =
3253         property_get_int32("ro.lmk.low", OOM_SCORE_ADJ_MAX + 1);
3254     level_oomadj[VMPRESS_LEVEL_MEDIUM] =
3255         property_get_int32("ro.lmk.medium", 800);
3256     level_oomadj[VMPRESS_LEVEL_CRITICAL] =
3257         property_get_int32("ro.lmk.critical", 0);
3258     debug_process_killing = property_get_bool("ro.lmk.debug", false);
3259 
3260     /* By default disable upgrade/downgrade logic */
3261     enable_pressure_upgrade =
3262         property_get_bool("ro.lmk.critical_upgrade", false);
3263     upgrade_pressure =
3264         (int64_t)property_get_int32("ro.lmk.upgrade_pressure", 100);
3265     downgrade_pressure =
3266         (int64_t)property_get_int32("ro.lmk.downgrade_pressure", 100);
3267     kill_heaviest_task =
3268         property_get_bool("ro.lmk.kill_heaviest_task", false);
3269     low_ram_device = property_get_bool("ro.config.low_ram", false);
3270     kill_timeout_ms =
3271         (unsigned long)property_get_int32("ro.lmk.kill_timeout_ms", 100);
3272     use_minfree_levels =
3273         property_get_bool("ro.lmk.use_minfree_levels", false);
3274     per_app_memcg =
3275         property_get_bool("ro.config.per_app_memcg", low_ram_device);
3276     swap_free_low_percentage = clamp(0, 100, property_get_int32("ro.lmk.swap_free_low_percentage",
3277         DEF_LOW_SWAP));
3278     psi_partial_stall_ms = property_get_int32("ro.lmk.psi_partial_stall_ms",
3279         low_ram_device ? DEF_PARTIAL_STALL_LOWRAM : DEF_PARTIAL_STALL);
3280     psi_complete_stall_ms = property_get_int32("ro.lmk.psi_complete_stall_ms",
3281         DEF_COMPLETE_STALL);
3282     thrashing_limit_pct = max(0, property_get_int32("ro.lmk.thrashing_limit",
3283         low_ram_device ? DEF_THRASHING_LOWRAM : DEF_THRASHING));
3284     thrashing_limit_decay_pct = clamp(0, 100, property_get_int32("ro.lmk.thrashing_limit_decay",
3285         low_ram_device ? DEF_THRASHING_DECAY_LOWRAM : DEF_THRASHING_DECAY));
3286     swap_util_max = clamp(0, 100, property_get_int32("ro.lmk.swap_util_max", 100));
3287 }
3288 
main(int argc,char ** argv)3289 int main(int argc, char **argv) {
3290     if ((argc > 1) && argv[1] && !strcmp(argv[1], "--reinit")) {
3291         if (property_set(LMKD_REINIT_PROP, "0")) {
3292             ALOGE("Failed to reset " LMKD_REINIT_PROP " property");
3293         }
3294         return issue_reinit();
3295     }
3296 
3297     update_props();
3298 
3299     ctx = create_android_logger(KILLINFO_LOG_TAG);
3300 
3301     if (!init()) {
3302         if (!use_inkernel_interface) {
3303             /*
3304              * MCL_ONFAULT pins pages as they fault instead of loading
3305              * everything immediately all at once. (Which would be bad,
3306              * because as of this writing, we have a lot of mapped pages we
3307              * never use.) Old kernels will see MCL_ONFAULT and fail with
3308              * EINVAL; we ignore this failure.
3309              *
3310              * N.B. read the man page for mlockall. MCL_CURRENT | MCL_ONFAULT
3311              * pins ⊆ MCL_CURRENT, converging to just MCL_CURRENT as we fault
3312              * in pages.
3313              */
3314             /* CAP_IPC_LOCK required */
3315             if (mlockall(MCL_CURRENT | MCL_FUTURE | MCL_ONFAULT) && (errno != EINVAL)) {
3316                 ALOGW("mlockall failed %s", strerror(errno));
3317             }
3318 
3319             /* CAP_NICE required */
3320             struct sched_param param = {
3321                     .sched_priority = 1,
3322             };
3323             if (sched_setscheduler(0, SCHED_FIFO, &param)) {
3324                 ALOGW("set SCHED_FIFO failed %s", strerror(errno));
3325             }
3326         }
3327 
3328         mainloop();
3329     }
3330 
3331     android_log_destroy(&ctx);
3332 
3333     ALOGI("exiting");
3334     return 0;
3335 }
3336