blob: f3c301e6956f12aebe6fe801e831fe73da85a5d1 [file] [log] [blame]
Todd Poynorc58c5142013-07-09 19:35:14 -07001/*
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
Wei Wangf1ee2e12018-11-21 00:11:44 -080019#include <dirent.h>
Todd Poynorc58c5142013-07-09 19:35:14 -070020#include <errno.h>
Robert Beneac72b2932017-08-21 15:18:31 -070021#include <inttypes.h>
Suren Baghdasaryanbb7747b2018-03-20 16:03:29 -070022#include <pwd.h>
Mark Salyzyna1f5b862016-10-17 14:28:00 -070023#include <sched.h>
Todd Poynorc58c5142013-07-09 19:35:14 -070024#include <signal.h>
Suren Baghdasaryanf584fff2018-03-20 13:53:17 -070025#include <stdbool.h>
Todd Poynorc58c5142013-07-09 19:35:14 -070026#include <stdlib.h>
27#include <string.h>
Mark Salyzyneb062742014-04-30 13:36:35 -070028#include <sys/cdefs.h>
Todd Poynorc58c5142013-07-09 19:35:14 -070029#include <sys/epoll.h>
30#include <sys/eventfd.h>
Colin Crossc4059002014-07-11 17:15:44 -070031#include <sys/mman.h>
Josh Gao84623be2021-03-18 17:16:08 -070032#include <sys/pidfd.h>
Wei Wangf1ee2e12018-11-21 00:11:44 -080033#include <sys/resource.h>
Todd Poynorc58c5142013-07-09 19:35:14 -070034#include <sys/socket.h>
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -070035#include <sys/syscall.h>
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -080036#include <sys/sysinfo.h>
Wei Wangf1ee2e12018-11-21 00:11:44 -080037#include <sys/time.h>
Mark Salyzyn5cc80b32018-03-21 12:24:58 -070038#include <sys/types.h>
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -070039#include <time.h>
Mark Salyzyneb062742014-04-30 13:36:35 -070040#include <unistd.h>
41
Robert Benea57397dc2017-07-31 17:15:20 -070042#include <cutils/properties.h>
Wei Wangf1ee2e12018-11-21 00:11:44 -080043#include <cutils/sched_policy.h>
Todd Poynorc58c5142013-07-09 19:35:14 -070044#include <cutils/sockets.h>
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -070045#include <liblmkd_utils.h>
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -080046#include <lmkd.h>
Mark Salyzyn6a63fde2017-01-10 13:19:54 -080047#include <log/log.h>
Suren Baghdasaryan08bfa982018-07-26 16:34:27 -070048#include <log/log_event_list.h>
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -070049#include <log/log_time.h>
Suren Baghdasaryan945658a2019-10-18 11:16:52 -070050#include <private/android_filesystem_config.h>
Suren Baghdasaryan55e31502019-01-08 12:54:48 -080051#include <psi/psi.h>
Wei Wangf1ee2e12018-11-21 00:11:44 -080052#include <system/thread_defs.h>
Mark Salyzyneb062742014-04-30 13:36:35 -070053
Yao Chen337606c2018-05-02 11:19:27 -070054#include "statslog.h"
Rajeev Kumar4aba9152018-01-31 17:54:56 -080055
Suren Baghdasaryan940e7cf2021-05-27 18:15:44 -070056#define BPF_FD_JUST_USE_INT
57#include "BpfSyscallWrappers.h"
58
Suren Baghdasaryan03e19872018-01-04 10:43:58 -080059/*
60 * Define LMKD_TRACE_KILLS to record lmkd kills in kernel traces
61 * to profile and correlate with OOM kills
62 */
63#ifdef LMKD_TRACE_KILLS
64
65#define ATRACE_TAG ATRACE_TAG_ALWAYS
66#include <cutils/trace.h>
67
68#define TRACE_KILL_START(pid) ATRACE_INT(__FUNCTION__, pid);
69#define TRACE_KILL_END() ATRACE_INT(__FUNCTION__, 0);
70
71#else /* LMKD_TRACE_KILLS */
72
Daniel Colascione56b95d72018-02-12 11:24:47 -080073#define TRACE_KILL_START(pid) ((void)(pid))
74#define TRACE_KILL_END() ((void)0)
Suren Baghdasaryan03e19872018-01-04 10:43:58 -080075
76#endif /* LMKD_TRACE_KILLS */
77
Mark Salyzyneb062742014-04-30 13:36:35 -070078#ifndef __unused
79#define __unused __attribute__((__unused__))
80#endif
Todd Poynorc58c5142013-07-09 19:35:14 -070081
82#define MEMCG_SYSFS_PATH "/dev/memcg/"
Robert Beneac72b2932017-08-21 15:18:31 -070083#define MEMCG_MEMORY_USAGE "/dev/memcg/memory.usage_in_bytes"
84#define MEMCG_MEMORYSW_USAGE "/dev/memcg/memory.memsw.usage_in_bytes"
Suren Baghdasaryand28a9732018-04-13 13:11:51 -070085#define ZONEINFO_PATH "/proc/zoneinfo"
86#define MEMINFO_PATH "/proc/meminfo"
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -070087#define VMSTAT_PATH "/proc/vmstat"
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -070088#define PROC_STATUS_TGID_FIELD "Tgid:"
Ioannis Ilkos279268a2020-08-01 10:50:40 +010089#define PROC_STATUS_RSS_FIELD "VmRSS:"
90#define PROC_STATUS_SWAP_FIELD "VmSwap:"
Todd Poynorc58c5142013-07-09 19:35:14 -070091#define LINE_MAX 128
92
Suren Baghdasaryan970a26a2019-09-19 15:27:21 -070093#define PERCEPTIBLE_APP_ADJ 200
94
Suren Baghdasaryan08bfa982018-07-26 16:34:27 -070095/* Android Logger event logtags (see event.logtags) */
Suren Baghdasaryan12cacae2019-09-16 12:06:30 -070096#define KILLINFO_LOG_TAG 10195355
Suren Baghdasaryan08bfa982018-07-26 16:34:27 -070097
Mark Salyzyna00ccd82018-04-09 09:50:32 -070098/* gid containing AID_SYSTEM required */
Todd Poynorc58c5142013-07-09 19:35:14 -070099#define INKERNEL_MINFREE_PATH "/sys/module/lowmemorykiller/parameters/minfree"
100#define INKERNEL_ADJ_PATH "/sys/module/lowmemorykiller/parameters/adj"
101
102#define ARRAY_SIZE(x) (sizeof(x) / sizeof(*(x)))
Robert Benea58d6a132017-06-01 16:32:31 -0700103#define EIGHT_MEGA (1 << 23)
Todd Poynorc58c5142013-07-09 19:35:14 -0700104
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -0700105#define TARGET_UPDATE_MIN_INTERVAL_MS 1000
Martin Liu1f72f5f2020-08-21 13:18:50 +0800106#define THRASHING_RESET_INTERVAL_MS 1000
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -0700107
108#define NS_PER_MS (NS_PER_SEC / MS_PER_SEC)
Suren Baghdasaryan55e31502019-01-08 12:54:48 -0800109#define US_PER_MS (US_PER_SEC / MS_PER_SEC)
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -0700110
Suren Baghdasaryanbb7747b2018-03-20 16:03:29 -0700111/* Defined as ProcessList.SYSTEM_ADJ in ProcessList.java */
112#define SYSTEM_ADJ (-900)
113
Greg Kaiserf5b1d142018-03-23 14:16:12 -0700114#define STRINGIFY(x) STRINGIFY_INTERNAL(x)
115#define STRINGIFY_INTERNAL(x) #x
116
Suren Baghdasaryan55e31502019-01-08 12:54:48 -0800117/*
118 * PSI monitor tracking window size.
119 * PSI monitor generates events at most once per window,
120 * therefore we poll memory state for the duration of
121 * PSI_WINDOW_SIZE_MS after the event happens.
122 */
123#define PSI_WINDOW_SIZE_MS 1000
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -0700124/* Polling period after PSI signal when pressure is high */
125#define PSI_POLL_PERIOD_SHORT_MS 10
126/* Polling period after PSI signal when pressure is low */
127#define PSI_POLL_PERIOD_LONG_MS 100
Suren Baghdasaryan55e31502019-01-08 12:54:48 -0800128
Suren Baghdasaryan08bfa982018-07-26 16:34:27 -0700129#define min(a, b) (((a) < (b)) ? (a) : (b))
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -0700130#define max(a, b) (((a) > (b)) ? (a) : (b))
Suren Baghdasaryan08bfa982018-07-26 16:34:27 -0700131
Suren Baghdasaryan53be36e2018-09-05 15:46:32 -0700132#define FAIL_REPORT_RLIMIT_MS 1000
133
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -0700134/*
135 * System property defaults
136 */
137/* ro.lmk.swap_free_low_percentage property defaults */
Suren Baghdasaryanfb1f5922020-05-19 13:07:23 -0700138#define DEF_LOW_SWAP 10
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -0700139/* ro.lmk.thrashing_limit property defaults */
140#define DEF_THRASHING_LOWRAM 30
141#define DEF_THRASHING 100
142/* ro.lmk.thrashing_limit_decay property defaults */
143#define DEF_THRASHING_DECAY_LOWRAM 50
144#define DEF_THRASHING_DECAY 10
Suren Baghdasaryan2f88e152019-07-15 15:42:09 -0700145/* ro.lmk.psi_partial_stall_ms property defaults */
146#define DEF_PARTIAL_STALL_LOWRAM 200
147#define DEF_PARTIAL_STALL 70
148/* ro.lmk.psi_complete_stall_ms property defaults */
149#define DEF_COMPLETE_STALL 700
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -0700150
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -0700151#define LMKD_REINIT_PROP "lmkd.reinit"
152
Todd Poynorc58c5142013-07-09 19:35:14 -0700153/* default to old in-kernel interface if no memory pressure events */
Mark Salyzyn5cc80b32018-03-21 12:24:58 -0700154static bool use_inkernel_interface = true;
Robert Benea7878c9b2017-09-11 16:53:28 -0700155static bool has_inkernel_module;
Todd Poynorc58c5142013-07-09 19:35:14 -0700156
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -0800157/* memory pressure levels */
158enum vmpressure_level {
159 VMPRESS_LEVEL_LOW = 0,
160 VMPRESS_LEVEL_MEDIUM,
161 VMPRESS_LEVEL_CRITICAL,
162 VMPRESS_LEVEL_COUNT
163};
Todd Poynorc58c5142013-07-09 19:35:14 -0700164
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -0800165static const char *level_name[] = {
166 "low",
167 "medium",
168 "critical"
169};
170
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -0800171struct {
Suren Baghdasaryane0f3dd12018-04-13 13:41:12 -0700172 int64_t min_nr_free_pages; /* recorded but not used yet */
173 int64_t max_nr_free_pages;
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -0800174} low_pressure_mem = { -1, -1 };
175
Suren Baghdasaryan55e31502019-01-08 12:54:48 -0800176struct psi_threshold {
177 enum psi_stall_type stall_type;
178 int threshold_ms;
179};
180
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -0800181static int level_oomadj[VMPRESS_LEVEL_COUNT];
Suren Baghdasaryan3e1a8492018-01-04 09:16:21 -0800182static int mpevfd[VMPRESS_LEVEL_COUNT] = { -1, -1, -1 };
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -0700183static bool pidfd_supported;
184static int last_kill_pid_or_fd = -1;
185static struct timespec last_kill_tm;
186
187/* lmkd configurable parameters */
Robert Beneac72b2932017-08-21 15:18:31 -0700188static bool debug_process_killing;
189static bool enable_pressure_upgrade;
190static int64_t upgrade_pressure;
Robert Benea3be16142017-09-13 15:20:30 -0700191static int64_t downgrade_pressure;
Suren Baghdasaryand1d59f82018-04-13 11:45:38 -0700192static bool low_ram_device;
Suren Baghdasaryaneb7c5492017-12-08 13:17:06 -0800193static bool kill_heaviest_task;
Suren Baghdasaryan30854e72018-01-17 17:28:01 -0800194static unsigned long kill_timeout_ms;
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -0700195static bool use_minfree_levels;
Suren Baghdasaryan8389fdb2018-06-19 18:38:12 -0700196static bool per_app_memcg;
Vic Yang65680692018-08-07 10:18:22 -0700197static int swap_free_low_percentage;
Suren Baghdasaryan2f88e152019-07-15 15:42:09 -0700198static int psi_partial_stall_ms;
199static int psi_complete_stall_ms;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -0700200static int thrashing_limit_pct;
201static int thrashing_limit_decay_pct;
Suren Baghdasaryan0142b3c2021-03-03 11:11:09 -0800202static int thrashing_critical_pct;
Suren Baghdasaryan51ee4c52020-04-21 12:27:01 -0700203static int swap_util_max;
Suren Baghdasaryan11221d42021-07-14 17:57:52 -0700204static int64_t filecache_min_kb;
Suren Baghdasaryan55e31502019-01-08 12:54:48 -0800205static bool use_psi_monitors = false;
Jing Ji5c480962019-12-04 09:22:05 -0800206static int kpoll_fd;
Suren Baghdasaryan55e31502019-01-08 12:54:48 -0800207static struct psi_threshold psi_thresholds[VMPRESS_LEVEL_COUNT] = {
208 { PSI_SOME, 70 }, /* 70ms out of 1sec for partial stall */
209 { PSI_SOME, 100 }, /* 100ms out of 1sec for partial stall */
210 { PSI_FULL, 70 }, /* 70ms out of 1sec for complete stall */
211};
Robert Benea57397dc2017-07-31 17:15:20 -0700212
Suren Baghdasaryan08bfa982018-07-26 16:34:27 -0700213static android_log_context ctx;
214
Suren Baghdasaryane12a0672019-07-15 14:50:49 -0700215enum polling_update {
216 POLLING_DO_NOT_CHANGE,
217 POLLING_START,
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -0700218 POLLING_PAUSE,
219 POLLING_RESUME,
Suren Baghdasaryane12a0672019-07-15 14:50:49 -0700220};
221
222/*
223 * Data used for periodic polling for the memory state of the device.
224 * Note that when system is not polling poll_handler is set to NULL,
225 * when polling starts poll_handler gets set and is reset back to
226 * NULL when polling stops.
227 */
228struct polling_params {
229 struct event_handler_info* poll_handler;
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -0700230 struct event_handler_info* paused_handler;
Suren Baghdasaryane12a0672019-07-15 14:50:49 -0700231 struct timespec poll_start_tm;
232 struct timespec last_poll_tm;
233 int polling_interval_ms;
234 enum polling_update update;
235};
236
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -0800237/* data required to handle events */
238struct event_handler_info {
239 int data;
Suren Baghdasaryane12a0672019-07-15 14:50:49 -0700240 void (*handler)(int data, uint32_t events, struct polling_params *poll_params);
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -0800241};
Todd Poynorc58c5142013-07-09 19:35:14 -0700242
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -0800243/* data required to handle socket events */
244struct sock_event_handler_info {
245 int sock;
Suren Baghdasaryan945658a2019-10-18 11:16:52 -0700246 pid_t pid;
Suren Baghdasaryan36baf442019-12-23 11:37:34 -0800247 uint32_t async_event_mask;
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -0800248 struct event_handler_info handler_info;
249};
250
Suren Baghdasaryanf2cbefd2019-10-21 17:59:22 -0700251/* max supported number of data connections (AMS, init, tests) */
252#define MAX_DATA_CONN 3
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -0800253
254/* socket event handler data */
255static struct sock_event_handler_info ctrl_sock;
256static struct sock_event_handler_info data_sock[MAX_DATA_CONN];
257
258/* vmpressure event handler data */
259static struct event_handler_info vmpressure_hinfo[VMPRESS_LEVEL_COUNT];
260
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -0700261/*
Suren Baghdasaryanf2cbefd2019-10-21 17:59:22 -0700262 * 1 ctrl listen socket, 3 ctrl data socket, 3 memory pressure levels,
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -0700263 * 1 lmk events + 1 fd to wait for process death
264 */
265#define MAX_EPOLL_EVENTS (1 + MAX_DATA_CONN + VMPRESS_LEVEL_COUNT + 1 + 1)
Todd Poynorc58c5142013-07-09 19:35:14 -0700266static int epollfd;
267static int maxevents;
268
Chong Zhang1cd12b52015-10-14 16:19:53 -0700269/* OOM score values used by both kernel and framework */
Todd Poynora08c1722013-09-16 19:26:47 -0700270#define OOM_SCORE_ADJ_MIN (-1000)
271#define OOM_SCORE_ADJ_MAX 1000
272
Todd Poynorc58c5142013-07-09 19:35:14 -0700273static int lowmem_adj[MAX_TARGETS];
274static int lowmem_minfree[MAX_TARGETS];
275static int lowmem_targets_size;
276
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700277/* Fields to parse in /proc/zoneinfo */
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -0700278/* zoneinfo per-zone fields */
279enum zoneinfo_zone_field {
280 ZI_ZONE_NR_FREE_PAGES = 0,
281 ZI_ZONE_MIN,
282 ZI_ZONE_LOW,
283 ZI_ZONE_HIGH,
284 ZI_ZONE_PRESENT,
285 ZI_ZONE_NR_FREE_CMA,
286 ZI_ZONE_FIELD_COUNT
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700287};
288
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -0700289static const char* const zoneinfo_zone_field_names[ZI_ZONE_FIELD_COUNT] = {
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700290 "nr_free_pages",
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -0700291 "min",
292 "low",
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700293 "high",
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -0700294 "present",
295 "nr_free_cma",
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700296};
297
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -0700298/* zoneinfo per-zone special fields */
299enum zoneinfo_zone_spec_field {
300 ZI_ZONE_SPEC_PROTECTION = 0,
301 ZI_ZONE_SPEC_PAGESETS,
302 ZI_ZONE_SPEC_FIELD_COUNT,
303};
304
305static const char* const zoneinfo_zone_spec_field_names[ZI_ZONE_SPEC_FIELD_COUNT] = {
306 "protection:",
307 "pagesets",
308};
309
310/* see __MAX_NR_ZONES definition in kernel mmzone.h */
311#define MAX_NR_ZONES 6
312
313union zoneinfo_zone_fields {
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700314 struct {
315 int64_t nr_free_pages;
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -0700316 int64_t min;
317 int64_t low;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700318 int64_t high;
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -0700319 int64_t present;
320 int64_t nr_free_cma;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700321 } field;
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -0700322 int64_t arr[ZI_ZONE_FIELD_COUNT];
323};
324
325struct zoneinfo_zone {
326 union zoneinfo_zone_fields fields;
327 int64_t protection[MAX_NR_ZONES];
328 int64_t max_protection;
329};
330
331/* zoneinfo per-node fields */
332enum zoneinfo_node_field {
333 ZI_NODE_NR_INACTIVE_FILE = 0,
334 ZI_NODE_NR_ACTIVE_FILE,
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -0700335 ZI_NODE_FIELD_COUNT
336};
337
338static const char* const zoneinfo_node_field_names[ZI_NODE_FIELD_COUNT] = {
339 "nr_inactive_file",
340 "nr_active_file",
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -0700341};
342
343union zoneinfo_node_fields {
344 struct {
345 int64_t nr_inactive_file;
346 int64_t nr_active_file;
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -0700347 } field;
348 int64_t arr[ZI_NODE_FIELD_COUNT];
349};
350
351struct zoneinfo_node {
352 int id;
353 int zone_count;
354 struct zoneinfo_zone zones[MAX_NR_ZONES];
355 union zoneinfo_node_fields fields;
356};
357
358/* for now two memory nodes is more than enough */
359#define MAX_NR_NODES 2
360
361struct zoneinfo {
362 int node_count;
363 struct zoneinfo_node nodes[MAX_NR_NODES];
364 int64_t totalreserve_pages;
365 int64_t total_inactive_file;
366 int64_t total_active_file;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700367};
368
369/* Fields to parse in /proc/meminfo */
370enum meminfo_field {
371 MI_NR_FREE_PAGES = 0,
372 MI_CACHED,
373 MI_SWAP_CACHED,
374 MI_BUFFERS,
375 MI_SHMEM,
376 MI_UNEVICTABLE,
Vic Yang65680692018-08-07 10:18:22 -0700377 MI_TOTAL_SWAP,
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700378 MI_FREE_SWAP,
Suren Baghdasaryan08bfa982018-07-26 16:34:27 -0700379 MI_ACTIVE_ANON,
380 MI_INACTIVE_ANON,
381 MI_ACTIVE_FILE,
382 MI_INACTIVE_FILE,
383 MI_SRECLAIMABLE,
384 MI_SUNRECLAIM,
385 MI_KERNEL_STACK,
386 MI_PAGE_TABLES,
387 MI_ION_HELP,
388 MI_ION_HELP_POOL,
389 MI_CMA_FREE,
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700390 MI_FIELD_COUNT
391};
392
393static const char* const meminfo_field_names[MI_FIELD_COUNT] = {
394 "MemFree:",
395 "Cached:",
396 "SwapCached:",
397 "Buffers:",
398 "Shmem:",
399 "Unevictable:",
Vic Yang65680692018-08-07 10:18:22 -0700400 "SwapTotal:",
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700401 "SwapFree:",
Suren Baghdasaryan08bfa982018-07-26 16:34:27 -0700402 "Active(anon):",
403 "Inactive(anon):",
404 "Active(file):",
405 "Inactive(file):",
406 "SReclaimable:",
407 "SUnreclaim:",
408 "KernelStack:",
409 "PageTables:",
410 "ION_heap:",
411 "ION_heap_pool:",
412 "CmaFree:",
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700413};
414
415union meminfo {
416 struct {
417 int64_t nr_free_pages;
418 int64_t cached;
419 int64_t swap_cached;
420 int64_t buffers;
421 int64_t shmem;
422 int64_t unevictable;
Vic Yang65680692018-08-07 10:18:22 -0700423 int64_t total_swap;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700424 int64_t free_swap;
Suren Baghdasaryan08bfa982018-07-26 16:34:27 -0700425 int64_t active_anon;
426 int64_t inactive_anon;
427 int64_t active_file;
428 int64_t inactive_file;
429 int64_t sreclaimable;
430 int64_t sunreclaimable;
431 int64_t kernel_stack;
432 int64_t page_tables;
433 int64_t ion_heap;
434 int64_t ion_heap_pool;
435 int64_t cma_free;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700436 /* fields below are calculated rather than read from the file */
437 int64_t nr_file_pages;
Suren Baghdasaryan940e7cf2021-05-27 18:15:44 -0700438 int64_t total_gpu_kb;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700439 } field;
440 int64_t arr[MI_FIELD_COUNT];
441};
442
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -0700443/* Fields to parse in /proc/vmstat */
444enum vmstat_field {
445 VS_FREE_PAGES,
446 VS_INACTIVE_FILE,
447 VS_ACTIVE_FILE,
448 VS_WORKINGSET_REFAULT,
Suren Baghdasaryandc60f972020-12-14 13:38:48 -0800449 VS_WORKINGSET_REFAULT_FILE,
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -0700450 VS_PGSCAN_KSWAPD,
451 VS_PGSCAN_DIRECT,
452 VS_PGSCAN_DIRECT_THROTTLE,
453 VS_FIELD_COUNT
454};
455
456static const char* const vmstat_field_names[MI_FIELD_COUNT] = {
457 "nr_free_pages",
458 "nr_inactive_file",
459 "nr_active_file",
460 "workingset_refault",
Suren Baghdasaryandc60f972020-12-14 13:38:48 -0800461 "workingset_refault_file",
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -0700462 "pgscan_kswapd",
463 "pgscan_direct",
464 "pgscan_direct_throttle",
465};
466
467union vmstat {
468 struct {
469 int64_t nr_free_pages;
470 int64_t nr_inactive_file;
471 int64_t nr_active_file;
472 int64_t workingset_refault;
Suren Baghdasaryandc60f972020-12-14 13:38:48 -0800473 int64_t workingset_refault_file;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -0700474 int64_t pgscan_kswapd;
475 int64_t pgscan_direct;
476 int64_t pgscan_direct_throttle;
477 } field;
478 int64_t arr[VS_FIELD_COUNT];
479};
480
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700481enum field_match_result {
482 NO_MATCH,
483 PARSE_FAIL,
484 PARSE_SUCCESS
485};
486
Todd Poynorc58c5142013-07-09 19:35:14 -0700487struct adjslot_list {
488 struct adjslot_list *next;
489 struct adjslot_list *prev;
490};
491
492struct proc {
493 struct adjslot_list asl;
494 int pid;
Suren Baghdasaryana10157c2019-07-19 10:55:39 -0700495 int pidfd;
Colin Cross748d2182014-06-13 14:52:43 -0700496 uid_t uid;
Todd Poynorc58c5142013-07-09 19:35:14 -0700497 int oomadj;
Suren Baghdasaryan945658a2019-10-18 11:16:52 -0700498 pid_t reg_pid; /* PID of the process that registered this record */
Todd Poynorc58c5142013-07-09 19:35:14 -0700499 struct proc *pidhash_next;
500};
501
Suren Baghdasaryan87966742018-04-13 12:43:41 -0700502struct reread_data {
503 const char* const filename;
504 int fd;
505};
506
Todd Poynorc58c5142013-07-09 19:35:14 -0700507#define PIDHASH_SZ 1024
508static struct proc *pidhash[PIDHASH_SZ];
509#define pid_hashfn(x) ((((x) >> 8) ^ (x)) & (PIDHASH_SZ - 1))
510
Chih-Hung Hsieheefa2462016-05-19 16:02:22 -0700511#define ADJTOSLOT(adj) ((adj) + -OOM_SCORE_ADJ_MIN)
Suren Baghdasaryana7394ea2018-10-12 11:07:40 -0700512#define ADJTOSLOT_COUNT (ADJTOSLOT(OOM_SCORE_ADJ_MAX) + 1)
513static struct adjslot_list procadjslot_list[ADJTOSLOT_COUNT];
514
515#define MAX_DISTINCT_OOM_ADJ 32
516#define KILLCNT_INVALID_IDX 0xFF
517/*
518 * Because killcnt array is sparse a two-level indirection is used
519 * to keep the size small. killcnt_idx stores index of the element in
520 * killcnt array. Index KILLCNT_INVALID_IDX indicates an unused slot.
521 */
522static uint8_t killcnt_idx[ADJTOSLOT_COUNT];
523static uint16_t killcnt[MAX_DISTINCT_OOM_ADJ];
524static int killcnt_free_idx = 0;
525static uint32_t killcnt_total = 0;
Todd Poynorc58c5142013-07-09 19:35:14 -0700526
Todd Poynorc58c5142013-07-09 19:35:14 -0700527/* PAGE_SIZE / 1024 */
528static long page_k;
529
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -0700530static void update_props();
531static bool init_monitors();
532static void destroy_monitors();
533
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -0700534static int clamp(int low, int high, int value) {
535 return max(min(value, high), low);
536}
537
Suren Baghdasaryan87966742018-04-13 12:43:41 -0700538static bool parse_int64(const char* str, int64_t* ret) {
539 char* endptr;
540 long long val = strtoll(str, &endptr, 10);
541 if (str == endptr || val > INT64_MAX) {
542 return false;
543 }
544 *ret = (int64_t)val;
545 return true;
546}
547
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -0700548static int find_field(const char* name, const char* const field_names[], int field_count) {
549 for (int i = 0; i < field_count; i++) {
550 if (!strcmp(name, field_names[i])) {
551 return i;
552 }
553 }
554 return -1;
555}
556
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700557static enum field_match_result match_field(const char* cp, const char* ap,
558 const char* const field_names[],
559 int field_count, int64_t* field,
560 int *field_idx) {
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -0700561 int i = find_field(cp, field_names, field_count);
562 if (i < 0) {
563 return NO_MATCH;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700564 }
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -0700565 *field_idx = i;
566 return parse_int64(ap, field) ? PARSE_SUCCESS : PARSE_FAIL;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700567}
568
Suren Baghdasaryan87966742018-04-13 12:43:41 -0700569/*
570 * Read file content from the beginning up to max_len bytes or EOF
571 * whichever happens first.
572 */
Colin Crossdba1cc62014-07-11 17:53:27 -0700573static ssize_t read_all(int fd, char *buf, size_t max_len)
574{
575 ssize_t ret = 0;
Suren Baghdasaryan87966742018-04-13 12:43:41 -0700576 off_t offset = 0;
Colin Crossdba1cc62014-07-11 17:53:27 -0700577
578 while (max_len > 0) {
Suren Baghdasaryan87966742018-04-13 12:43:41 -0700579 ssize_t r = TEMP_FAILURE_RETRY(pread(fd, buf, max_len, offset));
Colin Crossdba1cc62014-07-11 17:53:27 -0700580 if (r == 0) {
581 break;
582 }
583 if (r == -1) {
584 return -1;
585 }
586 ret += r;
587 buf += r;
Suren Baghdasaryan87966742018-04-13 12:43:41 -0700588 offset += r;
Colin Crossdba1cc62014-07-11 17:53:27 -0700589 max_len -= r;
590 }
591
592 return ret;
593}
594
Suren Baghdasaryan87966742018-04-13 12:43:41 -0700595/*
596 * Read a new or already opened file from the beginning.
597 * If the file has not been opened yet data->fd should be set to -1.
598 * To be used with files which are read often and possibly during high
599 * memory pressure to minimize file opening which by itself requires kernel
600 * memory allocation and might result in a stall on memory stressed system.
601 */
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -0700602static char *reread_file(struct reread_data *data) {
603 /* start with page-size buffer and increase if needed */
604 static ssize_t buf_size = PAGE_SIZE;
605 static char *new_buf, *buf = NULL;
Suren Baghdasaryan87966742018-04-13 12:43:41 -0700606 ssize_t size;
607
608 if (data->fd == -1) {
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -0700609 /* First-time buffer initialization */
Tom Cherry43f3d2b2019-12-04 12:46:57 -0800610 if (!buf && (buf = static_cast<char*>(malloc(buf_size))) == nullptr) {
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -0700611 return NULL;
612 }
613
614 data->fd = TEMP_FAILURE_RETRY(open(data->filename, O_RDONLY | O_CLOEXEC));
615 if (data->fd < 0) {
Suren Baghdasaryan87966742018-04-13 12:43:41 -0700616 ALOGE("%s open: %s", data->filename, strerror(errno));
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -0700617 return NULL;
Suren Baghdasaryan87966742018-04-13 12:43:41 -0700618 }
619 }
620
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -0700621 while (true) {
622 size = read_all(data->fd, buf, buf_size - 1);
623 if (size < 0) {
624 ALOGE("%s read: %s", data->filename, strerror(errno));
625 close(data->fd);
626 data->fd = -1;
627 return NULL;
628 }
629 if (size < buf_size - 1) {
630 break;
631 }
632 /*
633 * Since we are reading /proc files we can't use fstat to find out
634 * the real size of the file. Double the buffer size and keep retrying.
635 */
Tom Cherry43f3d2b2019-12-04 12:46:57 -0800636 if ((new_buf = static_cast<char*>(realloc(buf, buf_size * 2))) == nullptr) {
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -0700637 errno = ENOMEM;
638 return NULL;
639 }
640 buf = new_buf;
641 buf_size *= 2;
Suren Baghdasaryan87966742018-04-13 12:43:41 -0700642 }
Suren Baghdasaryan87966742018-04-13 12:43:41 -0700643 buf[size] = 0;
644
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -0700645 return buf;
Suren Baghdasaryan87966742018-04-13 12:43:41 -0700646}
647
Jing Ji5c480962019-12-04 09:22:05 -0800648static bool claim_record(struct proc* procp, pid_t pid) {
649 if (procp->reg_pid == pid) {
650 /* Record already belongs to the registrant */
651 return true;
652 }
653 if (procp->reg_pid == 0) {
654 /* Old registrant is gone, claim the record */
655 procp->reg_pid = pid;
656 return true;
657 }
658 /* The record is owned by another registrant */
659 return false;
660}
661
662static void remove_claims(pid_t pid) {
663 int i;
664
665 for (i = 0; i < PIDHASH_SZ; i++) {
666 struct proc* procp = pidhash[i];
667 while (procp) {
668 if (procp->reg_pid == pid) {
669 procp->reg_pid = 0;
670 }
671 procp = procp->pidhash_next;
672 }
673 }
674}
675
676static void ctrl_data_close(int dsock_idx) {
677 struct epoll_event epev;
678
679 ALOGI("closing lmkd data connection");
680 if (epoll_ctl(epollfd, EPOLL_CTL_DEL, data_sock[dsock_idx].sock, &epev) == -1) {
681 // Log a warning and keep going
682 ALOGW("epoll_ctl for data connection socket failed; errno=%d", errno);
683 }
684 maxevents--;
685
686 close(data_sock[dsock_idx].sock);
687 data_sock[dsock_idx].sock = -1;
688
689 /* Mark all records of the old registrant as unclaimed */
690 remove_claims(data_sock[dsock_idx].pid);
691}
692
693static ssize_t ctrl_data_read(int dsock_idx, char* buf, size_t bufsz, struct ucred* sender_cred) {
694 struct iovec iov = {buf, bufsz};
695 char control[CMSG_SPACE(sizeof(struct ucred))];
696 struct msghdr hdr = {
697 NULL, 0, &iov, 1, control, sizeof(control), 0,
698 };
699 ssize_t ret;
700 ret = TEMP_FAILURE_RETRY(recvmsg(data_sock[dsock_idx].sock, &hdr, 0));
701 if (ret == -1) {
702 ALOGE("control data socket read failed; %s", strerror(errno));
703 return -1;
704 }
705 if (ret == 0) {
706 ALOGE("Got EOF on control data socket");
707 return -1;
708 }
709
710 struct ucred* cred = NULL;
711 struct cmsghdr* cmsg = CMSG_FIRSTHDR(&hdr);
712 while (cmsg != NULL) {
713 if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_CREDENTIALS) {
714 cred = (struct ucred*)CMSG_DATA(cmsg);
715 break;
716 }
717 cmsg = CMSG_NXTHDR(&hdr, cmsg);
718 }
719
720 if (cred == NULL) {
721 ALOGE("Failed to retrieve sender credentials");
722 /* Close the connection */
723 ctrl_data_close(dsock_idx);
724 return -1;
725 }
726
727 memcpy(sender_cred, cred, sizeof(struct ucred));
728
729 /* Store PID of the peer */
730 data_sock[dsock_idx].pid = cred->pid;
731
732 return ret;
733}
734
735static int ctrl_data_write(int dsock_idx, char* buf, size_t bufsz) {
736 int ret = 0;
737
738 ret = TEMP_FAILURE_RETRY(write(data_sock[dsock_idx].sock, buf, bufsz));
739
740 if (ret == -1) {
741 ALOGE("control data socket write failed; errno=%d", errno);
742 } else if (ret == 0) {
743 ALOGE("Got EOF on control data socket");
744 ret = -1;
745 }
746
747 return ret;
748}
749
750/*
751 * Write the pid/uid pair over the data socket, note: all active clients
752 * will receive this unsolicited notification.
753 */
754static void ctrl_data_write_lmk_kill_occurred(pid_t pid, uid_t uid) {
755 LMKD_CTRL_PACKET packet;
756 size_t len = lmkd_pack_set_prockills(packet, pid, uid);
757
758 for (int i = 0; i < MAX_DATA_CONN; i++) {
Suren Baghdasaryan36baf442019-12-23 11:37:34 -0800759 if (data_sock[i].sock >= 0 && data_sock[i].async_event_mask & 1 << LMK_ASYNC_EVENT_KILL) {
Jing Ji5c480962019-12-04 09:22:05 -0800760 ctrl_data_write(i, (char*)packet, len);
761 }
762 }
763}
764
Vova Sharaienkoa92b76b2021-04-24 00:30:06 +0000765/*
766 * Write the kill_stat/memory_stat over the data socket to be propagated via AMS to statsd
767 */
768static void stats_write_lmk_kill_occurred(struct kill_stat *kill_st,
769 struct memory_stat *mem_st) {
770 LMK_KILL_OCCURRED_PACKET packet;
771 const size_t len = lmkd_pack_set_kill_occurred(packet, kill_st, mem_st);
772 if (len == 0) {
773 return;
774 }
775
776 for (int i = 0; i < MAX_DATA_CONN; i++) {
777 if (data_sock[i].sock >= 0 && data_sock[i].async_event_mask & 1 << LMK_ASYNC_EVENT_STAT) {
778 ctrl_data_write(i, packet, len);
779 }
780 }
781
782}
783
784static void stats_write_lmk_kill_occurred_pid(int pid, struct kill_stat *kill_st,
785 struct memory_stat *mem_st) {
786 kill_st->taskname = stats_get_task_name(pid);
787 if (kill_st->taskname != NULL) {
788 stats_write_lmk_kill_occurred(kill_st, mem_st);
789 }
790}
791
792/*
793 * Write the state_changed over the data socket to be propagated via AMS to statsd
794 */
795static void stats_write_lmk_state_changed(enum lmk_state state) {
796 LMKD_CTRL_PACKET packet_state_changed;
797 const size_t len = lmkd_pack_set_state_changed(packet_state_changed, state);
798 if (len == 0) {
799 return;
800 }
801 for (int i = 0; i < MAX_DATA_CONN; i++) {
802 if (data_sock[i].sock >= 0 && data_sock[i].async_event_mask & 1 << LMK_ASYNC_EVENT_STAT) {
803 ctrl_data_write(i, (char*)packet_state_changed, len);
804 }
805 }
806}
807
Jing Ji5c480962019-12-04 09:22:05 -0800808static void poll_kernel(int poll_fd) {
809 if (poll_fd == -1) {
810 // not waiting
811 return;
812 }
813
814 while (1) {
815 char rd_buf[256];
816 int bytes_read = TEMP_FAILURE_RETRY(pread(poll_fd, (void*)rd_buf, sizeof(rd_buf), 0));
817 if (bytes_read <= 0) break;
818 rd_buf[bytes_read] = '\0';
819
820 int64_t pid;
821 int64_t uid;
822 int64_t group_leader_pid;
823 int64_t rss_in_pages;
824 struct memory_stat mem_st = {};
825 int16_t oom_score_adj;
826 int16_t min_score_adj;
827 int64_t starttime;
828 char* taskname = 0;
829
830 int fields_read =
831 sscanf(rd_buf,
832 "%" SCNd64 " %" SCNd64 " %" SCNd64 " %" SCNd64 " %" SCNd64 " %" SCNd64
833 " %" SCNd16 " %" SCNd16 " %" SCNd64 "\n%m[^\n]",
834 &pid, &uid, &group_leader_pid, &mem_st.pgfault, &mem_st.pgmajfault,
835 &rss_in_pages, &oom_score_adj, &min_score_adj, &starttime, &taskname);
836
837 /* only the death of the group leader process is logged */
838 if (fields_read == 10 && group_leader_pid == pid) {
839 ctrl_data_write_lmk_kill_occurred((pid_t)pid, (uid_t)uid);
840 mem_st.process_start_time_ns = starttime * (NS_PER_SEC / sysconf(_SC_CLK_TCK));
841 mem_st.rss_in_bytes = rss_in_pages * PAGE_SIZE;
Suren Baghdasaryan3cc1f132020-09-09 20:19:02 -0700842
843 struct kill_stat kill_st = {
844 .uid = static_cast<int32_t>(uid),
845 .kill_reason = NONE,
846 .oom_score = oom_score_adj,
847 .min_oom_score = min_score_adj,
848 .free_mem_kb = 0,
849 .free_swap_kb = 0,
850 };
851 stats_write_lmk_kill_occurred_pid(pid, &kill_st, &mem_st);
Jing Ji5c480962019-12-04 09:22:05 -0800852 }
853
854 free(taskname);
855 }
856}
857
858static bool init_poll_kernel() {
859 kpoll_fd = TEMP_FAILURE_RETRY(open("/proc/lowmemorykiller", O_RDONLY | O_NONBLOCK | O_CLOEXEC));
860
861 if (kpoll_fd < 0) {
862 ALOGE("kernel lmk event file could not be opened; errno=%d", errno);
863 return false;
864 }
865
866 return true;
867}
868
Todd Poynorc58c5142013-07-09 19:35:14 -0700869static struct proc *pid_lookup(int pid) {
870 struct proc *procp;
871
872 for (procp = pidhash[pid_hashfn(pid)]; procp && procp->pid != pid;
873 procp = procp->pidhash_next)
874 ;
875
876 return procp;
877}
878
Tom Cherry43f3d2b2019-12-04 12:46:57 -0800879static void adjslot_insert(struct adjslot_list *head, struct adjslot_list *new_element)
Todd Poynorc58c5142013-07-09 19:35:14 -0700880{
881 struct adjslot_list *next = head->next;
Tom Cherry43f3d2b2019-12-04 12:46:57 -0800882 new_element->prev = head;
883 new_element->next = next;
884 next->prev = new_element;
885 head->next = new_element;
Todd Poynorc58c5142013-07-09 19:35:14 -0700886}
887
888static void adjslot_remove(struct adjslot_list *old)
889{
890 struct adjslot_list *prev = old->prev;
891 struct adjslot_list *next = old->next;
892 next->prev = prev;
893 prev->next = next;
894}
895
896static struct adjslot_list *adjslot_tail(struct adjslot_list *head) {
897 struct adjslot_list *asl = head->prev;
898
899 return asl == head ? NULL : asl;
900}
901
902static void proc_slot(struct proc *procp) {
903 int adjslot = ADJTOSLOT(procp->oomadj);
904
905 adjslot_insert(&procadjslot_list[adjslot], &procp->asl);
906}
907
908static void proc_unslot(struct proc *procp) {
909 adjslot_remove(&procp->asl);
910}
911
912static void proc_insert(struct proc *procp) {
913 int hval = pid_hashfn(procp->pid);
914
915 procp->pidhash_next = pidhash[hval];
916 pidhash[hval] = procp;
917 proc_slot(procp);
918}
919
920static int pid_remove(int pid) {
921 int hval = pid_hashfn(pid);
922 struct proc *procp;
923 struct proc *prevp;
924
925 for (procp = pidhash[hval], prevp = NULL; procp && procp->pid != pid;
926 procp = procp->pidhash_next)
927 prevp = procp;
928
929 if (!procp)
930 return -1;
931
932 if (!prevp)
933 pidhash[hval] = procp->pidhash_next;
934 else
935 prevp->pidhash_next = procp->pidhash_next;
936
937 proc_unslot(procp);
Suren Baghdasaryana10157c2019-07-19 10:55:39 -0700938 /*
939 * Close pidfd here if we are not waiting for corresponding process to die,
940 * in which case stop_wait_for_proc_kill() will close the pidfd later
941 */
942 if (procp->pidfd >= 0 && procp->pidfd != last_kill_pid_or_fd) {
943 close(procp->pidfd);
944 }
Todd Poynorc58c5142013-07-09 19:35:14 -0700945 free(procp);
946 return 0;
947}
948
Suren Baghdasaryanf584fff2018-03-20 13:53:17 -0700949/*
950 * Write a string to a file.
951 * Returns false if the file does not exist.
952 */
953static bool writefilestring(const char *path, const char *s,
954 bool err_if_missing) {
Nick Kralevich148d8dd2015-12-18 20:52:37 -0800955 int fd = open(path, O_WRONLY | O_CLOEXEC);
Suren Baghdasaryanf584fff2018-03-20 13:53:17 -0700956 ssize_t len = strlen(s);
957 ssize_t ret;
Todd Poynorc58c5142013-07-09 19:35:14 -0700958
959 if (fd < 0) {
Suren Baghdasaryanf584fff2018-03-20 13:53:17 -0700960 if (err_if_missing) {
961 ALOGE("Error opening %s; errno=%d", path, errno);
962 }
963 return false;
Todd Poynorc58c5142013-07-09 19:35:14 -0700964 }
965
Suren Baghdasaryanf584fff2018-03-20 13:53:17 -0700966 ret = TEMP_FAILURE_RETRY(write(fd, s, len));
Todd Poynorc58c5142013-07-09 19:35:14 -0700967 if (ret < 0) {
968 ALOGE("Error writing %s; errno=%d", path, errno);
969 } else if (ret < len) {
Suren Baghdasaryanf584fff2018-03-20 13:53:17 -0700970 ALOGE("Short write on %s; length=%zd", path, ret);
Todd Poynorc58c5142013-07-09 19:35:14 -0700971 }
972
973 close(fd);
Suren Baghdasaryanf584fff2018-03-20 13:53:17 -0700974 return true;
Todd Poynorc58c5142013-07-09 19:35:14 -0700975}
976
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -0700977static inline long get_time_diff_ms(struct timespec *from,
978 struct timespec *to) {
979 return (to->tv_sec - from->tv_sec) * (long)MS_PER_SEC +
980 (to->tv_nsec - from->tv_nsec) / (long)NS_PER_MS;
981}
982
Ioannis Ilkos279268a2020-08-01 10:50:40 +0100983/* Reads /proc/pid/status into buf. */
984static bool read_proc_status(int pid, char *buf, size_t buf_sz) {
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -0700985 char path[PATH_MAX];
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -0700986 int fd;
987 ssize_t size;
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -0700988
989 snprintf(path, PATH_MAX, "/proc/%d/status", pid);
990 fd = open(path, O_RDONLY | O_CLOEXEC);
991 if (fd < 0) {
Ioannis Ilkos279268a2020-08-01 10:50:40 +0100992 return false;
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -0700993 }
994
Ioannis Ilkos279268a2020-08-01 10:50:40 +0100995 size = read_all(fd, buf, buf_sz - 1);
996 close(fd);
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -0700997 if (size < 0) {
Ioannis Ilkos279268a2020-08-01 10:50:40 +0100998 return false;
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -0700999 }
1000 buf[size] = 0;
Ioannis Ilkos279268a2020-08-01 10:50:40 +01001001 return true;
1002}
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -07001003
Ioannis Ilkos279268a2020-08-01 10:50:40 +01001004/* Looks for tag in buf and parses the first integer */
1005static bool parse_status_tag(char *buf, const char *tag, int64_t *out) {
1006 char *pos = buf;
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -07001007 while (true) {
Ioannis Ilkos279268a2020-08-01 10:50:40 +01001008 pos = strstr(pos, tag);
1009 /* Stop if tag not found or found at the line beginning */
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -07001010 if (pos == NULL || pos == buf || pos[-1] == '\n') {
1011 break;
1012 }
1013 pos++;
1014 }
1015
1016 if (pos == NULL) {
Ioannis Ilkos279268a2020-08-01 10:50:40 +01001017 return false;
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -07001018 }
1019
Ioannis Ilkos279268a2020-08-01 10:50:40 +01001020 pos += strlen(tag);
1021 while (*pos == ' ') ++pos;
1022 return parse_int64(pos, out);
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -07001023}
1024
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07001025static int proc_get_size(int pid) {
1026 char path[PATH_MAX];
1027 char line[LINE_MAX];
1028 int fd;
1029 int rss = 0;
1030 int total;
1031 ssize_t ret;
1032
1033 /* gid containing AID_READPROC required */
1034 snprintf(path, PATH_MAX, "/proc/%d/statm", pid);
1035 fd = open(path, O_RDONLY | O_CLOEXEC);
1036 if (fd == -1)
1037 return -1;
1038
1039 ret = read_all(fd, line, sizeof(line) - 1);
1040 if (ret < 0) {
1041 close(fd);
1042 return -1;
1043 }
Suren Baghdasaryan632f1c52019-10-04 16:06:55 -07001044 line[ret] = '\0';
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07001045
1046 sscanf(line, "%d %d ", &total, &rss);
1047 close(fd);
1048 return rss;
1049}
1050
Suren Baghdasaryan632f1c52019-10-04 16:06:55 -07001051static char *proc_get_name(int pid, char *buf, size_t buf_size) {
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07001052 char path[PATH_MAX];
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07001053 int fd;
1054 char *cp;
1055 ssize_t ret;
1056
1057 /* gid containing AID_READPROC required */
1058 snprintf(path, PATH_MAX, "/proc/%d/cmdline", pid);
1059 fd = open(path, O_RDONLY | O_CLOEXEC);
1060 if (fd == -1) {
1061 return NULL;
1062 }
Suren Baghdasaryan632f1c52019-10-04 16:06:55 -07001063 ret = read_all(fd, buf, buf_size - 1);
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07001064 close(fd);
1065 if (ret < 0) {
1066 return NULL;
1067 }
Suren Baghdasaryan632f1c52019-10-04 16:06:55 -07001068 buf[ret] = '\0';
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07001069
Suren Baghdasaryan632f1c52019-10-04 16:06:55 -07001070 cp = strchr(buf, ' ');
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07001071 if (cp) {
1072 *cp = '\0';
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07001073 }
1074
Suren Baghdasaryan632f1c52019-10-04 16:06:55 -07001075 return buf;
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07001076}
1077
Suren Baghdasaryana93503e2019-10-22 17:12:01 -07001078static void cmd_procprio(LMKD_CTRL_PACKET packet, int field_count, struct ucred *cred) {
Todd Poynorc58c5142013-07-09 19:35:14 -07001079 struct proc *procp;
Suren Baghdasaryan632f1c52019-10-04 16:06:55 -07001080 char path[LINE_MAX];
Todd Poynorc58c5142013-07-09 19:35:14 -07001081 char val[20];
Robert Benea58d6a132017-06-01 16:32:31 -07001082 int soft_limit_mult;
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -08001083 struct lmk_procprio params;
Suren Baghdasaryanbb7747b2018-03-20 16:03:29 -07001084 bool is_system_server;
1085 struct passwd *pwdrec;
Ioannis Ilkos279268a2020-08-01 10:50:40 +01001086 int64_t tgid;
1087 char buf[PAGE_SIZE];
Todd Poynorc58c5142013-07-09 19:35:14 -07001088
Suren Baghdasaryana93503e2019-10-22 17:12:01 -07001089 lmkd_pack_get_procprio(packet, field_count, &params);
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -08001090
1091 if (params.oomadj < OOM_SCORE_ADJ_MIN ||
1092 params.oomadj > OOM_SCORE_ADJ_MAX) {
1093 ALOGE("Invalid PROCPRIO oomadj argument %d", params.oomadj);
Todd Poynorc58c5142013-07-09 19:35:14 -07001094 return;
1095 }
1096
Suren Baghdasaryana93503e2019-10-22 17:12:01 -07001097 if (params.ptype < PROC_TYPE_FIRST || params.ptype >= PROC_TYPE_COUNT) {
1098 ALOGE("Invalid PROCPRIO process type argument %d", params.ptype);
1099 return;
1100 }
1101
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -07001102 /* Check if registered process is a thread group leader */
Ioannis Ilkos279268a2020-08-01 10:50:40 +01001103 if (read_proc_status(params.pid, buf, sizeof(buf))) {
1104 if (parse_status_tag(buf, PROC_STATUS_TGID_FIELD, &tgid) && tgid != params.pid) {
1105 ALOGE("Attempt to register a task that is not a thread group leader "
1106 "(tid %d, tgid %" PRId64 ")", params.pid, tgid);
1107 return;
1108 }
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -07001109 }
1110
Mark Salyzyna00ccd82018-04-09 09:50:32 -07001111 /* gid containing AID_READPROC required */
1112 /* CAP_SYS_RESOURCE required */
1113 /* CAP_DAC_OVERRIDE required */
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -08001114 snprintf(path, sizeof(path), "/proc/%d/oom_score_adj", params.pid);
1115 snprintf(val, sizeof(val), "%d", params.oomadj);
Suren Baghdasaryanf584fff2018-03-20 13:53:17 -07001116 if (!writefilestring(path, val, false)) {
1117 ALOGW("Failed to open %s; errno=%d: process %d might have been killed",
1118 path, errno, params.pid);
1119 /* If this file does not exist the process is dead. */
1120 return;
1121 }
Todd Poynorc58c5142013-07-09 19:35:14 -07001122
Mark Salyzyn5cc80b32018-03-21 12:24:58 -07001123 if (use_inkernel_interface) {
Jing Ji5c480962019-12-04 09:22:05 -08001124 stats_store_taskname(params.pid, proc_get_name(params.pid, path, sizeof(path)));
Todd Poynorc58c5142013-07-09 19:35:14 -07001125 return;
Mark Salyzyn5cc80b32018-03-21 12:24:58 -07001126 }
Todd Poynorc58c5142013-07-09 19:35:14 -07001127
Suren Baghdasaryana93503e2019-10-22 17:12:01 -07001128 /* lmkd should not change soft limits for services */
1129 if (params.ptype == PROC_TYPE_APP && per_app_memcg) {
Suren Baghdasaryanb0bda552018-05-18 14:42:00 -07001130 if (params.oomadj >= 900) {
1131 soft_limit_mult = 0;
1132 } else if (params.oomadj >= 800) {
1133 soft_limit_mult = 0;
1134 } else if (params.oomadj >= 700) {
1135 soft_limit_mult = 0;
1136 } else if (params.oomadj >= 600) {
1137 // Launcher should be perceptible, don't kill it.
1138 params.oomadj = 200;
1139 soft_limit_mult = 1;
1140 } else if (params.oomadj >= 500) {
1141 soft_limit_mult = 0;
1142 } else if (params.oomadj >= 400) {
1143 soft_limit_mult = 0;
1144 } else if (params.oomadj >= 300) {
1145 soft_limit_mult = 1;
1146 } else if (params.oomadj >= 200) {
Srinivas Paladugua453f0b2018-10-09 14:21:10 -07001147 soft_limit_mult = 8;
Suren Baghdasaryanb0bda552018-05-18 14:42:00 -07001148 } else if (params.oomadj >= 100) {
1149 soft_limit_mult = 10;
1150 } else if (params.oomadj >= 0) {
1151 soft_limit_mult = 20;
1152 } else {
1153 // Persistent processes will have a large
1154 // soft limit 512MB.
1155 soft_limit_mult = 64;
1156 }
Robert Benea58d6a132017-06-01 16:32:31 -07001157
Suren Baghdasaryanbf919ff2018-05-21 19:48:47 -07001158 snprintf(path, sizeof(path), MEMCG_SYSFS_PATH
1159 "apps/uid_%d/pid_%d/memory.soft_limit_in_bytes",
1160 params.uid, params.pid);
Suren Baghdasaryanb0bda552018-05-18 14:42:00 -07001161 snprintf(val, sizeof(val), "%d", soft_limit_mult * EIGHT_MEGA);
Suren Baghdasaryanbf919ff2018-05-21 19:48:47 -07001162
1163 /*
1164 * system_server process has no memcg under /dev/memcg/apps but should be
1165 * registered with lmkd. This is the best way so far to identify it.
1166 */
1167 is_system_server = (params.oomadj == SYSTEM_ADJ &&
1168 (pwdrec = getpwnam("system")) != NULL &&
1169 params.uid == pwdrec->pw_uid);
1170 writefilestring(path, val, !is_system_server);
Robert Benea58d6a132017-06-01 16:32:31 -07001171 }
1172
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -08001173 procp = pid_lookup(params.pid);
Todd Poynorc58c5142013-07-09 19:35:14 -07001174 if (!procp) {
Suren Baghdasaryana10157c2019-07-19 10:55:39 -07001175 int pidfd = -1;
1176
1177 if (pidfd_supported) {
Josh Gao84623be2021-03-18 17:16:08 -07001178 pidfd = TEMP_FAILURE_RETRY(pidfd_open(params.pid, 0));
Suren Baghdasaryana10157c2019-07-19 10:55:39 -07001179 if (pidfd < 0) {
1180 ALOGE("pidfd_open for pid %d failed; errno=%d", params.pid, errno);
Todd Poynorc58c5142013-07-09 19:35:14 -07001181 return;
1182 }
Suren Baghdasaryana10157c2019-07-19 10:55:39 -07001183 }
Todd Poynorc58c5142013-07-09 19:35:14 -07001184
Tom Cherry43f3d2b2019-12-04 12:46:57 -08001185 procp = static_cast<struct proc*>(calloc(1, sizeof(struct proc)));
Suren Baghdasaryana10157c2019-07-19 10:55:39 -07001186 if (!procp) {
1187 // Oh, the irony. May need to rebuild our state.
1188 return;
1189 }
1190
1191 procp->pid = params.pid;
1192 procp->pidfd = pidfd;
1193 procp->uid = params.uid;
Suren Baghdasaryan945658a2019-10-18 11:16:52 -07001194 procp->reg_pid = cred->pid;
Suren Baghdasaryana10157c2019-07-19 10:55:39 -07001195 procp->oomadj = params.oomadj;
1196 proc_insert(procp);
Todd Poynorc58c5142013-07-09 19:35:14 -07001197 } else {
Suren Baghdasaryan945658a2019-10-18 11:16:52 -07001198 if (!claim_record(procp, cred->pid)) {
1199 char buf[LINE_MAX];
Suren Baghdasaryan9f1be122021-04-23 13:39:37 -07001200 char *taskname = proc_get_name(cred->pid, buf, sizeof(buf));
Suren Baghdasaryan945658a2019-10-18 11:16:52 -07001201 /* Only registrant of the record can remove it */
1202 ALOGE("%s (%d, %d) attempts to modify a process registered by another client",
Suren Baghdasaryan9f1be122021-04-23 13:39:37 -07001203 taskname ? taskname : "A process ", cred->uid, cred->pid);
Suren Baghdasaryan945658a2019-10-18 11:16:52 -07001204 return;
1205 }
Todd Poynorc58c5142013-07-09 19:35:14 -07001206 proc_unslot(procp);
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -08001207 procp->oomadj = params.oomadj;
Todd Poynorc58c5142013-07-09 19:35:14 -07001208 proc_slot(procp);
1209 }
1210}
1211
Suren Baghdasaryan945658a2019-10-18 11:16:52 -07001212static void cmd_procremove(LMKD_CTRL_PACKET packet, struct ucred *cred) {
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -08001213 struct lmk_procremove params;
Suren Baghdasaryan945658a2019-10-18 11:16:52 -07001214 struct proc *procp;
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -08001215
George Burgess IV3b36b902019-10-02 11:22:55 -07001216 lmkd_pack_get_procremove(packet, &params);
Suren Baghdasaryan945658a2019-10-18 11:16:52 -07001217
Mark Salyzyn5cc80b32018-03-21 12:24:58 -07001218 if (use_inkernel_interface) {
Jing Ji5c480962019-12-04 09:22:05 -08001219 /*
1220 * Perform an extra check before the pid is removed, after which it
1221 * will be impossible for poll_kernel to get the taskname. poll_kernel()
1222 * is potentially a long-running blocking function; however this method
1223 * handles AMS requests but does not block AMS.
1224 */
1225 poll_kernel(kpoll_fd);
1226
1227 stats_remove_taskname(params.pid);
Todd Poynorc58c5142013-07-09 19:35:14 -07001228 return;
Mark Salyzyn5cc80b32018-03-21 12:24:58 -07001229 }
Todd Poynorc58c5142013-07-09 19:35:14 -07001230
Suren Baghdasaryan945658a2019-10-18 11:16:52 -07001231 procp = pid_lookup(params.pid);
1232 if (!procp) {
1233 return;
1234 }
1235
1236 if (!claim_record(procp, cred->pid)) {
1237 char buf[LINE_MAX];
Suren Baghdasaryan9f1be122021-04-23 13:39:37 -07001238 char *taskname = proc_get_name(cred->pid, buf, sizeof(buf));
Suren Baghdasaryan945658a2019-10-18 11:16:52 -07001239 /* Only registrant of the record can remove it */
1240 ALOGE("%s (%d, %d) attempts to unregister a process registered by another client",
Suren Baghdasaryan9f1be122021-04-23 13:39:37 -07001241 taskname ? taskname : "A process ", cred->uid, cred->pid);
Suren Baghdasaryan945658a2019-10-18 11:16:52 -07001242 return;
1243 }
1244
Suren Baghdasaryan8b00c6d2018-10-12 11:28:33 -07001245 /*
1246 * WARNING: After pid_remove() procp is freed and can't be used!
1247 * Therefore placed at the end of the function.
1248 */
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -08001249 pid_remove(params.pid);
Todd Poynorc58c5142013-07-09 19:35:14 -07001250}
1251
Suren Baghdasaryan945658a2019-10-18 11:16:52 -07001252static void cmd_procpurge(struct ucred *cred) {
Suren Baghdasaryan83df0082018-10-10 14:17:17 -07001253 int i;
1254 struct proc *procp;
1255 struct proc *next;
1256
1257 if (use_inkernel_interface) {
Jim Blackler90853b62019-09-10 15:30:05 +01001258 stats_purge_tasknames();
Suren Baghdasaryan83df0082018-10-10 14:17:17 -07001259 return;
1260 }
1261
Suren Baghdasaryan83df0082018-10-10 14:17:17 -07001262 for (i = 0; i < PIDHASH_SZ; i++) {
1263 procp = pidhash[i];
1264 while (procp) {
1265 next = procp->pidhash_next;
Suren Baghdasaryan945658a2019-10-18 11:16:52 -07001266 /* Purge only records created by the requestor */
1267 if (claim_record(procp, cred->pid)) {
1268 pid_remove(procp->pid);
1269 }
Suren Baghdasaryan83df0082018-10-10 14:17:17 -07001270 procp = next;
1271 }
1272 }
Suren Baghdasaryan83df0082018-10-10 14:17:17 -07001273}
1274
Suren Baghdasaryan36baf442019-12-23 11:37:34 -08001275static void cmd_subscribe(int dsock_idx, LMKD_CTRL_PACKET packet) {
1276 struct lmk_subscribe params;
1277
1278 lmkd_pack_get_subscribe(packet, &params);
1279 data_sock[dsock_idx].async_event_mask |= 1 << params.evt_type;
1280}
1281
Suren Baghdasaryana7394ea2018-10-12 11:07:40 -07001282static void inc_killcnt(int oomadj) {
1283 int slot = ADJTOSLOT(oomadj);
1284 uint8_t idx = killcnt_idx[slot];
1285
1286 if (idx == KILLCNT_INVALID_IDX) {
1287 /* index is not assigned for this oomadj */
1288 if (killcnt_free_idx < MAX_DISTINCT_OOM_ADJ) {
1289 killcnt_idx[slot] = killcnt_free_idx;
1290 killcnt[killcnt_free_idx] = 1;
1291 killcnt_free_idx++;
1292 } else {
1293 ALOGW("Number of distinct oomadj levels exceeds %d",
1294 MAX_DISTINCT_OOM_ADJ);
1295 }
1296 } else {
1297 /*
1298 * wraparound is highly unlikely and is detectable using total
1299 * counter because it has to be equal to the sum of all counters
1300 */
1301 killcnt[idx]++;
1302 }
1303 /* increment total kill counter */
1304 killcnt_total++;
1305}
1306
1307static int get_killcnt(int min_oomadj, int max_oomadj) {
1308 int slot;
1309 int count = 0;
1310
1311 if (min_oomadj > max_oomadj)
1312 return 0;
1313
1314 /* special case to get total kill count */
1315 if (min_oomadj > OOM_SCORE_ADJ_MAX)
1316 return killcnt_total;
1317
1318 while (min_oomadj <= max_oomadj &&
1319 (slot = ADJTOSLOT(min_oomadj)) < ADJTOSLOT_COUNT) {
1320 uint8_t idx = killcnt_idx[slot];
1321 if (idx != KILLCNT_INVALID_IDX) {
1322 count += killcnt[idx];
1323 }
1324 min_oomadj++;
1325 }
1326
1327 return count;
1328}
1329
1330static int cmd_getkillcnt(LMKD_CTRL_PACKET packet) {
1331 struct lmk_getkillcnt params;
1332
1333 if (use_inkernel_interface) {
1334 /* kernel driver does not expose this information */
1335 return 0;
1336 }
1337
1338 lmkd_pack_get_getkillcnt(packet, &params);
1339
1340 return get_killcnt(params.min_oomadj, params.max_oomadj);
1341}
1342
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -08001343static void cmd_target(int ntargets, LMKD_CTRL_PACKET packet) {
Todd Poynorc58c5142013-07-09 19:35:14 -07001344 int i;
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -08001345 struct lmk_target target;
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -07001346 char minfree_str[PROPERTY_VALUE_MAX];
1347 char *pstr = minfree_str;
1348 char *pend = minfree_str + sizeof(minfree_str);
1349 static struct timespec last_req_tm;
1350 struct timespec curr_tm;
Todd Poynorc58c5142013-07-09 19:35:14 -07001351
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -07001352 if (ntargets < 1 || ntargets > (int)ARRAY_SIZE(lowmem_adj))
Todd Poynorc58c5142013-07-09 19:35:14 -07001353 return;
1354
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -07001355 /*
1356 * Ratelimit minfree updates to once per TARGET_UPDATE_MIN_INTERVAL_MS
1357 * to prevent DoS attacks
1358 */
1359 if (clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm) != 0) {
1360 ALOGE("Failed to get current time");
1361 return;
1362 }
1363
1364 if (get_time_diff_ms(&last_req_tm, &curr_tm) <
1365 TARGET_UPDATE_MIN_INTERVAL_MS) {
1366 ALOGE("Ignoring frequent updated to lmkd limits");
1367 return;
1368 }
1369
1370 last_req_tm = curr_tm;
1371
Todd Poynorc58c5142013-07-09 19:35:14 -07001372 for (i = 0; i < ntargets; i++) {
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -08001373 lmkd_pack_get_target(packet, i, &target);
1374 lowmem_minfree[i] = target.minfree;
1375 lowmem_adj[i] = target.oom_adj_score;
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -07001376
1377 pstr += snprintf(pstr, pend - pstr, "%d:%d,", target.minfree,
1378 target.oom_adj_score);
1379 if (pstr >= pend) {
1380 /* if no more space in the buffer then terminate the loop */
1381 pstr = pend;
1382 break;
1383 }
Todd Poynorc58c5142013-07-09 19:35:14 -07001384 }
1385
1386 lowmem_targets_size = ntargets;
1387
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -07001388 /* Override the last extra comma */
1389 pstr[-1] = '\0';
1390 property_set("sys.lmk.minfree_levels", minfree_str);
1391
Robert Benea7878c9b2017-09-11 16:53:28 -07001392 if (has_inkernel_module) {
Todd Poynorc58c5142013-07-09 19:35:14 -07001393 char minfreestr[128];
1394 char killpriostr[128];
1395
1396 minfreestr[0] = '\0';
1397 killpriostr[0] = '\0';
1398
1399 for (i = 0; i < lowmem_targets_size; i++) {
1400 char val[40];
1401
1402 if (i) {
1403 strlcat(minfreestr, ",", sizeof(minfreestr));
1404 strlcat(killpriostr, ",", sizeof(killpriostr));
1405 }
1406
Robert Benea7878c9b2017-09-11 16:53:28 -07001407 snprintf(val, sizeof(val), "%d", use_inkernel_interface ? lowmem_minfree[i] : 0);
Todd Poynorc58c5142013-07-09 19:35:14 -07001408 strlcat(minfreestr, val, sizeof(minfreestr));
Robert Benea7878c9b2017-09-11 16:53:28 -07001409 snprintf(val, sizeof(val), "%d", use_inkernel_interface ? lowmem_adj[i] : 0);
Todd Poynorc58c5142013-07-09 19:35:14 -07001410 strlcat(killpriostr, val, sizeof(killpriostr));
1411 }
1412
Suren Baghdasaryanf584fff2018-03-20 13:53:17 -07001413 writefilestring(INKERNEL_MINFREE_PATH, minfreestr, true);
1414 writefilestring(INKERNEL_ADJ_PATH, killpriostr, true);
Todd Poynorc58c5142013-07-09 19:35:14 -07001415 }
1416}
1417
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08001418static void ctrl_command_handler(int dsock_idx) {
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -08001419 LMKD_CTRL_PACKET packet;
Suren Baghdasaryan945658a2019-10-18 11:16:52 -07001420 struct ucred cred;
Todd Poynorc58c5142013-07-09 19:35:14 -07001421 int len;
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -08001422 enum lmk_cmd cmd;
Todd Poynorc58c5142013-07-09 19:35:14 -07001423 int nargs;
1424 int targets;
Suren Baghdasaryana7394ea2018-10-12 11:07:40 -07001425 int kill_cnt;
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07001426 int result;
Todd Poynorc58c5142013-07-09 19:35:14 -07001427
Suren Baghdasaryan945658a2019-10-18 11:16:52 -07001428 len = ctrl_data_read(dsock_idx, (char *)packet, CTRL_PACKET_MAX_SIZE, &cred);
Todd Poynorc58c5142013-07-09 19:35:14 -07001429 if (len <= 0)
1430 return;
1431
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -08001432 if (len < (int)sizeof(int)) {
1433 ALOGE("Wrong control socket read length len=%d", len);
1434 return;
1435 }
1436
1437 cmd = lmkd_pack_get_cmd(packet);
Todd Poynorc58c5142013-07-09 19:35:14 -07001438 nargs = len / sizeof(int) - 1;
1439 if (nargs < 0)
1440 goto wronglen;
1441
Todd Poynorc58c5142013-07-09 19:35:14 -07001442 switch(cmd) {
1443 case LMK_TARGET:
1444 targets = nargs / 2;
1445 if (nargs & 0x1 || targets > (int)ARRAY_SIZE(lowmem_adj))
1446 goto wronglen;
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -08001447 cmd_target(targets, packet);
Todd Poynorc58c5142013-07-09 19:35:14 -07001448 break;
1449 case LMK_PROCPRIO:
Suren Baghdasaryana93503e2019-10-22 17:12:01 -07001450 /* process type field is optional for backward compatibility */
1451 if (nargs < 3 || nargs > 4)
Todd Poynorc58c5142013-07-09 19:35:14 -07001452 goto wronglen;
Suren Baghdasaryana93503e2019-10-22 17:12:01 -07001453 cmd_procprio(packet, nargs, &cred);
Todd Poynorc58c5142013-07-09 19:35:14 -07001454 break;
1455 case LMK_PROCREMOVE:
1456 if (nargs != 1)
1457 goto wronglen;
Suren Baghdasaryan945658a2019-10-18 11:16:52 -07001458 cmd_procremove(packet, &cred);
Todd Poynorc58c5142013-07-09 19:35:14 -07001459 break;
Suren Baghdasaryan83df0082018-10-10 14:17:17 -07001460 case LMK_PROCPURGE:
1461 if (nargs != 0)
1462 goto wronglen;
Suren Baghdasaryan945658a2019-10-18 11:16:52 -07001463 cmd_procpurge(&cred);
Suren Baghdasaryan83df0082018-10-10 14:17:17 -07001464 break;
Suren Baghdasaryana7394ea2018-10-12 11:07:40 -07001465 case LMK_GETKILLCNT:
1466 if (nargs != 2)
1467 goto wronglen;
1468 kill_cnt = cmd_getkillcnt(packet);
1469 len = lmkd_pack_set_getkillcnt_repl(packet, kill_cnt);
1470 if (ctrl_data_write(dsock_idx, (char *)packet, len) != len)
1471 return;
1472 break;
Suren Baghdasaryan36baf442019-12-23 11:37:34 -08001473 case LMK_SUBSCRIBE:
1474 if (nargs != 1)
1475 goto wronglen;
1476 cmd_subscribe(dsock_idx, packet);
1477 break;
Jing Ji5c480962019-12-04 09:22:05 -08001478 case LMK_PROCKILL:
1479 /* This command code is NOT expected at all */
1480 ALOGE("Received unexpected command code %d", cmd);
1481 break;
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07001482 case LMK_UPDATE_PROPS:
1483 if (nargs != 0)
1484 goto wronglen;
1485 update_props();
1486 if (!use_inkernel_interface) {
1487 /* Reinitialize monitors to apply new settings */
1488 destroy_monitors();
1489 result = init_monitors() ? 0 : -1;
1490 } else {
1491 result = 0;
1492 }
1493 len = lmkd_pack_set_update_props_repl(packet, result);
1494 if (ctrl_data_write(dsock_idx, (char *)packet, len) != len) {
1495 ALOGE("Failed to report operation results");
1496 }
1497 if (!result) {
1498 ALOGI("Properties reinitilized");
1499 } else {
1500 /* New settings can't be supported, crash to be restarted */
1501 ALOGE("New configuration is not supported. Exiting...");
1502 exit(1);
1503 }
1504 break;
Todd Poynorc58c5142013-07-09 19:35:14 -07001505 default:
1506 ALOGE("Received unknown command code %d", cmd);
1507 return;
1508 }
1509
1510 return;
1511
1512wronglen:
1513 ALOGE("Wrong control socket read length cmd=%d len=%d", cmd, len);
1514}
1515
Suren Baghdasaryane12a0672019-07-15 14:50:49 -07001516static void ctrl_data_handler(int data, uint32_t events,
1517 struct polling_params *poll_params __unused) {
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08001518 if (events & EPOLLIN) {
1519 ctrl_command_handler(data);
Todd Poynorc58c5142013-07-09 19:35:14 -07001520 }
1521}
1522
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08001523static int get_free_dsock() {
1524 for (int i = 0; i < MAX_DATA_CONN; i++) {
1525 if (data_sock[i].sock < 0) {
1526 return i;
1527 }
1528 }
1529 return -1;
1530}
Todd Poynorc58c5142013-07-09 19:35:14 -07001531
Suren Baghdasaryane12a0672019-07-15 14:50:49 -07001532static void ctrl_connect_handler(int data __unused, uint32_t events __unused,
1533 struct polling_params *poll_params __unused) {
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08001534 struct epoll_event epev;
1535 int free_dscock_idx = get_free_dsock();
1536
1537 if (free_dscock_idx < 0) {
1538 /*
1539 * Number of data connections exceeded max supported. This should not
1540 * happen but if it does we drop all existing connections and accept
1541 * the new one. This prevents inactive connections from monopolizing
1542 * data socket and if we drop ActivityManager connection it will
1543 * immediately reconnect.
1544 */
1545 for (int i = 0; i < MAX_DATA_CONN; i++) {
1546 ctrl_data_close(i);
1547 }
1548 free_dscock_idx = 0;
Todd Poynorc58c5142013-07-09 19:35:14 -07001549 }
1550
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08001551 data_sock[free_dscock_idx].sock = accept(ctrl_sock.sock, NULL, NULL);
1552 if (data_sock[free_dscock_idx].sock < 0) {
Todd Poynorc58c5142013-07-09 19:35:14 -07001553 ALOGE("lmkd control socket accept failed; errno=%d", errno);
1554 return;
1555 }
1556
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08001557 ALOGI("lmkd data connection established");
1558 /* use data to store data connection idx */
1559 data_sock[free_dscock_idx].handler_info.data = free_dscock_idx;
1560 data_sock[free_dscock_idx].handler_info.handler = ctrl_data_handler;
Suren Baghdasaryan36baf442019-12-23 11:37:34 -08001561 data_sock[free_dscock_idx].async_event_mask = 0;
Todd Poynorc58c5142013-07-09 19:35:14 -07001562 epev.events = EPOLLIN;
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08001563 epev.data.ptr = (void *)&(data_sock[free_dscock_idx].handler_info);
1564 if (epoll_ctl(epollfd, EPOLL_CTL_ADD, data_sock[free_dscock_idx].sock, &epev) == -1) {
Todd Poynorc58c5142013-07-09 19:35:14 -07001565 ALOGE("epoll_ctl for data connection socket failed; errno=%d", errno);
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08001566 ctrl_data_close(free_dscock_idx);
Todd Poynorc58c5142013-07-09 19:35:14 -07001567 return;
1568 }
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08001569 maxevents++;
Todd Poynorc58c5142013-07-09 19:35:14 -07001570}
1571
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001572/*
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07001573 * /proc/zoneinfo parsing routines
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001574 * Expected file format is:
1575 *
1576 * Node <node_id>, zone <zone_name>
1577 * (
1578 * per-node stats
1579 * (<per-node field name> <value>)+
1580 * )?
1581 * (pages free <value>
1582 * (<per-zone field name> <value>)+
1583 * pagesets
1584 * (<unused fields>)*
1585 * )+
1586 * ...
1587 */
1588static void zoneinfo_parse_protection(char *buf, struct zoneinfo_zone *zone) {
1589 int zone_idx;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001590 int64_t max = 0;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001591 char *save_ptr;
1592
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001593 for (buf = strtok_r(buf, "(), ", &save_ptr), zone_idx = 0;
1594 buf && zone_idx < MAX_NR_ZONES;
1595 buf = strtok_r(NULL, "), ", &save_ptr), zone_idx++) {
1596 long long zoneval = strtoll(buf, &buf, 0);
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001597 if (zoneval > max) {
1598 max = (zoneval > INT64_MAX) ? INT64_MAX : zoneval;
1599 }
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001600 zone->protection[zone_idx] = zoneval;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001601 }
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001602 zone->max_protection = max;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001603}
1604
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001605static int zoneinfo_parse_zone(char **buf, struct zoneinfo_zone *zone) {
1606 for (char *line = strtok_r(NULL, "\n", buf); line;
1607 line = strtok_r(NULL, "\n", buf)) {
1608 char *cp;
1609 char *ap;
1610 char *save_ptr;
1611 int64_t val;
1612 int field_idx;
1613 enum field_match_result match_res;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001614
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001615 cp = strtok_r(line, " ", &save_ptr);
1616 if (!cp) {
1617 return false;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001618 }
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001619
1620 field_idx = find_field(cp, zoneinfo_zone_spec_field_names, ZI_ZONE_SPEC_FIELD_COUNT);
1621 if (field_idx >= 0) {
1622 /* special field */
1623 if (field_idx == ZI_ZONE_SPEC_PAGESETS) {
1624 /* no mode fields we are interested in */
1625 return true;
1626 }
1627
1628 /* protection field */
1629 ap = strtok_r(NULL, ")", &save_ptr);
1630 if (ap) {
1631 zoneinfo_parse_protection(ap, zone);
1632 }
1633 continue;
1634 }
1635
1636 ap = strtok_r(NULL, " ", &save_ptr);
1637 if (!ap) {
1638 continue;
1639 }
1640
1641 match_res = match_field(cp, ap, zoneinfo_zone_field_names, ZI_ZONE_FIELD_COUNT,
1642 &val, &field_idx);
1643 if (match_res == PARSE_FAIL) {
1644 return false;
1645 }
1646 if (match_res == PARSE_SUCCESS) {
1647 zone->fields.arr[field_idx] = val;
1648 }
1649 if (field_idx == ZI_ZONE_PRESENT && val == 0) {
1650 /* zone is not populated, stop parsing it */
1651 return true;
1652 }
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001653 }
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001654 return false;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001655}
1656
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001657static int zoneinfo_parse_node(char **buf, struct zoneinfo_node *node) {
1658 int fields_to_match = ZI_NODE_FIELD_COUNT;
1659
1660 for (char *line = strtok_r(NULL, "\n", buf); line;
1661 line = strtok_r(NULL, "\n", buf)) {
1662 char *cp;
1663 char *ap;
1664 char *save_ptr;
1665 int64_t val;
1666 int field_idx;
1667 enum field_match_result match_res;
1668
1669 cp = strtok_r(line, " ", &save_ptr);
1670 if (!cp) {
1671 return false;
1672 }
1673
1674 ap = strtok_r(NULL, " ", &save_ptr);
1675 if (!ap) {
1676 return false;
1677 }
1678
1679 match_res = match_field(cp, ap, zoneinfo_node_field_names, ZI_NODE_FIELD_COUNT,
1680 &val, &field_idx);
1681 if (match_res == PARSE_FAIL) {
1682 return false;
1683 }
1684 if (match_res == PARSE_SUCCESS) {
1685 node->fields.arr[field_idx] = val;
1686 fields_to_match--;
1687 if (!fields_to_match) {
1688 return true;
1689 }
1690 }
1691 }
1692 return false;
1693}
1694
1695static int zoneinfo_parse(struct zoneinfo *zi) {
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001696 static struct reread_data file_data = {
1697 .filename = ZONEINFO_PATH,
1698 .fd = -1,
1699 };
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -07001700 char *buf;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001701 char *save_ptr;
1702 char *line;
Greg Kaiser259984f2019-10-02 07:07:32 -07001703 char zone_name[LINE_MAX + 1];
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001704 struct zoneinfo_node *node = NULL;
1705 int node_idx = 0;
1706 int zone_idx = 0;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001707
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001708 memset(zi, 0, sizeof(struct zoneinfo));
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001709
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -07001710 if ((buf = reread_file(&file_data)) == NULL) {
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001711 return -1;
1712 }
1713
1714 for (line = strtok_r(buf, "\n", &save_ptr); line;
1715 line = strtok_r(NULL, "\n", &save_ptr)) {
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001716 int node_id;
1717 if (sscanf(line, "Node %d, zone %" STRINGIFY(LINE_MAX) "s", &node_id, zone_name) == 2) {
1718 if (!node || node->id != node_id) {
1719 /* new node is found */
1720 if (node) {
1721 node->zone_count = zone_idx + 1;
1722 node_idx++;
1723 if (node_idx == MAX_NR_NODES) {
1724 /* max node count exceeded */
1725 ALOGE("%s parse error", file_data.filename);
1726 return -1;
1727 }
1728 }
1729 node = &zi->nodes[node_idx];
1730 node->id = node_id;
1731 zone_idx = 0;
1732 if (!zoneinfo_parse_node(&save_ptr, node)) {
1733 ALOGE("%s parse error", file_data.filename);
1734 return -1;
1735 }
1736 } else {
1737 /* new zone is found */
1738 zone_idx++;
1739 }
1740 if (!zoneinfo_parse_zone(&save_ptr, &node->zones[zone_idx])) {
1741 ALOGE("%s parse error", file_data.filename);
1742 return -1;
1743 }
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001744 }
1745 }
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001746 if (!node) {
1747 ALOGE("%s parse error", file_data.filename);
1748 return -1;
1749 }
1750 node->zone_count = zone_idx + 1;
1751 zi->node_count = node_idx + 1;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001752
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001753 /* calculate totals fields */
1754 for (node_idx = 0; node_idx < zi->node_count; node_idx++) {
1755 node = &zi->nodes[node_idx];
1756 for (zone_idx = 0; zone_idx < node->zone_count; zone_idx++) {
1757 struct zoneinfo_zone *zone = &zi->nodes[node_idx].zones[zone_idx];
1758 zi->totalreserve_pages += zone->max_protection + zone->fields.field.high;
1759 }
1760 zi->total_inactive_file += node->fields.field.nr_inactive_file;
1761 zi->total_active_file += node->fields.field.nr_active_file;
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001762 }
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001763 return 0;
1764}
1765
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07001766/* /proc/meminfo parsing routines */
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001767static bool meminfo_parse_line(char *line, union meminfo *mi) {
1768 char *cp = line;
1769 char *ap;
1770 char *save_ptr;
1771 int64_t val;
1772 int field_idx;
1773 enum field_match_result match_res;
1774
1775 cp = strtok_r(line, " ", &save_ptr);
1776 if (!cp) {
1777 return false;
1778 }
1779
1780 ap = strtok_r(NULL, " ", &save_ptr);
1781 if (!ap) {
1782 return false;
1783 }
1784
1785 match_res = match_field(cp, ap, meminfo_field_names, MI_FIELD_COUNT,
1786 &val, &field_idx);
1787 if (match_res == PARSE_SUCCESS) {
1788 mi->arr[field_idx] = val / page_k;
1789 }
1790 return (match_res != PARSE_FAIL);
1791}
1792
Suren Baghdasaryan940e7cf2021-05-27 18:15:44 -07001793static int64_t read_gpu_total_kb() {
1794 static int fd = android::bpf::bpfFdGet(
1795 "/sys/fs/bpf/map_gpu_mem_gpu_mem_total_map", BPF_F_RDONLY);
1796 static constexpr uint64_t kBpfKeyGpuTotalUsage = 0;
1797 uint64_t value;
1798
1799 if (fd < 0) {
1800 return 0;
1801 }
1802
1803 return android::bpf::findMapEntry(fd, &kBpfKeyGpuTotalUsage, &value)
1804 ? 0
1805 : (int32_t)(value / 1024);
1806}
1807
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001808static int meminfo_parse(union meminfo *mi) {
1809 static struct reread_data file_data = {
1810 .filename = MEMINFO_PATH,
1811 .fd = -1,
1812 };
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -07001813 char *buf;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001814 char *save_ptr;
1815 char *line;
1816
1817 memset(mi, 0, sizeof(union meminfo));
1818
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -07001819 if ((buf = reread_file(&file_data)) == NULL) {
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001820 return -1;
1821 }
1822
1823 for (line = strtok_r(buf, "\n", &save_ptr); line;
1824 line = strtok_r(NULL, "\n", &save_ptr)) {
1825 if (!meminfo_parse_line(line, mi)) {
1826 ALOGE("%s parse error", file_data.filename);
1827 return -1;
1828 }
1829 }
1830 mi->field.nr_file_pages = mi->field.cached + mi->field.swap_cached +
1831 mi->field.buffers;
Suren Baghdasaryan940e7cf2021-05-27 18:15:44 -07001832 mi->field.total_gpu_kb = read_gpu_total_kb();
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001833
1834 return 0;
1835}
1836
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07001837/* /proc/vmstat parsing routines */
1838static bool vmstat_parse_line(char *line, union vmstat *vs) {
1839 char *cp;
1840 char *ap;
1841 char *save_ptr;
1842 int64_t val;
1843 int field_idx;
1844 enum field_match_result match_res;
1845
1846 cp = strtok_r(line, " ", &save_ptr);
1847 if (!cp) {
1848 return false;
1849 }
1850
1851 ap = strtok_r(NULL, " ", &save_ptr);
1852 if (!ap) {
1853 return false;
1854 }
1855
1856 match_res = match_field(cp, ap, vmstat_field_names, VS_FIELD_COUNT,
1857 &val, &field_idx);
1858 if (match_res == PARSE_SUCCESS) {
1859 vs->arr[field_idx] = val;
1860 }
1861 return (match_res != PARSE_FAIL);
1862}
1863
1864static int vmstat_parse(union vmstat *vs) {
1865 static struct reread_data file_data = {
1866 .filename = VMSTAT_PATH,
1867 .fd = -1,
1868 };
1869 char *buf;
1870 char *save_ptr;
1871 char *line;
1872
1873 memset(vs, 0, sizeof(union vmstat));
1874
1875 if ((buf = reread_file(&file_data)) == NULL) {
1876 return -1;
1877 }
1878
1879 for (line = strtok_r(buf, "\n", &save_ptr); line;
1880 line = strtok_r(NULL, "\n", &save_ptr)) {
1881 if (!vmstat_parse_line(line, vs)) {
1882 ALOGE("%s parse error", file_data.filename);
1883 return -1;
1884 }
1885 }
1886
1887 return 0;
1888}
1889
Suren Baghdasaryand7b4fcb2020-07-23 18:00:43 -07001890enum wakeup_reason {
1891 Event,
1892 Polling
1893};
1894
1895struct wakeup_info {
1896 struct timespec wakeup_tm;
1897 struct timespec prev_wakeup_tm;
1898 struct timespec last_event_tm;
1899 int wakeups_since_event;
1900 int skipped_wakeups;
1901};
1902
1903/*
1904 * After the initial memory pressure event is received lmkd schedules periodic wakeups to check
1905 * the memory conditions and kill if needed (polling). This is done because pressure events are
1906 * rate-limited and memory conditions can change in between events. Therefore after the initial
1907 * event there might be multiple wakeups. This function records the wakeup information such as the
1908 * timestamps of the last event and the last wakeup, the number of wakeups since the last event
1909 * and how many of those wakeups were skipped (some wakeups are skipped if previously killed
1910 * process is still freeing its memory).
1911 */
1912static void record_wakeup_time(struct timespec *tm, enum wakeup_reason reason,
1913 struct wakeup_info *wi) {
1914 wi->prev_wakeup_tm = wi->wakeup_tm;
1915 wi->wakeup_tm = *tm;
1916 if (reason == Event) {
1917 wi->last_event_tm = *tm;
1918 wi->wakeups_since_event = 0;
1919 wi->skipped_wakeups = 0;
1920 } else {
1921 wi->wakeups_since_event++;
1922 }
1923}
1924
Ioannis Ilkos279268a2020-08-01 10:50:40 +01001925static void killinfo_log(struct proc* procp, int min_oom_score, int rss_kb,
Ioannis Ilkos48848902021-02-18 19:53:33 +00001926 int swap_kb, int kill_reason, union meminfo *mi,
Suren Baghdasaryand7b4fcb2020-07-23 18:00:43 -07001927 struct wakeup_info *wi, struct timespec *tm) {
Suren Baghdasaryan12cacae2019-09-16 12:06:30 -07001928 /* log process information */
1929 android_log_write_int32(ctx, procp->pid);
1930 android_log_write_int32(ctx, procp->uid);
1931 android_log_write_int32(ctx, procp->oomadj);
1932 android_log_write_int32(ctx, min_oom_score);
Ioannis Ilkos279268a2020-08-01 10:50:40 +01001933 android_log_write_int32(ctx, (int32_t)min(rss_kb, INT32_MAX));
Suren Baghdasaryan12cacae2019-09-16 12:06:30 -07001934 android_log_write_int32(ctx, kill_reason);
1935
1936 /* log meminfo fields */
Suren Baghdasaryan08bfa982018-07-26 16:34:27 -07001937 for (int field_idx = 0; field_idx < MI_FIELD_COUNT; field_idx++) {
1938 android_log_write_int32(ctx, (int32_t)min(mi->arr[field_idx] * page_k, INT32_MAX));
1939 }
1940
Suren Baghdasaryand7b4fcb2020-07-23 18:00:43 -07001941 /* log lmkd wakeup information */
1942 android_log_write_int32(ctx, (int32_t)get_time_diff_ms(&wi->last_event_tm, tm));
1943 android_log_write_int32(ctx, (int32_t)get_time_diff_ms(&wi->prev_wakeup_tm, tm));
1944 android_log_write_int32(ctx, wi->wakeups_since_event);
1945 android_log_write_int32(ctx, wi->skipped_wakeups);
Ioannis Ilkos282437f2021-03-04 17:50:05 +00001946 android_log_write_int32(ctx, (int32_t)min(swap_kb, INT32_MAX));
Suren Baghdasaryan940e7cf2021-05-27 18:15:44 -07001947 android_log_write_int32(ctx, (int32_t)mi->field.total_gpu_kb);
Suren Baghdasaryand7b4fcb2020-07-23 18:00:43 -07001948
Suren Baghdasaryan08bfa982018-07-26 16:34:27 -07001949 android_log_write_list(ctx, LOG_ID_EVENTS);
1950 android_log_reset(ctx);
1951}
1952
Todd Poynorc58c5142013-07-09 19:35:14 -07001953static struct proc *proc_adj_lru(int oomadj) {
1954 return (struct proc *)adjslot_tail(&procadjslot_list[ADJTOSLOT(oomadj)]);
1955}
1956
Suren Baghdasaryaneb7c5492017-12-08 13:17:06 -08001957static struct proc *proc_get_heaviest(int oomadj) {
1958 struct adjslot_list *head = &procadjslot_list[ADJTOSLOT(oomadj)];
1959 struct adjslot_list *curr = head->next;
1960 struct proc *maxprocp = NULL;
1961 int maxsize = 0;
1962 while (curr != head) {
1963 int pid = ((struct proc *)curr)->pid;
1964 int tasksize = proc_get_size(pid);
Suren Baghdasaryan5263aa72021-04-29 15:28:57 -07001965 if (tasksize < 0) {
Suren Baghdasaryaneb7c5492017-12-08 13:17:06 -08001966 struct adjslot_list *next = curr->next;
1967 pid_remove(pid);
1968 curr = next;
1969 } else {
1970 if (tasksize > maxsize) {
1971 maxsize = tasksize;
1972 maxprocp = (struct proc *)curr;
1973 }
1974 curr = curr->next;
1975 }
1976 }
1977 return maxprocp;
1978}
1979
Wei Wangf1ee2e12018-11-21 00:11:44 -08001980static void set_process_group_and_prio(int pid, SchedPolicy sp, int prio) {
1981 DIR* d;
1982 char proc_path[PATH_MAX];
1983 struct dirent* de;
1984
1985 snprintf(proc_path, sizeof(proc_path), "/proc/%d/task", pid);
1986 if (!(d = opendir(proc_path))) {
1987 ALOGW("Failed to open %s; errno=%d: process pid(%d) might have died", proc_path, errno,
1988 pid);
1989 return;
1990 }
1991
1992 while ((de = readdir(d))) {
1993 int t_pid;
1994
1995 if (de->d_name[0] == '.') continue;
1996 t_pid = atoi(de->d_name);
1997
1998 if (!t_pid) {
1999 ALOGW("Failed to get t_pid for '%s' of pid(%d)", de->d_name, pid);
2000 continue;
2001 }
2002
2003 if (setpriority(PRIO_PROCESS, t_pid, prio) && errno != ESRCH) {
2004 ALOGW("Unable to raise priority of killing t_pid (%d): errno=%d", t_pid, errno);
2005 }
2006
2007 if (set_cpuset_policy(t_pid, sp)) {
2008 ALOGW("Failed to set_cpuset_policy on pid(%d) t_pid(%d) to %d", pid, t_pid, (int)sp);
2009 continue;
2010 }
2011 }
2012 closedir(d);
2013}
2014
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002015static bool is_kill_pending(void) {
2016 char buf[24];
2017
2018 if (last_kill_pid_or_fd < 0) {
2019 return false;
2020 }
2021
2022 if (pidfd_supported) {
2023 return true;
2024 }
2025
2026 /* when pidfd is not supported base the decision on /proc/<pid> existence */
2027 snprintf(buf, sizeof(buf), "/proc/%d/", last_kill_pid_or_fd);
2028 if (access(buf, F_OK) == 0) {
2029 return true;
2030 }
2031
2032 return false;
2033}
2034
2035static bool is_waiting_for_kill(void) {
2036 return pidfd_supported && last_kill_pid_or_fd >= 0;
2037}
2038
2039static void stop_wait_for_proc_kill(bool finished) {
2040 struct epoll_event epev;
2041
2042 if (last_kill_pid_or_fd < 0) {
2043 return;
2044 }
2045
2046 if (debug_process_killing) {
2047 struct timespec curr_tm;
2048
2049 if (clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm) != 0) {
2050 /*
2051 * curr_tm is used here merely to report kill duration, so this failure is not fatal.
2052 * Log an error and continue.
2053 */
2054 ALOGE("Failed to get current time");
2055 }
2056
2057 if (finished) {
2058 ALOGI("Process got killed in %ldms",
2059 get_time_diff_ms(&last_kill_tm, &curr_tm));
2060 } else {
2061 ALOGI("Stop waiting for process kill after %ldms",
2062 get_time_diff_ms(&last_kill_tm, &curr_tm));
2063 }
2064 }
2065
2066 if (pidfd_supported) {
2067 /* unregister fd */
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07002068 if (epoll_ctl(epollfd, EPOLL_CTL_DEL, last_kill_pid_or_fd, &epev)) {
2069 // Log an error and keep going
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002070 ALOGE("epoll_ctl for last killed process failed; errno=%d", errno);
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002071 }
2072 maxevents--;
2073 close(last_kill_pid_or_fd);
2074 }
2075
2076 last_kill_pid_or_fd = -1;
2077}
2078
2079static void kill_done_handler(int data __unused, uint32_t events __unused,
2080 struct polling_params *poll_params) {
2081 stop_wait_for_proc_kill(true);
2082 poll_params->update = POLLING_RESUME;
2083}
2084
Suren Baghdasaryana10157c2019-07-19 10:55:39 -07002085static void start_wait_for_proc_kill(int pid_or_fd) {
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002086 static struct event_handler_info kill_done_hinfo = { 0, kill_done_handler };
2087 struct epoll_event epev;
2088
2089 if (last_kill_pid_or_fd >= 0) {
2090 /* Should not happen but if it does we should stop previous wait */
2091 ALOGE("Attempt to wait for a kill while another wait is in progress");
2092 stop_wait_for_proc_kill(false);
2093 }
2094
Suren Baghdasaryana10157c2019-07-19 10:55:39 -07002095 last_kill_pid_or_fd = pid_or_fd;
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002096
Suren Baghdasaryana10157c2019-07-19 10:55:39 -07002097 if (!pidfd_supported) {
2098 /* If pidfd is not supported just store PID and exit */
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002099 return;
2100 }
2101
2102 epev.events = EPOLLIN;
2103 epev.data.ptr = (void *)&kill_done_hinfo;
2104 if (epoll_ctl(epollfd, EPOLL_CTL_ADD, last_kill_pid_or_fd, &epev) != 0) {
2105 ALOGE("epoll_ctl for last kill failed; errno=%d", errno);
2106 close(last_kill_pid_or_fd);
2107 last_kill_pid_or_fd = -1;
2108 return;
2109 }
2110 maxevents++;
2111}
Tim Murraya79ec0f2018-10-25 17:05:41 -07002112
Ioannis Ilkos279268a2020-08-01 10:50:40 +01002113/* Kill one process specified by procp. Returns the size (in pages) of the process killed */
Suren Baghdasaryan3cc1f132020-09-09 20:19:02 -07002114static int kill_one_process(struct proc* procp, int min_oom_score, enum kill_reasons kill_reason,
Suren Baghdasaryand7b4fcb2020-07-23 18:00:43 -07002115 const char *kill_desc, union meminfo *mi, struct wakeup_info *wi,
2116 struct timespec *tm) {
Colin Cross3d57a512014-07-14 12:39:56 -07002117 int pid = procp->pid;
Suren Baghdasaryana10157c2019-07-19 10:55:39 -07002118 int pidfd = procp->pidfd;
Colin Cross3d57a512014-07-14 12:39:56 -07002119 uid_t uid = procp->uid;
2120 char *taskname;
Colin Cross3d57a512014-07-14 12:39:56 -07002121 int r;
Suren Baghdasaryan8b00c6d2018-10-12 11:28:33 -07002122 int result = -1;
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07002123 struct memory_stat *mem_st;
Suren Baghdasaryan3cc1f132020-09-09 20:19:02 -07002124 struct kill_stat kill_st;
Ioannis Ilkos279268a2020-08-01 10:50:40 +01002125 int64_t tgid;
2126 int64_t rss_kb;
2127 int64_t swap_kb;
2128 char buf[PAGE_SIZE];
Rajeev Kumar4aba9152018-01-31 17:54:56 -08002129
Ioannis Ilkos279268a2020-08-01 10:50:40 +01002130 if (!read_proc_status(pid, buf, sizeof(buf))) {
2131 goto out;
2132 }
2133 if (!parse_status_tag(buf, PROC_STATUS_TGID_FIELD, &tgid)) {
2134 ALOGE("Unable to parse tgid from /proc/%d/status", pid);
2135 goto out;
2136 }
2137 if (tgid != pid) {
2138 ALOGE("Possible pid reuse detected (pid %d, tgid %" PRId64 ")!", pid, tgid);
2139 goto out;
2140 }
2141 // Zombie processes will not have RSS / Swap fields.
2142 if (!parse_status_tag(buf, PROC_STATUS_RSS_FIELD, &rss_kb)) {
2143 goto out;
2144 }
2145 if (!parse_status_tag(buf, PROC_STATUS_SWAP_FIELD, &swap_kb)) {
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -07002146 goto out;
2147 }
2148
Suren Baghdasaryan632f1c52019-10-04 16:06:55 -07002149 taskname = proc_get_name(pid, buf, sizeof(buf));
Ioannis Ilkos279268a2020-08-01 10:50:40 +01002150 // taskname will point inside buf, do not reuse buf onwards.
Colin Cross3d57a512014-07-14 12:39:56 -07002151 if (!taskname) {
Suren Baghdasaryan8b00c6d2018-10-12 11:28:33 -07002152 goto out;
Colin Cross3d57a512014-07-14 12:39:56 -07002153 }
2154
Ioannis Ilkos279268a2020-08-01 10:50:40 +01002155 mem_st = stats_read_memory_stat(per_app_memcg, pid, uid, rss_kb * 1024, swap_kb * 1024);
Rajeev Kumar4aba9152018-01-31 17:54:56 -08002156
Suren Baghdasaryan03e19872018-01-04 10:43:58 -08002157 TRACE_KILL_START(pid);
2158
Mark Salyzyna00ccd82018-04-09 09:50:32 -07002159 /* CAP_KILL required */
Suren Baghdasaryana10157c2019-07-19 10:55:39 -07002160 if (pidfd < 0) {
2161 start_wait_for_proc_kill(pid);
2162 r = kill(pid, SIGKILL);
2163 } else {
2164 start_wait_for_proc_kill(pidfd);
Josh Gao84623be2021-03-18 17:16:08 -07002165 r = pidfd_send_signal(pidfd, SIGKILL, NULL, 0);
Suren Baghdasaryana10157c2019-07-19 10:55:39 -07002166 }
Wei Wangf1ee2e12018-11-21 00:11:44 -08002167
Suren Baghdasaryanc2e05b62019-09-04 16:44:47 -07002168 TRACE_KILL_END();
2169
2170 if (r) {
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002171 stop_wait_for_proc_kill(false);
Suren Baghdasaryanc2e05b62019-09-04 16:44:47 -07002172 ALOGE("kill(%d): errno=%d", pid, errno);
2173 /* Delete process record even when we fail to kill so that we don't get stuck on it */
2174 goto out;
2175 }
2176
Wei Wangf1ee2e12018-11-21 00:11:44 -08002177 set_process_group_and_prio(pid, SP_FOREGROUND, ANDROID_PRIORITY_HIGHEST);
2178
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002179 last_kill_tm = *tm;
2180
Suren Baghdasaryana7394ea2018-10-12 11:07:40 -07002181 inc_killcnt(procp->oomadj);
Suren Baghdasaryan12cacae2019-09-16 12:06:30 -07002182
Ioannis Ilkos48848902021-02-18 19:53:33 +00002183 killinfo_log(procp, min_oom_score, rss_kb, swap_kb, kill_reason, mi, wi, tm);
Suren Baghdasaryan12cacae2019-09-16 12:06:30 -07002184
2185 if (kill_desc) {
Ioannis Ilkos48848902021-02-18 19:53:33 +00002186 ALOGI("Kill '%s' (%d), uid %d, oom_score_adj %d to free %" PRId64 "kB rss, %" PRId64
2187 "kB swap; reason: %s", taskname, pid, uid, procp->oomadj, rss_kb, swap_kb, kill_desc);
Suren Baghdasaryan89454e62019-07-15 15:50:17 -07002188 } else {
Ioannis Ilkos48848902021-02-18 19:53:33 +00002189 ALOGI("Kill '%s' (%d), uid %d, oom_score_adj %d to free %" PRId64 "kB rss, %" PRId64
2190 "kb swap", taskname, pid, uid, procp->oomadj, rss_kb, swap_kb);
Suren Baghdasaryan89454e62019-07-15 15:50:17 -07002191 }
Colin Cross3d57a512014-07-14 12:39:56 -07002192
Suren Baghdasaryan3cc1f132020-09-09 20:19:02 -07002193 kill_st.uid = static_cast<int32_t>(uid);
2194 kill_st.taskname = taskname;
2195 kill_st.kill_reason = kill_reason;
2196 kill_st.oom_score = procp->oomadj;
2197 kill_st.min_oom_score = min_oom_score;
2198 kill_st.free_mem_kb = mi->field.nr_free_pages * page_k;
2199 kill_st.free_swap_kb = mi->field.free_swap * page_k;
2200 stats_write_lmk_kill_occurred(&kill_st, mem_st);
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07002201
Jing Ji5c480962019-12-04 09:22:05 -08002202 ctrl_data_write_lmk_kill_occurred((pid_t)pid, uid);
2203
Ioannis Ilkos279268a2020-08-01 10:50:40 +01002204 result = rss_kb / page_k;
Mark Salyzyn1d5fdf32018-02-04 15:27:23 -08002205
Suren Baghdasaryan8b00c6d2018-10-12 11:28:33 -07002206out:
2207 /*
2208 * WARNING: After pid_remove() procp is freed and can't be used!
2209 * Therefore placed at the end of the function.
2210 */
2211 pid_remove(pid);
2212 return result;
Colin Cross3d57a512014-07-14 12:39:56 -07002213}
2214
2215/*
Chris Morin74b4df92021-02-26 00:00:35 -08002216 * Find one process to kill at or above the given oom_score_adj level.
Suren Baghdasaryan85c31b52018-10-26 11:32:15 -07002217 * Returns size of the killed process.
Colin Cross3d57a512014-07-14 12:39:56 -07002218 */
Suren Baghdasaryan3cc1f132020-09-09 20:19:02 -07002219static int find_and_kill_process(int min_score_adj, enum kill_reasons kill_reason,
2220 const char *kill_desc, union meminfo *mi,
2221 struct wakeup_info *wi, struct timespec *tm) {
Colin Cross3d57a512014-07-14 12:39:56 -07002222 int i;
Suren Baghdasaryan85c31b52018-10-26 11:32:15 -07002223 int killed_size = 0;
Yang Lu5dfffbc2018-05-15 04:59:44 +00002224 bool lmk_state_change_start = false;
Suren Baghdasaryan858e8c62021-03-03 11:05:09 -08002225 bool choose_heaviest_task = kill_heaviest_task;
Rajeev Kumar4aba9152018-01-31 17:54:56 -08002226
Chong Zhang1cd12b52015-10-14 16:19:53 -07002227 for (i = OOM_SCORE_ADJ_MAX; i >= min_score_adj; i--) {
Colin Cross3d57a512014-07-14 12:39:56 -07002228 struct proc *procp;
2229
Suren Baghdasaryan858e8c62021-03-03 11:05:09 -08002230 if (!choose_heaviest_task && i <= PERCEPTIBLE_APP_ADJ) {
2231 /*
2232 * If we have to choose a perceptible process, choose the heaviest one to
2233 * hopefully minimize the number of victims.
2234 */
2235 choose_heaviest_task = true;
2236 }
2237
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002238 while (true) {
Suren Baghdasaryan858e8c62021-03-03 11:05:09 -08002239 procp = choose_heaviest_task ?
Suren Baghdasaryan36b2c492018-04-13 11:49:54 -07002240 proc_get_heaviest(i) : proc_adj_lru(i);
Colin Cross3d57a512014-07-14 12:39:56 -07002241
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002242 if (!procp)
2243 break;
2244
Suren Baghdasaryand7b4fcb2020-07-23 18:00:43 -07002245 killed_size = kill_one_process(procp, min_score_adj, kill_reason, kill_desc,
2246 mi, wi, tm);
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002247 if (killed_size >= 0) {
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07002248 if (!lmk_state_change_start) {
Yang Lu5dfffbc2018-05-15 04:59:44 +00002249 lmk_state_change_start = true;
Vova Sharaienkoa92b76b2021-04-24 00:30:06 +00002250 stats_write_lmk_state_changed(STATE_START);
Yang Lu5dfffbc2018-05-15 04:59:44 +00002251 }
Suren Baghdasaryan85c31b52018-10-26 11:32:15 -07002252 break;
Colin Cross3d57a512014-07-14 12:39:56 -07002253 }
2254 }
Suren Baghdasaryan85c31b52018-10-26 11:32:15 -07002255 if (killed_size) {
2256 break;
2257 }
Colin Cross3d57a512014-07-14 12:39:56 -07002258 }
2259
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07002260 if (lmk_state_change_start) {
Vova Sharaienkoa92b76b2021-04-24 00:30:06 +00002261 stats_write_lmk_state_changed(STATE_STOP);
Rajeev Kumar4aba9152018-01-31 17:54:56 -08002262 }
Rajeev Kumar4aba9152018-01-31 17:54:56 -08002263
Suren Baghdasaryan85c31b52018-10-26 11:32:15 -07002264 return killed_size;
Colin Cross3d57a512014-07-14 12:39:56 -07002265}
2266
Suren Baghdasaryan87966742018-04-13 12:43:41 -07002267static int64_t get_memory_usage(struct reread_data *file_data) {
Robert Beneac72b2932017-08-21 15:18:31 -07002268 int64_t mem_usage;
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -07002269 char *buf;
Suren Baghdasaryan87966742018-04-13 12:43:41 -07002270
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -07002271 if ((buf = reread_file(file_data)) == NULL) {
Robert Beneac72b2932017-08-21 15:18:31 -07002272 return -1;
2273 }
2274
Suren Baghdasaryan87966742018-04-13 12:43:41 -07002275 if (!parse_int64(buf, &mem_usage)) {
2276 ALOGE("%s parse error", file_data->filename);
Robert Beneac72b2932017-08-21 15:18:31 -07002277 return -1;
2278 }
Robert Beneac72b2932017-08-21 15:18:31 -07002279 if (mem_usage == 0) {
2280 ALOGE("No memory!");
2281 return -1;
2282 }
2283 return mem_usage;
2284}
2285
Suren Baghdasaryane0f3dd12018-04-13 13:41:12 -07002286void record_low_pressure_levels(union meminfo *mi) {
2287 if (low_pressure_mem.min_nr_free_pages == -1 ||
2288 low_pressure_mem.min_nr_free_pages > mi->field.nr_free_pages) {
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002289 if (debug_process_killing) {
Suren Baghdasaryane0f3dd12018-04-13 13:41:12 -07002290 ALOGI("Low pressure min memory update from %" PRId64 " to %" PRId64,
2291 low_pressure_mem.min_nr_free_pages, mi->field.nr_free_pages);
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002292 }
Suren Baghdasaryane0f3dd12018-04-13 13:41:12 -07002293 low_pressure_mem.min_nr_free_pages = mi->field.nr_free_pages;
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002294 }
2295 /*
2296 * Free memory at low vmpressure events occasionally gets spikes,
2297 * possibly a stale low vmpressure event with memory already
2298 * freed up (no memory pressure should have been reported).
Suren Baghdasaryane0f3dd12018-04-13 13:41:12 -07002299 * Ignore large jumps in max_nr_free_pages that would mess up our stats.
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002300 */
Suren Baghdasaryane0f3dd12018-04-13 13:41:12 -07002301 if (low_pressure_mem.max_nr_free_pages == -1 ||
2302 (low_pressure_mem.max_nr_free_pages < mi->field.nr_free_pages &&
2303 mi->field.nr_free_pages - low_pressure_mem.max_nr_free_pages <
2304 low_pressure_mem.max_nr_free_pages * 0.1)) {
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002305 if (debug_process_killing) {
Suren Baghdasaryane0f3dd12018-04-13 13:41:12 -07002306 ALOGI("Low pressure max memory update from %" PRId64 " to %" PRId64,
2307 low_pressure_mem.max_nr_free_pages, mi->field.nr_free_pages);
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002308 }
Suren Baghdasaryane0f3dd12018-04-13 13:41:12 -07002309 low_pressure_mem.max_nr_free_pages = mi->field.nr_free_pages;
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002310 }
2311}
2312
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08002313enum vmpressure_level upgrade_level(enum vmpressure_level level) {
2314 return (enum vmpressure_level)((level < VMPRESS_LEVEL_CRITICAL) ?
2315 level + 1 : level);
2316}
2317
2318enum vmpressure_level downgrade_level(enum vmpressure_level level) {
2319 return (enum vmpressure_level)((level > VMPRESS_LEVEL_LOW) ?
2320 level - 1 : level);
2321}
2322
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002323enum zone_watermark {
2324 WMARK_MIN = 0,
2325 WMARK_LOW,
2326 WMARK_HIGH,
2327 WMARK_NONE
2328};
2329
Suren Baghdasaryan81c75b22019-08-14 09:48:35 -07002330struct zone_watermarks {
2331 long high_wmark;
2332 long low_wmark;
2333 long min_wmark;
2334};
2335
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002336/*
2337 * Returns lowest breached watermark or WMARK_NONE.
2338 */
Suren Baghdasaryan81c75b22019-08-14 09:48:35 -07002339static enum zone_watermark get_lowest_watermark(union meminfo *mi,
2340 struct zone_watermarks *watermarks)
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002341{
Suren Baghdasaryan81c75b22019-08-14 09:48:35 -07002342 int64_t nr_free_pages = mi->field.nr_free_pages - mi->field.cma_free;
2343
2344 if (nr_free_pages < watermarks->min_wmark) {
2345 return WMARK_MIN;
2346 }
2347 if (nr_free_pages < watermarks->low_wmark) {
2348 return WMARK_LOW;
2349 }
2350 if (nr_free_pages < watermarks->high_wmark) {
2351 return WMARK_HIGH;
2352 }
2353 return WMARK_NONE;
2354}
2355
2356void calc_zone_watermarks(struct zoneinfo *zi, struct zone_watermarks *watermarks) {
2357 memset(watermarks, 0, sizeof(struct zone_watermarks));
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002358
2359 for (int node_idx = 0; node_idx < zi->node_count; node_idx++) {
2360 struct zoneinfo_node *node = &zi->nodes[node_idx];
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002361 for (int zone_idx = 0; zone_idx < node->zone_count; zone_idx++) {
2362 struct zoneinfo_zone *zone = &node->zones[zone_idx];
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002363
2364 if (!zone->fields.field.present) {
2365 continue;
2366 }
2367
Suren Baghdasaryan81c75b22019-08-14 09:48:35 -07002368 watermarks->high_wmark += zone->max_protection + zone->fields.field.high;
2369 watermarks->low_wmark += zone->max_protection + zone->fields.field.low;
2370 watermarks->min_wmark += zone->max_protection + zone->fields.field.min;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002371 }
2372 }
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002373}
2374
Suren Baghdasaryan51ee4c52020-04-21 12:27:01 -07002375static int calc_swap_utilization(union meminfo *mi) {
2376 int64_t swap_used = mi->field.total_swap - mi->field.free_swap;
2377 int64_t total_swappable = mi->field.active_anon + mi->field.inactive_anon +
2378 mi->field.shmem + swap_used;
2379 return total_swappable > 0 ? (swap_used * 100) / total_swappable : 0;
2380}
2381
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002382static void mp_event_psi(int data, uint32_t events, struct polling_params *poll_params) {
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002383 enum reclaim_state {
2384 NO_RECLAIM = 0,
2385 KSWAPD_RECLAIM,
2386 DIRECT_RECLAIM,
2387 };
2388 static int64_t init_ws_refault;
Martin Liu1f72f5f2020-08-21 13:18:50 +08002389 static int64_t prev_workingset_refault;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002390 static int64_t base_file_lru;
2391 static int64_t init_pgscan_kswapd;
2392 static int64_t init_pgscan_direct;
2393 static int64_t swap_low_threshold;
2394 static bool killing;
Martin Liu1f72f5f2020-08-21 13:18:50 +08002395 static int thrashing_limit = thrashing_limit_pct;
Suren Baghdasaryan81c75b22019-08-14 09:48:35 -07002396 static struct zone_watermarks watermarks;
2397 static struct timespec wmark_update_tm;
Suren Baghdasaryand7b4fcb2020-07-23 18:00:43 -07002398 static struct wakeup_info wi;
Martin Liu1f72f5f2020-08-21 13:18:50 +08002399 static struct timespec thrashing_reset_tm;
2400 static int64_t prev_thrash_growth = 0;
Suren Baghdasaryan11221d42021-07-14 17:57:52 -07002401 static bool check_filecache = false;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002402
2403 union meminfo mi;
2404 union vmstat vs;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002405 struct timespec curr_tm;
2406 int64_t thrashing = 0;
2407 bool swap_is_low = false;
2408 enum vmpressure_level level = (enum vmpressure_level)data;
2409 enum kill_reasons kill_reason = NONE;
2410 bool cycle_after_kill = false;
2411 enum reclaim_state reclaim = NO_RECLAIM;
2412 enum zone_watermark wmark = WMARK_NONE;
Suren Baghdasaryan89454e62019-07-15 15:50:17 -07002413 char kill_desc[LINE_MAX];
Suren Baghdasaryan970a26a2019-09-19 15:27:21 -07002414 bool cut_thrashing_limit = false;
2415 int min_score_adj = 0;
Suren Baghdasaryan51ee4c52020-04-21 12:27:01 -07002416 int swap_util = 0;
Martin Liu1f72f5f2020-08-21 13:18:50 +08002417 long since_thrashing_reset_ms;
Suren Baghdasaryandc60f972020-12-14 13:38:48 -08002418 int64_t workingset_refault_file;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002419
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002420 if (clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm) != 0) {
2421 ALOGE("Failed to get current time");
2422 return;
2423 }
2424
Suren Baghdasaryand7b4fcb2020-07-23 18:00:43 -07002425 record_wakeup_time(&curr_tm, events ? Event : Polling, &wi);
2426
Suren Baghdasaryan03dccf32020-04-28 16:02:13 -07002427 bool kill_pending = is_kill_pending();
Suren Baghdasaryaned715a32020-05-11 16:31:57 -07002428 if (kill_pending && (kill_timeout_ms == 0 ||
2429 get_time_diff_ms(&last_kill_tm, &curr_tm) < static_cast<long>(kill_timeout_ms))) {
Suren Baghdasaryan03dccf32020-04-28 16:02:13 -07002430 /* Skip while still killing a process */
Suren Baghdasaryand7b4fcb2020-07-23 18:00:43 -07002431 wi.skipped_wakeups++;
Suren Baghdasaryan03dccf32020-04-28 16:02:13 -07002432 goto no_kill;
2433 }
2434 /*
2435 * Process is dead or kill timeout is over, stop waiting. This has no effect if pidfds are
2436 * supported and death notification already caused waiting to stop.
2437 */
2438 stop_wait_for_proc_kill(!kill_pending);
2439
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002440 if (vmstat_parse(&vs) < 0) {
2441 ALOGE("Failed to parse vmstat!");
2442 return;
2443 }
Suren Baghdasaryandc60f972020-12-14 13:38:48 -08002444 /* Starting 5.9 kernel workingset_refault vmstat field was renamed workingset_refault_file */
2445 workingset_refault_file = vs.field.workingset_refault ? : vs.field.workingset_refault_file;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002446
2447 if (meminfo_parse(&mi) < 0) {
2448 ALOGE("Failed to parse meminfo!");
2449 return;
2450 }
2451
2452 /* Reset states after process got killed */
2453 if (killing) {
2454 killing = false;
2455 cycle_after_kill = true;
2456 /* Reset file-backed pagecache size and refault amounts after a kill */
2457 base_file_lru = vs.field.nr_inactive_file + vs.field.nr_active_file;
Suren Baghdasaryandc60f972020-12-14 13:38:48 -08002458 init_ws_refault = workingset_refault_file;
Martin Liu1f72f5f2020-08-21 13:18:50 +08002459 thrashing_reset_tm = curr_tm;
2460 prev_thrash_growth = 0;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002461 }
2462
2463 /* Check free swap levels */
2464 if (swap_free_low_percentage) {
2465 if (!swap_low_threshold) {
2466 swap_low_threshold = mi.field.total_swap * swap_free_low_percentage / 100;
2467 }
2468 swap_is_low = mi.field.free_swap < swap_low_threshold;
2469 }
2470
2471 /* Identify reclaim state */
2472 if (vs.field.pgscan_direct > init_pgscan_direct) {
2473 init_pgscan_direct = vs.field.pgscan_direct;
2474 init_pgscan_kswapd = vs.field.pgscan_kswapd;
2475 reclaim = DIRECT_RECLAIM;
2476 } else if (vs.field.pgscan_kswapd > init_pgscan_kswapd) {
2477 init_pgscan_kswapd = vs.field.pgscan_kswapd;
2478 reclaim = KSWAPD_RECLAIM;
Suren Baghdasaryandc60f972020-12-14 13:38:48 -08002479 } else if (workingset_refault_file == prev_workingset_refault) {
Suren Baghdasaryan11221d42021-07-14 17:57:52 -07002480 /*
2481 * Device is not thrashing and not reclaiming, bail out early until we see these stats
2482 * changing
2483 */
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002484 goto no_kill;
2485 }
2486
Suren Baghdasaryandc60f972020-12-14 13:38:48 -08002487 prev_workingset_refault = workingset_refault_file;
Martin Liu1f72f5f2020-08-21 13:18:50 +08002488
2489 /*
2490 * It's possible we fail to find an eligible process to kill (ex. no process is
2491 * above oom_adj_min). When this happens, we should retry to find a new process
2492 * for a kill whenever a new eligible process is available. This is especially
2493 * important for a slow growing refault case. While retrying, we should keep
2494 * monitoring new thrashing counter as someone could release the memory to mitigate
2495 * the thrashing. Thus, when thrashing reset window comes, we decay the prev thrashing
Suren Baghdasaryan11221d42021-07-14 17:57:52 -07002496 * counter by window counts. If the counter is still greater than thrashing limit,
Martin Liu1f72f5f2020-08-21 13:18:50 +08002497 * we preserve the current prev_thrash counter so we will retry kill again. Otherwise,
2498 * we reset the prev_thrash counter so we will stop retrying.
2499 */
2500 since_thrashing_reset_ms = get_time_diff_ms(&thrashing_reset_tm, &curr_tm);
2501 if (since_thrashing_reset_ms > THRASHING_RESET_INTERVAL_MS) {
2502 long windows_passed;
2503 /* Calculate prev_thrash_growth if we crossed THRASHING_RESET_INTERVAL_MS */
Suren Baghdasaryandc60f972020-12-14 13:38:48 -08002504 prev_thrash_growth = (workingset_refault_file - init_ws_refault) * 100
Martin Liuc3108412020-09-03 22:12:14 +08002505 / (base_file_lru + 1);
Martin Liu1f72f5f2020-08-21 13:18:50 +08002506 windows_passed = (since_thrashing_reset_ms / THRASHING_RESET_INTERVAL_MS);
2507 /*
2508 * Decay prev_thrashing unless over-the-limit thrashing was registered in the window we
2509 * just crossed, which means there were no eligible processes to kill. We preserve the
2510 * counter in that case to ensure a kill if a new eligible process appears.
2511 */
2512 if (windows_passed > 1 || prev_thrash_growth < thrashing_limit) {
2513 prev_thrash_growth >>= windows_passed;
2514 }
2515
2516 /* Record file-backed pagecache size when crossing THRASHING_RESET_INTERVAL_MS */
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002517 base_file_lru = vs.field.nr_inactive_file + vs.field.nr_active_file;
Suren Baghdasaryandc60f972020-12-14 13:38:48 -08002518 init_ws_refault = workingset_refault_file;
Martin Liu1f72f5f2020-08-21 13:18:50 +08002519 thrashing_reset_tm = curr_tm;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002520 thrashing_limit = thrashing_limit_pct;
2521 } else {
2522 /* Calculate what % of the file-backed pagecache refaulted so far */
Suren Baghdasaryandc60f972020-12-14 13:38:48 -08002523 thrashing = (workingset_refault_file - init_ws_refault) * 100 / (base_file_lru + 1);
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002524 }
Martin Liu1f72f5f2020-08-21 13:18:50 +08002525 /* Add previous cycle's decayed thrashing amount */
2526 thrashing += prev_thrash_growth;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002527
Suren Baghdasaryan81c75b22019-08-14 09:48:35 -07002528 /*
2529 * Refresh watermarks once per min in case user updated one of the margins.
2530 * TODO: b/140521024 replace this periodic update with an API for AMS to notify LMKD
2531 * that zone watermarks were changed by the system software.
2532 */
2533 if (watermarks.high_wmark == 0 || get_time_diff_ms(&wmark_update_tm, &curr_tm) > 60000) {
2534 struct zoneinfo zi;
2535
2536 if (zoneinfo_parse(&zi) < 0) {
2537 ALOGE("Failed to parse zoneinfo!");
2538 return;
2539 }
2540
2541 calc_zone_watermarks(&zi, &watermarks);
2542 wmark_update_tm = curr_tm;
Martin Liu1f72f5f2020-08-21 13:18:50 +08002543 }
Suren Baghdasaryan81c75b22019-08-14 09:48:35 -07002544
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002545 /* Find out which watermark is breached if any */
Suren Baghdasaryan81c75b22019-08-14 09:48:35 -07002546 wmark = get_lowest_watermark(&mi, &watermarks);
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002547
2548 /*
2549 * TODO: move this logic into a separate function
2550 * Decide if killing a process is necessary and record the reason
2551 */
2552 if (cycle_after_kill && wmark < WMARK_LOW) {
2553 /*
2554 * Prevent kills not freeing enough memory which might lead to OOM kill.
2555 * This might happen when a process is consuming memory faster than reclaim can
2556 * free even after a kill. Mostly happens when running memory stress tests.
2557 */
2558 kill_reason = PRESSURE_AFTER_KILL;
Suren Baghdasaryan89454e62019-07-15 15:50:17 -07002559 strncpy(kill_desc, "min watermark is breached even after kill", sizeof(kill_desc));
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002560 } else if (level == VMPRESS_LEVEL_CRITICAL && events != 0) {
2561 /*
2562 * Device is too busy reclaiming memory which might lead to ANR.
2563 * Critical level is triggered when PSI complete stall (all tasks are blocked because
2564 * of the memory congestion) breaches the configured threshold.
2565 */
2566 kill_reason = NOT_RESPONDING;
Suren Baghdasaryan89454e62019-07-15 15:50:17 -07002567 strncpy(kill_desc, "device is not responding", sizeof(kill_desc));
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002568 } else if (swap_is_low && thrashing > thrashing_limit_pct) {
2569 /* Page cache is thrashing while swap is low */
2570 kill_reason = LOW_SWAP_AND_THRASHING;
Suren Baghdasaryan89454e62019-07-15 15:50:17 -07002571 snprintf(kill_desc, sizeof(kill_desc), "device is low on swap (%" PRId64
2572 "kB < %" PRId64 "kB) and thrashing (%" PRId64 "%%)",
2573 mi.field.free_swap * page_k, swap_low_threshold * page_k, thrashing);
Suren Baghdasaryan0142b3c2021-03-03 11:11:09 -08002574 /* Do not kill perceptible apps unless below min watermark or heavily thrashing */
2575 if (wmark > WMARK_MIN && thrashing < thrashing_critical_pct) {
Suren Baghdasaryan48135c42020-05-19 12:59:18 -07002576 min_score_adj = PERCEPTIBLE_APP_ADJ + 1;
2577 }
Suren Baghdasaryan11221d42021-07-14 17:57:52 -07002578 check_filecache = true;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002579 } else if (swap_is_low && wmark < WMARK_HIGH) {
2580 /* Both free memory and swap are low */
2581 kill_reason = LOW_MEM_AND_SWAP;
Suren Baghdasaryan89454e62019-07-15 15:50:17 -07002582 snprintf(kill_desc, sizeof(kill_desc), "%s watermark is breached and swap is low (%"
Suren Baghdasaryan23678182021-03-02 18:33:09 -08002583 PRId64 "kB < %" PRId64 "kB)", wmark < WMARK_LOW ? "min" : "low",
Suren Baghdasaryan89454e62019-07-15 15:50:17 -07002584 mi.field.free_swap * page_k, swap_low_threshold * page_k);
Suren Baghdasaryan0142b3c2021-03-03 11:11:09 -08002585 /* Do not kill perceptible apps unless below min watermark or heavily thrashing */
2586 if (wmark > WMARK_MIN && thrashing < thrashing_critical_pct) {
Suren Baghdasaryan48135c42020-05-19 12:59:18 -07002587 min_score_adj = PERCEPTIBLE_APP_ADJ + 1;
2588 }
Suren Baghdasaryan51ee4c52020-04-21 12:27:01 -07002589 } else if (wmark < WMARK_HIGH && swap_util_max < 100 &&
2590 (swap_util = calc_swap_utilization(&mi)) > swap_util_max) {
2591 /*
2592 * Too much anon memory is swapped out but swap is not low.
2593 * Non-swappable allocations created memory pressure.
2594 */
2595 kill_reason = LOW_MEM_AND_SWAP_UTIL;
2596 snprintf(kill_desc, sizeof(kill_desc), "%s watermark is breached and swap utilization"
Suren Baghdasaryan23678182021-03-02 18:33:09 -08002597 " is high (%d%% > %d%%)", wmark < WMARK_LOW ? "min" : "low",
Suren Baghdasaryan51ee4c52020-04-21 12:27:01 -07002598 swap_util, swap_util_max);
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002599 } else if (wmark < WMARK_HIGH && thrashing > thrashing_limit) {
2600 /* Page cache is thrashing while memory is low */
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002601 kill_reason = LOW_MEM_AND_THRASHING;
Suren Baghdasaryan89454e62019-07-15 15:50:17 -07002602 snprintf(kill_desc, sizeof(kill_desc), "%s watermark is breached and thrashing (%"
Suren Baghdasaryan23678182021-03-02 18:33:09 -08002603 PRId64 "%%)", wmark < WMARK_LOW ? "min" : "low", thrashing);
Suren Baghdasaryan970a26a2019-09-19 15:27:21 -07002604 cut_thrashing_limit = true;
Suren Baghdasaryan0142b3c2021-03-03 11:11:09 -08002605 /* Do not kill perceptible apps unless thrashing at critical levels */
2606 if (thrashing < thrashing_critical_pct) {
2607 min_score_adj = PERCEPTIBLE_APP_ADJ + 1;
2608 }
Suren Baghdasaryan11221d42021-07-14 17:57:52 -07002609 check_filecache = true;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002610 } else if (reclaim == DIRECT_RECLAIM && thrashing > thrashing_limit) {
2611 /* Page cache is thrashing while in direct reclaim (mostly happens on lowram devices) */
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002612 kill_reason = DIRECT_RECL_AND_THRASHING;
Suren Baghdasaryan89454e62019-07-15 15:50:17 -07002613 snprintf(kill_desc, sizeof(kill_desc), "device is in direct reclaim and thrashing (%"
2614 PRId64 "%%)", thrashing);
Suren Baghdasaryan970a26a2019-09-19 15:27:21 -07002615 cut_thrashing_limit = true;
Suren Baghdasaryan0142b3c2021-03-03 11:11:09 -08002616 /* Do not kill perceptible apps unless thrashing at critical levels */
2617 if (thrashing < thrashing_critical_pct) {
2618 min_score_adj = PERCEPTIBLE_APP_ADJ + 1;
2619 }
Suren Baghdasaryan11221d42021-07-14 17:57:52 -07002620 check_filecache = true;
2621 } else if (check_filecache) {
2622 int64_t file_lru_kb = (vs.field.nr_inactive_file + vs.field.nr_active_file) * page_k;
2623
2624 if (file_lru_kb < filecache_min_kb) {
2625 /* File cache is too low after thrashing, keep killing background processes */
2626 kill_reason = LOW_FILECACHE_AFTER_THRASHING;
2627 snprintf(kill_desc, sizeof(kill_desc),
2628 "filecache is low (%" PRId64 "kB < %" PRId64 "kB) after thrashing",
2629 file_lru_kb, filecache_min_kb);
2630 min_score_adj = PERCEPTIBLE_APP_ADJ + 1;
2631 } else {
2632 /* File cache is big enough, stop checking */
2633 check_filecache = false;
2634 }
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002635 }
2636
2637 /* Kill a process if necessary */
2638 if (kill_reason != NONE) {
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002639 int pages_freed = find_and_kill_process(min_score_adj, kill_reason, kill_desc, &mi,
Suren Baghdasaryand7b4fcb2020-07-23 18:00:43 -07002640 &wi, &curr_tm);
Suren Baghdasaryan970a26a2019-09-19 15:27:21 -07002641 if (pages_freed > 0) {
2642 killing = true;
2643 if (cut_thrashing_limit) {
2644 /*
2645 * Cut thrasing limit by thrashing_limit_decay_pct percentage of the current
2646 * thrashing limit until the system stops thrashing.
2647 */
2648 thrashing_limit = (thrashing_limit * (100 - thrashing_limit_decay_pct)) / 100;
2649 }
2650 }
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002651 }
2652
2653no_kill:
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002654 /* Do not poll if kernel supports pidfd waiting */
2655 if (is_waiting_for_kill()) {
2656 /* Pause polling if we are waiting for process death notification */
2657 poll_params->update = POLLING_PAUSE;
2658 return;
2659 }
2660
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002661 /*
2662 * Start polling after initial PSI event;
2663 * extend polling while device is in direct reclaim or process is being killed;
2664 * do not extend when kswapd reclaims because that might go on for a long time
2665 * without causing memory pressure
2666 */
2667 if (events || killing || reclaim == DIRECT_RECLAIM) {
2668 poll_params->update = POLLING_START;
2669 }
2670
2671 /* Decide the polling interval */
2672 if (swap_is_low || killing) {
2673 /* Fast polling during and after a kill or when swap is low */
2674 poll_params->polling_interval_ms = PSI_POLL_PERIOD_SHORT_MS;
2675 } else {
2676 /* By default use long intervals */
2677 poll_params->polling_interval_ms = PSI_POLL_PERIOD_LONG_MS;
2678 }
2679}
2680
Suren Baghdasaryane12a0672019-07-15 14:50:49 -07002681static void mp_event_common(int data, uint32_t events, struct polling_params *poll_params) {
Todd Poynorc58c5142013-07-09 19:35:14 -07002682 unsigned long long evcount;
Robert Beneac72b2932017-08-21 15:18:31 -07002683 int64_t mem_usage, memsw_usage;
Robert Benea3be16142017-09-13 15:20:30 -07002684 int64_t mem_pressure;
Suren Baghdasaryane0f3dd12018-04-13 13:41:12 -07002685 union meminfo mi;
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07002686 struct zoneinfo zi;
Suren Baghdasaryan53be36e2018-09-05 15:46:32 -07002687 struct timespec curr_tm;
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -07002688 static unsigned long kill_skip_count = 0;
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08002689 enum vmpressure_level level = (enum vmpressure_level)data;
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07002690 long other_free = 0, other_file = 0;
2691 int min_score_adj;
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07002692 int minfree = 0;
Suren Baghdasaryan87966742018-04-13 12:43:41 -07002693 static struct reread_data mem_usage_file_data = {
2694 .filename = MEMCG_MEMORY_USAGE,
2695 .fd = -1,
2696 };
2697 static struct reread_data memsw_usage_file_data = {
2698 .filename = MEMCG_MEMORYSW_USAGE,
2699 .fd = -1,
2700 };
Suren Baghdasaryand7b4fcb2020-07-23 18:00:43 -07002701 static struct wakeup_info wi;
Todd Poynorc58c5142013-07-09 19:35:14 -07002702
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08002703 if (debug_process_killing) {
2704 ALOGI("%s memory pressure event is triggered", level_name[level]);
2705 }
2706
2707 if (!use_psi_monitors) {
2708 /*
2709 * Check all event counters from low to critical
2710 * and upgrade to the highest priority one. By reading
2711 * eventfd we also reset the event counters.
2712 */
Tom Cherry43f3d2b2019-12-04 12:46:57 -08002713 for (int lvl = VMPRESS_LEVEL_LOW; lvl < VMPRESS_LEVEL_COUNT; lvl++) {
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08002714 if (mpevfd[lvl] != -1 &&
2715 TEMP_FAILURE_RETRY(read(mpevfd[lvl],
2716 &evcount, sizeof(evcount))) > 0 &&
2717 evcount > 0 && lvl > level) {
Tom Cherry43f3d2b2019-12-04 12:46:57 -08002718 level = static_cast<vmpressure_level>(lvl);
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08002719 }
Suren Baghdasaryan3e1a8492018-01-04 09:16:21 -08002720 }
2721 }
Todd Poynorc58c5142013-07-09 19:35:14 -07002722
Suren Baghdasaryane12a0672019-07-15 14:50:49 -07002723 /* Start polling after initial PSI event */
2724 if (use_psi_monitors && events) {
2725 /* Override polling params only if current event is more critical */
2726 if (!poll_params->poll_handler || data > poll_params->poll_handler->data) {
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002727 poll_params->polling_interval_ms = PSI_POLL_PERIOD_SHORT_MS;
Suren Baghdasaryane12a0672019-07-15 14:50:49 -07002728 poll_params->update = POLLING_START;
2729 }
2730 }
2731
Suren Baghdasaryan53be36e2018-09-05 15:46:32 -07002732 if (clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm) != 0) {
2733 ALOGE("Failed to get current time");
2734 return;
2735 }
2736
Suren Baghdasaryand7b4fcb2020-07-23 18:00:43 -07002737 record_wakeup_time(&curr_tm, events ? Event : Polling, &wi);
2738
Suren Baghdasaryaned715a32020-05-11 16:31:57 -07002739 if (kill_timeout_ms &&
2740 get_time_diff_ms(&last_kill_tm, &curr_tm) < static_cast<long>(kill_timeout_ms)) {
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002741 /*
2742 * If we're within the no-kill timeout, see if there's pending reclaim work
2743 * from the last killed process. If so, skip killing for now.
2744 */
2745 if (is_kill_pending()) {
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -07002746 kill_skip_count++;
Suren Baghdasaryand7b4fcb2020-07-23 18:00:43 -07002747 wi.skipped_wakeups++;
Suren Baghdasaryan30854e72018-01-17 17:28:01 -08002748 return;
2749 }
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002750 /*
2751 * Process is dead, stop waiting. This has no effect if pidfds are supported and
2752 * death notification already caused waiting to stop.
2753 */
2754 stop_wait_for_proc_kill(true);
2755 } else {
2756 /*
2757 * Killing took longer than no-kill timeout. Stop waiting for the last process
2758 * to die because we are ready to kill again.
2759 */
2760 stop_wait_for_proc_kill(false);
Suren Baghdasaryan30854e72018-01-17 17:28:01 -08002761 }
2762
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -07002763 if (kill_skip_count > 0) {
Suren Baghdasaryaneff82332018-05-10 16:10:56 -07002764 ALOGI("%lu memory pressure events were skipped after a kill!",
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -07002765 kill_skip_count);
2766 kill_skip_count = 0;
Suren Baghdasaryan30854e72018-01-17 17:28:01 -08002767 }
2768
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07002769 if (meminfo_parse(&mi) < 0 || zoneinfo_parse(&zi) < 0) {
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002770 ALOGE("Failed to get free memory!");
2771 return;
2772 }
2773
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07002774 if (use_minfree_levels) {
2775 int i;
2776
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07002777 other_free = mi.field.nr_free_pages - zi.totalreserve_pages;
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07002778 if (mi.field.nr_file_pages > (mi.field.shmem + mi.field.unevictable + mi.field.swap_cached)) {
2779 other_file = (mi.field.nr_file_pages - mi.field.shmem -
2780 mi.field.unevictable - mi.field.swap_cached);
2781 } else {
2782 other_file = 0;
2783 }
2784
2785 min_score_adj = OOM_SCORE_ADJ_MAX + 1;
2786 for (i = 0; i < lowmem_targets_size; i++) {
2787 minfree = lowmem_minfree[i];
2788 if (other_free < minfree && other_file < minfree) {
2789 min_score_adj = lowmem_adj[i];
2790 break;
2791 }
2792 }
2793
Suren Baghdasaryanb0bda552018-05-18 14:42:00 -07002794 if (min_score_adj == OOM_SCORE_ADJ_MAX + 1) {
2795 if (debug_process_killing) {
2796 ALOGI("Ignore %s memory pressure event "
2797 "(free memory=%ldkB, cache=%ldkB, limit=%ldkB)",
2798 level_name[level], other_free * page_k, other_file * page_k,
2799 (long)lowmem_minfree[lowmem_targets_size - 1] * page_k);
2800 }
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07002801 return;
Suren Baghdasaryanb0bda552018-05-18 14:42:00 -07002802 }
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07002803
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07002804 goto do_kill;
2805 }
2806
Suren Baghdasaryane0f3dd12018-04-13 13:41:12 -07002807 if (level == VMPRESS_LEVEL_LOW) {
2808 record_low_pressure_levels(&mi);
2809 }
2810
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002811 if (level_oomadj[level] > OOM_SCORE_ADJ_MAX) {
2812 /* Do not monitor this pressure level */
2813 return;
2814 }
2815
Suren Baghdasaryan87966742018-04-13 12:43:41 -07002816 if ((mem_usage = get_memory_usage(&mem_usage_file_data)) < 0) {
2817 goto do_kill;
2818 }
2819 if ((memsw_usage = get_memory_usage(&memsw_usage_file_data)) < 0) {
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08002820 goto do_kill;
Robert Benea3be16142017-09-13 15:20:30 -07002821 }
Robert Beneac72b2932017-08-21 15:18:31 -07002822
Robert Benea3be16142017-09-13 15:20:30 -07002823 // Calculate percent for swappinness.
2824 mem_pressure = (mem_usage * 100) / memsw_usage;
2825
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08002826 if (enable_pressure_upgrade && level != VMPRESS_LEVEL_CRITICAL) {
Robert Benea3be16142017-09-13 15:20:30 -07002827 // We are swapping too much.
2828 if (mem_pressure < upgrade_pressure) {
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08002829 level = upgrade_level(level);
2830 if (debug_process_killing) {
2831 ALOGI("Event upgraded to %s", level_name[level]);
2832 }
Robert Beneac72b2932017-08-21 15:18:31 -07002833 }
2834 }
2835
Vic Yang65680692018-08-07 10:18:22 -07002836 // If we still have enough swap space available, check if we want to
2837 // ignore/downgrade pressure events.
2838 if (mi.field.free_swap >=
2839 mi.field.total_swap * swap_free_low_percentage / 100) {
2840 // If the pressure is larger than downgrade_pressure lmk will not
2841 // kill any process, since enough memory is available.
2842 if (mem_pressure > downgrade_pressure) {
2843 if (debug_process_killing) {
2844 ALOGI("Ignore %s memory pressure", level_name[level]);
2845 }
2846 return;
2847 } else if (level == VMPRESS_LEVEL_CRITICAL && mem_pressure > upgrade_pressure) {
2848 if (debug_process_killing) {
2849 ALOGI("Downgrade critical memory pressure");
2850 }
2851 // Downgrade event, since enough memory available.
2852 level = downgrade_level(level);
Robert Benea3be16142017-09-13 15:20:30 -07002853 }
Robert Benea3be16142017-09-13 15:20:30 -07002854 }
2855
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08002856do_kill:
Suren Baghdasaryand1d59f82018-04-13 11:45:38 -07002857 if (low_ram_device) {
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002858 /* For Go devices kill only one task */
Suren Baghdasaryan3cc1f132020-09-09 20:19:02 -07002859 if (find_and_kill_process(level_oomadj[level], NONE, NULL, &mi, &wi, &curr_tm) == 0) {
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002860 if (debug_process_killing) {
2861 ALOGI("Nothing to kill");
2862 }
2863 }
2864 } else {
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07002865 int pages_freed;
Suren Baghdasaryan53be36e2018-09-05 15:46:32 -07002866 static struct timespec last_report_tm;
2867 static unsigned long report_skip_count = 0;
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07002868
2869 if (!use_minfree_levels) {
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07002870 /* Free up enough memory to downgrate the memory pressure to low level */
Suren Baghdasaryan85c31b52018-10-26 11:32:15 -07002871 if (mi.field.nr_free_pages >= low_pressure_mem.max_nr_free_pages) {
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07002872 if (debug_process_killing) {
2873 ALOGI("Ignoring pressure since more memory is "
2874 "available (%" PRId64 ") than watermark (%" PRId64 ")",
2875 mi.field.nr_free_pages, low_pressure_mem.max_nr_free_pages);
2876 }
2877 return;
2878 }
2879 min_score_adj = level_oomadj[level];
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002880 }
2881
Suren Baghdasaryan3cc1f132020-09-09 20:19:02 -07002882 pages_freed = find_and_kill_process(min_score_adj, NONE, NULL, &mi, &wi, &curr_tm);
Suren Baghdasaryaneff82332018-05-10 16:10:56 -07002883
Suren Baghdasaryan53be36e2018-09-05 15:46:32 -07002884 if (pages_freed == 0) {
2885 /* Rate limit kill reports when nothing was reclaimed */
2886 if (get_time_diff_ms(&last_report_tm, &curr_tm) < FAIL_REPORT_RLIMIT_MS) {
2887 report_skip_count++;
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -07002888 return;
2889 }
Robert Benea7f68a3f2017-08-11 16:03:20 -07002890 }
Suren Baghdasaryan53be36e2018-09-05 15:46:32 -07002891
Suren Baghdasaryan12cacae2019-09-16 12:06:30 -07002892 /* Log whenever we kill or when report rate limit allows */
Suren Baghdasaryan53be36e2018-09-05 15:46:32 -07002893 if (use_minfree_levels) {
Chris Morin74b4df92021-02-26 00:00:35 -08002894 ALOGI("Reclaimed %ldkB, cache(%ldkB) and free(%" PRId64 "kB)-reserved(%" PRId64 "kB) "
2895 "below min(%ldkB) for oom_score_adj %d",
Suren Baghdasaryan85c31b52018-10-26 11:32:15 -07002896 pages_freed * page_k,
Suren Baghdasaryan53be36e2018-09-05 15:46:32 -07002897 other_file * page_k, mi.field.nr_free_pages * page_k,
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07002898 zi.totalreserve_pages * page_k,
Suren Baghdasaryan53be36e2018-09-05 15:46:32 -07002899 minfree * page_k, min_score_adj);
2900 } else {
Chris Morin74b4df92021-02-26 00:00:35 -08002901 ALOGI("Reclaimed %ldkB at oom_score_adj %d", pages_freed * page_k, min_score_adj);
Suren Baghdasaryan53be36e2018-09-05 15:46:32 -07002902 }
2903
2904 if (report_skip_count > 0) {
2905 ALOGI("Suppressed %lu failed kill reports", report_skip_count);
2906 report_skip_count = 0;
2907 }
2908
2909 last_report_tm = curr_tm;
Colin Cross01db2712014-07-11 17:16:56 -07002910 }
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002911 if (is_waiting_for_kill()) {
2912 /* pause polling if we are waiting for process death notification */
2913 poll_params->update = POLLING_PAUSE;
2914 }
Todd Poynorc58c5142013-07-09 19:35:14 -07002915}
2916
Suren Baghdasaryan2f88e152019-07-15 15:42:09 -07002917static bool init_mp_psi(enum vmpressure_level level, bool use_new_strategy) {
2918 int fd;
2919
2920 /* Do not register a handler if threshold_ms is not set */
2921 if (!psi_thresholds[level].threshold_ms) {
2922 return true;
2923 }
2924
2925 fd = init_psi_monitor(psi_thresholds[level].stall_type,
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08002926 psi_thresholds[level].threshold_ms * US_PER_MS,
2927 PSI_WINDOW_SIZE_MS * US_PER_MS);
2928
2929 if (fd < 0) {
2930 return false;
2931 }
2932
Suren Baghdasaryan2f88e152019-07-15 15:42:09 -07002933 vmpressure_hinfo[level].handler = use_new_strategy ? mp_event_psi : mp_event_common;
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08002934 vmpressure_hinfo[level].data = level;
2935 if (register_psi_monitor(epollfd, fd, &vmpressure_hinfo[level]) < 0) {
2936 destroy_psi_monitor(fd);
2937 return false;
2938 }
2939 maxevents++;
2940 mpevfd[level] = fd;
2941
2942 return true;
2943}
2944
2945static void destroy_mp_psi(enum vmpressure_level level) {
2946 int fd = mpevfd[level];
2947
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07002948 if (fd < 0) {
2949 return;
2950 }
2951
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08002952 if (unregister_psi_monitor(epollfd, fd) < 0) {
2953 ALOGE("Failed to unregister psi monitor for %s memory pressure; errno=%d",
2954 level_name[level], errno);
2955 }
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07002956 maxevents--;
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08002957 destroy_psi_monitor(fd);
2958 mpevfd[level] = -1;
2959}
2960
2961static bool init_psi_monitors() {
Suren Baghdasaryan2f88e152019-07-15 15:42:09 -07002962 /*
2963 * When PSI is used on low-ram devices or on high-end devices without memfree levels
2964 * use new kill strategy based on zone watermarks, free swap and thrashing stats
2965 */
2966 bool use_new_strategy =
2967 property_get_bool("ro.lmk.use_new_strategy", low_ram_device || !use_minfree_levels);
2968
2969 /* In default PSI mode override stall amounts using system properties */
2970 if (use_new_strategy) {
2971 /* Do not use low pressure level */
2972 psi_thresholds[VMPRESS_LEVEL_LOW].threshold_ms = 0;
2973 psi_thresholds[VMPRESS_LEVEL_MEDIUM].threshold_ms = psi_partial_stall_ms;
2974 psi_thresholds[VMPRESS_LEVEL_CRITICAL].threshold_ms = psi_complete_stall_ms;
2975 }
2976
2977 if (!init_mp_psi(VMPRESS_LEVEL_LOW, use_new_strategy)) {
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08002978 return false;
2979 }
Suren Baghdasaryan2f88e152019-07-15 15:42:09 -07002980 if (!init_mp_psi(VMPRESS_LEVEL_MEDIUM, use_new_strategy)) {
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08002981 destroy_mp_psi(VMPRESS_LEVEL_LOW);
2982 return false;
2983 }
Suren Baghdasaryan2f88e152019-07-15 15:42:09 -07002984 if (!init_mp_psi(VMPRESS_LEVEL_CRITICAL, use_new_strategy)) {
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08002985 destroy_mp_psi(VMPRESS_LEVEL_MEDIUM);
2986 destroy_mp_psi(VMPRESS_LEVEL_LOW);
2987 return false;
2988 }
2989 return true;
2990}
2991
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08002992static bool init_mp_common(enum vmpressure_level level) {
Todd Poynorc58c5142013-07-09 19:35:14 -07002993 int mpfd;
2994 int evfd;
2995 int evctlfd;
2996 char buf[256];
2997 struct epoll_event epev;
2998 int ret;
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08002999 int level_idx = (int)level;
3000 const char *levelstr = level_name[level_idx];
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08003001
Mark Salyzyna00ccd82018-04-09 09:50:32 -07003002 /* gid containing AID_SYSTEM required */
Nick Kralevich148d8dd2015-12-18 20:52:37 -08003003 mpfd = open(MEMCG_SYSFS_PATH "memory.pressure_level", O_RDONLY | O_CLOEXEC);
Todd Poynorc58c5142013-07-09 19:35:14 -07003004 if (mpfd < 0) {
3005 ALOGI("No kernel memory.pressure_level support (errno=%d)", errno);
3006 goto err_open_mpfd;
3007 }
3008
Nick Kralevich148d8dd2015-12-18 20:52:37 -08003009 evctlfd = open(MEMCG_SYSFS_PATH "cgroup.event_control", O_WRONLY | O_CLOEXEC);
Todd Poynorc58c5142013-07-09 19:35:14 -07003010 if (evctlfd < 0) {
3011 ALOGI("No kernel memory cgroup event control (errno=%d)", errno);
3012 goto err_open_evctlfd;
3013 }
3014
Nick Kralevich148d8dd2015-12-18 20:52:37 -08003015 evfd = eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC);
Todd Poynorc58c5142013-07-09 19:35:14 -07003016 if (evfd < 0) {
3017 ALOGE("eventfd failed for level %s; errno=%d", levelstr, errno);
3018 goto err_eventfd;
3019 }
3020
3021 ret = snprintf(buf, sizeof(buf), "%d %d %s", evfd, mpfd, levelstr);
3022 if (ret >= (ssize_t)sizeof(buf)) {
3023 ALOGE("cgroup.event_control line overflow for level %s", levelstr);
3024 goto err;
3025 }
3026
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003027 ret = TEMP_FAILURE_RETRY(write(evctlfd, buf, strlen(buf) + 1));
Todd Poynorc58c5142013-07-09 19:35:14 -07003028 if (ret == -1) {
3029 ALOGE("cgroup.event_control write failed for level %s; errno=%d",
3030 levelstr, errno);
3031 goto err;
3032 }
3033
3034 epev.events = EPOLLIN;
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003035 /* use data to store event level */
3036 vmpressure_hinfo[level_idx].data = level_idx;
3037 vmpressure_hinfo[level_idx].handler = mp_event_common;
3038 epev.data.ptr = (void *)&vmpressure_hinfo[level_idx];
Todd Poynorc58c5142013-07-09 19:35:14 -07003039 ret = epoll_ctl(epollfd, EPOLL_CTL_ADD, evfd, &epev);
3040 if (ret == -1) {
3041 ALOGE("epoll_ctl for level %s failed; errno=%d", levelstr, errno);
3042 goto err;
3043 }
3044 maxevents++;
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08003045 mpevfd[level] = evfd;
Suren Baghdasaryanceffaf22018-01-04 08:54:53 -08003046 close(evctlfd);
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08003047 return true;
Todd Poynorc58c5142013-07-09 19:35:14 -07003048
3049err:
3050 close(evfd);
3051err_eventfd:
3052 close(evctlfd);
3053err_open_evctlfd:
3054 close(mpfd);
3055err_open_mpfd:
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08003056 return false;
Robert Benea58d6a132017-06-01 16:32:31 -07003057}
3058
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07003059static void destroy_mp_common(enum vmpressure_level level) {
3060 struct epoll_event epev;
3061 int fd = mpevfd[level];
3062
3063 if (fd < 0) {
3064 return;
3065 }
3066
3067 if (epoll_ctl(epollfd, EPOLL_CTL_DEL, fd, &epev)) {
3068 // Log an error and keep going
3069 ALOGE("epoll_ctl for level %s failed; errno=%d", level_name[level], errno);
3070 }
3071 maxevents--;
3072 close(fd);
3073 mpevfd[level] = -1;
3074}
3075
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07003076static void kernel_event_handler(int data __unused, uint32_t events __unused,
3077 struct polling_params *poll_params __unused) {
Jing Ji5c480962019-12-04 09:22:05 -08003078 poll_kernel(kpoll_fd);
Jim Blackler700b7192019-04-26 11:18:29 +01003079}
3080
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07003081static bool init_monitors() {
3082 /* Try to use psi monitor first if kernel has it */
3083 use_psi_monitors = property_get_bool("ro.lmk.use_psi", true) &&
3084 init_psi_monitors();
3085 /* Fall back to vmpressure */
3086 if (!use_psi_monitors &&
3087 (!init_mp_common(VMPRESS_LEVEL_LOW) ||
3088 !init_mp_common(VMPRESS_LEVEL_MEDIUM) ||
3089 !init_mp_common(VMPRESS_LEVEL_CRITICAL))) {
3090 ALOGE("Kernel does not support memory pressure events or in-kernel low memory killer");
3091 return false;
3092 }
3093 if (use_psi_monitors) {
3094 ALOGI("Using psi monitors for memory pressure detection");
3095 } else {
3096 ALOGI("Using vmpressure for memory pressure detection");
3097 }
3098 return true;
3099}
3100
3101static void destroy_monitors() {
3102 if (use_psi_monitors) {
3103 destroy_mp_psi(VMPRESS_LEVEL_CRITICAL);
3104 destroy_mp_psi(VMPRESS_LEVEL_MEDIUM);
3105 destroy_mp_psi(VMPRESS_LEVEL_LOW);
3106 } else {
3107 destroy_mp_common(VMPRESS_LEVEL_CRITICAL);
3108 destroy_mp_common(VMPRESS_LEVEL_MEDIUM);
3109 destroy_mp_common(VMPRESS_LEVEL_LOW);
3110 }
3111}
3112
Todd Poynorc58c5142013-07-09 19:35:14 -07003113static int init(void) {
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07003114 static struct event_handler_info kernel_poll_hinfo = { 0, kernel_event_handler };
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -07003115 struct reread_data file_data = {
3116 .filename = ZONEINFO_PATH,
3117 .fd = -1,
3118 };
Todd Poynorc58c5142013-07-09 19:35:14 -07003119 struct epoll_event epev;
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003120 int pidfd;
Todd Poynorc58c5142013-07-09 19:35:14 -07003121 int i;
3122 int ret;
3123
3124 page_k = sysconf(_SC_PAGESIZE);
3125 if (page_k == -1)
3126 page_k = PAGE_SIZE;
3127 page_k /= 1024;
3128
3129 epollfd = epoll_create(MAX_EPOLL_EVENTS);
3130 if (epollfd == -1) {
3131 ALOGE("epoll_create failed (errno=%d)", errno);
3132 return -1;
3133 }
3134
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003135 // mark data connections as not connected
3136 for (int i = 0; i < MAX_DATA_CONN; i++) {
3137 data_sock[i].sock = -1;
3138 }
3139
3140 ctrl_sock.sock = android_get_control_socket("lmkd");
3141 if (ctrl_sock.sock < 0) {
Todd Poynorc58c5142013-07-09 19:35:14 -07003142 ALOGE("get lmkd control socket failed");
3143 return -1;
3144 }
3145
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003146 ret = listen(ctrl_sock.sock, MAX_DATA_CONN);
Todd Poynorc58c5142013-07-09 19:35:14 -07003147 if (ret < 0) {
3148 ALOGE("lmkd control socket listen failed (errno=%d)", errno);
3149 return -1;
3150 }
3151
3152 epev.events = EPOLLIN;
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003153 ctrl_sock.handler_info.handler = ctrl_connect_handler;
3154 epev.data.ptr = (void *)&(ctrl_sock.handler_info);
3155 if (epoll_ctl(epollfd, EPOLL_CTL_ADD, ctrl_sock.sock, &epev) == -1) {
Todd Poynorc58c5142013-07-09 19:35:14 -07003156 ALOGE("epoll_ctl for lmkd control socket failed (errno=%d)", errno);
3157 return -1;
3158 }
3159 maxevents++;
3160
Robert Benea7878c9b2017-09-11 16:53:28 -07003161 has_inkernel_module = !access(INKERNEL_MINFREE_PATH, W_OK);
Suren Baghdasaryane6613ea2018-01-18 17:27:30 -08003162 use_inkernel_interface = has_inkernel_module;
Todd Poynorc58c5142013-07-09 19:35:14 -07003163
3164 if (use_inkernel_interface) {
3165 ALOGI("Using in-kernel low memory killer interface");
Jing Ji5c480962019-12-04 09:22:05 -08003166 if (init_poll_kernel()) {
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07003167 epev.events = EPOLLIN;
3168 epev.data.ptr = (void*)&kernel_poll_hinfo;
Jing Ji5c480962019-12-04 09:22:05 -08003169 if (epoll_ctl(epollfd, EPOLL_CTL_ADD, kpoll_fd, &epev) != 0) {
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07003170 ALOGE("epoll_ctl for lmk events failed (errno=%d)", errno);
Jing Ji5c480962019-12-04 09:22:05 -08003171 close(kpoll_fd);
3172 kpoll_fd = -1;
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07003173 } else {
3174 maxevents++;
Jing Ji5c480962019-12-04 09:22:05 -08003175 /* let the others know it does support reporting kills */
3176 property_set("sys.lmk.reportkills", "1");
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07003177 }
Jim Blackler700b7192019-04-26 11:18:29 +01003178 }
Todd Poynorc58c5142013-07-09 19:35:14 -07003179 } else {
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07003180 if (!init_monitors()) {
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08003181 return -1;
3182 }
Jing Ji5c480962019-12-04 09:22:05 -08003183 /* let the others know it does support reporting kills */
3184 property_set("sys.lmk.reportkills", "1");
Todd Poynorc58c5142013-07-09 19:35:14 -07003185 }
3186
Chong Zhang1cd12b52015-10-14 16:19:53 -07003187 for (i = 0; i <= ADJTOSLOT(OOM_SCORE_ADJ_MAX); i++) {
Todd Poynorc58c5142013-07-09 19:35:14 -07003188 procadjslot_list[i].next = &procadjslot_list[i];
3189 procadjslot_list[i].prev = &procadjslot_list[i];
3190 }
3191
Suren Baghdasaryana7394ea2018-10-12 11:07:40 -07003192 memset(killcnt_idx, KILLCNT_INVALID_IDX, sizeof(killcnt_idx));
3193
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -07003194 /*
3195 * Read zoneinfo as the biggest file we read to create and size the initial
3196 * read buffer and avoid memory re-allocations during memory pressure
3197 */
3198 if (reread_file(&file_data) == NULL) {
3199 ALOGE("Failed to read %s: %s", file_data.filename, strerror(errno));
3200 }
3201
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003202 /* check if kernel supports pidfd_open syscall */
Josh Gao84623be2021-03-18 17:16:08 -07003203 pidfd = TEMP_FAILURE_RETRY(pidfd_open(getpid(), 0));
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003204 if (pidfd < 0) {
3205 pidfd_supported = (errno != ENOSYS);
3206 } else {
3207 pidfd_supported = true;
3208 close(pidfd);
3209 }
3210 ALOGI("Process polling is %s", pidfd_supported ? "supported" : "not supported" );
3211
Todd Poynorc58c5142013-07-09 19:35:14 -07003212 return 0;
3213}
3214
Suren Baghdasaryan03dccf32020-04-28 16:02:13 -07003215static bool polling_paused(struct polling_params *poll_params) {
3216 return poll_params->paused_handler != NULL;
3217}
3218
3219static void resume_polling(struct polling_params *poll_params, struct timespec curr_tm) {
3220 poll_params->poll_start_tm = curr_tm;
3221 poll_params->poll_handler = poll_params->paused_handler;
Martin Liu589b5752020-09-02 23:15:18 +08003222 poll_params->polling_interval_ms = PSI_POLL_PERIOD_SHORT_MS;
3223 poll_params->paused_handler = NULL;
Suren Baghdasaryan03dccf32020-04-28 16:02:13 -07003224}
3225
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003226static void call_handler(struct event_handler_info* handler_info,
3227 struct polling_params *poll_params, uint32_t events) {
3228 struct timespec curr_tm;
3229
Suren Baghdasaryan9ca53342020-04-24 16:54:55 -07003230 poll_params->update = POLLING_DO_NOT_CHANGE;
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003231 handler_info->handler(handler_info->data, events, poll_params);
3232 clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm);
Suren Baghdasaryan9ca53342020-04-24 16:54:55 -07003233 if (poll_params->poll_handler == handler_info) {
3234 poll_params->last_poll_tm = curr_tm;
3235 }
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003236
3237 switch (poll_params->update) {
3238 case POLLING_START:
3239 /*
3240 * Poll for the duration of PSI_WINDOW_SIZE_MS after the
3241 * initial PSI event because psi events are rate-limited
3242 * at one per sec.
3243 */
3244 poll_params->poll_start_tm = curr_tm;
Greg Kaiser5e80ed52019-10-10 06:52:23 -07003245 poll_params->poll_handler = handler_info;
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003246 break;
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003247 case POLLING_PAUSE:
3248 poll_params->paused_handler = handler_info;
3249 poll_params->poll_handler = NULL;
3250 break;
3251 case POLLING_RESUME:
Suren Baghdasaryan03dccf32020-04-28 16:02:13 -07003252 resume_polling(poll_params, curr_tm);
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003253 break;
3254 case POLLING_DO_NOT_CHANGE:
3255 if (get_time_diff_ms(&poll_params->poll_start_tm, &curr_tm) > PSI_WINDOW_SIZE_MS) {
3256 /* Polled for the duration of PSI window, time to stop */
3257 poll_params->poll_handler = NULL;
3258 }
Suren Baghdasaryan9ca53342020-04-24 16:54:55 -07003259 break;
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003260 }
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003261}
3262
Todd Poynorc58c5142013-07-09 19:35:14 -07003263static void mainloop(void) {
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003264 struct event_handler_info* handler_info;
Suren Baghdasaryane12a0672019-07-15 14:50:49 -07003265 struct polling_params poll_params;
3266 struct timespec curr_tm;
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003267 struct epoll_event *evt;
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08003268 long delay = -1;
Suren Baghdasaryane12a0672019-07-15 14:50:49 -07003269
3270 poll_params.poll_handler = NULL;
Suren Baghdasaryan9ca53342020-04-24 16:54:55 -07003271 poll_params.paused_handler = NULL;
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003272
Todd Poynorc58c5142013-07-09 19:35:14 -07003273 while (1) {
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07003274 struct epoll_event events[MAX_EPOLL_EVENTS];
Todd Poynorc58c5142013-07-09 19:35:14 -07003275 int nevents;
3276 int i;
3277
Suren Baghdasaryane12a0672019-07-15 14:50:49 -07003278 if (poll_params.poll_handler) {
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003279 bool poll_now;
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08003280
3281 clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm);
Martin Liu589b5752020-09-02 23:15:18 +08003282 if (poll_params.update == POLLING_RESUME) {
3283 /* Just transitioned into POLLING_RESUME, poll immediately. */
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003284 poll_now = true;
3285 nevents = 0;
3286 } else {
3287 /* Calculate next timeout */
3288 delay = get_time_diff_ms(&poll_params.last_poll_tm, &curr_tm);
3289 delay = (delay < poll_params.polling_interval_ms) ?
3290 poll_params.polling_interval_ms - delay : poll_params.polling_interval_ms;
Suren Baghdasaryane12a0672019-07-15 14:50:49 -07003291
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003292 /* Wait for events until the next polling timeout */
3293 nevents = epoll_wait(epollfd, events, maxevents, delay);
3294
3295 /* Update current time after wait */
3296 clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm);
3297 poll_now = (get_time_diff_ms(&poll_params.last_poll_tm, &curr_tm) >=
3298 poll_params.polling_interval_ms);
3299 }
3300 if (poll_now) {
3301 call_handler(poll_params.poll_handler, &poll_params, 0);
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08003302 }
3303 } else {
Suren Baghdasaryan03dccf32020-04-28 16:02:13 -07003304 if (kill_timeout_ms && is_waiting_for_kill()) {
3305 clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm);
3306 delay = kill_timeout_ms - get_time_diff_ms(&last_kill_tm, &curr_tm);
3307 /* Wait for pidfds notification or kill timeout to expire */
3308 nevents = (delay > 0) ? epoll_wait(epollfd, events, maxevents, delay) : 0;
3309 if (nevents == 0) {
3310 /* Kill notification timed out */
3311 stop_wait_for_proc_kill(false);
3312 if (polling_paused(&poll_params)) {
3313 clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm);
Martin Liu589b5752020-09-02 23:15:18 +08003314 poll_params.update = POLLING_RESUME;
Suren Baghdasaryan03dccf32020-04-28 16:02:13 -07003315 resume_polling(&poll_params, curr_tm);
3316 }
3317 }
3318 } else {
3319 /* Wait for events with no timeout */
3320 nevents = epoll_wait(epollfd, events, maxevents, -1);
3321 }
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08003322 }
Todd Poynorc58c5142013-07-09 19:35:14 -07003323
3324 if (nevents == -1) {
3325 if (errno == EINTR)
3326 continue;
3327 ALOGE("epoll_wait failed (errno=%d)", errno);
3328 continue;
3329 }
3330
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003331 /*
3332 * First pass to see if any data socket connections were dropped.
3333 * Dropped connection should be handled before any other events
3334 * to deallocate data connection and correctly handle cases when
3335 * connection gets dropped and reestablished in the same epoll cycle.
3336 * In such cases it's essential to handle connection closures first.
3337 */
3338 for (i = 0, evt = &events[0]; i < nevents; ++i, evt++) {
3339 if ((evt->events & EPOLLHUP) && evt->data.ptr) {
3340 ALOGI("lmkd data connection dropped");
3341 handler_info = (struct event_handler_info*)evt->data.ptr;
3342 ctrl_data_close(handler_info->data);
3343 }
3344 }
3345
3346 /* Second pass to handle all other events */
3347 for (i = 0, evt = &events[0]; i < nevents; ++i, evt++) {
Suren Baghdasaryane12a0672019-07-15 14:50:49 -07003348 if (evt->events & EPOLLERR) {
Todd Poynorc58c5142013-07-09 19:35:14 -07003349 ALOGD("EPOLLERR on event #%d", i);
Suren Baghdasaryane12a0672019-07-15 14:50:49 -07003350 }
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003351 if (evt->events & EPOLLHUP) {
3352 /* This case was handled in the first pass */
3353 continue;
3354 }
3355 if (evt->data.ptr) {
3356 handler_info = (struct event_handler_info*)evt->data.ptr;
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003357 call_handler(handler_info, &poll_params, evt->events);
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003358 }
Todd Poynorc58c5142013-07-09 19:35:14 -07003359 }
3360 }
3361}
3362
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07003363int issue_reinit() {
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07003364 int sock;
Colin Crossd5b510e2014-07-14 14:31:15 -07003365
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07003366 sock = lmkd_connect();
3367 if (sock < 0) {
3368 ALOGE("failed to connect to lmkd: %s", strerror(errno));
3369 return -1;
3370 }
3371
3372 enum update_props_result res = lmkd_update_props(sock);
3373 switch (res) {
3374 case UPDATE_PROPS_SUCCESS:
3375 ALOGI("lmkd updated properties successfully");
3376 break;
3377 case UPDATE_PROPS_SEND_ERR:
3378 ALOGE("failed to send lmkd request: %s", strerror(errno));
3379 break;
3380 case UPDATE_PROPS_RECV_ERR:
3381 ALOGE("failed to receive lmkd reply: %s", strerror(errno));
3382 break;
3383 case UPDATE_PROPS_FORMAT_ERR:
3384 ALOGE("lmkd reply is invalid");
3385 break;
3386 case UPDATE_PROPS_FAIL:
3387 ALOGE("lmkd failed to update its properties");
3388 break;
3389 }
3390
3391 close(sock);
3392 return res == UPDATE_PROPS_SUCCESS ? 0 : -1;
3393}
3394
3395static void update_props() {
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08003396 /* By default disable low level vmpressure events */
3397 level_oomadj[VMPRESS_LEVEL_LOW] =
3398 property_get_int32("ro.lmk.low", OOM_SCORE_ADJ_MAX + 1);
3399 level_oomadj[VMPRESS_LEVEL_MEDIUM] =
3400 property_get_int32("ro.lmk.medium", 800);
3401 level_oomadj[VMPRESS_LEVEL_CRITICAL] =
3402 property_get_int32("ro.lmk.critical", 0);
Robert Benea7f68a3f2017-08-11 16:03:20 -07003403 debug_process_killing = property_get_bool("ro.lmk.debug", false);
Suren Baghdasaryan3faa3032017-12-08 13:08:41 -08003404
3405 /* By default disable upgrade/downgrade logic */
3406 enable_pressure_upgrade =
3407 property_get_bool("ro.lmk.critical_upgrade", false);
3408 upgrade_pressure =
3409 (int64_t)property_get_int32("ro.lmk.upgrade_pressure", 100);
3410 downgrade_pressure =
3411 (int64_t)property_get_int32("ro.lmk.downgrade_pressure", 100);
Suren Baghdasaryaneb7c5492017-12-08 13:17:06 -08003412 kill_heaviest_task =
Suren Baghdasaryan36b2c492018-04-13 11:49:54 -07003413 property_get_bool("ro.lmk.kill_heaviest_task", false);
Suren Baghdasaryand1d59f82018-04-13 11:45:38 -07003414 low_ram_device = property_get_bool("ro.config.low_ram", false);
Suren Baghdasaryan30854e72018-01-17 17:28:01 -08003415 kill_timeout_ms =
Suren Baghdasaryan7d1f4f02020-07-08 11:40:10 -07003416 (unsigned long)property_get_int32("ro.lmk.kill_timeout_ms", 100);
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07003417 use_minfree_levels =
3418 property_get_bool("ro.lmk.use_minfree_levels", false);
Suren Baghdasaryan8389fdb2018-06-19 18:38:12 -07003419 per_app_memcg =
3420 property_get_bool("ro.config.per_app_memcg", low_ram_device);
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07003421 swap_free_low_percentage = clamp(0, 100, property_get_int32("ro.lmk.swap_free_low_percentage",
Suren Baghdasaryanfb1f5922020-05-19 13:07:23 -07003422 DEF_LOW_SWAP));
Suren Baghdasaryan2f88e152019-07-15 15:42:09 -07003423 psi_partial_stall_ms = property_get_int32("ro.lmk.psi_partial_stall_ms",
3424 low_ram_device ? DEF_PARTIAL_STALL_LOWRAM : DEF_PARTIAL_STALL);
3425 psi_complete_stall_ms = property_get_int32("ro.lmk.psi_complete_stall_ms",
3426 DEF_COMPLETE_STALL);
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07003427 thrashing_limit_pct = max(0, property_get_int32("ro.lmk.thrashing_limit",
3428 low_ram_device ? DEF_THRASHING_LOWRAM : DEF_THRASHING));
3429 thrashing_limit_decay_pct = clamp(0, 100, property_get_int32("ro.lmk.thrashing_limit_decay",
3430 low_ram_device ? DEF_THRASHING_DECAY_LOWRAM : DEF_THRASHING_DECAY));
Suren Baghdasaryan0142b3c2021-03-03 11:11:09 -08003431 thrashing_critical_pct = max(0, property_get_int32("ro.lmk.thrashing_limit_critical",
3432 thrashing_limit_pct * 2));
Suren Baghdasaryan51ee4c52020-04-21 12:27:01 -07003433 swap_util_max = clamp(0, 100, property_get_int32("ro.lmk.swap_util_max", 100));
Suren Baghdasaryan11221d42021-07-14 17:57:52 -07003434 filecache_min_kb = property_get_int64("ro.lmk.filecache_min_kb", 0);
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07003435}
3436
3437int main(int argc, char **argv) {
3438 if ((argc > 1) && argv[1] && !strcmp(argv[1], "--reinit")) {
3439 if (property_set(LMKD_REINIT_PROP, "0")) {
3440 ALOGE("Failed to reset " LMKD_REINIT_PROP " property");
3441 }
3442 return issue_reinit();
3443 }
3444
3445 update_props();
Robert Benea57397dc2017-07-31 17:15:20 -07003446
Suren Baghdasaryan12cacae2019-09-16 12:06:30 -07003447 ctx = create_android_logger(KILLINFO_LOG_TAG);
Suren Baghdasaryan08bfa982018-07-26 16:34:27 -07003448
Mark Salyzyn5cc80b32018-03-21 12:24:58 -07003449 if (!init()) {
3450 if (!use_inkernel_interface) {
3451 /*
3452 * MCL_ONFAULT pins pages as they fault instead of loading
3453 * everything immediately all at once. (Which would be bad,
3454 * because as of this writing, we have a lot of mapped pages we
3455 * never use.) Old kernels will see MCL_ONFAULT and fail with
3456 * EINVAL; we ignore this failure.
3457 *
3458 * N.B. read the man page for mlockall. MCL_CURRENT | MCL_ONFAULT
3459 * pins ⊆ MCL_CURRENT, converging to just MCL_CURRENT as we fault
3460 * in pages.
3461 */
Mark Salyzyna00ccd82018-04-09 09:50:32 -07003462 /* CAP_IPC_LOCK required */
Mark Salyzyn5cc80b32018-03-21 12:24:58 -07003463 if (mlockall(MCL_CURRENT | MCL_FUTURE | MCL_ONFAULT) && (errno != EINVAL)) {
3464 ALOGW("mlockall failed %s", strerror(errno));
3465 }
Daniel Colascione46648332018-01-03 12:01:02 -08003466
Mark Salyzyna00ccd82018-04-09 09:50:32 -07003467 /* CAP_NICE required */
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07003468 struct sched_param param = {
3469 .sched_priority = 1,
3470 };
Mark Salyzyna00ccd82018-04-09 09:50:32 -07003471 if (sched_setscheduler(0, SCHED_FIFO, &param)) {
3472 ALOGW("set SCHED_FIFO failed %s", strerror(errno));
3473 }
Mark Salyzyn5cc80b32018-03-21 12:24:58 -07003474 }
3475
Todd Poynorc58c5142013-07-09 19:35:14 -07003476 mainloop();
Mark Salyzyn5cc80b32018-03-21 12:24:58 -07003477 }
Todd Poynorc58c5142013-07-09 19:35:14 -07003478
Suren Baghdasaryan08bfa982018-07-26 16:34:27 -07003479 android_log_destroy(&ctx);
3480
Todd Poynorc58c5142013-07-09 19:35:14 -07003481 ALOGI("exiting");
3482 return 0;
3483}