blob: 4e4490fb9834a6ab7517adb243ebf4c0396d73ae [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
Suren Baghdasaryan34928bb2021-07-29 17:02:51 -070068static inline void trace_kill_start(int pid, const char *desc) {
69 ATRACE_INT("kill_one_process", pid);
70 ATRACE_BEGIN(desc);
71}
72
73static inline void trace_kill_end() {
74 ATRACE_END();
75 ATRACE_INT("kill_one_process", 0);
76}
Suren Baghdasaryan03e19872018-01-04 10:43:58 -080077
78#else /* LMKD_TRACE_KILLS */
79
Suren Baghdasaryan34928bb2021-07-29 17:02:51 -070080static inline void trace_kill_start(int, const char *) {}
81static inline void trace_kill_end() {}
Suren Baghdasaryan03e19872018-01-04 10:43:58 -080082
83#endif /* LMKD_TRACE_KILLS */
84
Mark Salyzyneb062742014-04-30 13:36:35 -070085#ifndef __unused
86#define __unused __attribute__((__unused__))
87#endif
Todd Poynorc58c5142013-07-09 19:35:14 -070088
89#define MEMCG_SYSFS_PATH "/dev/memcg/"
Robert Beneac72b2932017-08-21 15:18:31 -070090#define MEMCG_MEMORY_USAGE "/dev/memcg/memory.usage_in_bytes"
91#define MEMCG_MEMORYSW_USAGE "/dev/memcg/memory.memsw.usage_in_bytes"
Suren Baghdasaryand28a9732018-04-13 13:11:51 -070092#define ZONEINFO_PATH "/proc/zoneinfo"
93#define MEMINFO_PATH "/proc/meminfo"
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -070094#define VMSTAT_PATH "/proc/vmstat"
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -070095#define PROC_STATUS_TGID_FIELD "Tgid:"
Ioannis Ilkos279268a2020-08-01 10:50:40 +010096#define PROC_STATUS_RSS_FIELD "VmRSS:"
97#define PROC_STATUS_SWAP_FIELD "VmSwap:"
Todd Poynorc58c5142013-07-09 19:35:14 -070098#define LINE_MAX 128
99
Suren Baghdasaryan970a26a2019-09-19 15:27:21 -0700100#define PERCEPTIBLE_APP_ADJ 200
101
Suren Baghdasaryan08bfa982018-07-26 16:34:27 -0700102/* Android Logger event logtags (see event.logtags) */
Suren Baghdasaryan12cacae2019-09-16 12:06:30 -0700103#define KILLINFO_LOG_TAG 10195355
Suren Baghdasaryan08bfa982018-07-26 16:34:27 -0700104
Mark Salyzyna00ccd82018-04-09 09:50:32 -0700105/* gid containing AID_SYSTEM required */
Todd Poynorc58c5142013-07-09 19:35:14 -0700106#define INKERNEL_MINFREE_PATH "/sys/module/lowmemorykiller/parameters/minfree"
107#define INKERNEL_ADJ_PATH "/sys/module/lowmemorykiller/parameters/adj"
108
109#define ARRAY_SIZE(x) (sizeof(x) / sizeof(*(x)))
Robert Benea58d6a132017-06-01 16:32:31 -0700110#define EIGHT_MEGA (1 << 23)
Todd Poynorc58c5142013-07-09 19:35:14 -0700111
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -0700112#define TARGET_UPDATE_MIN_INTERVAL_MS 1000
Martin Liu1f72f5f2020-08-21 13:18:50 +0800113#define THRASHING_RESET_INTERVAL_MS 1000
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -0700114
115#define NS_PER_MS (NS_PER_SEC / MS_PER_SEC)
Suren Baghdasaryan55e31502019-01-08 12:54:48 -0800116#define US_PER_MS (US_PER_SEC / MS_PER_SEC)
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -0700117
Suren Baghdasaryanbb7747b2018-03-20 16:03:29 -0700118/* Defined as ProcessList.SYSTEM_ADJ in ProcessList.java */
119#define SYSTEM_ADJ (-900)
120
Greg Kaiserf5b1d142018-03-23 14:16:12 -0700121#define STRINGIFY(x) STRINGIFY_INTERNAL(x)
122#define STRINGIFY_INTERNAL(x) #x
123
Suren Baghdasaryan55e31502019-01-08 12:54:48 -0800124/*
Suren Baghdasaryand0a80042021-08-03 15:40:23 -0700125 * Read lmk property with persist.device_config.lmkd_native.<name> overriding ro.lmk.<name>
126 * persist.device_config.lmkd_native.* properties are being set by experiments. If a new property
127 * can be controlled by an experiment then use GET_LMK_PROPERTY instead of property_get_xxx and
128 * add "on property" triggers in lmkd.rc to react to the experiment flag changes.
129 */
130#define GET_LMK_PROPERTY(type, name, def) \
131 property_get_##type("persist.device_config.lmkd_native." name, \
132 property_get_##type("ro.lmk." name, def))
133
134/*
Suren Baghdasaryan55e31502019-01-08 12:54:48 -0800135 * PSI monitor tracking window size.
136 * PSI monitor generates events at most once per window,
137 * therefore we poll memory state for the duration of
138 * PSI_WINDOW_SIZE_MS after the event happens.
139 */
140#define PSI_WINDOW_SIZE_MS 1000
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -0700141/* Polling period after PSI signal when pressure is high */
142#define PSI_POLL_PERIOD_SHORT_MS 10
143/* Polling period after PSI signal when pressure is low */
144#define PSI_POLL_PERIOD_LONG_MS 100
Suren Baghdasaryan55e31502019-01-08 12:54:48 -0800145
Suren Baghdasaryan08bfa982018-07-26 16:34:27 -0700146#define min(a, b) (((a) < (b)) ? (a) : (b))
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -0700147#define max(a, b) (((a) > (b)) ? (a) : (b))
Suren Baghdasaryan08bfa982018-07-26 16:34:27 -0700148
Suren Baghdasaryan53be36e2018-09-05 15:46:32 -0700149#define FAIL_REPORT_RLIMIT_MS 1000
150
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -0700151/*
152 * System property defaults
153 */
154/* ro.lmk.swap_free_low_percentage property defaults */
Suren Baghdasaryanfb1f5922020-05-19 13:07:23 -0700155#define DEF_LOW_SWAP 10
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -0700156/* ro.lmk.thrashing_limit property defaults */
157#define DEF_THRASHING_LOWRAM 30
158#define DEF_THRASHING 100
159/* ro.lmk.thrashing_limit_decay property defaults */
160#define DEF_THRASHING_DECAY_LOWRAM 50
161#define DEF_THRASHING_DECAY 10
Suren Baghdasaryan2f88e152019-07-15 15:42:09 -0700162/* ro.lmk.psi_partial_stall_ms property defaults */
163#define DEF_PARTIAL_STALL_LOWRAM 200
164#define DEF_PARTIAL_STALL 70
165/* ro.lmk.psi_complete_stall_ms property defaults */
166#define DEF_COMPLETE_STALL 700
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -0700167
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -0700168#define LMKD_REINIT_PROP "lmkd.reinit"
169
Todd Poynorc58c5142013-07-09 19:35:14 -0700170/* default to old in-kernel interface if no memory pressure events */
Mark Salyzyn5cc80b32018-03-21 12:24:58 -0700171static bool use_inkernel_interface = true;
Robert Benea7878c9b2017-09-11 16:53:28 -0700172static bool has_inkernel_module;
Todd Poynorc58c5142013-07-09 19:35:14 -0700173
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -0800174/* memory pressure levels */
175enum vmpressure_level {
176 VMPRESS_LEVEL_LOW = 0,
177 VMPRESS_LEVEL_MEDIUM,
178 VMPRESS_LEVEL_CRITICAL,
179 VMPRESS_LEVEL_COUNT
180};
Todd Poynorc58c5142013-07-09 19:35:14 -0700181
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -0800182static const char *level_name[] = {
183 "low",
184 "medium",
185 "critical"
186};
187
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -0800188struct {
Suren Baghdasaryane0f3dd12018-04-13 13:41:12 -0700189 int64_t min_nr_free_pages; /* recorded but not used yet */
190 int64_t max_nr_free_pages;
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -0800191} low_pressure_mem = { -1, -1 };
192
Suren Baghdasaryan55e31502019-01-08 12:54:48 -0800193struct psi_threshold {
194 enum psi_stall_type stall_type;
195 int threshold_ms;
196};
197
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -0800198static int level_oomadj[VMPRESS_LEVEL_COUNT];
Suren Baghdasaryan3e1a8492018-01-04 09:16:21 -0800199static int mpevfd[VMPRESS_LEVEL_COUNT] = { -1, -1, -1 };
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -0700200static bool pidfd_supported;
201static int last_kill_pid_or_fd = -1;
202static struct timespec last_kill_tm;
203
204/* lmkd configurable parameters */
Robert Beneac72b2932017-08-21 15:18:31 -0700205static bool debug_process_killing;
206static bool enable_pressure_upgrade;
207static int64_t upgrade_pressure;
Robert Benea3be16142017-09-13 15:20:30 -0700208static int64_t downgrade_pressure;
Suren Baghdasaryand1d59f82018-04-13 11:45:38 -0700209static bool low_ram_device;
Suren Baghdasaryaneb7c5492017-12-08 13:17:06 -0800210static bool kill_heaviest_task;
Suren Baghdasaryan30854e72018-01-17 17:28:01 -0800211static unsigned long kill_timeout_ms;
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -0700212static bool use_minfree_levels;
Suren Baghdasaryan8389fdb2018-06-19 18:38:12 -0700213static bool per_app_memcg;
Vic Yang65680692018-08-07 10:18:22 -0700214static int swap_free_low_percentage;
Suren Baghdasaryan2f88e152019-07-15 15:42:09 -0700215static int psi_partial_stall_ms;
216static int psi_complete_stall_ms;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -0700217static int thrashing_limit_pct;
218static int thrashing_limit_decay_pct;
Suren Baghdasaryan0142b3c2021-03-03 11:11:09 -0800219static int thrashing_critical_pct;
Suren Baghdasaryan51ee4c52020-04-21 12:27:01 -0700220static int swap_util_max;
Suren Baghdasaryan11221d42021-07-14 17:57:52 -0700221static int64_t filecache_min_kb;
Suren Baghdasaryan55e31502019-01-08 12:54:48 -0800222static bool use_psi_monitors = false;
Jing Ji5c480962019-12-04 09:22:05 -0800223static int kpoll_fd;
Suren Baghdasaryan55e31502019-01-08 12:54:48 -0800224static struct psi_threshold psi_thresholds[VMPRESS_LEVEL_COUNT] = {
225 { PSI_SOME, 70 }, /* 70ms out of 1sec for partial stall */
226 { PSI_SOME, 100 }, /* 100ms out of 1sec for partial stall */
227 { PSI_FULL, 70 }, /* 70ms out of 1sec for complete stall */
228};
Robert Benea57397dc2017-07-31 17:15:20 -0700229
Suren Baghdasaryan08bfa982018-07-26 16:34:27 -0700230static android_log_context ctx;
231
Suren Baghdasaryane12a0672019-07-15 14:50:49 -0700232enum polling_update {
233 POLLING_DO_NOT_CHANGE,
234 POLLING_START,
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -0700235 POLLING_PAUSE,
236 POLLING_RESUME,
Suren Baghdasaryane12a0672019-07-15 14:50:49 -0700237};
238
239/*
240 * Data used for periodic polling for the memory state of the device.
241 * Note that when system is not polling poll_handler is set to NULL,
242 * when polling starts poll_handler gets set and is reset back to
243 * NULL when polling stops.
244 */
245struct polling_params {
246 struct event_handler_info* poll_handler;
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -0700247 struct event_handler_info* paused_handler;
Suren Baghdasaryane12a0672019-07-15 14:50:49 -0700248 struct timespec poll_start_tm;
249 struct timespec last_poll_tm;
250 int polling_interval_ms;
251 enum polling_update update;
252};
253
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -0800254/* data required to handle events */
255struct event_handler_info {
256 int data;
Suren Baghdasaryane12a0672019-07-15 14:50:49 -0700257 void (*handler)(int data, uint32_t events, struct polling_params *poll_params);
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -0800258};
Todd Poynorc58c5142013-07-09 19:35:14 -0700259
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -0800260/* data required to handle socket events */
261struct sock_event_handler_info {
262 int sock;
Suren Baghdasaryan945658a2019-10-18 11:16:52 -0700263 pid_t pid;
Suren Baghdasaryan36baf442019-12-23 11:37:34 -0800264 uint32_t async_event_mask;
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -0800265 struct event_handler_info handler_info;
266};
267
Suren Baghdasaryanf2cbefd2019-10-21 17:59:22 -0700268/* max supported number of data connections (AMS, init, tests) */
269#define MAX_DATA_CONN 3
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -0800270
271/* socket event handler data */
272static struct sock_event_handler_info ctrl_sock;
273static struct sock_event_handler_info data_sock[MAX_DATA_CONN];
274
275/* vmpressure event handler data */
276static struct event_handler_info vmpressure_hinfo[VMPRESS_LEVEL_COUNT];
277
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -0700278/*
Suren Baghdasaryanf2cbefd2019-10-21 17:59:22 -0700279 * 1 ctrl listen socket, 3 ctrl data socket, 3 memory pressure levels,
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -0700280 * 1 lmk events + 1 fd to wait for process death
281 */
282#define MAX_EPOLL_EVENTS (1 + MAX_DATA_CONN + VMPRESS_LEVEL_COUNT + 1 + 1)
Todd Poynorc58c5142013-07-09 19:35:14 -0700283static int epollfd;
284static int maxevents;
285
Chong Zhang1cd12b52015-10-14 16:19:53 -0700286/* OOM score values used by both kernel and framework */
Todd Poynora08c1722013-09-16 19:26:47 -0700287#define OOM_SCORE_ADJ_MIN (-1000)
288#define OOM_SCORE_ADJ_MAX 1000
289
Todd Poynorc58c5142013-07-09 19:35:14 -0700290static int lowmem_adj[MAX_TARGETS];
291static int lowmem_minfree[MAX_TARGETS];
292static int lowmem_targets_size;
293
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700294/* Fields to parse in /proc/zoneinfo */
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -0700295/* zoneinfo per-zone fields */
296enum zoneinfo_zone_field {
297 ZI_ZONE_NR_FREE_PAGES = 0,
298 ZI_ZONE_MIN,
299 ZI_ZONE_LOW,
300 ZI_ZONE_HIGH,
301 ZI_ZONE_PRESENT,
302 ZI_ZONE_NR_FREE_CMA,
303 ZI_ZONE_FIELD_COUNT
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700304};
305
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -0700306static const char* const zoneinfo_zone_field_names[ZI_ZONE_FIELD_COUNT] = {
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700307 "nr_free_pages",
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -0700308 "min",
309 "low",
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700310 "high",
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -0700311 "present",
312 "nr_free_cma",
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700313};
314
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -0700315/* zoneinfo per-zone special fields */
316enum zoneinfo_zone_spec_field {
317 ZI_ZONE_SPEC_PROTECTION = 0,
318 ZI_ZONE_SPEC_PAGESETS,
319 ZI_ZONE_SPEC_FIELD_COUNT,
320};
321
322static const char* const zoneinfo_zone_spec_field_names[ZI_ZONE_SPEC_FIELD_COUNT] = {
323 "protection:",
324 "pagesets",
325};
326
327/* see __MAX_NR_ZONES definition in kernel mmzone.h */
328#define MAX_NR_ZONES 6
329
330union zoneinfo_zone_fields {
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700331 struct {
332 int64_t nr_free_pages;
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -0700333 int64_t min;
334 int64_t low;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700335 int64_t high;
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -0700336 int64_t present;
337 int64_t nr_free_cma;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700338 } field;
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -0700339 int64_t arr[ZI_ZONE_FIELD_COUNT];
340};
341
342struct zoneinfo_zone {
343 union zoneinfo_zone_fields fields;
344 int64_t protection[MAX_NR_ZONES];
345 int64_t max_protection;
346};
347
348/* zoneinfo per-node fields */
349enum zoneinfo_node_field {
350 ZI_NODE_NR_INACTIVE_FILE = 0,
351 ZI_NODE_NR_ACTIVE_FILE,
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -0700352 ZI_NODE_FIELD_COUNT
353};
354
355static const char* const zoneinfo_node_field_names[ZI_NODE_FIELD_COUNT] = {
356 "nr_inactive_file",
357 "nr_active_file",
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -0700358};
359
360union zoneinfo_node_fields {
361 struct {
362 int64_t nr_inactive_file;
363 int64_t nr_active_file;
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -0700364 } field;
365 int64_t arr[ZI_NODE_FIELD_COUNT];
366};
367
368struct zoneinfo_node {
369 int id;
370 int zone_count;
371 struct zoneinfo_zone zones[MAX_NR_ZONES];
372 union zoneinfo_node_fields fields;
373};
374
375/* for now two memory nodes is more than enough */
376#define MAX_NR_NODES 2
377
378struct zoneinfo {
379 int node_count;
380 struct zoneinfo_node nodes[MAX_NR_NODES];
381 int64_t totalreserve_pages;
382 int64_t total_inactive_file;
383 int64_t total_active_file;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700384};
385
386/* Fields to parse in /proc/meminfo */
387enum meminfo_field {
388 MI_NR_FREE_PAGES = 0,
389 MI_CACHED,
390 MI_SWAP_CACHED,
391 MI_BUFFERS,
392 MI_SHMEM,
393 MI_UNEVICTABLE,
Vic Yang65680692018-08-07 10:18:22 -0700394 MI_TOTAL_SWAP,
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700395 MI_FREE_SWAP,
Suren Baghdasaryan08bfa982018-07-26 16:34:27 -0700396 MI_ACTIVE_ANON,
397 MI_INACTIVE_ANON,
398 MI_ACTIVE_FILE,
399 MI_INACTIVE_FILE,
400 MI_SRECLAIMABLE,
401 MI_SUNRECLAIM,
402 MI_KERNEL_STACK,
403 MI_PAGE_TABLES,
404 MI_ION_HELP,
405 MI_ION_HELP_POOL,
406 MI_CMA_FREE,
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700407 MI_FIELD_COUNT
408};
409
410static const char* const meminfo_field_names[MI_FIELD_COUNT] = {
411 "MemFree:",
412 "Cached:",
413 "SwapCached:",
414 "Buffers:",
415 "Shmem:",
416 "Unevictable:",
Vic Yang65680692018-08-07 10:18:22 -0700417 "SwapTotal:",
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700418 "SwapFree:",
Suren Baghdasaryan08bfa982018-07-26 16:34:27 -0700419 "Active(anon):",
420 "Inactive(anon):",
421 "Active(file):",
422 "Inactive(file):",
423 "SReclaimable:",
424 "SUnreclaim:",
425 "KernelStack:",
426 "PageTables:",
427 "ION_heap:",
428 "ION_heap_pool:",
429 "CmaFree:",
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700430};
431
432union meminfo {
433 struct {
434 int64_t nr_free_pages;
435 int64_t cached;
436 int64_t swap_cached;
437 int64_t buffers;
438 int64_t shmem;
439 int64_t unevictable;
Vic Yang65680692018-08-07 10:18:22 -0700440 int64_t total_swap;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700441 int64_t free_swap;
Suren Baghdasaryan08bfa982018-07-26 16:34:27 -0700442 int64_t active_anon;
443 int64_t inactive_anon;
444 int64_t active_file;
445 int64_t inactive_file;
446 int64_t sreclaimable;
447 int64_t sunreclaimable;
448 int64_t kernel_stack;
449 int64_t page_tables;
450 int64_t ion_heap;
451 int64_t ion_heap_pool;
452 int64_t cma_free;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700453 /* fields below are calculated rather than read from the file */
454 int64_t nr_file_pages;
Suren Baghdasaryan940e7cf2021-05-27 18:15:44 -0700455 int64_t total_gpu_kb;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700456 } field;
457 int64_t arr[MI_FIELD_COUNT];
458};
459
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -0700460/* Fields to parse in /proc/vmstat */
461enum vmstat_field {
462 VS_FREE_PAGES,
463 VS_INACTIVE_FILE,
464 VS_ACTIVE_FILE,
465 VS_WORKINGSET_REFAULT,
Suren Baghdasaryandc60f972020-12-14 13:38:48 -0800466 VS_WORKINGSET_REFAULT_FILE,
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -0700467 VS_PGSCAN_KSWAPD,
468 VS_PGSCAN_DIRECT,
469 VS_PGSCAN_DIRECT_THROTTLE,
470 VS_FIELD_COUNT
471};
472
473static const char* const vmstat_field_names[MI_FIELD_COUNT] = {
474 "nr_free_pages",
475 "nr_inactive_file",
476 "nr_active_file",
477 "workingset_refault",
Suren Baghdasaryandc60f972020-12-14 13:38:48 -0800478 "workingset_refault_file",
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -0700479 "pgscan_kswapd",
480 "pgscan_direct",
481 "pgscan_direct_throttle",
482};
483
484union vmstat {
485 struct {
486 int64_t nr_free_pages;
487 int64_t nr_inactive_file;
488 int64_t nr_active_file;
489 int64_t workingset_refault;
Suren Baghdasaryandc60f972020-12-14 13:38:48 -0800490 int64_t workingset_refault_file;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -0700491 int64_t pgscan_kswapd;
492 int64_t pgscan_direct;
493 int64_t pgscan_direct_throttle;
494 } field;
495 int64_t arr[VS_FIELD_COUNT];
496};
497
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700498enum field_match_result {
499 NO_MATCH,
500 PARSE_FAIL,
501 PARSE_SUCCESS
502};
503
Todd Poynorc58c5142013-07-09 19:35:14 -0700504struct adjslot_list {
505 struct adjslot_list *next;
506 struct adjslot_list *prev;
507};
508
509struct proc {
510 struct adjslot_list asl;
511 int pid;
Suren Baghdasaryana10157c2019-07-19 10:55:39 -0700512 int pidfd;
Colin Cross748d2182014-06-13 14:52:43 -0700513 uid_t uid;
Todd Poynorc58c5142013-07-09 19:35:14 -0700514 int oomadj;
Suren Baghdasaryan945658a2019-10-18 11:16:52 -0700515 pid_t reg_pid; /* PID of the process that registered this record */
Todd Poynorc58c5142013-07-09 19:35:14 -0700516 struct proc *pidhash_next;
517};
518
Suren Baghdasaryan87966742018-04-13 12:43:41 -0700519struct reread_data {
520 const char* const filename;
521 int fd;
522};
523
Todd Poynorc58c5142013-07-09 19:35:14 -0700524#define PIDHASH_SZ 1024
525static struct proc *pidhash[PIDHASH_SZ];
526#define pid_hashfn(x) ((((x) >> 8) ^ (x)) & (PIDHASH_SZ - 1))
527
Chih-Hung Hsieheefa2462016-05-19 16:02:22 -0700528#define ADJTOSLOT(adj) ((adj) + -OOM_SCORE_ADJ_MIN)
Suren Baghdasaryana7394ea2018-10-12 11:07:40 -0700529#define ADJTOSLOT_COUNT (ADJTOSLOT(OOM_SCORE_ADJ_MAX) + 1)
530static struct adjslot_list procadjslot_list[ADJTOSLOT_COUNT];
531
532#define MAX_DISTINCT_OOM_ADJ 32
533#define KILLCNT_INVALID_IDX 0xFF
534/*
535 * Because killcnt array is sparse a two-level indirection is used
536 * to keep the size small. killcnt_idx stores index of the element in
537 * killcnt array. Index KILLCNT_INVALID_IDX indicates an unused slot.
538 */
539static uint8_t killcnt_idx[ADJTOSLOT_COUNT];
540static uint16_t killcnt[MAX_DISTINCT_OOM_ADJ];
541static int killcnt_free_idx = 0;
542static uint32_t killcnt_total = 0;
Todd Poynorc58c5142013-07-09 19:35:14 -0700543
Todd Poynorc58c5142013-07-09 19:35:14 -0700544/* PAGE_SIZE / 1024 */
545static long page_k;
546
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -0700547static void update_props();
548static bool init_monitors();
549static void destroy_monitors();
550
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -0700551static int clamp(int low, int high, int value) {
552 return max(min(value, high), low);
553}
554
Suren Baghdasaryan87966742018-04-13 12:43:41 -0700555static bool parse_int64(const char* str, int64_t* ret) {
556 char* endptr;
557 long long val = strtoll(str, &endptr, 10);
558 if (str == endptr || val > INT64_MAX) {
559 return false;
560 }
561 *ret = (int64_t)val;
562 return true;
563}
564
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -0700565static int find_field(const char* name, const char* const field_names[], int field_count) {
566 for (int i = 0; i < field_count; i++) {
567 if (!strcmp(name, field_names[i])) {
568 return i;
569 }
570 }
571 return -1;
572}
573
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700574static enum field_match_result match_field(const char* cp, const char* ap,
575 const char* const field_names[],
576 int field_count, int64_t* field,
577 int *field_idx) {
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -0700578 int i = find_field(cp, field_names, field_count);
579 if (i < 0) {
580 return NO_MATCH;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700581 }
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -0700582 *field_idx = i;
583 return parse_int64(ap, field) ? PARSE_SUCCESS : PARSE_FAIL;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700584}
585
Suren Baghdasaryan87966742018-04-13 12:43:41 -0700586/*
587 * Read file content from the beginning up to max_len bytes or EOF
588 * whichever happens first.
589 */
Colin Crossdba1cc62014-07-11 17:53:27 -0700590static ssize_t read_all(int fd, char *buf, size_t max_len)
591{
592 ssize_t ret = 0;
Suren Baghdasaryan87966742018-04-13 12:43:41 -0700593 off_t offset = 0;
Colin Crossdba1cc62014-07-11 17:53:27 -0700594
595 while (max_len > 0) {
Suren Baghdasaryan87966742018-04-13 12:43:41 -0700596 ssize_t r = TEMP_FAILURE_RETRY(pread(fd, buf, max_len, offset));
Colin Crossdba1cc62014-07-11 17:53:27 -0700597 if (r == 0) {
598 break;
599 }
600 if (r == -1) {
601 return -1;
602 }
603 ret += r;
604 buf += r;
Suren Baghdasaryan87966742018-04-13 12:43:41 -0700605 offset += r;
Colin Crossdba1cc62014-07-11 17:53:27 -0700606 max_len -= r;
607 }
608
609 return ret;
610}
611
Suren Baghdasaryan87966742018-04-13 12:43:41 -0700612/*
613 * Read a new or already opened file from the beginning.
614 * If the file has not been opened yet data->fd should be set to -1.
615 * To be used with files which are read often and possibly during high
616 * memory pressure to minimize file opening which by itself requires kernel
617 * memory allocation and might result in a stall on memory stressed system.
618 */
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -0700619static char *reread_file(struct reread_data *data) {
620 /* start with page-size buffer and increase if needed */
621 static ssize_t buf_size = PAGE_SIZE;
622 static char *new_buf, *buf = NULL;
Suren Baghdasaryan87966742018-04-13 12:43:41 -0700623 ssize_t size;
624
625 if (data->fd == -1) {
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -0700626 /* First-time buffer initialization */
Tom Cherry43f3d2b2019-12-04 12:46:57 -0800627 if (!buf && (buf = static_cast<char*>(malloc(buf_size))) == nullptr) {
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -0700628 return NULL;
629 }
630
631 data->fd = TEMP_FAILURE_RETRY(open(data->filename, O_RDONLY | O_CLOEXEC));
632 if (data->fd < 0) {
Suren Baghdasaryan87966742018-04-13 12:43:41 -0700633 ALOGE("%s open: %s", data->filename, strerror(errno));
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -0700634 return NULL;
Suren Baghdasaryan87966742018-04-13 12:43:41 -0700635 }
636 }
637
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -0700638 while (true) {
639 size = read_all(data->fd, buf, buf_size - 1);
640 if (size < 0) {
641 ALOGE("%s read: %s", data->filename, strerror(errno));
642 close(data->fd);
643 data->fd = -1;
644 return NULL;
645 }
646 if (size < buf_size - 1) {
647 break;
648 }
649 /*
650 * Since we are reading /proc files we can't use fstat to find out
651 * the real size of the file. Double the buffer size and keep retrying.
652 */
Tom Cherry43f3d2b2019-12-04 12:46:57 -0800653 if ((new_buf = static_cast<char*>(realloc(buf, buf_size * 2))) == nullptr) {
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -0700654 errno = ENOMEM;
655 return NULL;
656 }
657 buf = new_buf;
658 buf_size *= 2;
Suren Baghdasaryan87966742018-04-13 12:43:41 -0700659 }
Suren Baghdasaryan87966742018-04-13 12:43:41 -0700660 buf[size] = 0;
661
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -0700662 return buf;
Suren Baghdasaryan87966742018-04-13 12:43:41 -0700663}
664
Jing Ji5c480962019-12-04 09:22:05 -0800665static bool claim_record(struct proc* procp, pid_t pid) {
666 if (procp->reg_pid == pid) {
667 /* Record already belongs to the registrant */
668 return true;
669 }
670 if (procp->reg_pid == 0) {
671 /* Old registrant is gone, claim the record */
672 procp->reg_pid = pid;
673 return true;
674 }
675 /* The record is owned by another registrant */
676 return false;
677}
678
679static void remove_claims(pid_t pid) {
680 int i;
681
682 for (i = 0; i < PIDHASH_SZ; i++) {
683 struct proc* procp = pidhash[i];
684 while (procp) {
685 if (procp->reg_pid == pid) {
686 procp->reg_pid = 0;
687 }
688 procp = procp->pidhash_next;
689 }
690 }
691}
692
693static void ctrl_data_close(int dsock_idx) {
694 struct epoll_event epev;
695
696 ALOGI("closing lmkd data connection");
697 if (epoll_ctl(epollfd, EPOLL_CTL_DEL, data_sock[dsock_idx].sock, &epev) == -1) {
698 // Log a warning and keep going
699 ALOGW("epoll_ctl for data connection socket failed; errno=%d", errno);
700 }
701 maxevents--;
702
703 close(data_sock[dsock_idx].sock);
704 data_sock[dsock_idx].sock = -1;
705
706 /* Mark all records of the old registrant as unclaimed */
707 remove_claims(data_sock[dsock_idx].pid);
708}
709
710static ssize_t ctrl_data_read(int dsock_idx, char* buf, size_t bufsz, struct ucred* sender_cred) {
711 struct iovec iov = {buf, bufsz};
712 char control[CMSG_SPACE(sizeof(struct ucred))];
713 struct msghdr hdr = {
714 NULL, 0, &iov, 1, control, sizeof(control), 0,
715 };
716 ssize_t ret;
717 ret = TEMP_FAILURE_RETRY(recvmsg(data_sock[dsock_idx].sock, &hdr, 0));
718 if (ret == -1) {
719 ALOGE("control data socket read failed; %s", strerror(errno));
720 return -1;
721 }
722 if (ret == 0) {
723 ALOGE("Got EOF on control data socket");
724 return -1;
725 }
726
727 struct ucred* cred = NULL;
728 struct cmsghdr* cmsg = CMSG_FIRSTHDR(&hdr);
729 while (cmsg != NULL) {
730 if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_CREDENTIALS) {
731 cred = (struct ucred*)CMSG_DATA(cmsg);
732 break;
733 }
734 cmsg = CMSG_NXTHDR(&hdr, cmsg);
735 }
736
737 if (cred == NULL) {
738 ALOGE("Failed to retrieve sender credentials");
739 /* Close the connection */
740 ctrl_data_close(dsock_idx);
741 return -1;
742 }
743
744 memcpy(sender_cred, cred, sizeof(struct ucred));
745
746 /* Store PID of the peer */
747 data_sock[dsock_idx].pid = cred->pid;
748
749 return ret;
750}
751
752static int ctrl_data_write(int dsock_idx, char* buf, size_t bufsz) {
753 int ret = 0;
754
755 ret = TEMP_FAILURE_RETRY(write(data_sock[dsock_idx].sock, buf, bufsz));
756
757 if (ret == -1) {
758 ALOGE("control data socket write failed; errno=%d", errno);
759 } else if (ret == 0) {
760 ALOGE("Got EOF on control data socket");
761 ret = -1;
762 }
763
764 return ret;
765}
766
767/*
768 * Write the pid/uid pair over the data socket, note: all active clients
769 * will receive this unsolicited notification.
770 */
771static void ctrl_data_write_lmk_kill_occurred(pid_t pid, uid_t uid) {
772 LMKD_CTRL_PACKET packet;
773 size_t len = lmkd_pack_set_prockills(packet, pid, uid);
774
775 for (int i = 0; i < MAX_DATA_CONN; i++) {
Suren Baghdasaryan36baf442019-12-23 11:37:34 -0800776 if (data_sock[i].sock >= 0 && data_sock[i].async_event_mask & 1 << LMK_ASYNC_EVENT_KILL) {
Jing Ji5c480962019-12-04 09:22:05 -0800777 ctrl_data_write(i, (char*)packet, len);
778 }
779 }
780}
781
Vova Sharaienkoa92b76b2021-04-24 00:30:06 +0000782/*
783 * Write the kill_stat/memory_stat over the data socket to be propagated via AMS to statsd
784 */
785static void stats_write_lmk_kill_occurred(struct kill_stat *kill_st,
786 struct memory_stat *mem_st) {
787 LMK_KILL_OCCURRED_PACKET packet;
788 const size_t len = lmkd_pack_set_kill_occurred(packet, kill_st, mem_st);
789 if (len == 0) {
790 return;
791 }
792
793 for (int i = 0; i < MAX_DATA_CONN; i++) {
794 if (data_sock[i].sock >= 0 && data_sock[i].async_event_mask & 1 << LMK_ASYNC_EVENT_STAT) {
795 ctrl_data_write(i, packet, len);
796 }
797 }
798
799}
800
801static void stats_write_lmk_kill_occurred_pid(int pid, struct kill_stat *kill_st,
802 struct memory_stat *mem_st) {
803 kill_st->taskname = stats_get_task_name(pid);
804 if (kill_st->taskname != NULL) {
805 stats_write_lmk_kill_occurred(kill_st, mem_st);
806 }
807}
808
809/*
810 * Write the state_changed over the data socket to be propagated via AMS to statsd
811 */
812static void stats_write_lmk_state_changed(enum lmk_state state) {
813 LMKD_CTRL_PACKET packet_state_changed;
814 const size_t len = lmkd_pack_set_state_changed(packet_state_changed, state);
815 if (len == 0) {
816 return;
817 }
818 for (int i = 0; i < MAX_DATA_CONN; i++) {
819 if (data_sock[i].sock >= 0 && data_sock[i].async_event_mask & 1 << LMK_ASYNC_EVENT_STAT) {
820 ctrl_data_write(i, (char*)packet_state_changed, len);
821 }
822 }
823}
824
Jing Ji5c480962019-12-04 09:22:05 -0800825static void poll_kernel(int poll_fd) {
826 if (poll_fd == -1) {
827 // not waiting
828 return;
829 }
830
831 while (1) {
832 char rd_buf[256];
833 int bytes_read = TEMP_FAILURE_RETRY(pread(poll_fd, (void*)rd_buf, sizeof(rd_buf), 0));
834 if (bytes_read <= 0) break;
835 rd_buf[bytes_read] = '\0';
836
837 int64_t pid;
838 int64_t uid;
839 int64_t group_leader_pid;
840 int64_t rss_in_pages;
841 struct memory_stat mem_st = {};
842 int16_t oom_score_adj;
843 int16_t min_score_adj;
844 int64_t starttime;
845 char* taskname = 0;
846
847 int fields_read =
848 sscanf(rd_buf,
849 "%" SCNd64 " %" SCNd64 " %" SCNd64 " %" SCNd64 " %" SCNd64 " %" SCNd64
850 " %" SCNd16 " %" SCNd16 " %" SCNd64 "\n%m[^\n]",
851 &pid, &uid, &group_leader_pid, &mem_st.pgfault, &mem_st.pgmajfault,
852 &rss_in_pages, &oom_score_adj, &min_score_adj, &starttime, &taskname);
853
854 /* only the death of the group leader process is logged */
855 if (fields_read == 10 && group_leader_pid == pid) {
856 ctrl_data_write_lmk_kill_occurred((pid_t)pid, (uid_t)uid);
857 mem_st.process_start_time_ns = starttime * (NS_PER_SEC / sysconf(_SC_CLK_TCK));
858 mem_st.rss_in_bytes = rss_in_pages * PAGE_SIZE;
Suren Baghdasaryan3cc1f132020-09-09 20:19:02 -0700859
860 struct kill_stat kill_st = {
861 .uid = static_cast<int32_t>(uid),
862 .kill_reason = NONE,
863 .oom_score = oom_score_adj,
864 .min_oom_score = min_score_adj,
865 .free_mem_kb = 0,
866 .free_swap_kb = 0,
867 };
868 stats_write_lmk_kill_occurred_pid(pid, &kill_st, &mem_st);
Jing Ji5c480962019-12-04 09:22:05 -0800869 }
870
871 free(taskname);
872 }
873}
874
875static bool init_poll_kernel() {
876 kpoll_fd = TEMP_FAILURE_RETRY(open("/proc/lowmemorykiller", O_RDONLY | O_NONBLOCK | O_CLOEXEC));
877
878 if (kpoll_fd < 0) {
879 ALOGE("kernel lmk event file could not be opened; errno=%d", errno);
880 return false;
881 }
882
883 return true;
884}
885
Todd Poynorc58c5142013-07-09 19:35:14 -0700886static struct proc *pid_lookup(int pid) {
887 struct proc *procp;
888
889 for (procp = pidhash[pid_hashfn(pid)]; procp && procp->pid != pid;
890 procp = procp->pidhash_next)
891 ;
892
893 return procp;
894}
895
Tom Cherry43f3d2b2019-12-04 12:46:57 -0800896static void adjslot_insert(struct adjslot_list *head, struct adjslot_list *new_element)
Todd Poynorc58c5142013-07-09 19:35:14 -0700897{
898 struct adjslot_list *next = head->next;
Tom Cherry43f3d2b2019-12-04 12:46:57 -0800899 new_element->prev = head;
900 new_element->next = next;
901 next->prev = new_element;
902 head->next = new_element;
Todd Poynorc58c5142013-07-09 19:35:14 -0700903}
904
905static void adjslot_remove(struct adjslot_list *old)
906{
907 struct adjslot_list *prev = old->prev;
908 struct adjslot_list *next = old->next;
909 next->prev = prev;
910 prev->next = next;
911}
912
913static struct adjslot_list *adjslot_tail(struct adjslot_list *head) {
914 struct adjslot_list *asl = head->prev;
915
916 return asl == head ? NULL : asl;
917}
918
919static void proc_slot(struct proc *procp) {
920 int adjslot = ADJTOSLOT(procp->oomadj);
921
922 adjslot_insert(&procadjslot_list[adjslot], &procp->asl);
923}
924
925static void proc_unslot(struct proc *procp) {
926 adjslot_remove(&procp->asl);
927}
928
929static void proc_insert(struct proc *procp) {
930 int hval = pid_hashfn(procp->pid);
931
932 procp->pidhash_next = pidhash[hval];
933 pidhash[hval] = procp;
934 proc_slot(procp);
935}
936
937static int pid_remove(int pid) {
938 int hval = pid_hashfn(pid);
939 struct proc *procp;
940 struct proc *prevp;
941
942 for (procp = pidhash[hval], prevp = NULL; procp && procp->pid != pid;
943 procp = procp->pidhash_next)
944 prevp = procp;
945
946 if (!procp)
947 return -1;
948
949 if (!prevp)
950 pidhash[hval] = procp->pidhash_next;
951 else
952 prevp->pidhash_next = procp->pidhash_next;
953
954 proc_unslot(procp);
Suren Baghdasaryana10157c2019-07-19 10:55:39 -0700955 /*
956 * Close pidfd here if we are not waiting for corresponding process to die,
957 * in which case stop_wait_for_proc_kill() will close the pidfd later
958 */
959 if (procp->pidfd >= 0 && procp->pidfd != last_kill_pid_or_fd) {
960 close(procp->pidfd);
961 }
Todd Poynorc58c5142013-07-09 19:35:14 -0700962 free(procp);
963 return 0;
964}
965
Suren Baghdasaryanf584fff2018-03-20 13:53:17 -0700966/*
967 * Write a string to a file.
968 * Returns false if the file does not exist.
969 */
970static bool writefilestring(const char *path, const char *s,
971 bool err_if_missing) {
Nick Kralevich148d8dd2015-12-18 20:52:37 -0800972 int fd = open(path, O_WRONLY | O_CLOEXEC);
Suren Baghdasaryanf584fff2018-03-20 13:53:17 -0700973 ssize_t len = strlen(s);
974 ssize_t ret;
Todd Poynorc58c5142013-07-09 19:35:14 -0700975
976 if (fd < 0) {
Suren Baghdasaryanf584fff2018-03-20 13:53:17 -0700977 if (err_if_missing) {
978 ALOGE("Error opening %s; errno=%d", path, errno);
979 }
980 return false;
Todd Poynorc58c5142013-07-09 19:35:14 -0700981 }
982
Suren Baghdasaryanf584fff2018-03-20 13:53:17 -0700983 ret = TEMP_FAILURE_RETRY(write(fd, s, len));
Todd Poynorc58c5142013-07-09 19:35:14 -0700984 if (ret < 0) {
985 ALOGE("Error writing %s; errno=%d", path, errno);
986 } else if (ret < len) {
Suren Baghdasaryanf584fff2018-03-20 13:53:17 -0700987 ALOGE("Short write on %s; length=%zd", path, ret);
Todd Poynorc58c5142013-07-09 19:35:14 -0700988 }
989
990 close(fd);
Suren Baghdasaryanf584fff2018-03-20 13:53:17 -0700991 return true;
Todd Poynorc58c5142013-07-09 19:35:14 -0700992}
993
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -0700994static inline long get_time_diff_ms(struct timespec *from,
995 struct timespec *to) {
996 return (to->tv_sec - from->tv_sec) * (long)MS_PER_SEC +
997 (to->tv_nsec - from->tv_nsec) / (long)NS_PER_MS;
998}
999
Ioannis Ilkos279268a2020-08-01 10:50:40 +01001000/* Reads /proc/pid/status into buf. */
1001static bool read_proc_status(int pid, char *buf, size_t buf_sz) {
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -07001002 char path[PATH_MAX];
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -07001003 int fd;
1004 ssize_t size;
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -07001005
1006 snprintf(path, PATH_MAX, "/proc/%d/status", pid);
1007 fd = open(path, O_RDONLY | O_CLOEXEC);
1008 if (fd < 0) {
Ioannis Ilkos279268a2020-08-01 10:50:40 +01001009 return false;
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -07001010 }
1011
Ioannis Ilkos279268a2020-08-01 10:50:40 +01001012 size = read_all(fd, buf, buf_sz - 1);
1013 close(fd);
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -07001014 if (size < 0) {
Ioannis Ilkos279268a2020-08-01 10:50:40 +01001015 return false;
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -07001016 }
1017 buf[size] = 0;
Ioannis Ilkos279268a2020-08-01 10:50:40 +01001018 return true;
1019}
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -07001020
Ioannis Ilkos279268a2020-08-01 10:50:40 +01001021/* Looks for tag in buf and parses the first integer */
1022static bool parse_status_tag(char *buf, const char *tag, int64_t *out) {
1023 char *pos = buf;
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -07001024 while (true) {
Ioannis Ilkos279268a2020-08-01 10:50:40 +01001025 pos = strstr(pos, tag);
1026 /* Stop if tag not found or found at the line beginning */
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -07001027 if (pos == NULL || pos == buf || pos[-1] == '\n') {
1028 break;
1029 }
1030 pos++;
1031 }
1032
1033 if (pos == NULL) {
Ioannis Ilkos279268a2020-08-01 10:50:40 +01001034 return false;
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -07001035 }
1036
Ioannis Ilkos279268a2020-08-01 10:50:40 +01001037 pos += strlen(tag);
1038 while (*pos == ' ') ++pos;
1039 return parse_int64(pos, out);
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -07001040}
1041
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07001042static int proc_get_size(int pid) {
1043 char path[PATH_MAX];
1044 char line[LINE_MAX];
1045 int fd;
1046 int rss = 0;
1047 int total;
1048 ssize_t ret;
1049
1050 /* gid containing AID_READPROC required */
1051 snprintf(path, PATH_MAX, "/proc/%d/statm", pid);
1052 fd = open(path, O_RDONLY | O_CLOEXEC);
1053 if (fd == -1)
1054 return -1;
1055
1056 ret = read_all(fd, line, sizeof(line) - 1);
1057 if (ret < 0) {
1058 close(fd);
1059 return -1;
1060 }
Suren Baghdasaryan632f1c52019-10-04 16:06:55 -07001061 line[ret] = '\0';
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07001062
1063 sscanf(line, "%d %d ", &total, &rss);
1064 close(fd);
1065 return rss;
1066}
1067
Suren Baghdasaryan632f1c52019-10-04 16:06:55 -07001068static char *proc_get_name(int pid, char *buf, size_t buf_size) {
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07001069 char path[PATH_MAX];
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07001070 int fd;
1071 char *cp;
1072 ssize_t ret;
1073
1074 /* gid containing AID_READPROC required */
1075 snprintf(path, PATH_MAX, "/proc/%d/cmdline", pid);
1076 fd = open(path, O_RDONLY | O_CLOEXEC);
1077 if (fd == -1) {
1078 return NULL;
1079 }
Suren Baghdasaryan632f1c52019-10-04 16:06:55 -07001080 ret = read_all(fd, buf, buf_size - 1);
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07001081 close(fd);
1082 if (ret < 0) {
1083 return NULL;
1084 }
Suren Baghdasaryan632f1c52019-10-04 16:06:55 -07001085 buf[ret] = '\0';
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07001086
Suren Baghdasaryan632f1c52019-10-04 16:06:55 -07001087 cp = strchr(buf, ' ');
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07001088 if (cp) {
1089 *cp = '\0';
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07001090 }
1091
Suren Baghdasaryan632f1c52019-10-04 16:06:55 -07001092 return buf;
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07001093}
1094
Suren Baghdasaryana93503e2019-10-22 17:12:01 -07001095static void cmd_procprio(LMKD_CTRL_PACKET packet, int field_count, struct ucred *cred) {
Todd Poynorc58c5142013-07-09 19:35:14 -07001096 struct proc *procp;
Suren Baghdasaryan632f1c52019-10-04 16:06:55 -07001097 char path[LINE_MAX];
Todd Poynorc58c5142013-07-09 19:35:14 -07001098 char val[20];
Robert Benea58d6a132017-06-01 16:32:31 -07001099 int soft_limit_mult;
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -08001100 struct lmk_procprio params;
Suren Baghdasaryanbb7747b2018-03-20 16:03:29 -07001101 bool is_system_server;
1102 struct passwd *pwdrec;
Ioannis Ilkos279268a2020-08-01 10:50:40 +01001103 int64_t tgid;
1104 char buf[PAGE_SIZE];
Todd Poynorc58c5142013-07-09 19:35:14 -07001105
Suren Baghdasaryana93503e2019-10-22 17:12:01 -07001106 lmkd_pack_get_procprio(packet, field_count, &params);
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -08001107
1108 if (params.oomadj < OOM_SCORE_ADJ_MIN ||
1109 params.oomadj > OOM_SCORE_ADJ_MAX) {
1110 ALOGE("Invalid PROCPRIO oomadj argument %d", params.oomadj);
Todd Poynorc58c5142013-07-09 19:35:14 -07001111 return;
1112 }
1113
Suren Baghdasaryana93503e2019-10-22 17:12:01 -07001114 if (params.ptype < PROC_TYPE_FIRST || params.ptype >= PROC_TYPE_COUNT) {
1115 ALOGE("Invalid PROCPRIO process type argument %d", params.ptype);
1116 return;
1117 }
1118
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -07001119 /* Check if registered process is a thread group leader */
Ioannis Ilkos279268a2020-08-01 10:50:40 +01001120 if (read_proc_status(params.pid, buf, sizeof(buf))) {
1121 if (parse_status_tag(buf, PROC_STATUS_TGID_FIELD, &tgid) && tgid != params.pid) {
1122 ALOGE("Attempt to register a task that is not a thread group leader "
1123 "(tid %d, tgid %" PRId64 ")", params.pid, tgid);
1124 return;
1125 }
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -07001126 }
1127
Mark Salyzyna00ccd82018-04-09 09:50:32 -07001128 /* gid containing AID_READPROC required */
1129 /* CAP_SYS_RESOURCE required */
1130 /* CAP_DAC_OVERRIDE required */
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -08001131 snprintf(path, sizeof(path), "/proc/%d/oom_score_adj", params.pid);
1132 snprintf(val, sizeof(val), "%d", params.oomadj);
Suren Baghdasaryanf584fff2018-03-20 13:53:17 -07001133 if (!writefilestring(path, val, false)) {
1134 ALOGW("Failed to open %s; errno=%d: process %d might have been killed",
1135 path, errno, params.pid);
1136 /* If this file does not exist the process is dead. */
1137 return;
1138 }
Todd Poynorc58c5142013-07-09 19:35:14 -07001139
Mark Salyzyn5cc80b32018-03-21 12:24:58 -07001140 if (use_inkernel_interface) {
Jing Ji5c480962019-12-04 09:22:05 -08001141 stats_store_taskname(params.pid, proc_get_name(params.pid, path, sizeof(path)));
Todd Poynorc58c5142013-07-09 19:35:14 -07001142 return;
Mark Salyzyn5cc80b32018-03-21 12:24:58 -07001143 }
Todd Poynorc58c5142013-07-09 19:35:14 -07001144
Suren Baghdasaryana93503e2019-10-22 17:12:01 -07001145 /* lmkd should not change soft limits for services */
1146 if (params.ptype == PROC_TYPE_APP && per_app_memcg) {
Suren Baghdasaryanb0bda552018-05-18 14:42:00 -07001147 if (params.oomadj >= 900) {
1148 soft_limit_mult = 0;
1149 } else if (params.oomadj >= 800) {
1150 soft_limit_mult = 0;
1151 } else if (params.oomadj >= 700) {
1152 soft_limit_mult = 0;
1153 } else if (params.oomadj >= 600) {
1154 // Launcher should be perceptible, don't kill it.
1155 params.oomadj = 200;
1156 soft_limit_mult = 1;
1157 } else if (params.oomadj >= 500) {
1158 soft_limit_mult = 0;
1159 } else if (params.oomadj >= 400) {
1160 soft_limit_mult = 0;
1161 } else if (params.oomadj >= 300) {
1162 soft_limit_mult = 1;
1163 } else if (params.oomadj >= 200) {
Srinivas Paladugua453f0b2018-10-09 14:21:10 -07001164 soft_limit_mult = 8;
Suren Baghdasaryanb0bda552018-05-18 14:42:00 -07001165 } else if (params.oomadj >= 100) {
1166 soft_limit_mult = 10;
1167 } else if (params.oomadj >= 0) {
1168 soft_limit_mult = 20;
1169 } else {
1170 // Persistent processes will have a large
1171 // soft limit 512MB.
1172 soft_limit_mult = 64;
1173 }
Robert Benea58d6a132017-06-01 16:32:31 -07001174
Suren Baghdasaryanbf919ff2018-05-21 19:48:47 -07001175 snprintf(path, sizeof(path), MEMCG_SYSFS_PATH
1176 "apps/uid_%d/pid_%d/memory.soft_limit_in_bytes",
1177 params.uid, params.pid);
Suren Baghdasaryanb0bda552018-05-18 14:42:00 -07001178 snprintf(val, sizeof(val), "%d", soft_limit_mult * EIGHT_MEGA);
Suren Baghdasaryanbf919ff2018-05-21 19:48:47 -07001179
1180 /*
1181 * system_server process has no memcg under /dev/memcg/apps but should be
1182 * registered with lmkd. This is the best way so far to identify it.
1183 */
1184 is_system_server = (params.oomadj == SYSTEM_ADJ &&
1185 (pwdrec = getpwnam("system")) != NULL &&
1186 params.uid == pwdrec->pw_uid);
1187 writefilestring(path, val, !is_system_server);
Robert Benea58d6a132017-06-01 16:32:31 -07001188 }
1189
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -08001190 procp = pid_lookup(params.pid);
Todd Poynorc58c5142013-07-09 19:35:14 -07001191 if (!procp) {
Suren Baghdasaryana10157c2019-07-19 10:55:39 -07001192 int pidfd = -1;
1193
1194 if (pidfd_supported) {
Josh Gao84623be2021-03-18 17:16:08 -07001195 pidfd = TEMP_FAILURE_RETRY(pidfd_open(params.pid, 0));
Suren Baghdasaryana10157c2019-07-19 10:55:39 -07001196 if (pidfd < 0) {
1197 ALOGE("pidfd_open for pid %d failed; errno=%d", params.pid, errno);
Todd Poynorc58c5142013-07-09 19:35:14 -07001198 return;
1199 }
Suren Baghdasaryana10157c2019-07-19 10:55:39 -07001200 }
Todd Poynorc58c5142013-07-09 19:35:14 -07001201
Tom Cherry43f3d2b2019-12-04 12:46:57 -08001202 procp = static_cast<struct proc*>(calloc(1, sizeof(struct proc)));
Suren Baghdasaryana10157c2019-07-19 10:55:39 -07001203 if (!procp) {
1204 // Oh, the irony. May need to rebuild our state.
1205 return;
1206 }
1207
1208 procp->pid = params.pid;
1209 procp->pidfd = pidfd;
1210 procp->uid = params.uid;
Suren Baghdasaryan945658a2019-10-18 11:16:52 -07001211 procp->reg_pid = cred->pid;
Suren Baghdasaryana10157c2019-07-19 10:55:39 -07001212 procp->oomadj = params.oomadj;
1213 proc_insert(procp);
Todd Poynorc58c5142013-07-09 19:35:14 -07001214 } else {
Suren Baghdasaryan945658a2019-10-18 11:16:52 -07001215 if (!claim_record(procp, cred->pid)) {
1216 char buf[LINE_MAX];
Suren Baghdasaryan9f1be122021-04-23 13:39:37 -07001217 char *taskname = proc_get_name(cred->pid, buf, sizeof(buf));
Suren Baghdasaryan945658a2019-10-18 11:16:52 -07001218 /* Only registrant of the record can remove it */
1219 ALOGE("%s (%d, %d) attempts to modify a process registered by another client",
Suren Baghdasaryan9f1be122021-04-23 13:39:37 -07001220 taskname ? taskname : "A process ", cred->uid, cred->pid);
Suren Baghdasaryan945658a2019-10-18 11:16:52 -07001221 return;
1222 }
Todd Poynorc58c5142013-07-09 19:35:14 -07001223 proc_unslot(procp);
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -08001224 procp->oomadj = params.oomadj;
Todd Poynorc58c5142013-07-09 19:35:14 -07001225 proc_slot(procp);
1226 }
1227}
1228
Suren Baghdasaryan945658a2019-10-18 11:16:52 -07001229static void cmd_procremove(LMKD_CTRL_PACKET packet, struct ucred *cred) {
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -08001230 struct lmk_procremove params;
Suren Baghdasaryan945658a2019-10-18 11:16:52 -07001231 struct proc *procp;
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -08001232
George Burgess IV3b36b902019-10-02 11:22:55 -07001233 lmkd_pack_get_procremove(packet, &params);
Suren Baghdasaryan945658a2019-10-18 11:16:52 -07001234
Mark Salyzyn5cc80b32018-03-21 12:24:58 -07001235 if (use_inkernel_interface) {
Jing Ji5c480962019-12-04 09:22:05 -08001236 /*
1237 * Perform an extra check before the pid is removed, after which it
1238 * will be impossible for poll_kernel to get the taskname. poll_kernel()
1239 * is potentially a long-running blocking function; however this method
1240 * handles AMS requests but does not block AMS.
1241 */
1242 poll_kernel(kpoll_fd);
1243
1244 stats_remove_taskname(params.pid);
Todd Poynorc58c5142013-07-09 19:35:14 -07001245 return;
Mark Salyzyn5cc80b32018-03-21 12:24:58 -07001246 }
Todd Poynorc58c5142013-07-09 19:35:14 -07001247
Suren Baghdasaryan945658a2019-10-18 11:16:52 -07001248 procp = pid_lookup(params.pid);
1249 if (!procp) {
1250 return;
1251 }
1252
1253 if (!claim_record(procp, cred->pid)) {
1254 char buf[LINE_MAX];
Suren Baghdasaryan9f1be122021-04-23 13:39:37 -07001255 char *taskname = proc_get_name(cred->pid, buf, sizeof(buf));
Suren Baghdasaryan945658a2019-10-18 11:16:52 -07001256 /* Only registrant of the record can remove it */
1257 ALOGE("%s (%d, %d) attempts to unregister a process registered by another client",
Suren Baghdasaryan9f1be122021-04-23 13:39:37 -07001258 taskname ? taskname : "A process ", cred->uid, cred->pid);
Suren Baghdasaryan945658a2019-10-18 11:16:52 -07001259 return;
1260 }
1261
Suren Baghdasaryan8b00c6d2018-10-12 11:28:33 -07001262 /*
1263 * WARNING: After pid_remove() procp is freed and can't be used!
1264 * Therefore placed at the end of the function.
1265 */
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -08001266 pid_remove(params.pid);
Todd Poynorc58c5142013-07-09 19:35:14 -07001267}
1268
Suren Baghdasaryan945658a2019-10-18 11:16:52 -07001269static void cmd_procpurge(struct ucred *cred) {
Suren Baghdasaryan83df0082018-10-10 14:17:17 -07001270 int i;
1271 struct proc *procp;
1272 struct proc *next;
1273
1274 if (use_inkernel_interface) {
Jim Blackler90853b62019-09-10 15:30:05 +01001275 stats_purge_tasknames();
Suren Baghdasaryan83df0082018-10-10 14:17:17 -07001276 return;
1277 }
1278
Suren Baghdasaryan83df0082018-10-10 14:17:17 -07001279 for (i = 0; i < PIDHASH_SZ; i++) {
1280 procp = pidhash[i];
1281 while (procp) {
1282 next = procp->pidhash_next;
Suren Baghdasaryan945658a2019-10-18 11:16:52 -07001283 /* Purge only records created by the requestor */
1284 if (claim_record(procp, cred->pid)) {
1285 pid_remove(procp->pid);
1286 }
Suren Baghdasaryan83df0082018-10-10 14:17:17 -07001287 procp = next;
1288 }
1289 }
Suren Baghdasaryan83df0082018-10-10 14:17:17 -07001290}
1291
Suren Baghdasaryan36baf442019-12-23 11:37:34 -08001292static void cmd_subscribe(int dsock_idx, LMKD_CTRL_PACKET packet) {
1293 struct lmk_subscribe params;
1294
1295 lmkd_pack_get_subscribe(packet, &params);
1296 data_sock[dsock_idx].async_event_mask |= 1 << params.evt_type;
1297}
1298
Suren Baghdasaryana7394ea2018-10-12 11:07:40 -07001299static void inc_killcnt(int oomadj) {
1300 int slot = ADJTOSLOT(oomadj);
1301 uint8_t idx = killcnt_idx[slot];
1302
1303 if (idx == KILLCNT_INVALID_IDX) {
1304 /* index is not assigned for this oomadj */
1305 if (killcnt_free_idx < MAX_DISTINCT_OOM_ADJ) {
1306 killcnt_idx[slot] = killcnt_free_idx;
1307 killcnt[killcnt_free_idx] = 1;
1308 killcnt_free_idx++;
1309 } else {
1310 ALOGW("Number of distinct oomadj levels exceeds %d",
1311 MAX_DISTINCT_OOM_ADJ);
1312 }
1313 } else {
1314 /*
1315 * wraparound is highly unlikely and is detectable using total
1316 * counter because it has to be equal to the sum of all counters
1317 */
1318 killcnt[idx]++;
1319 }
1320 /* increment total kill counter */
1321 killcnt_total++;
1322}
1323
1324static int get_killcnt(int min_oomadj, int max_oomadj) {
1325 int slot;
1326 int count = 0;
1327
1328 if (min_oomadj > max_oomadj)
1329 return 0;
1330
1331 /* special case to get total kill count */
1332 if (min_oomadj > OOM_SCORE_ADJ_MAX)
1333 return killcnt_total;
1334
1335 while (min_oomadj <= max_oomadj &&
1336 (slot = ADJTOSLOT(min_oomadj)) < ADJTOSLOT_COUNT) {
1337 uint8_t idx = killcnt_idx[slot];
1338 if (idx != KILLCNT_INVALID_IDX) {
1339 count += killcnt[idx];
1340 }
1341 min_oomadj++;
1342 }
1343
1344 return count;
1345}
1346
1347static int cmd_getkillcnt(LMKD_CTRL_PACKET packet) {
1348 struct lmk_getkillcnt params;
1349
1350 if (use_inkernel_interface) {
1351 /* kernel driver does not expose this information */
1352 return 0;
1353 }
1354
1355 lmkd_pack_get_getkillcnt(packet, &params);
1356
1357 return get_killcnt(params.min_oomadj, params.max_oomadj);
1358}
1359
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -08001360static void cmd_target(int ntargets, LMKD_CTRL_PACKET packet) {
Todd Poynorc58c5142013-07-09 19:35:14 -07001361 int i;
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -08001362 struct lmk_target target;
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -07001363 char minfree_str[PROPERTY_VALUE_MAX];
1364 char *pstr = minfree_str;
1365 char *pend = minfree_str + sizeof(minfree_str);
1366 static struct timespec last_req_tm;
1367 struct timespec curr_tm;
Todd Poynorc58c5142013-07-09 19:35:14 -07001368
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -07001369 if (ntargets < 1 || ntargets > (int)ARRAY_SIZE(lowmem_adj))
Todd Poynorc58c5142013-07-09 19:35:14 -07001370 return;
1371
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -07001372 /*
1373 * Ratelimit minfree updates to once per TARGET_UPDATE_MIN_INTERVAL_MS
1374 * to prevent DoS attacks
1375 */
1376 if (clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm) != 0) {
1377 ALOGE("Failed to get current time");
1378 return;
1379 }
1380
1381 if (get_time_diff_ms(&last_req_tm, &curr_tm) <
1382 TARGET_UPDATE_MIN_INTERVAL_MS) {
1383 ALOGE("Ignoring frequent updated to lmkd limits");
1384 return;
1385 }
1386
1387 last_req_tm = curr_tm;
1388
Todd Poynorc58c5142013-07-09 19:35:14 -07001389 for (i = 0; i < ntargets; i++) {
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -08001390 lmkd_pack_get_target(packet, i, &target);
1391 lowmem_minfree[i] = target.minfree;
1392 lowmem_adj[i] = target.oom_adj_score;
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -07001393
1394 pstr += snprintf(pstr, pend - pstr, "%d:%d,", target.minfree,
1395 target.oom_adj_score);
1396 if (pstr >= pend) {
1397 /* if no more space in the buffer then terminate the loop */
1398 pstr = pend;
1399 break;
1400 }
Todd Poynorc58c5142013-07-09 19:35:14 -07001401 }
1402
1403 lowmem_targets_size = ntargets;
1404
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -07001405 /* Override the last extra comma */
1406 pstr[-1] = '\0';
1407 property_set("sys.lmk.minfree_levels", minfree_str);
1408
Robert Benea7878c9b2017-09-11 16:53:28 -07001409 if (has_inkernel_module) {
Todd Poynorc58c5142013-07-09 19:35:14 -07001410 char minfreestr[128];
1411 char killpriostr[128];
1412
1413 minfreestr[0] = '\0';
1414 killpriostr[0] = '\0';
1415
1416 for (i = 0; i < lowmem_targets_size; i++) {
1417 char val[40];
1418
1419 if (i) {
1420 strlcat(minfreestr, ",", sizeof(minfreestr));
1421 strlcat(killpriostr, ",", sizeof(killpriostr));
1422 }
1423
Robert Benea7878c9b2017-09-11 16:53:28 -07001424 snprintf(val, sizeof(val), "%d", use_inkernel_interface ? lowmem_minfree[i] : 0);
Todd Poynorc58c5142013-07-09 19:35:14 -07001425 strlcat(minfreestr, val, sizeof(minfreestr));
Robert Benea7878c9b2017-09-11 16:53:28 -07001426 snprintf(val, sizeof(val), "%d", use_inkernel_interface ? lowmem_adj[i] : 0);
Todd Poynorc58c5142013-07-09 19:35:14 -07001427 strlcat(killpriostr, val, sizeof(killpriostr));
1428 }
1429
Suren Baghdasaryanf584fff2018-03-20 13:53:17 -07001430 writefilestring(INKERNEL_MINFREE_PATH, minfreestr, true);
1431 writefilestring(INKERNEL_ADJ_PATH, killpriostr, true);
Todd Poynorc58c5142013-07-09 19:35:14 -07001432 }
1433}
1434
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08001435static void ctrl_command_handler(int dsock_idx) {
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -08001436 LMKD_CTRL_PACKET packet;
Suren Baghdasaryan945658a2019-10-18 11:16:52 -07001437 struct ucred cred;
Todd Poynorc58c5142013-07-09 19:35:14 -07001438 int len;
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -08001439 enum lmk_cmd cmd;
Todd Poynorc58c5142013-07-09 19:35:14 -07001440 int nargs;
1441 int targets;
Suren Baghdasaryana7394ea2018-10-12 11:07:40 -07001442 int kill_cnt;
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07001443 int result;
Todd Poynorc58c5142013-07-09 19:35:14 -07001444
Suren Baghdasaryan945658a2019-10-18 11:16:52 -07001445 len = ctrl_data_read(dsock_idx, (char *)packet, CTRL_PACKET_MAX_SIZE, &cred);
Todd Poynorc58c5142013-07-09 19:35:14 -07001446 if (len <= 0)
1447 return;
1448
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -08001449 if (len < (int)sizeof(int)) {
1450 ALOGE("Wrong control socket read length len=%d", len);
1451 return;
1452 }
1453
1454 cmd = lmkd_pack_get_cmd(packet);
Todd Poynorc58c5142013-07-09 19:35:14 -07001455 nargs = len / sizeof(int) - 1;
1456 if (nargs < 0)
1457 goto wronglen;
1458
Todd Poynorc58c5142013-07-09 19:35:14 -07001459 switch(cmd) {
1460 case LMK_TARGET:
1461 targets = nargs / 2;
1462 if (nargs & 0x1 || targets > (int)ARRAY_SIZE(lowmem_adj))
1463 goto wronglen;
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -08001464 cmd_target(targets, packet);
Todd Poynorc58c5142013-07-09 19:35:14 -07001465 break;
1466 case LMK_PROCPRIO:
Suren Baghdasaryana93503e2019-10-22 17:12:01 -07001467 /* process type field is optional for backward compatibility */
1468 if (nargs < 3 || nargs > 4)
Todd Poynorc58c5142013-07-09 19:35:14 -07001469 goto wronglen;
Suren Baghdasaryana93503e2019-10-22 17:12:01 -07001470 cmd_procprio(packet, nargs, &cred);
Todd Poynorc58c5142013-07-09 19:35:14 -07001471 break;
1472 case LMK_PROCREMOVE:
1473 if (nargs != 1)
1474 goto wronglen;
Suren Baghdasaryan945658a2019-10-18 11:16:52 -07001475 cmd_procremove(packet, &cred);
Todd Poynorc58c5142013-07-09 19:35:14 -07001476 break;
Suren Baghdasaryan83df0082018-10-10 14:17:17 -07001477 case LMK_PROCPURGE:
1478 if (nargs != 0)
1479 goto wronglen;
Suren Baghdasaryan945658a2019-10-18 11:16:52 -07001480 cmd_procpurge(&cred);
Suren Baghdasaryan83df0082018-10-10 14:17:17 -07001481 break;
Suren Baghdasaryana7394ea2018-10-12 11:07:40 -07001482 case LMK_GETKILLCNT:
1483 if (nargs != 2)
1484 goto wronglen;
1485 kill_cnt = cmd_getkillcnt(packet);
1486 len = lmkd_pack_set_getkillcnt_repl(packet, kill_cnt);
1487 if (ctrl_data_write(dsock_idx, (char *)packet, len) != len)
1488 return;
1489 break;
Suren Baghdasaryan36baf442019-12-23 11:37:34 -08001490 case LMK_SUBSCRIBE:
1491 if (nargs != 1)
1492 goto wronglen;
1493 cmd_subscribe(dsock_idx, packet);
1494 break;
Jing Ji5c480962019-12-04 09:22:05 -08001495 case LMK_PROCKILL:
1496 /* This command code is NOT expected at all */
1497 ALOGE("Received unexpected command code %d", cmd);
1498 break;
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07001499 case LMK_UPDATE_PROPS:
1500 if (nargs != 0)
1501 goto wronglen;
1502 update_props();
1503 if (!use_inkernel_interface) {
1504 /* Reinitialize monitors to apply new settings */
1505 destroy_monitors();
1506 result = init_monitors() ? 0 : -1;
1507 } else {
1508 result = 0;
1509 }
1510 len = lmkd_pack_set_update_props_repl(packet, result);
1511 if (ctrl_data_write(dsock_idx, (char *)packet, len) != len) {
1512 ALOGE("Failed to report operation results");
1513 }
1514 if (!result) {
1515 ALOGI("Properties reinitilized");
1516 } else {
1517 /* New settings can't be supported, crash to be restarted */
1518 ALOGE("New configuration is not supported. Exiting...");
1519 exit(1);
1520 }
1521 break;
Todd Poynorc58c5142013-07-09 19:35:14 -07001522 default:
1523 ALOGE("Received unknown command code %d", cmd);
1524 return;
1525 }
1526
1527 return;
1528
1529wronglen:
1530 ALOGE("Wrong control socket read length cmd=%d len=%d", cmd, len);
1531}
1532
Suren Baghdasaryane12a0672019-07-15 14:50:49 -07001533static void ctrl_data_handler(int data, uint32_t events,
1534 struct polling_params *poll_params __unused) {
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08001535 if (events & EPOLLIN) {
1536 ctrl_command_handler(data);
Todd Poynorc58c5142013-07-09 19:35:14 -07001537 }
1538}
1539
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08001540static int get_free_dsock() {
1541 for (int i = 0; i < MAX_DATA_CONN; i++) {
1542 if (data_sock[i].sock < 0) {
1543 return i;
1544 }
1545 }
1546 return -1;
1547}
Todd Poynorc58c5142013-07-09 19:35:14 -07001548
Suren Baghdasaryane12a0672019-07-15 14:50:49 -07001549static void ctrl_connect_handler(int data __unused, uint32_t events __unused,
1550 struct polling_params *poll_params __unused) {
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08001551 struct epoll_event epev;
1552 int free_dscock_idx = get_free_dsock();
1553
1554 if (free_dscock_idx < 0) {
1555 /*
1556 * Number of data connections exceeded max supported. This should not
1557 * happen but if it does we drop all existing connections and accept
1558 * the new one. This prevents inactive connections from monopolizing
1559 * data socket and if we drop ActivityManager connection it will
1560 * immediately reconnect.
1561 */
1562 for (int i = 0; i < MAX_DATA_CONN; i++) {
1563 ctrl_data_close(i);
1564 }
1565 free_dscock_idx = 0;
Todd Poynorc58c5142013-07-09 19:35:14 -07001566 }
1567
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08001568 data_sock[free_dscock_idx].sock = accept(ctrl_sock.sock, NULL, NULL);
1569 if (data_sock[free_dscock_idx].sock < 0) {
Todd Poynorc58c5142013-07-09 19:35:14 -07001570 ALOGE("lmkd control socket accept failed; errno=%d", errno);
1571 return;
1572 }
1573
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08001574 ALOGI("lmkd data connection established");
1575 /* use data to store data connection idx */
1576 data_sock[free_dscock_idx].handler_info.data = free_dscock_idx;
1577 data_sock[free_dscock_idx].handler_info.handler = ctrl_data_handler;
Suren Baghdasaryan36baf442019-12-23 11:37:34 -08001578 data_sock[free_dscock_idx].async_event_mask = 0;
Todd Poynorc58c5142013-07-09 19:35:14 -07001579 epev.events = EPOLLIN;
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08001580 epev.data.ptr = (void *)&(data_sock[free_dscock_idx].handler_info);
1581 if (epoll_ctl(epollfd, EPOLL_CTL_ADD, data_sock[free_dscock_idx].sock, &epev) == -1) {
Todd Poynorc58c5142013-07-09 19:35:14 -07001582 ALOGE("epoll_ctl for data connection socket failed; errno=%d", errno);
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08001583 ctrl_data_close(free_dscock_idx);
Todd Poynorc58c5142013-07-09 19:35:14 -07001584 return;
1585 }
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08001586 maxevents++;
Todd Poynorc58c5142013-07-09 19:35:14 -07001587}
1588
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001589/*
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07001590 * /proc/zoneinfo parsing routines
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001591 * Expected file format is:
1592 *
1593 * Node <node_id>, zone <zone_name>
1594 * (
1595 * per-node stats
1596 * (<per-node field name> <value>)+
1597 * )?
1598 * (pages free <value>
1599 * (<per-zone field name> <value>)+
1600 * pagesets
1601 * (<unused fields>)*
1602 * )+
1603 * ...
1604 */
1605static void zoneinfo_parse_protection(char *buf, struct zoneinfo_zone *zone) {
1606 int zone_idx;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001607 int64_t max = 0;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001608 char *save_ptr;
1609
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001610 for (buf = strtok_r(buf, "(), ", &save_ptr), zone_idx = 0;
1611 buf && zone_idx < MAX_NR_ZONES;
1612 buf = strtok_r(NULL, "), ", &save_ptr), zone_idx++) {
1613 long long zoneval = strtoll(buf, &buf, 0);
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001614 if (zoneval > max) {
1615 max = (zoneval > INT64_MAX) ? INT64_MAX : zoneval;
1616 }
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001617 zone->protection[zone_idx] = zoneval;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001618 }
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001619 zone->max_protection = max;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001620}
1621
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001622static int zoneinfo_parse_zone(char **buf, struct zoneinfo_zone *zone) {
1623 for (char *line = strtok_r(NULL, "\n", buf); line;
1624 line = strtok_r(NULL, "\n", buf)) {
1625 char *cp;
1626 char *ap;
1627 char *save_ptr;
1628 int64_t val;
1629 int field_idx;
1630 enum field_match_result match_res;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001631
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001632 cp = strtok_r(line, " ", &save_ptr);
1633 if (!cp) {
1634 return false;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001635 }
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001636
1637 field_idx = find_field(cp, zoneinfo_zone_spec_field_names, ZI_ZONE_SPEC_FIELD_COUNT);
1638 if (field_idx >= 0) {
1639 /* special field */
1640 if (field_idx == ZI_ZONE_SPEC_PAGESETS) {
1641 /* no mode fields we are interested in */
1642 return true;
1643 }
1644
1645 /* protection field */
1646 ap = strtok_r(NULL, ")", &save_ptr);
1647 if (ap) {
1648 zoneinfo_parse_protection(ap, zone);
1649 }
1650 continue;
1651 }
1652
1653 ap = strtok_r(NULL, " ", &save_ptr);
1654 if (!ap) {
1655 continue;
1656 }
1657
1658 match_res = match_field(cp, ap, zoneinfo_zone_field_names, ZI_ZONE_FIELD_COUNT,
1659 &val, &field_idx);
1660 if (match_res == PARSE_FAIL) {
1661 return false;
1662 }
1663 if (match_res == PARSE_SUCCESS) {
1664 zone->fields.arr[field_idx] = val;
1665 }
1666 if (field_idx == ZI_ZONE_PRESENT && val == 0) {
1667 /* zone is not populated, stop parsing it */
1668 return true;
1669 }
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001670 }
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001671 return false;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001672}
1673
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001674static int zoneinfo_parse_node(char **buf, struct zoneinfo_node *node) {
1675 int fields_to_match = ZI_NODE_FIELD_COUNT;
1676
1677 for (char *line = strtok_r(NULL, "\n", buf); line;
1678 line = strtok_r(NULL, "\n", buf)) {
1679 char *cp;
1680 char *ap;
1681 char *save_ptr;
1682 int64_t val;
1683 int field_idx;
1684 enum field_match_result match_res;
1685
1686 cp = strtok_r(line, " ", &save_ptr);
1687 if (!cp) {
1688 return false;
1689 }
1690
1691 ap = strtok_r(NULL, " ", &save_ptr);
1692 if (!ap) {
1693 return false;
1694 }
1695
1696 match_res = match_field(cp, ap, zoneinfo_node_field_names, ZI_NODE_FIELD_COUNT,
1697 &val, &field_idx);
1698 if (match_res == PARSE_FAIL) {
1699 return false;
1700 }
1701 if (match_res == PARSE_SUCCESS) {
1702 node->fields.arr[field_idx] = val;
1703 fields_to_match--;
1704 if (!fields_to_match) {
1705 return true;
1706 }
1707 }
1708 }
1709 return false;
1710}
1711
1712static int zoneinfo_parse(struct zoneinfo *zi) {
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001713 static struct reread_data file_data = {
1714 .filename = ZONEINFO_PATH,
1715 .fd = -1,
1716 };
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -07001717 char *buf;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001718 char *save_ptr;
1719 char *line;
Greg Kaiser259984f2019-10-02 07:07:32 -07001720 char zone_name[LINE_MAX + 1];
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001721 struct zoneinfo_node *node = NULL;
1722 int node_idx = 0;
1723 int zone_idx = 0;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001724
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001725 memset(zi, 0, sizeof(struct zoneinfo));
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001726
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -07001727 if ((buf = reread_file(&file_data)) == NULL) {
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001728 return -1;
1729 }
1730
1731 for (line = strtok_r(buf, "\n", &save_ptr); line;
1732 line = strtok_r(NULL, "\n", &save_ptr)) {
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001733 int node_id;
1734 if (sscanf(line, "Node %d, zone %" STRINGIFY(LINE_MAX) "s", &node_id, zone_name) == 2) {
1735 if (!node || node->id != node_id) {
1736 /* new node is found */
1737 if (node) {
1738 node->zone_count = zone_idx + 1;
1739 node_idx++;
1740 if (node_idx == MAX_NR_NODES) {
1741 /* max node count exceeded */
1742 ALOGE("%s parse error", file_data.filename);
1743 return -1;
1744 }
1745 }
1746 node = &zi->nodes[node_idx];
1747 node->id = node_id;
1748 zone_idx = 0;
1749 if (!zoneinfo_parse_node(&save_ptr, node)) {
1750 ALOGE("%s parse error", file_data.filename);
1751 return -1;
1752 }
1753 } else {
1754 /* new zone is found */
1755 zone_idx++;
1756 }
1757 if (!zoneinfo_parse_zone(&save_ptr, &node->zones[zone_idx])) {
1758 ALOGE("%s parse error", file_data.filename);
1759 return -1;
1760 }
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001761 }
1762 }
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001763 if (!node) {
1764 ALOGE("%s parse error", file_data.filename);
1765 return -1;
1766 }
1767 node->zone_count = zone_idx + 1;
1768 zi->node_count = node_idx + 1;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001769
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001770 /* calculate totals fields */
1771 for (node_idx = 0; node_idx < zi->node_count; node_idx++) {
1772 node = &zi->nodes[node_idx];
1773 for (zone_idx = 0; zone_idx < node->zone_count; zone_idx++) {
1774 struct zoneinfo_zone *zone = &zi->nodes[node_idx].zones[zone_idx];
1775 zi->totalreserve_pages += zone->max_protection + zone->fields.field.high;
1776 }
1777 zi->total_inactive_file += node->fields.field.nr_inactive_file;
1778 zi->total_active_file += node->fields.field.nr_active_file;
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001779 }
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001780 return 0;
1781}
1782
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07001783/* /proc/meminfo parsing routines */
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001784static bool meminfo_parse_line(char *line, union meminfo *mi) {
1785 char *cp = line;
1786 char *ap;
1787 char *save_ptr;
1788 int64_t val;
1789 int field_idx;
1790 enum field_match_result match_res;
1791
1792 cp = strtok_r(line, " ", &save_ptr);
1793 if (!cp) {
1794 return false;
1795 }
1796
1797 ap = strtok_r(NULL, " ", &save_ptr);
1798 if (!ap) {
1799 return false;
1800 }
1801
1802 match_res = match_field(cp, ap, meminfo_field_names, MI_FIELD_COUNT,
1803 &val, &field_idx);
1804 if (match_res == PARSE_SUCCESS) {
1805 mi->arr[field_idx] = val / page_k;
1806 }
1807 return (match_res != PARSE_FAIL);
1808}
1809
Suren Baghdasaryan940e7cf2021-05-27 18:15:44 -07001810static int64_t read_gpu_total_kb() {
1811 static int fd = android::bpf::bpfFdGet(
1812 "/sys/fs/bpf/map_gpu_mem_gpu_mem_total_map", BPF_F_RDONLY);
1813 static constexpr uint64_t kBpfKeyGpuTotalUsage = 0;
1814 uint64_t value;
1815
1816 if (fd < 0) {
1817 return 0;
1818 }
1819
1820 return android::bpf::findMapEntry(fd, &kBpfKeyGpuTotalUsage, &value)
1821 ? 0
1822 : (int32_t)(value / 1024);
1823}
1824
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001825static int meminfo_parse(union meminfo *mi) {
1826 static struct reread_data file_data = {
1827 .filename = MEMINFO_PATH,
1828 .fd = -1,
1829 };
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -07001830 char *buf;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001831 char *save_ptr;
1832 char *line;
1833
1834 memset(mi, 0, sizeof(union meminfo));
1835
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -07001836 if ((buf = reread_file(&file_data)) == NULL) {
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001837 return -1;
1838 }
1839
1840 for (line = strtok_r(buf, "\n", &save_ptr); line;
1841 line = strtok_r(NULL, "\n", &save_ptr)) {
1842 if (!meminfo_parse_line(line, mi)) {
1843 ALOGE("%s parse error", file_data.filename);
1844 return -1;
1845 }
1846 }
1847 mi->field.nr_file_pages = mi->field.cached + mi->field.swap_cached +
1848 mi->field.buffers;
Suren Baghdasaryan940e7cf2021-05-27 18:15:44 -07001849 mi->field.total_gpu_kb = read_gpu_total_kb();
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001850
1851 return 0;
1852}
1853
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07001854/* /proc/vmstat parsing routines */
1855static bool vmstat_parse_line(char *line, union vmstat *vs) {
1856 char *cp;
1857 char *ap;
1858 char *save_ptr;
1859 int64_t val;
1860 int field_idx;
1861 enum field_match_result match_res;
1862
1863 cp = strtok_r(line, " ", &save_ptr);
1864 if (!cp) {
1865 return false;
1866 }
1867
1868 ap = strtok_r(NULL, " ", &save_ptr);
1869 if (!ap) {
1870 return false;
1871 }
1872
1873 match_res = match_field(cp, ap, vmstat_field_names, VS_FIELD_COUNT,
1874 &val, &field_idx);
1875 if (match_res == PARSE_SUCCESS) {
1876 vs->arr[field_idx] = val;
1877 }
1878 return (match_res != PARSE_FAIL);
1879}
1880
1881static int vmstat_parse(union vmstat *vs) {
1882 static struct reread_data file_data = {
1883 .filename = VMSTAT_PATH,
1884 .fd = -1,
1885 };
1886 char *buf;
1887 char *save_ptr;
1888 char *line;
1889
1890 memset(vs, 0, sizeof(union vmstat));
1891
1892 if ((buf = reread_file(&file_data)) == NULL) {
1893 return -1;
1894 }
1895
1896 for (line = strtok_r(buf, "\n", &save_ptr); line;
1897 line = strtok_r(NULL, "\n", &save_ptr)) {
1898 if (!vmstat_parse_line(line, vs)) {
1899 ALOGE("%s parse error", file_data.filename);
1900 return -1;
1901 }
1902 }
1903
1904 return 0;
1905}
1906
Suren Baghdasaryand7b4fcb2020-07-23 18:00:43 -07001907enum wakeup_reason {
1908 Event,
1909 Polling
1910};
1911
1912struct wakeup_info {
1913 struct timespec wakeup_tm;
1914 struct timespec prev_wakeup_tm;
1915 struct timespec last_event_tm;
1916 int wakeups_since_event;
1917 int skipped_wakeups;
1918};
1919
1920/*
1921 * After the initial memory pressure event is received lmkd schedules periodic wakeups to check
1922 * the memory conditions and kill if needed (polling). This is done because pressure events are
1923 * rate-limited and memory conditions can change in between events. Therefore after the initial
1924 * event there might be multiple wakeups. This function records the wakeup information such as the
1925 * timestamps of the last event and the last wakeup, the number of wakeups since the last event
1926 * and how many of those wakeups were skipped (some wakeups are skipped if previously killed
1927 * process is still freeing its memory).
1928 */
1929static void record_wakeup_time(struct timespec *tm, enum wakeup_reason reason,
1930 struct wakeup_info *wi) {
1931 wi->prev_wakeup_tm = wi->wakeup_tm;
1932 wi->wakeup_tm = *tm;
1933 if (reason == Event) {
1934 wi->last_event_tm = *tm;
1935 wi->wakeups_since_event = 0;
1936 wi->skipped_wakeups = 0;
1937 } else {
1938 wi->wakeups_since_event++;
1939 }
1940}
1941
Suren Baghdasaryan39b54802021-08-09 15:10:25 -07001942struct kill_info {
1943 enum kill_reasons kill_reason;
1944 const char *kill_desc;
1945 int thrashing;
1946 int max_thrashing;
1947};
1948
Ioannis Ilkos279268a2020-08-01 10:50:40 +01001949static void killinfo_log(struct proc* procp, int min_oom_score, int rss_kb,
Suren Baghdasaryan39b54802021-08-09 15:10:25 -07001950 int swap_kb, struct kill_info *ki, union meminfo *mi,
Suren Baghdasaryand7b4fcb2020-07-23 18:00:43 -07001951 struct wakeup_info *wi, struct timespec *tm) {
Suren Baghdasaryan12cacae2019-09-16 12:06:30 -07001952 /* log process information */
1953 android_log_write_int32(ctx, procp->pid);
1954 android_log_write_int32(ctx, procp->uid);
1955 android_log_write_int32(ctx, procp->oomadj);
1956 android_log_write_int32(ctx, min_oom_score);
Ioannis Ilkos279268a2020-08-01 10:50:40 +01001957 android_log_write_int32(ctx, (int32_t)min(rss_kb, INT32_MAX));
Suren Baghdasaryan39b54802021-08-09 15:10:25 -07001958 android_log_write_int32(ctx, ki ? ki->kill_reason : NONE);
Suren Baghdasaryan12cacae2019-09-16 12:06:30 -07001959
1960 /* log meminfo fields */
Suren Baghdasaryan08bfa982018-07-26 16:34:27 -07001961 for (int field_idx = 0; field_idx < MI_FIELD_COUNT; field_idx++) {
1962 android_log_write_int32(ctx, (int32_t)min(mi->arr[field_idx] * page_k, INT32_MAX));
1963 }
1964
Suren Baghdasaryand7b4fcb2020-07-23 18:00:43 -07001965 /* log lmkd wakeup information */
1966 android_log_write_int32(ctx, (int32_t)get_time_diff_ms(&wi->last_event_tm, tm));
1967 android_log_write_int32(ctx, (int32_t)get_time_diff_ms(&wi->prev_wakeup_tm, tm));
1968 android_log_write_int32(ctx, wi->wakeups_since_event);
1969 android_log_write_int32(ctx, wi->skipped_wakeups);
Ioannis Ilkos282437f2021-03-04 17:50:05 +00001970 android_log_write_int32(ctx, (int32_t)min(swap_kb, INT32_MAX));
Suren Baghdasaryan940e7cf2021-05-27 18:15:44 -07001971 android_log_write_int32(ctx, (int32_t)mi->field.total_gpu_kb);
Suren Baghdasaryan39b54802021-08-09 15:10:25 -07001972 if (ki) {
1973 android_log_write_int32(ctx, ki->thrashing);
1974 android_log_write_int32(ctx, ki->max_thrashing);
1975 } else {
1976 android_log_write_int32(ctx, 0);
1977 android_log_write_int32(ctx, 0);
1978 }
Suren Baghdasaryand7b4fcb2020-07-23 18:00:43 -07001979
Suren Baghdasaryan08bfa982018-07-26 16:34:27 -07001980 android_log_write_list(ctx, LOG_ID_EVENTS);
1981 android_log_reset(ctx);
1982}
1983
Todd Poynorc58c5142013-07-09 19:35:14 -07001984static struct proc *proc_adj_lru(int oomadj) {
1985 return (struct proc *)adjslot_tail(&procadjslot_list[ADJTOSLOT(oomadj)]);
1986}
1987
Suren Baghdasaryaneb7c5492017-12-08 13:17:06 -08001988static struct proc *proc_get_heaviest(int oomadj) {
1989 struct adjslot_list *head = &procadjslot_list[ADJTOSLOT(oomadj)];
1990 struct adjslot_list *curr = head->next;
1991 struct proc *maxprocp = NULL;
1992 int maxsize = 0;
1993 while (curr != head) {
1994 int pid = ((struct proc *)curr)->pid;
1995 int tasksize = proc_get_size(pid);
Suren Baghdasaryan5263aa72021-04-29 15:28:57 -07001996 if (tasksize < 0) {
Suren Baghdasaryaneb7c5492017-12-08 13:17:06 -08001997 struct adjslot_list *next = curr->next;
1998 pid_remove(pid);
1999 curr = next;
2000 } else {
2001 if (tasksize > maxsize) {
2002 maxsize = tasksize;
2003 maxprocp = (struct proc *)curr;
2004 }
2005 curr = curr->next;
2006 }
2007 }
2008 return maxprocp;
2009}
2010
Wei Wangf1ee2e12018-11-21 00:11:44 -08002011static void set_process_group_and_prio(int pid, SchedPolicy sp, int prio) {
2012 DIR* d;
2013 char proc_path[PATH_MAX];
2014 struct dirent* de;
2015
2016 snprintf(proc_path, sizeof(proc_path), "/proc/%d/task", pid);
2017 if (!(d = opendir(proc_path))) {
2018 ALOGW("Failed to open %s; errno=%d: process pid(%d) might have died", proc_path, errno,
2019 pid);
2020 return;
2021 }
2022
2023 while ((de = readdir(d))) {
2024 int t_pid;
2025
2026 if (de->d_name[0] == '.') continue;
2027 t_pid = atoi(de->d_name);
2028
2029 if (!t_pid) {
2030 ALOGW("Failed to get t_pid for '%s' of pid(%d)", de->d_name, pid);
2031 continue;
2032 }
2033
2034 if (setpriority(PRIO_PROCESS, t_pid, prio) && errno != ESRCH) {
2035 ALOGW("Unable to raise priority of killing t_pid (%d): errno=%d", t_pid, errno);
2036 }
2037
2038 if (set_cpuset_policy(t_pid, sp)) {
2039 ALOGW("Failed to set_cpuset_policy on pid(%d) t_pid(%d) to %d", pid, t_pid, (int)sp);
2040 continue;
2041 }
2042 }
2043 closedir(d);
2044}
2045
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002046static bool is_kill_pending(void) {
2047 char buf[24];
2048
2049 if (last_kill_pid_or_fd < 0) {
2050 return false;
2051 }
2052
2053 if (pidfd_supported) {
2054 return true;
2055 }
2056
2057 /* when pidfd is not supported base the decision on /proc/<pid> existence */
2058 snprintf(buf, sizeof(buf), "/proc/%d/", last_kill_pid_or_fd);
2059 if (access(buf, F_OK) == 0) {
2060 return true;
2061 }
2062
2063 return false;
2064}
2065
2066static bool is_waiting_for_kill(void) {
2067 return pidfd_supported && last_kill_pid_or_fd >= 0;
2068}
2069
2070static void stop_wait_for_proc_kill(bool finished) {
2071 struct epoll_event epev;
2072
2073 if (last_kill_pid_or_fd < 0) {
2074 return;
2075 }
2076
2077 if (debug_process_killing) {
2078 struct timespec curr_tm;
2079
2080 if (clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm) != 0) {
2081 /*
2082 * curr_tm is used here merely to report kill duration, so this failure is not fatal.
2083 * Log an error and continue.
2084 */
2085 ALOGE("Failed to get current time");
2086 }
2087
2088 if (finished) {
2089 ALOGI("Process got killed in %ldms",
2090 get_time_diff_ms(&last_kill_tm, &curr_tm));
2091 } else {
2092 ALOGI("Stop waiting for process kill after %ldms",
2093 get_time_diff_ms(&last_kill_tm, &curr_tm));
2094 }
2095 }
2096
2097 if (pidfd_supported) {
2098 /* unregister fd */
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07002099 if (epoll_ctl(epollfd, EPOLL_CTL_DEL, last_kill_pid_or_fd, &epev)) {
2100 // Log an error and keep going
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002101 ALOGE("epoll_ctl for last killed process failed; errno=%d", errno);
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002102 }
2103 maxevents--;
2104 close(last_kill_pid_or_fd);
2105 }
2106
2107 last_kill_pid_or_fd = -1;
2108}
2109
2110static void kill_done_handler(int data __unused, uint32_t events __unused,
2111 struct polling_params *poll_params) {
2112 stop_wait_for_proc_kill(true);
2113 poll_params->update = POLLING_RESUME;
2114}
2115
Suren Baghdasaryana10157c2019-07-19 10:55:39 -07002116static void start_wait_for_proc_kill(int pid_or_fd) {
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002117 static struct event_handler_info kill_done_hinfo = { 0, kill_done_handler };
2118 struct epoll_event epev;
2119
2120 if (last_kill_pid_or_fd >= 0) {
2121 /* Should not happen but if it does we should stop previous wait */
2122 ALOGE("Attempt to wait for a kill while another wait is in progress");
2123 stop_wait_for_proc_kill(false);
2124 }
2125
Suren Baghdasaryana10157c2019-07-19 10:55:39 -07002126 last_kill_pid_or_fd = pid_or_fd;
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002127
Suren Baghdasaryana10157c2019-07-19 10:55:39 -07002128 if (!pidfd_supported) {
2129 /* If pidfd is not supported just store PID and exit */
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002130 return;
2131 }
2132
2133 epev.events = EPOLLIN;
2134 epev.data.ptr = (void *)&kill_done_hinfo;
2135 if (epoll_ctl(epollfd, EPOLL_CTL_ADD, last_kill_pid_or_fd, &epev) != 0) {
2136 ALOGE("epoll_ctl for last kill failed; errno=%d", errno);
2137 close(last_kill_pid_or_fd);
2138 last_kill_pid_or_fd = -1;
2139 return;
2140 }
2141 maxevents++;
2142}
Tim Murraya79ec0f2018-10-25 17:05:41 -07002143
Ioannis Ilkos279268a2020-08-01 10:50:40 +01002144/* Kill one process specified by procp. Returns the size (in pages) of the process killed */
Suren Baghdasaryane1604752021-07-22 16:21:21 -07002145static int kill_one_process(struct proc* procp, int min_oom_score, struct kill_info *ki,
2146 union meminfo *mi, struct wakeup_info *wi, struct timespec *tm) {
Colin Cross3d57a512014-07-14 12:39:56 -07002147 int pid = procp->pid;
Suren Baghdasaryana10157c2019-07-19 10:55:39 -07002148 int pidfd = procp->pidfd;
Colin Cross3d57a512014-07-14 12:39:56 -07002149 uid_t uid = procp->uid;
2150 char *taskname;
Colin Cross3d57a512014-07-14 12:39:56 -07002151 int r;
Suren Baghdasaryan8b00c6d2018-10-12 11:28:33 -07002152 int result = -1;
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07002153 struct memory_stat *mem_st;
Suren Baghdasaryan3cc1f132020-09-09 20:19:02 -07002154 struct kill_stat kill_st;
Ioannis Ilkos279268a2020-08-01 10:50:40 +01002155 int64_t tgid;
2156 int64_t rss_kb;
2157 int64_t swap_kb;
2158 char buf[PAGE_SIZE];
Suren Baghdasaryan34928bb2021-07-29 17:02:51 -07002159 char desc[LINE_MAX];
Rajeev Kumar4aba9152018-01-31 17:54:56 -08002160
Ioannis Ilkos279268a2020-08-01 10:50:40 +01002161 if (!read_proc_status(pid, buf, sizeof(buf))) {
2162 goto out;
2163 }
2164 if (!parse_status_tag(buf, PROC_STATUS_TGID_FIELD, &tgid)) {
2165 ALOGE("Unable to parse tgid from /proc/%d/status", pid);
2166 goto out;
2167 }
2168 if (tgid != pid) {
2169 ALOGE("Possible pid reuse detected (pid %d, tgid %" PRId64 ")!", pid, tgid);
2170 goto out;
2171 }
2172 // Zombie processes will not have RSS / Swap fields.
2173 if (!parse_status_tag(buf, PROC_STATUS_RSS_FIELD, &rss_kb)) {
2174 goto out;
2175 }
2176 if (!parse_status_tag(buf, PROC_STATUS_SWAP_FIELD, &swap_kb)) {
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -07002177 goto out;
2178 }
2179
Suren Baghdasaryan632f1c52019-10-04 16:06:55 -07002180 taskname = proc_get_name(pid, buf, sizeof(buf));
Ioannis Ilkos279268a2020-08-01 10:50:40 +01002181 // taskname will point inside buf, do not reuse buf onwards.
Colin Cross3d57a512014-07-14 12:39:56 -07002182 if (!taskname) {
Suren Baghdasaryan8b00c6d2018-10-12 11:28:33 -07002183 goto out;
Colin Cross3d57a512014-07-14 12:39:56 -07002184 }
2185
Ioannis Ilkos279268a2020-08-01 10:50:40 +01002186 mem_st = stats_read_memory_stat(per_app_memcg, pid, uid, rss_kb * 1024, swap_kb * 1024);
Rajeev Kumar4aba9152018-01-31 17:54:56 -08002187
George Burgess IVe849f142021-08-05 06:59:42 +00002188 snprintf(desc, sizeof(desc), "lmk,%d,%d,%d,%d,%d", pid, ki ? (int)ki->kill_reason : -1,
2189 procp->oomadj, min_oom_score, ki ? ki->max_thrashing : -1);
Suren Baghdasaryan34928bb2021-07-29 17:02:51 -07002190 trace_kill_start(pid, desc);
Suren Baghdasaryan03e19872018-01-04 10:43:58 -08002191
Mark Salyzyna00ccd82018-04-09 09:50:32 -07002192 /* CAP_KILL required */
Suren Baghdasaryana10157c2019-07-19 10:55:39 -07002193 if (pidfd < 0) {
2194 start_wait_for_proc_kill(pid);
2195 r = kill(pid, SIGKILL);
2196 } else {
2197 start_wait_for_proc_kill(pidfd);
Josh Gao84623be2021-03-18 17:16:08 -07002198 r = pidfd_send_signal(pidfd, SIGKILL, NULL, 0);
Suren Baghdasaryana10157c2019-07-19 10:55:39 -07002199 }
Wei Wangf1ee2e12018-11-21 00:11:44 -08002200
Suren Baghdasaryan34928bb2021-07-29 17:02:51 -07002201 trace_kill_end();
Suren Baghdasaryanc2e05b62019-09-04 16:44:47 -07002202
2203 if (r) {
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002204 stop_wait_for_proc_kill(false);
Suren Baghdasaryanc2e05b62019-09-04 16:44:47 -07002205 ALOGE("kill(%d): errno=%d", pid, errno);
2206 /* Delete process record even when we fail to kill so that we don't get stuck on it */
2207 goto out;
2208 }
2209
Wei Wangf1ee2e12018-11-21 00:11:44 -08002210 set_process_group_and_prio(pid, SP_FOREGROUND, ANDROID_PRIORITY_HIGHEST);
2211
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002212 last_kill_tm = *tm;
2213
Suren Baghdasaryana7394ea2018-10-12 11:07:40 -07002214 inc_killcnt(procp->oomadj);
Suren Baghdasaryan12cacae2019-09-16 12:06:30 -07002215
Suren Baghdasaryane1604752021-07-22 16:21:21 -07002216 if (ki) {
2217 kill_st.kill_reason = ki->kill_reason;
2218 kill_st.thrashing = ki->thrashing;
2219 kill_st.max_thrashing = ki->max_thrashing;
Ioannis Ilkos48848902021-02-18 19:53:33 +00002220 ALOGI("Kill '%s' (%d), uid %d, oom_score_adj %d to free %" PRId64 "kB rss, %" PRId64
Suren Baghdasaryane1604752021-07-22 16:21:21 -07002221 "kB swap; reason: %s", taskname, pid, uid, procp->oomadj, rss_kb, swap_kb,
2222 ki->kill_desc);
Suren Baghdasaryan89454e62019-07-15 15:50:17 -07002223 } else {
Suren Baghdasaryane1604752021-07-22 16:21:21 -07002224 kill_st.kill_reason = NONE;
2225 kill_st.thrashing = 0;
2226 kill_st.max_thrashing = 0;
Ioannis Ilkos48848902021-02-18 19:53:33 +00002227 ALOGI("Kill '%s' (%d), uid %d, oom_score_adj %d to free %" PRId64 "kB rss, %" PRId64
2228 "kb swap", taskname, pid, uid, procp->oomadj, rss_kb, swap_kb);
Suren Baghdasaryan89454e62019-07-15 15:50:17 -07002229 }
Suren Baghdasaryan39b54802021-08-09 15:10:25 -07002230 killinfo_log(procp, min_oom_score, rss_kb, swap_kb, ki, mi, wi, tm);
Colin Cross3d57a512014-07-14 12:39:56 -07002231
Suren Baghdasaryan3cc1f132020-09-09 20:19:02 -07002232 kill_st.uid = static_cast<int32_t>(uid);
2233 kill_st.taskname = taskname;
Suren Baghdasaryan3cc1f132020-09-09 20:19:02 -07002234 kill_st.oom_score = procp->oomadj;
2235 kill_st.min_oom_score = min_oom_score;
2236 kill_st.free_mem_kb = mi->field.nr_free_pages * page_k;
2237 kill_st.free_swap_kb = mi->field.free_swap * page_k;
2238 stats_write_lmk_kill_occurred(&kill_st, mem_st);
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07002239
Jing Ji5c480962019-12-04 09:22:05 -08002240 ctrl_data_write_lmk_kill_occurred((pid_t)pid, uid);
2241
Ioannis Ilkos279268a2020-08-01 10:50:40 +01002242 result = rss_kb / page_k;
Mark Salyzyn1d5fdf32018-02-04 15:27:23 -08002243
Suren Baghdasaryan8b00c6d2018-10-12 11:28:33 -07002244out:
2245 /*
2246 * WARNING: After pid_remove() procp is freed and can't be used!
2247 * Therefore placed at the end of the function.
2248 */
2249 pid_remove(pid);
2250 return result;
Colin Cross3d57a512014-07-14 12:39:56 -07002251}
2252
2253/*
Chris Morin74b4df92021-02-26 00:00:35 -08002254 * Find one process to kill at or above the given oom_score_adj level.
Suren Baghdasaryan85c31b52018-10-26 11:32:15 -07002255 * Returns size of the killed process.
Colin Cross3d57a512014-07-14 12:39:56 -07002256 */
Suren Baghdasaryane1604752021-07-22 16:21:21 -07002257static int find_and_kill_process(int min_score_adj, struct kill_info *ki, union meminfo *mi,
Suren Baghdasaryan3cc1f132020-09-09 20:19:02 -07002258 struct wakeup_info *wi, struct timespec *tm) {
Colin Cross3d57a512014-07-14 12:39:56 -07002259 int i;
Suren Baghdasaryan85c31b52018-10-26 11:32:15 -07002260 int killed_size = 0;
Yang Lu5dfffbc2018-05-15 04:59:44 +00002261 bool lmk_state_change_start = false;
Suren Baghdasaryan858e8c62021-03-03 11:05:09 -08002262 bool choose_heaviest_task = kill_heaviest_task;
Rajeev Kumar4aba9152018-01-31 17:54:56 -08002263
Chong Zhang1cd12b52015-10-14 16:19:53 -07002264 for (i = OOM_SCORE_ADJ_MAX; i >= min_score_adj; i--) {
Colin Cross3d57a512014-07-14 12:39:56 -07002265 struct proc *procp;
2266
Suren Baghdasaryan858e8c62021-03-03 11:05:09 -08002267 if (!choose_heaviest_task && i <= PERCEPTIBLE_APP_ADJ) {
2268 /*
2269 * If we have to choose a perceptible process, choose the heaviest one to
2270 * hopefully minimize the number of victims.
2271 */
2272 choose_heaviest_task = true;
2273 }
2274
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002275 while (true) {
Suren Baghdasaryan858e8c62021-03-03 11:05:09 -08002276 procp = choose_heaviest_task ?
Suren Baghdasaryan36b2c492018-04-13 11:49:54 -07002277 proc_get_heaviest(i) : proc_adj_lru(i);
Colin Cross3d57a512014-07-14 12:39:56 -07002278
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002279 if (!procp)
2280 break;
2281
Suren Baghdasaryane1604752021-07-22 16:21:21 -07002282 killed_size = kill_one_process(procp, min_score_adj, ki, mi, wi, tm);
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002283 if (killed_size >= 0) {
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07002284 if (!lmk_state_change_start) {
Yang Lu5dfffbc2018-05-15 04:59:44 +00002285 lmk_state_change_start = true;
Vova Sharaienkoa92b76b2021-04-24 00:30:06 +00002286 stats_write_lmk_state_changed(STATE_START);
Yang Lu5dfffbc2018-05-15 04:59:44 +00002287 }
Suren Baghdasaryan85c31b52018-10-26 11:32:15 -07002288 break;
Colin Cross3d57a512014-07-14 12:39:56 -07002289 }
2290 }
Suren Baghdasaryan85c31b52018-10-26 11:32:15 -07002291 if (killed_size) {
2292 break;
2293 }
Colin Cross3d57a512014-07-14 12:39:56 -07002294 }
2295
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07002296 if (lmk_state_change_start) {
Vova Sharaienkoa92b76b2021-04-24 00:30:06 +00002297 stats_write_lmk_state_changed(STATE_STOP);
Rajeev Kumar4aba9152018-01-31 17:54:56 -08002298 }
Rajeev Kumar4aba9152018-01-31 17:54:56 -08002299
Suren Baghdasaryan85c31b52018-10-26 11:32:15 -07002300 return killed_size;
Colin Cross3d57a512014-07-14 12:39:56 -07002301}
2302
Suren Baghdasaryan87966742018-04-13 12:43:41 -07002303static int64_t get_memory_usage(struct reread_data *file_data) {
Robert Beneac72b2932017-08-21 15:18:31 -07002304 int64_t mem_usage;
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -07002305 char *buf;
Suren Baghdasaryan87966742018-04-13 12:43:41 -07002306
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -07002307 if ((buf = reread_file(file_data)) == NULL) {
Robert Beneac72b2932017-08-21 15:18:31 -07002308 return -1;
2309 }
2310
Suren Baghdasaryan87966742018-04-13 12:43:41 -07002311 if (!parse_int64(buf, &mem_usage)) {
2312 ALOGE("%s parse error", file_data->filename);
Robert Beneac72b2932017-08-21 15:18:31 -07002313 return -1;
2314 }
Robert Beneac72b2932017-08-21 15:18:31 -07002315 if (mem_usage == 0) {
2316 ALOGE("No memory!");
2317 return -1;
2318 }
2319 return mem_usage;
2320}
2321
Suren Baghdasaryane0f3dd12018-04-13 13:41:12 -07002322void record_low_pressure_levels(union meminfo *mi) {
2323 if (low_pressure_mem.min_nr_free_pages == -1 ||
2324 low_pressure_mem.min_nr_free_pages > mi->field.nr_free_pages) {
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002325 if (debug_process_killing) {
Suren Baghdasaryane0f3dd12018-04-13 13:41:12 -07002326 ALOGI("Low pressure min memory update from %" PRId64 " to %" PRId64,
2327 low_pressure_mem.min_nr_free_pages, mi->field.nr_free_pages);
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002328 }
Suren Baghdasaryane0f3dd12018-04-13 13:41:12 -07002329 low_pressure_mem.min_nr_free_pages = mi->field.nr_free_pages;
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002330 }
2331 /*
2332 * Free memory at low vmpressure events occasionally gets spikes,
2333 * possibly a stale low vmpressure event with memory already
2334 * freed up (no memory pressure should have been reported).
Suren Baghdasaryane0f3dd12018-04-13 13:41:12 -07002335 * Ignore large jumps in max_nr_free_pages that would mess up our stats.
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002336 */
Suren Baghdasaryane0f3dd12018-04-13 13:41:12 -07002337 if (low_pressure_mem.max_nr_free_pages == -1 ||
2338 (low_pressure_mem.max_nr_free_pages < mi->field.nr_free_pages &&
2339 mi->field.nr_free_pages - low_pressure_mem.max_nr_free_pages <
2340 low_pressure_mem.max_nr_free_pages * 0.1)) {
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002341 if (debug_process_killing) {
Suren Baghdasaryane0f3dd12018-04-13 13:41:12 -07002342 ALOGI("Low pressure max memory update from %" PRId64 " to %" PRId64,
2343 low_pressure_mem.max_nr_free_pages, mi->field.nr_free_pages);
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002344 }
Suren Baghdasaryane0f3dd12018-04-13 13:41:12 -07002345 low_pressure_mem.max_nr_free_pages = mi->field.nr_free_pages;
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002346 }
2347}
2348
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08002349enum vmpressure_level upgrade_level(enum vmpressure_level level) {
2350 return (enum vmpressure_level)((level < VMPRESS_LEVEL_CRITICAL) ?
2351 level + 1 : level);
2352}
2353
2354enum vmpressure_level downgrade_level(enum vmpressure_level level) {
2355 return (enum vmpressure_level)((level > VMPRESS_LEVEL_LOW) ?
2356 level - 1 : level);
2357}
2358
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002359enum zone_watermark {
2360 WMARK_MIN = 0,
2361 WMARK_LOW,
2362 WMARK_HIGH,
2363 WMARK_NONE
2364};
2365
Suren Baghdasaryan81c75b22019-08-14 09:48:35 -07002366struct zone_watermarks {
2367 long high_wmark;
2368 long low_wmark;
2369 long min_wmark;
2370};
2371
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002372/*
2373 * Returns lowest breached watermark or WMARK_NONE.
2374 */
Suren Baghdasaryan81c75b22019-08-14 09:48:35 -07002375static enum zone_watermark get_lowest_watermark(union meminfo *mi,
2376 struct zone_watermarks *watermarks)
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002377{
Suren Baghdasaryan81c75b22019-08-14 09:48:35 -07002378 int64_t nr_free_pages = mi->field.nr_free_pages - mi->field.cma_free;
2379
2380 if (nr_free_pages < watermarks->min_wmark) {
2381 return WMARK_MIN;
2382 }
2383 if (nr_free_pages < watermarks->low_wmark) {
2384 return WMARK_LOW;
2385 }
2386 if (nr_free_pages < watermarks->high_wmark) {
2387 return WMARK_HIGH;
2388 }
2389 return WMARK_NONE;
2390}
2391
2392void calc_zone_watermarks(struct zoneinfo *zi, struct zone_watermarks *watermarks) {
2393 memset(watermarks, 0, sizeof(struct zone_watermarks));
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002394
2395 for (int node_idx = 0; node_idx < zi->node_count; node_idx++) {
2396 struct zoneinfo_node *node = &zi->nodes[node_idx];
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002397 for (int zone_idx = 0; zone_idx < node->zone_count; zone_idx++) {
2398 struct zoneinfo_zone *zone = &node->zones[zone_idx];
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002399
2400 if (!zone->fields.field.present) {
2401 continue;
2402 }
2403
Suren Baghdasaryan81c75b22019-08-14 09:48:35 -07002404 watermarks->high_wmark += zone->max_protection + zone->fields.field.high;
2405 watermarks->low_wmark += zone->max_protection + zone->fields.field.low;
2406 watermarks->min_wmark += zone->max_protection + zone->fields.field.min;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002407 }
2408 }
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002409}
2410
Suren Baghdasaryan51ee4c52020-04-21 12:27:01 -07002411static int calc_swap_utilization(union meminfo *mi) {
2412 int64_t swap_used = mi->field.total_swap - mi->field.free_swap;
2413 int64_t total_swappable = mi->field.active_anon + mi->field.inactive_anon +
2414 mi->field.shmem + swap_used;
2415 return total_swappable > 0 ? (swap_used * 100) / total_swappable : 0;
2416}
2417
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002418static void mp_event_psi(int data, uint32_t events, struct polling_params *poll_params) {
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002419 enum reclaim_state {
2420 NO_RECLAIM = 0,
2421 KSWAPD_RECLAIM,
2422 DIRECT_RECLAIM,
2423 };
2424 static int64_t init_ws_refault;
Martin Liu1f72f5f2020-08-21 13:18:50 +08002425 static int64_t prev_workingset_refault;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002426 static int64_t base_file_lru;
2427 static int64_t init_pgscan_kswapd;
2428 static int64_t init_pgscan_direct;
2429 static int64_t swap_low_threshold;
2430 static bool killing;
Martin Liu1f72f5f2020-08-21 13:18:50 +08002431 static int thrashing_limit = thrashing_limit_pct;
Suren Baghdasaryan81c75b22019-08-14 09:48:35 -07002432 static struct zone_watermarks watermarks;
2433 static struct timespec wmark_update_tm;
Suren Baghdasaryand7b4fcb2020-07-23 18:00:43 -07002434 static struct wakeup_info wi;
Martin Liu1f72f5f2020-08-21 13:18:50 +08002435 static struct timespec thrashing_reset_tm;
2436 static int64_t prev_thrash_growth = 0;
Suren Baghdasaryan11221d42021-07-14 17:57:52 -07002437 static bool check_filecache = false;
Suren Baghdasaryane1604752021-07-22 16:21:21 -07002438 static int max_thrashing = 0;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002439
2440 union meminfo mi;
2441 union vmstat vs;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002442 struct timespec curr_tm;
2443 int64_t thrashing = 0;
2444 bool swap_is_low = false;
2445 enum vmpressure_level level = (enum vmpressure_level)data;
2446 enum kill_reasons kill_reason = NONE;
2447 bool cycle_after_kill = false;
2448 enum reclaim_state reclaim = NO_RECLAIM;
2449 enum zone_watermark wmark = WMARK_NONE;
Suren Baghdasaryan89454e62019-07-15 15:50:17 -07002450 char kill_desc[LINE_MAX];
Suren Baghdasaryan970a26a2019-09-19 15:27:21 -07002451 bool cut_thrashing_limit = false;
2452 int min_score_adj = 0;
Suren Baghdasaryan51ee4c52020-04-21 12:27:01 -07002453 int swap_util = 0;
Martin Liu1f72f5f2020-08-21 13:18:50 +08002454 long since_thrashing_reset_ms;
Suren Baghdasaryandc60f972020-12-14 13:38:48 -08002455 int64_t workingset_refault_file;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002456
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002457 if (clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm) != 0) {
2458 ALOGE("Failed to get current time");
2459 return;
2460 }
2461
Suren Baghdasaryand7b4fcb2020-07-23 18:00:43 -07002462 record_wakeup_time(&curr_tm, events ? Event : Polling, &wi);
2463
Suren Baghdasaryan03dccf32020-04-28 16:02:13 -07002464 bool kill_pending = is_kill_pending();
Suren Baghdasaryaned715a32020-05-11 16:31:57 -07002465 if (kill_pending && (kill_timeout_ms == 0 ||
2466 get_time_diff_ms(&last_kill_tm, &curr_tm) < static_cast<long>(kill_timeout_ms))) {
Suren Baghdasaryan03dccf32020-04-28 16:02:13 -07002467 /* Skip while still killing a process */
Suren Baghdasaryand7b4fcb2020-07-23 18:00:43 -07002468 wi.skipped_wakeups++;
Suren Baghdasaryan03dccf32020-04-28 16:02:13 -07002469 goto no_kill;
2470 }
2471 /*
2472 * Process is dead or kill timeout is over, stop waiting. This has no effect if pidfds are
2473 * supported and death notification already caused waiting to stop.
2474 */
2475 stop_wait_for_proc_kill(!kill_pending);
2476
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002477 if (vmstat_parse(&vs) < 0) {
2478 ALOGE("Failed to parse vmstat!");
2479 return;
2480 }
Suren Baghdasaryandc60f972020-12-14 13:38:48 -08002481 /* Starting 5.9 kernel workingset_refault vmstat field was renamed workingset_refault_file */
2482 workingset_refault_file = vs.field.workingset_refault ? : vs.field.workingset_refault_file;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002483
2484 if (meminfo_parse(&mi) < 0) {
2485 ALOGE("Failed to parse meminfo!");
2486 return;
2487 }
2488
2489 /* Reset states after process got killed */
2490 if (killing) {
2491 killing = false;
2492 cycle_after_kill = true;
2493 /* Reset file-backed pagecache size and refault amounts after a kill */
2494 base_file_lru = vs.field.nr_inactive_file + vs.field.nr_active_file;
Suren Baghdasaryandc60f972020-12-14 13:38:48 -08002495 init_ws_refault = workingset_refault_file;
Martin Liu1f72f5f2020-08-21 13:18:50 +08002496 thrashing_reset_tm = curr_tm;
2497 prev_thrash_growth = 0;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002498 }
2499
2500 /* Check free swap levels */
2501 if (swap_free_low_percentage) {
2502 if (!swap_low_threshold) {
2503 swap_low_threshold = mi.field.total_swap * swap_free_low_percentage / 100;
2504 }
2505 swap_is_low = mi.field.free_swap < swap_low_threshold;
2506 }
2507
2508 /* Identify reclaim state */
2509 if (vs.field.pgscan_direct > init_pgscan_direct) {
2510 init_pgscan_direct = vs.field.pgscan_direct;
2511 init_pgscan_kswapd = vs.field.pgscan_kswapd;
2512 reclaim = DIRECT_RECLAIM;
2513 } else if (vs.field.pgscan_kswapd > init_pgscan_kswapd) {
2514 init_pgscan_kswapd = vs.field.pgscan_kswapd;
2515 reclaim = KSWAPD_RECLAIM;
Suren Baghdasaryandc60f972020-12-14 13:38:48 -08002516 } else if (workingset_refault_file == prev_workingset_refault) {
Suren Baghdasaryan11221d42021-07-14 17:57:52 -07002517 /*
2518 * Device is not thrashing and not reclaiming, bail out early until we see these stats
2519 * changing
2520 */
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002521 goto no_kill;
2522 }
2523
Suren Baghdasaryandc60f972020-12-14 13:38:48 -08002524 prev_workingset_refault = workingset_refault_file;
Martin Liu1f72f5f2020-08-21 13:18:50 +08002525
2526 /*
2527 * It's possible we fail to find an eligible process to kill (ex. no process is
2528 * above oom_adj_min). When this happens, we should retry to find a new process
2529 * for a kill whenever a new eligible process is available. This is especially
2530 * important for a slow growing refault case. While retrying, we should keep
2531 * monitoring new thrashing counter as someone could release the memory to mitigate
2532 * the thrashing. Thus, when thrashing reset window comes, we decay the prev thrashing
Suren Baghdasaryan11221d42021-07-14 17:57:52 -07002533 * counter by window counts. If the counter is still greater than thrashing limit,
Martin Liu1f72f5f2020-08-21 13:18:50 +08002534 * we preserve the current prev_thrash counter so we will retry kill again. Otherwise,
2535 * we reset the prev_thrash counter so we will stop retrying.
2536 */
2537 since_thrashing_reset_ms = get_time_diff_ms(&thrashing_reset_tm, &curr_tm);
2538 if (since_thrashing_reset_ms > THRASHING_RESET_INTERVAL_MS) {
2539 long windows_passed;
2540 /* Calculate prev_thrash_growth if we crossed THRASHING_RESET_INTERVAL_MS */
Suren Baghdasaryandc60f972020-12-14 13:38:48 -08002541 prev_thrash_growth = (workingset_refault_file - init_ws_refault) * 100
Martin Liuc3108412020-09-03 22:12:14 +08002542 / (base_file_lru + 1);
Martin Liu1f72f5f2020-08-21 13:18:50 +08002543 windows_passed = (since_thrashing_reset_ms / THRASHING_RESET_INTERVAL_MS);
2544 /*
2545 * Decay prev_thrashing unless over-the-limit thrashing was registered in the window we
2546 * just crossed, which means there were no eligible processes to kill. We preserve the
2547 * counter in that case to ensure a kill if a new eligible process appears.
2548 */
2549 if (windows_passed > 1 || prev_thrash_growth < thrashing_limit) {
2550 prev_thrash_growth >>= windows_passed;
2551 }
2552
2553 /* Record file-backed pagecache size when crossing THRASHING_RESET_INTERVAL_MS */
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002554 base_file_lru = vs.field.nr_inactive_file + vs.field.nr_active_file;
Suren Baghdasaryandc60f972020-12-14 13:38:48 -08002555 init_ws_refault = workingset_refault_file;
Martin Liu1f72f5f2020-08-21 13:18:50 +08002556 thrashing_reset_tm = curr_tm;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002557 thrashing_limit = thrashing_limit_pct;
2558 } else {
2559 /* Calculate what % of the file-backed pagecache refaulted so far */
Suren Baghdasaryandc60f972020-12-14 13:38:48 -08002560 thrashing = (workingset_refault_file - init_ws_refault) * 100 / (base_file_lru + 1);
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002561 }
Martin Liu1f72f5f2020-08-21 13:18:50 +08002562 /* Add previous cycle's decayed thrashing amount */
2563 thrashing += prev_thrash_growth;
Suren Baghdasaryane1604752021-07-22 16:21:21 -07002564 if (max_thrashing < thrashing) {
2565 max_thrashing = thrashing;
2566 }
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002567
Suren Baghdasaryan81c75b22019-08-14 09:48:35 -07002568 /*
2569 * Refresh watermarks once per min in case user updated one of the margins.
2570 * TODO: b/140521024 replace this periodic update with an API for AMS to notify LMKD
2571 * that zone watermarks were changed by the system software.
2572 */
2573 if (watermarks.high_wmark == 0 || get_time_diff_ms(&wmark_update_tm, &curr_tm) > 60000) {
2574 struct zoneinfo zi;
2575
2576 if (zoneinfo_parse(&zi) < 0) {
2577 ALOGE("Failed to parse zoneinfo!");
2578 return;
2579 }
2580
2581 calc_zone_watermarks(&zi, &watermarks);
2582 wmark_update_tm = curr_tm;
Martin Liu1f72f5f2020-08-21 13:18:50 +08002583 }
Suren Baghdasaryan81c75b22019-08-14 09:48:35 -07002584
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002585 /* Find out which watermark is breached if any */
Suren Baghdasaryan81c75b22019-08-14 09:48:35 -07002586 wmark = get_lowest_watermark(&mi, &watermarks);
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002587
2588 /*
2589 * TODO: move this logic into a separate function
2590 * Decide if killing a process is necessary and record the reason
2591 */
2592 if (cycle_after_kill && wmark < WMARK_LOW) {
2593 /*
2594 * Prevent kills not freeing enough memory which might lead to OOM kill.
2595 * This might happen when a process is consuming memory faster than reclaim can
2596 * free even after a kill. Mostly happens when running memory stress tests.
2597 */
2598 kill_reason = PRESSURE_AFTER_KILL;
Suren Baghdasaryan89454e62019-07-15 15:50:17 -07002599 strncpy(kill_desc, "min watermark is breached even after kill", sizeof(kill_desc));
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002600 } else if (level == VMPRESS_LEVEL_CRITICAL && events != 0) {
2601 /*
2602 * Device is too busy reclaiming memory which might lead to ANR.
2603 * Critical level is triggered when PSI complete stall (all tasks are blocked because
2604 * of the memory congestion) breaches the configured threshold.
2605 */
2606 kill_reason = NOT_RESPONDING;
Suren Baghdasaryan89454e62019-07-15 15:50:17 -07002607 strncpy(kill_desc, "device is not responding", sizeof(kill_desc));
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002608 } else if (swap_is_low && thrashing > thrashing_limit_pct) {
2609 /* Page cache is thrashing while swap is low */
2610 kill_reason = LOW_SWAP_AND_THRASHING;
Suren Baghdasaryan89454e62019-07-15 15:50:17 -07002611 snprintf(kill_desc, sizeof(kill_desc), "device is low on swap (%" PRId64
2612 "kB < %" PRId64 "kB) and thrashing (%" PRId64 "%%)",
2613 mi.field.free_swap * page_k, swap_low_threshold * page_k, thrashing);
Suren Baghdasaryan0142b3c2021-03-03 11:11:09 -08002614 /* Do not kill perceptible apps unless below min watermark or heavily thrashing */
2615 if (wmark > WMARK_MIN && thrashing < thrashing_critical_pct) {
Suren Baghdasaryan48135c42020-05-19 12:59:18 -07002616 min_score_adj = PERCEPTIBLE_APP_ADJ + 1;
2617 }
Suren Baghdasaryan11221d42021-07-14 17:57:52 -07002618 check_filecache = true;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002619 } else if (swap_is_low && wmark < WMARK_HIGH) {
2620 /* Both free memory and swap are low */
2621 kill_reason = LOW_MEM_AND_SWAP;
Suren Baghdasaryan89454e62019-07-15 15:50:17 -07002622 snprintf(kill_desc, sizeof(kill_desc), "%s watermark is breached and swap is low (%"
Suren Baghdasaryan23678182021-03-02 18:33:09 -08002623 PRId64 "kB < %" PRId64 "kB)", wmark < WMARK_LOW ? "min" : "low",
Suren Baghdasaryan89454e62019-07-15 15:50:17 -07002624 mi.field.free_swap * page_k, swap_low_threshold * page_k);
Suren Baghdasaryan0142b3c2021-03-03 11:11:09 -08002625 /* Do not kill perceptible apps unless below min watermark or heavily thrashing */
2626 if (wmark > WMARK_MIN && thrashing < thrashing_critical_pct) {
Suren Baghdasaryan48135c42020-05-19 12:59:18 -07002627 min_score_adj = PERCEPTIBLE_APP_ADJ + 1;
2628 }
Suren Baghdasaryan51ee4c52020-04-21 12:27:01 -07002629 } else if (wmark < WMARK_HIGH && swap_util_max < 100 &&
2630 (swap_util = calc_swap_utilization(&mi)) > swap_util_max) {
2631 /*
2632 * Too much anon memory is swapped out but swap is not low.
2633 * Non-swappable allocations created memory pressure.
2634 */
2635 kill_reason = LOW_MEM_AND_SWAP_UTIL;
2636 snprintf(kill_desc, sizeof(kill_desc), "%s watermark is breached and swap utilization"
Suren Baghdasaryan23678182021-03-02 18:33:09 -08002637 " is high (%d%% > %d%%)", wmark < WMARK_LOW ? "min" : "low",
Suren Baghdasaryan51ee4c52020-04-21 12:27:01 -07002638 swap_util, swap_util_max);
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002639 } else if (wmark < WMARK_HIGH && thrashing > thrashing_limit) {
2640 /* Page cache is thrashing while memory is low */
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002641 kill_reason = LOW_MEM_AND_THRASHING;
Suren Baghdasaryan89454e62019-07-15 15:50:17 -07002642 snprintf(kill_desc, sizeof(kill_desc), "%s watermark is breached and thrashing (%"
Suren Baghdasaryan23678182021-03-02 18:33:09 -08002643 PRId64 "%%)", wmark < WMARK_LOW ? "min" : "low", thrashing);
Suren Baghdasaryan970a26a2019-09-19 15:27:21 -07002644 cut_thrashing_limit = true;
Suren Baghdasaryan0142b3c2021-03-03 11:11:09 -08002645 /* Do not kill perceptible apps unless thrashing at critical levels */
2646 if (thrashing < thrashing_critical_pct) {
2647 min_score_adj = PERCEPTIBLE_APP_ADJ + 1;
2648 }
Suren Baghdasaryan11221d42021-07-14 17:57:52 -07002649 check_filecache = true;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002650 } else if (reclaim == DIRECT_RECLAIM && thrashing > thrashing_limit) {
2651 /* Page cache is thrashing while in direct reclaim (mostly happens on lowram devices) */
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002652 kill_reason = DIRECT_RECL_AND_THRASHING;
Suren Baghdasaryan89454e62019-07-15 15:50:17 -07002653 snprintf(kill_desc, sizeof(kill_desc), "device is in direct reclaim and thrashing (%"
2654 PRId64 "%%)", thrashing);
Suren Baghdasaryan970a26a2019-09-19 15:27:21 -07002655 cut_thrashing_limit = true;
Suren Baghdasaryan0142b3c2021-03-03 11:11:09 -08002656 /* Do not kill perceptible apps unless thrashing at critical levels */
2657 if (thrashing < thrashing_critical_pct) {
2658 min_score_adj = PERCEPTIBLE_APP_ADJ + 1;
2659 }
Suren Baghdasaryan11221d42021-07-14 17:57:52 -07002660 check_filecache = true;
2661 } else if (check_filecache) {
2662 int64_t file_lru_kb = (vs.field.nr_inactive_file + vs.field.nr_active_file) * page_k;
2663
2664 if (file_lru_kb < filecache_min_kb) {
2665 /* File cache is too low after thrashing, keep killing background processes */
2666 kill_reason = LOW_FILECACHE_AFTER_THRASHING;
2667 snprintf(kill_desc, sizeof(kill_desc),
2668 "filecache is low (%" PRId64 "kB < %" PRId64 "kB) after thrashing",
2669 file_lru_kb, filecache_min_kb);
2670 min_score_adj = PERCEPTIBLE_APP_ADJ + 1;
2671 } else {
2672 /* File cache is big enough, stop checking */
2673 check_filecache = false;
2674 }
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002675 }
2676
2677 /* Kill a process if necessary */
2678 if (kill_reason != NONE) {
Suren Baghdasaryane1604752021-07-22 16:21:21 -07002679 struct kill_info ki = {
2680 .kill_reason = kill_reason,
2681 .kill_desc = kill_desc,
2682 .thrashing = (int)thrashing,
2683 .max_thrashing = max_thrashing,
2684 };
2685 int pages_freed = find_and_kill_process(min_score_adj, &ki, &mi, &wi, &curr_tm);
Suren Baghdasaryan970a26a2019-09-19 15:27:21 -07002686 if (pages_freed > 0) {
2687 killing = true;
Suren Baghdasaryane1604752021-07-22 16:21:21 -07002688 max_thrashing = 0;
Suren Baghdasaryan970a26a2019-09-19 15:27:21 -07002689 if (cut_thrashing_limit) {
2690 /*
2691 * Cut thrasing limit by thrashing_limit_decay_pct percentage of the current
2692 * thrashing limit until the system stops thrashing.
2693 */
2694 thrashing_limit = (thrashing_limit * (100 - thrashing_limit_decay_pct)) / 100;
2695 }
2696 }
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002697 }
2698
2699no_kill:
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002700 /* Do not poll if kernel supports pidfd waiting */
2701 if (is_waiting_for_kill()) {
2702 /* Pause polling if we are waiting for process death notification */
2703 poll_params->update = POLLING_PAUSE;
2704 return;
2705 }
2706
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002707 /*
2708 * Start polling after initial PSI event;
2709 * extend polling while device is in direct reclaim or process is being killed;
2710 * do not extend when kswapd reclaims because that might go on for a long time
2711 * without causing memory pressure
2712 */
2713 if (events || killing || reclaim == DIRECT_RECLAIM) {
2714 poll_params->update = POLLING_START;
2715 }
2716
2717 /* Decide the polling interval */
2718 if (swap_is_low || killing) {
2719 /* Fast polling during and after a kill or when swap is low */
2720 poll_params->polling_interval_ms = PSI_POLL_PERIOD_SHORT_MS;
2721 } else {
2722 /* By default use long intervals */
2723 poll_params->polling_interval_ms = PSI_POLL_PERIOD_LONG_MS;
2724 }
2725}
2726
Suren Baghdasaryane12a0672019-07-15 14:50:49 -07002727static void mp_event_common(int data, uint32_t events, struct polling_params *poll_params) {
Todd Poynorc58c5142013-07-09 19:35:14 -07002728 unsigned long long evcount;
Robert Beneac72b2932017-08-21 15:18:31 -07002729 int64_t mem_usage, memsw_usage;
Robert Benea3be16142017-09-13 15:20:30 -07002730 int64_t mem_pressure;
Suren Baghdasaryane0f3dd12018-04-13 13:41:12 -07002731 union meminfo mi;
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07002732 struct zoneinfo zi;
Suren Baghdasaryan53be36e2018-09-05 15:46:32 -07002733 struct timespec curr_tm;
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -07002734 static unsigned long kill_skip_count = 0;
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08002735 enum vmpressure_level level = (enum vmpressure_level)data;
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07002736 long other_free = 0, other_file = 0;
2737 int min_score_adj;
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07002738 int minfree = 0;
Suren Baghdasaryan87966742018-04-13 12:43:41 -07002739 static struct reread_data mem_usage_file_data = {
2740 .filename = MEMCG_MEMORY_USAGE,
2741 .fd = -1,
2742 };
2743 static struct reread_data memsw_usage_file_data = {
2744 .filename = MEMCG_MEMORYSW_USAGE,
2745 .fd = -1,
2746 };
Suren Baghdasaryand7b4fcb2020-07-23 18:00:43 -07002747 static struct wakeup_info wi;
Todd Poynorc58c5142013-07-09 19:35:14 -07002748
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08002749 if (debug_process_killing) {
2750 ALOGI("%s memory pressure event is triggered", level_name[level]);
2751 }
2752
2753 if (!use_psi_monitors) {
2754 /*
2755 * Check all event counters from low to critical
2756 * and upgrade to the highest priority one. By reading
2757 * eventfd we also reset the event counters.
2758 */
Tom Cherry43f3d2b2019-12-04 12:46:57 -08002759 for (int lvl = VMPRESS_LEVEL_LOW; lvl < VMPRESS_LEVEL_COUNT; lvl++) {
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08002760 if (mpevfd[lvl] != -1 &&
2761 TEMP_FAILURE_RETRY(read(mpevfd[lvl],
2762 &evcount, sizeof(evcount))) > 0 &&
2763 evcount > 0 && lvl > level) {
Tom Cherry43f3d2b2019-12-04 12:46:57 -08002764 level = static_cast<vmpressure_level>(lvl);
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08002765 }
Suren Baghdasaryan3e1a8492018-01-04 09:16:21 -08002766 }
2767 }
Todd Poynorc58c5142013-07-09 19:35:14 -07002768
Suren Baghdasaryane12a0672019-07-15 14:50:49 -07002769 /* Start polling after initial PSI event */
2770 if (use_psi_monitors && events) {
2771 /* Override polling params only if current event is more critical */
2772 if (!poll_params->poll_handler || data > poll_params->poll_handler->data) {
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002773 poll_params->polling_interval_ms = PSI_POLL_PERIOD_SHORT_MS;
Suren Baghdasaryane12a0672019-07-15 14:50:49 -07002774 poll_params->update = POLLING_START;
2775 }
2776 }
2777
Suren Baghdasaryan53be36e2018-09-05 15:46:32 -07002778 if (clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm) != 0) {
2779 ALOGE("Failed to get current time");
2780 return;
2781 }
2782
Suren Baghdasaryand7b4fcb2020-07-23 18:00:43 -07002783 record_wakeup_time(&curr_tm, events ? Event : Polling, &wi);
2784
Suren Baghdasaryaned715a32020-05-11 16:31:57 -07002785 if (kill_timeout_ms &&
2786 get_time_diff_ms(&last_kill_tm, &curr_tm) < static_cast<long>(kill_timeout_ms)) {
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002787 /*
2788 * If we're within the no-kill timeout, see if there's pending reclaim work
2789 * from the last killed process. If so, skip killing for now.
2790 */
2791 if (is_kill_pending()) {
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -07002792 kill_skip_count++;
Suren Baghdasaryand7b4fcb2020-07-23 18:00:43 -07002793 wi.skipped_wakeups++;
Suren Baghdasaryan30854e72018-01-17 17:28:01 -08002794 return;
2795 }
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002796 /*
2797 * Process is dead, stop waiting. This has no effect if pidfds are supported and
2798 * death notification already caused waiting to stop.
2799 */
2800 stop_wait_for_proc_kill(true);
2801 } else {
2802 /*
2803 * Killing took longer than no-kill timeout. Stop waiting for the last process
2804 * to die because we are ready to kill again.
2805 */
2806 stop_wait_for_proc_kill(false);
Suren Baghdasaryan30854e72018-01-17 17:28:01 -08002807 }
2808
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -07002809 if (kill_skip_count > 0) {
Suren Baghdasaryaneff82332018-05-10 16:10:56 -07002810 ALOGI("%lu memory pressure events were skipped after a kill!",
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -07002811 kill_skip_count);
2812 kill_skip_count = 0;
Suren Baghdasaryan30854e72018-01-17 17:28:01 -08002813 }
2814
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07002815 if (meminfo_parse(&mi) < 0 || zoneinfo_parse(&zi) < 0) {
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002816 ALOGE("Failed to get free memory!");
2817 return;
2818 }
2819
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07002820 if (use_minfree_levels) {
2821 int i;
2822
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07002823 other_free = mi.field.nr_free_pages - zi.totalreserve_pages;
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07002824 if (mi.field.nr_file_pages > (mi.field.shmem + mi.field.unevictable + mi.field.swap_cached)) {
2825 other_file = (mi.field.nr_file_pages - mi.field.shmem -
2826 mi.field.unevictable - mi.field.swap_cached);
2827 } else {
2828 other_file = 0;
2829 }
2830
2831 min_score_adj = OOM_SCORE_ADJ_MAX + 1;
2832 for (i = 0; i < lowmem_targets_size; i++) {
2833 minfree = lowmem_minfree[i];
2834 if (other_free < minfree && other_file < minfree) {
2835 min_score_adj = lowmem_adj[i];
2836 break;
2837 }
2838 }
2839
Suren Baghdasaryanb0bda552018-05-18 14:42:00 -07002840 if (min_score_adj == OOM_SCORE_ADJ_MAX + 1) {
2841 if (debug_process_killing) {
2842 ALOGI("Ignore %s memory pressure event "
2843 "(free memory=%ldkB, cache=%ldkB, limit=%ldkB)",
2844 level_name[level], other_free * page_k, other_file * page_k,
2845 (long)lowmem_minfree[lowmem_targets_size - 1] * page_k);
2846 }
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07002847 return;
Suren Baghdasaryanb0bda552018-05-18 14:42:00 -07002848 }
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07002849
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07002850 goto do_kill;
2851 }
2852
Suren Baghdasaryane0f3dd12018-04-13 13:41:12 -07002853 if (level == VMPRESS_LEVEL_LOW) {
2854 record_low_pressure_levels(&mi);
2855 }
2856
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002857 if (level_oomadj[level] > OOM_SCORE_ADJ_MAX) {
2858 /* Do not monitor this pressure level */
2859 return;
2860 }
2861
Suren Baghdasaryan87966742018-04-13 12:43:41 -07002862 if ((mem_usage = get_memory_usage(&mem_usage_file_data)) < 0) {
2863 goto do_kill;
2864 }
2865 if ((memsw_usage = get_memory_usage(&memsw_usage_file_data)) < 0) {
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08002866 goto do_kill;
Robert Benea3be16142017-09-13 15:20:30 -07002867 }
Robert Beneac72b2932017-08-21 15:18:31 -07002868
Robert Benea3be16142017-09-13 15:20:30 -07002869 // Calculate percent for swappinness.
2870 mem_pressure = (mem_usage * 100) / memsw_usage;
2871
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08002872 if (enable_pressure_upgrade && level != VMPRESS_LEVEL_CRITICAL) {
Robert Benea3be16142017-09-13 15:20:30 -07002873 // We are swapping too much.
2874 if (mem_pressure < upgrade_pressure) {
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08002875 level = upgrade_level(level);
2876 if (debug_process_killing) {
2877 ALOGI("Event upgraded to %s", level_name[level]);
2878 }
Robert Beneac72b2932017-08-21 15:18:31 -07002879 }
2880 }
2881
Vic Yang65680692018-08-07 10:18:22 -07002882 // If we still have enough swap space available, check if we want to
2883 // ignore/downgrade pressure events.
2884 if (mi.field.free_swap >=
2885 mi.field.total_swap * swap_free_low_percentage / 100) {
2886 // If the pressure is larger than downgrade_pressure lmk will not
2887 // kill any process, since enough memory is available.
2888 if (mem_pressure > downgrade_pressure) {
2889 if (debug_process_killing) {
2890 ALOGI("Ignore %s memory pressure", level_name[level]);
2891 }
2892 return;
2893 } else if (level == VMPRESS_LEVEL_CRITICAL && mem_pressure > upgrade_pressure) {
2894 if (debug_process_killing) {
2895 ALOGI("Downgrade critical memory pressure");
2896 }
2897 // Downgrade event, since enough memory available.
2898 level = downgrade_level(level);
Robert Benea3be16142017-09-13 15:20:30 -07002899 }
Robert Benea3be16142017-09-13 15:20:30 -07002900 }
2901
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08002902do_kill:
Suren Baghdasaryand1d59f82018-04-13 11:45:38 -07002903 if (low_ram_device) {
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002904 /* For Go devices kill only one task */
Suren Baghdasaryane1604752021-07-22 16:21:21 -07002905 if (find_and_kill_process(level_oomadj[level], NULL, &mi, &wi, &curr_tm) == 0) {
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002906 if (debug_process_killing) {
2907 ALOGI("Nothing to kill");
2908 }
2909 }
2910 } else {
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07002911 int pages_freed;
Suren Baghdasaryan53be36e2018-09-05 15:46:32 -07002912 static struct timespec last_report_tm;
2913 static unsigned long report_skip_count = 0;
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07002914
2915 if (!use_minfree_levels) {
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07002916 /* Free up enough memory to downgrate the memory pressure to low level */
Suren Baghdasaryan85c31b52018-10-26 11:32:15 -07002917 if (mi.field.nr_free_pages >= low_pressure_mem.max_nr_free_pages) {
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07002918 if (debug_process_killing) {
2919 ALOGI("Ignoring pressure since more memory is "
2920 "available (%" PRId64 ") than watermark (%" PRId64 ")",
2921 mi.field.nr_free_pages, low_pressure_mem.max_nr_free_pages);
2922 }
2923 return;
2924 }
2925 min_score_adj = level_oomadj[level];
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002926 }
2927
Suren Baghdasaryane1604752021-07-22 16:21:21 -07002928 pages_freed = find_and_kill_process(min_score_adj, NULL, &mi, &wi, &curr_tm);
Suren Baghdasaryaneff82332018-05-10 16:10:56 -07002929
Suren Baghdasaryan53be36e2018-09-05 15:46:32 -07002930 if (pages_freed == 0) {
2931 /* Rate limit kill reports when nothing was reclaimed */
2932 if (get_time_diff_ms(&last_report_tm, &curr_tm) < FAIL_REPORT_RLIMIT_MS) {
2933 report_skip_count++;
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -07002934 return;
2935 }
Robert Benea7f68a3f2017-08-11 16:03:20 -07002936 }
Suren Baghdasaryan53be36e2018-09-05 15:46:32 -07002937
Suren Baghdasaryan12cacae2019-09-16 12:06:30 -07002938 /* Log whenever we kill or when report rate limit allows */
Suren Baghdasaryan53be36e2018-09-05 15:46:32 -07002939 if (use_minfree_levels) {
Chris Morin74b4df92021-02-26 00:00:35 -08002940 ALOGI("Reclaimed %ldkB, cache(%ldkB) and free(%" PRId64 "kB)-reserved(%" PRId64 "kB) "
2941 "below min(%ldkB) for oom_score_adj %d",
Suren Baghdasaryan85c31b52018-10-26 11:32:15 -07002942 pages_freed * page_k,
Suren Baghdasaryan53be36e2018-09-05 15:46:32 -07002943 other_file * page_k, mi.field.nr_free_pages * page_k,
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07002944 zi.totalreserve_pages * page_k,
Suren Baghdasaryan53be36e2018-09-05 15:46:32 -07002945 minfree * page_k, min_score_adj);
2946 } else {
Chris Morin74b4df92021-02-26 00:00:35 -08002947 ALOGI("Reclaimed %ldkB at oom_score_adj %d", pages_freed * page_k, min_score_adj);
Suren Baghdasaryan53be36e2018-09-05 15:46:32 -07002948 }
2949
2950 if (report_skip_count > 0) {
2951 ALOGI("Suppressed %lu failed kill reports", report_skip_count);
2952 report_skip_count = 0;
2953 }
2954
2955 last_report_tm = curr_tm;
Colin Cross01db2712014-07-11 17:16:56 -07002956 }
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002957 if (is_waiting_for_kill()) {
2958 /* pause polling if we are waiting for process death notification */
2959 poll_params->update = POLLING_PAUSE;
2960 }
Todd Poynorc58c5142013-07-09 19:35:14 -07002961}
2962
Suren Baghdasaryan2f88e152019-07-15 15:42:09 -07002963static bool init_mp_psi(enum vmpressure_level level, bool use_new_strategy) {
2964 int fd;
2965
2966 /* Do not register a handler if threshold_ms is not set */
2967 if (!psi_thresholds[level].threshold_ms) {
2968 return true;
2969 }
2970
2971 fd = init_psi_monitor(psi_thresholds[level].stall_type,
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08002972 psi_thresholds[level].threshold_ms * US_PER_MS,
2973 PSI_WINDOW_SIZE_MS * US_PER_MS);
2974
2975 if (fd < 0) {
2976 return false;
2977 }
2978
Suren Baghdasaryan2f88e152019-07-15 15:42:09 -07002979 vmpressure_hinfo[level].handler = use_new_strategy ? mp_event_psi : mp_event_common;
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08002980 vmpressure_hinfo[level].data = level;
2981 if (register_psi_monitor(epollfd, fd, &vmpressure_hinfo[level]) < 0) {
2982 destroy_psi_monitor(fd);
2983 return false;
2984 }
2985 maxevents++;
2986 mpevfd[level] = fd;
2987
2988 return true;
2989}
2990
2991static void destroy_mp_psi(enum vmpressure_level level) {
2992 int fd = mpevfd[level];
2993
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07002994 if (fd < 0) {
2995 return;
2996 }
2997
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08002998 if (unregister_psi_monitor(epollfd, fd) < 0) {
2999 ALOGE("Failed to unregister psi monitor for %s memory pressure; errno=%d",
3000 level_name[level], errno);
3001 }
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07003002 maxevents--;
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08003003 destroy_psi_monitor(fd);
3004 mpevfd[level] = -1;
3005}
3006
3007static bool init_psi_monitors() {
Suren Baghdasaryan2f88e152019-07-15 15:42:09 -07003008 /*
3009 * When PSI is used on low-ram devices or on high-end devices without memfree levels
3010 * use new kill strategy based on zone watermarks, free swap and thrashing stats
3011 */
3012 bool use_new_strategy =
Suren Baghdasaryand0a80042021-08-03 15:40:23 -07003013 GET_LMK_PROPERTY(bool, "use_new_strategy", low_ram_device || !use_minfree_levels);
Suren Baghdasaryan2f88e152019-07-15 15:42:09 -07003014
3015 /* In default PSI mode override stall amounts using system properties */
3016 if (use_new_strategy) {
3017 /* Do not use low pressure level */
3018 psi_thresholds[VMPRESS_LEVEL_LOW].threshold_ms = 0;
3019 psi_thresholds[VMPRESS_LEVEL_MEDIUM].threshold_ms = psi_partial_stall_ms;
3020 psi_thresholds[VMPRESS_LEVEL_CRITICAL].threshold_ms = psi_complete_stall_ms;
3021 }
3022
3023 if (!init_mp_psi(VMPRESS_LEVEL_LOW, use_new_strategy)) {
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08003024 return false;
3025 }
Suren Baghdasaryan2f88e152019-07-15 15:42:09 -07003026 if (!init_mp_psi(VMPRESS_LEVEL_MEDIUM, use_new_strategy)) {
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08003027 destroy_mp_psi(VMPRESS_LEVEL_LOW);
3028 return false;
3029 }
Suren Baghdasaryan2f88e152019-07-15 15:42:09 -07003030 if (!init_mp_psi(VMPRESS_LEVEL_CRITICAL, use_new_strategy)) {
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08003031 destroy_mp_psi(VMPRESS_LEVEL_MEDIUM);
3032 destroy_mp_psi(VMPRESS_LEVEL_LOW);
3033 return false;
3034 }
3035 return true;
3036}
3037
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003038static bool init_mp_common(enum vmpressure_level level) {
Todd Poynorc58c5142013-07-09 19:35:14 -07003039 int mpfd;
3040 int evfd;
3041 int evctlfd;
3042 char buf[256];
3043 struct epoll_event epev;
3044 int ret;
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003045 int level_idx = (int)level;
3046 const char *levelstr = level_name[level_idx];
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08003047
Mark Salyzyna00ccd82018-04-09 09:50:32 -07003048 /* gid containing AID_SYSTEM required */
Nick Kralevich148d8dd2015-12-18 20:52:37 -08003049 mpfd = open(MEMCG_SYSFS_PATH "memory.pressure_level", O_RDONLY | O_CLOEXEC);
Todd Poynorc58c5142013-07-09 19:35:14 -07003050 if (mpfd < 0) {
3051 ALOGI("No kernel memory.pressure_level support (errno=%d)", errno);
3052 goto err_open_mpfd;
3053 }
3054
Nick Kralevich148d8dd2015-12-18 20:52:37 -08003055 evctlfd = open(MEMCG_SYSFS_PATH "cgroup.event_control", O_WRONLY | O_CLOEXEC);
Todd Poynorc58c5142013-07-09 19:35:14 -07003056 if (evctlfd < 0) {
3057 ALOGI("No kernel memory cgroup event control (errno=%d)", errno);
3058 goto err_open_evctlfd;
3059 }
3060
Nick Kralevich148d8dd2015-12-18 20:52:37 -08003061 evfd = eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC);
Todd Poynorc58c5142013-07-09 19:35:14 -07003062 if (evfd < 0) {
3063 ALOGE("eventfd failed for level %s; errno=%d", levelstr, errno);
3064 goto err_eventfd;
3065 }
3066
3067 ret = snprintf(buf, sizeof(buf), "%d %d %s", evfd, mpfd, levelstr);
3068 if (ret >= (ssize_t)sizeof(buf)) {
3069 ALOGE("cgroup.event_control line overflow for level %s", levelstr);
3070 goto err;
3071 }
3072
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003073 ret = TEMP_FAILURE_RETRY(write(evctlfd, buf, strlen(buf) + 1));
Todd Poynorc58c5142013-07-09 19:35:14 -07003074 if (ret == -1) {
3075 ALOGE("cgroup.event_control write failed for level %s; errno=%d",
3076 levelstr, errno);
3077 goto err;
3078 }
3079
3080 epev.events = EPOLLIN;
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003081 /* use data to store event level */
3082 vmpressure_hinfo[level_idx].data = level_idx;
3083 vmpressure_hinfo[level_idx].handler = mp_event_common;
3084 epev.data.ptr = (void *)&vmpressure_hinfo[level_idx];
Todd Poynorc58c5142013-07-09 19:35:14 -07003085 ret = epoll_ctl(epollfd, EPOLL_CTL_ADD, evfd, &epev);
3086 if (ret == -1) {
3087 ALOGE("epoll_ctl for level %s failed; errno=%d", levelstr, errno);
3088 goto err;
3089 }
3090 maxevents++;
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08003091 mpevfd[level] = evfd;
Suren Baghdasaryanceffaf22018-01-04 08:54:53 -08003092 close(evctlfd);
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08003093 return true;
Todd Poynorc58c5142013-07-09 19:35:14 -07003094
3095err:
3096 close(evfd);
3097err_eventfd:
3098 close(evctlfd);
3099err_open_evctlfd:
3100 close(mpfd);
3101err_open_mpfd:
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08003102 return false;
Robert Benea58d6a132017-06-01 16:32:31 -07003103}
3104
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07003105static void destroy_mp_common(enum vmpressure_level level) {
3106 struct epoll_event epev;
3107 int fd = mpevfd[level];
3108
3109 if (fd < 0) {
3110 return;
3111 }
3112
3113 if (epoll_ctl(epollfd, EPOLL_CTL_DEL, fd, &epev)) {
3114 // Log an error and keep going
3115 ALOGE("epoll_ctl for level %s failed; errno=%d", level_name[level], errno);
3116 }
3117 maxevents--;
3118 close(fd);
3119 mpevfd[level] = -1;
3120}
3121
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07003122static void kernel_event_handler(int data __unused, uint32_t events __unused,
3123 struct polling_params *poll_params __unused) {
Jing Ji5c480962019-12-04 09:22:05 -08003124 poll_kernel(kpoll_fd);
Jim Blackler700b7192019-04-26 11:18:29 +01003125}
3126
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07003127static bool init_monitors() {
3128 /* Try to use psi monitor first if kernel has it */
Suren Baghdasaryand0a80042021-08-03 15:40:23 -07003129 use_psi_monitors = GET_LMK_PROPERTY(bool, "use_psi", true) &&
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07003130 init_psi_monitors();
3131 /* Fall back to vmpressure */
3132 if (!use_psi_monitors &&
3133 (!init_mp_common(VMPRESS_LEVEL_LOW) ||
3134 !init_mp_common(VMPRESS_LEVEL_MEDIUM) ||
3135 !init_mp_common(VMPRESS_LEVEL_CRITICAL))) {
3136 ALOGE("Kernel does not support memory pressure events or in-kernel low memory killer");
3137 return false;
3138 }
3139 if (use_psi_monitors) {
3140 ALOGI("Using psi monitors for memory pressure detection");
3141 } else {
3142 ALOGI("Using vmpressure for memory pressure detection");
3143 }
3144 return true;
3145}
3146
3147static void destroy_monitors() {
3148 if (use_psi_monitors) {
3149 destroy_mp_psi(VMPRESS_LEVEL_CRITICAL);
3150 destroy_mp_psi(VMPRESS_LEVEL_MEDIUM);
3151 destroy_mp_psi(VMPRESS_LEVEL_LOW);
3152 } else {
3153 destroy_mp_common(VMPRESS_LEVEL_CRITICAL);
3154 destroy_mp_common(VMPRESS_LEVEL_MEDIUM);
3155 destroy_mp_common(VMPRESS_LEVEL_LOW);
3156 }
3157}
3158
Todd Poynorc58c5142013-07-09 19:35:14 -07003159static int init(void) {
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07003160 static struct event_handler_info kernel_poll_hinfo = { 0, kernel_event_handler };
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -07003161 struct reread_data file_data = {
3162 .filename = ZONEINFO_PATH,
3163 .fd = -1,
3164 };
Todd Poynorc58c5142013-07-09 19:35:14 -07003165 struct epoll_event epev;
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003166 int pidfd;
Todd Poynorc58c5142013-07-09 19:35:14 -07003167 int i;
3168 int ret;
3169
3170 page_k = sysconf(_SC_PAGESIZE);
3171 if (page_k == -1)
3172 page_k = PAGE_SIZE;
3173 page_k /= 1024;
3174
3175 epollfd = epoll_create(MAX_EPOLL_EVENTS);
3176 if (epollfd == -1) {
3177 ALOGE("epoll_create failed (errno=%d)", errno);
3178 return -1;
3179 }
3180
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003181 // mark data connections as not connected
3182 for (int i = 0; i < MAX_DATA_CONN; i++) {
3183 data_sock[i].sock = -1;
3184 }
3185
3186 ctrl_sock.sock = android_get_control_socket("lmkd");
3187 if (ctrl_sock.sock < 0) {
Todd Poynorc58c5142013-07-09 19:35:14 -07003188 ALOGE("get lmkd control socket failed");
3189 return -1;
3190 }
3191
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003192 ret = listen(ctrl_sock.sock, MAX_DATA_CONN);
Todd Poynorc58c5142013-07-09 19:35:14 -07003193 if (ret < 0) {
3194 ALOGE("lmkd control socket listen failed (errno=%d)", errno);
3195 return -1;
3196 }
3197
3198 epev.events = EPOLLIN;
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003199 ctrl_sock.handler_info.handler = ctrl_connect_handler;
3200 epev.data.ptr = (void *)&(ctrl_sock.handler_info);
3201 if (epoll_ctl(epollfd, EPOLL_CTL_ADD, ctrl_sock.sock, &epev) == -1) {
Todd Poynorc58c5142013-07-09 19:35:14 -07003202 ALOGE("epoll_ctl for lmkd control socket failed (errno=%d)", errno);
3203 return -1;
3204 }
3205 maxevents++;
3206
Robert Benea7878c9b2017-09-11 16:53:28 -07003207 has_inkernel_module = !access(INKERNEL_MINFREE_PATH, W_OK);
Suren Baghdasaryane6613ea2018-01-18 17:27:30 -08003208 use_inkernel_interface = has_inkernel_module;
Todd Poynorc58c5142013-07-09 19:35:14 -07003209
3210 if (use_inkernel_interface) {
3211 ALOGI("Using in-kernel low memory killer interface");
Jing Ji5c480962019-12-04 09:22:05 -08003212 if (init_poll_kernel()) {
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07003213 epev.events = EPOLLIN;
3214 epev.data.ptr = (void*)&kernel_poll_hinfo;
Jing Ji5c480962019-12-04 09:22:05 -08003215 if (epoll_ctl(epollfd, EPOLL_CTL_ADD, kpoll_fd, &epev) != 0) {
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07003216 ALOGE("epoll_ctl for lmk events failed (errno=%d)", errno);
Jing Ji5c480962019-12-04 09:22:05 -08003217 close(kpoll_fd);
3218 kpoll_fd = -1;
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07003219 } else {
3220 maxevents++;
Jing Ji5c480962019-12-04 09:22:05 -08003221 /* let the others know it does support reporting kills */
3222 property_set("sys.lmk.reportkills", "1");
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07003223 }
Jim Blackler700b7192019-04-26 11:18:29 +01003224 }
Todd Poynorc58c5142013-07-09 19:35:14 -07003225 } else {
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07003226 if (!init_monitors()) {
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08003227 return -1;
3228 }
Jing Ji5c480962019-12-04 09:22:05 -08003229 /* let the others know it does support reporting kills */
3230 property_set("sys.lmk.reportkills", "1");
Todd Poynorc58c5142013-07-09 19:35:14 -07003231 }
3232
Chong Zhang1cd12b52015-10-14 16:19:53 -07003233 for (i = 0; i <= ADJTOSLOT(OOM_SCORE_ADJ_MAX); i++) {
Todd Poynorc58c5142013-07-09 19:35:14 -07003234 procadjslot_list[i].next = &procadjslot_list[i];
3235 procadjslot_list[i].prev = &procadjslot_list[i];
3236 }
3237
Suren Baghdasaryana7394ea2018-10-12 11:07:40 -07003238 memset(killcnt_idx, KILLCNT_INVALID_IDX, sizeof(killcnt_idx));
3239
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -07003240 /*
3241 * Read zoneinfo as the biggest file we read to create and size the initial
3242 * read buffer and avoid memory re-allocations during memory pressure
3243 */
3244 if (reread_file(&file_data) == NULL) {
3245 ALOGE("Failed to read %s: %s", file_data.filename, strerror(errno));
3246 }
3247
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003248 /* check if kernel supports pidfd_open syscall */
Josh Gao84623be2021-03-18 17:16:08 -07003249 pidfd = TEMP_FAILURE_RETRY(pidfd_open(getpid(), 0));
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003250 if (pidfd < 0) {
3251 pidfd_supported = (errno != ENOSYS);
3252 } else {
3253 pidfd_supported = true;
3254 close(pidfd);
3255 }
3256 ALOGI("Process polling is %s", pidfd_supported ? "supported" : "not supported" );
3257
Todd Poynorc58c5142013-07-09 19:35:14 -07003258 return 0;
3259}
3260
Suren Baghdasaryan03dccf32020-04-28 16:02:13 -07003261static bool polling_paused(struct polling_params *poll_params) {
3262 return poll_params->paused_handler != NULL;
3263}
3264
3265static void resume_polling(struct polling_params *poll_params, struct timespec curr_tm) {
3266 poll_params->poll_start_tm = curr_tm;
3267 poll_params->poll_handler = poll_params->paused_handler;
Martin Liu589b5752020-09-02 23:15:18 +08003268 poll_params->polling_interval_ms = PSI_POLL_PERIOD_SHORT_MS;
3269 poll_params->paused_handler = NULL;
Suren Baghdasaryan03dccf32020-04-28 16:02:13 -07003270}
3271
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003272static void call_handler(struct event_handler_info* handler_info,
3273 struct polling_params *poll_params, uint32_t events) {
3274 struct timespec curr_tm;
3275
Suren Baghdasaryan9ca53342020-04-24 16:54:55 -07003276 poll_params->update = POLLING_DO_NOT_CHANGE;
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003277 handler_info->handler(handler_info->data, events, poll_params);
3278 clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm);
Suren Baghdasaryan9ca53342020-04-24 16:54:55 -07003279 if (poll_params->poll_handler == handler_info) {
3280 poll_params->last_poll_tm = curr_tm;
3281 }
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003282
3283 switch (poll_params->update) {
3284 case POLLING_START:
3285 /*
3286 * Poll for the duration of PSI_WINDOW_SIZE_MS after the
3287 * initial PSI event because psi events are rate-limited
3288 * at one per sec.
3289 */
3290 poll_params->poll_start_tm = curr_tm;
Greg Kaiser5e80ed52019-10-10 06:52:23 -07003291 poll_params->poll_handler = handler_info;
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003292 break;
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003293 case POLLING_PAUSE:
3294 poll_params->paused_handler = handler_info;
3295 poll_params->poll_handler = NULL;
3296 break;
3297 case POLLING_RESUME:
Suren Baghdasaryan03dccf32020-04-28 16:02:13 -07003298 resume_polling(poll_params, curr_tm);
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003299 break;
3300 case POLLING_DO_NOT_CHANGE:
3301 if (get_time_diff_ms(&poll_params->poll_start_tm, &curr_tm) > PSI_WINDOW_SIZE_MS) {
3302 /* Polled for the duration of PSI window, time to stop */
3303 poll_params->poll_handler = NULL;
3304 }
Suren Baghdasaryan9ca53342020-04-24 16:54:55 -07003305 break;
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003306 }
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003307}
3308
Todd Poynorc58c5142013-07-09 19:35:14 -07003309static void mainloop(void) {
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003310 struct event_handler_info* handler_info;
Suren Baghdasaryane12a0672019-07-15 14:50:49 -07003311 struct polling_params poll_params;
3312 struct timespec curr_tm;
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003313 struct epoll_event *evt;
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08003314 long delay = -1;
Suren Baghdasaryane12a0672019-07-15 14:50:49 -07003315
3316 poll_params.poll_handler = NULL;
Suren Baghdasaryan9ca53342020-04-24 16:54:55 -07003317 poll_params.paused_handler = NULL;
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003318
Todd Poynorc58c5142013-07-09 19:35:14 -07003319 while (1) {
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07003320 struct epoll_event events[MAX_EPOLL_EVENTS];
Todd Poynorc58c5142013-07-09 19:35:14 -07003321 int nevents;
3322 int i;
3323
Suren Baghdasaryane12a0672019-07-15 14:50:49 -07003324 if (poll_params.poll_handler) {
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003325 bool poll_now;
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08003326
3327 clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm);
Martin Liu589b5752020-09-02 23:15:18 +08003328 if (poll_params.update == POLLING_RESUME) {
3329 /* Just transitioned into POLLING_RESUME, poll immediately. */
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003330 poll_now = true;
3331 nevents = 0;
3332 } else {
3333 /* Calculate next timeout */
3334 delay = get_time_diff_ms(&poll_params.last_poll_tm, &curr_tm);
3335 delay = (delay < poll_params.polling_interval_ms) ?
3336 poll_params.polling_interval_ms - delay : poll_params.polling_interval_ms;
Suren Baghdasaryane12a0672019-07-15 14:50:49 -07003337
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003338 /* Wait for events until the next polling timeout */
3339 nevents = epoll_wait(epollfd, events, maxevents, delay);
3340
3341 /* Update current time after wait */
3342 clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm);
3343 poll_now = (get_time_diff_ms(&poll_params.last_poll_tm, &curr_tm) >=
3344 poll_params.polling_interval_ms);
3345 }
3346 if (poll_now) {
3347 call_handler(poll_params.poll_handler, &poll_params, 0);
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08003348 }
3349 } else {
Suren Baghdasaryan03dccf32020-04-28 16:02:13 -07003350 if (kill_timeout_ms && is_waiting_for_kill()) {
3351 clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm);
3352 delay = kill_timeout_ms - get_time_diff_ms(&last_kill_tm, &curr_tm);
3353 /* Wait for pidfds notification or kill timeout to expire */
3354 nevents = (delay > 0) ? epoll_wait(epollfd, events, maxevents, delay) : 0;
3355 if (nevents == 0) {
3356 /* Kill notification timed out */
3357 stop_wait_for_proc_kill(false);
3358 if (polling_paused(&poll_params)) {
3359 clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm);
Martin Liu589b5752020-09-02 23:15:18 +08003360 poll_params.update = POLLING_RESUME;
Suren Baghdasaryan03dccf32020-04-28 16:02:13 -07003361 resume_polling(&poll_params, curr_tm);
3362 }
3363 }
3364 } else {
3365 /* Wait for events with no timeout */
3366 nevents = epoll_wait(epollfd, events, maxevents, -1);
3367 }
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08003368 }
Todd Poynorc58c5142013-07-09 19:35:14 -07003369
3370 if (nevents == -1) {
3371 if (errno == EINTR)
3372 continue;
3373 ALOGE("epoll_wait failed (errno=%d)", errno);
3374 continue;
3375 }
3376
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003377 /*
3378 * First pass to see if any data socket connections were dropped.
3379 * Dropped connection should be handled before any other events
3380 * to deallocate data connection and correctly handle cases when
3381 * connection gets dropped and reestablished in the same epoll cycle.
3382 * In such cases it's essential to handle connection closures first.
3383 */
3384 for (i = 0, evt = &events[0]; i < nevents; ++i, evt++) {
3385 if ((evt->events & EPOLLHUP) && evt->data.ptr) {
3386 ALOGI("lmkd data connection dropped");
3387 handler_info = (struct event_handler_info*)evt->data.ptr;
3388 ctrl_data_close(handler_info->data);
3389 }
3390 }
3391
3392 /* Second pass to handle all other events */
3393 for (i = 0, evt = &events[0]; i < nevents; ++i, evt++) {
Suren Baghdasaryane12a0672019-07-15 14:50:49 -07003394 if (evt->events & EPOLLERR) {
Todd Poynorc58c5142013-07-09 19:35:14 -07003395 ALOGD("EPOLLERR on event #%d", i);
Suren Baghdasaryane12a0672019-07-15 14:50:49 -07003396 }
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003397 if (evt->events & EPOLLHUP) {
3398 /* This case was handled in the first pass */
3399 continue;
3400 }
3401 if (evt->data.ptr) {
3402 handler_info = (struct event_handler_info*)evt->data.ptr;
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003403 call_handler(handler_info, &poll_params, evt->events);
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003404 }
Todd Poynorc58c5142013-07-09 19:35:14 -07003405 }
3406 }
3407}
3408
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07003409int issue_reinit() {
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07003410 int sock;
Colin Crossd5b510e2014-07-14 14:31:15 -07003411
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07003412 sock = lmkd_connect();
3413 if (sock < 0) {
3414 ALOGE("failed to connect to lmkd: %s", strerror(errno));
3415 return -1;
3416 }
3417
3418 enum update_props_result res = lmkd_update_props(sock);
3419 switch (res) {
3420 case UPDATE_PROPS_SUCCESS:
3421 ALOGI("lmkd updated properties successfully");
3422 break;
3423 case UPDATE_PROPS_SEND_ERR:
3424 ALOGE("failed to send lmkd request: %s", strerror(errno));
3425 break;
3426 case UPDATE_PROPS_RECV_ERR:
3427 ALOGE("failed to receive lmkd reply: %s", strerror(errno));
3428 break;
3429 case UPDATE_PROPS_FORMAT_ERR:
3430 ALOGE("lmkd reply is invalid");
3431 break;
3432 case UPDATE_PROPS_FAIL:
3433 ALOGE("lmkd failed to update its properties");
3434 break;
3435 }
3436
3437 close(sock);
3438 return res == UPDATE_PROPS_SUCCESS ? 0 : -1;
3439}
3440
3441static void update_props() {
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08003442 /* By default disable low level vmpressure events */
3443 level_oomadj[VMPRESS_LEVEL_LOW] =
Suren Baghdasaryand0a80042021-08-03 15:40:23 -07003444 GET_LMK_PROPERTY(int32, "low", OOM_SCORE_ADJ_MAX + 1);
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08003445 level_oomadj[VMPRESS_LEVEL_MEDIUM] =
Suren Baghdasaryand0a80042021-08-03 15:40:23 -07003446 GET_LMK_PROPERTY(int32, "medium", 800);
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08003447 level_oomadj[VMPRESS_LEVEL_CRITICAL] =
Suren Baghdasaryand0a80042021-08-03 15:40:23 -07003448 GET_LMK_PROPERTY(int32, "critical", 0);
3449 debug_process_killing = GET_LMK_PROPERTY(bool, "debug", false);
Suren Baghdasaryan3faa3032017-12-08 13:08:41 -08003450
3451 /* By default disable upgrade/downgrade logic */
3452 enable_pressure_upgrade =
Suren Baghdasaryand0a80042021-08-03 15:40:23 -07003453 GET_LMK_PROPERTY(bool, "critical_upgrade", false);
Suren Baghdasaryan3faa3032017-12-08 13:08:41 -08003454 upgrade_pressure =
Suren Baghdasaryand0a80042021-08-03 15:40:23 -07003455 (int64_t)GET_LMK_PROPERTY(int32, "upgrade_pressure", 100);
Suren Baghdasaryan3faa3032017-12-08 13:08:41 -08003456 downgrade_pressure =
Suren Baghdasaryand0a80042021-08-03 15:40:23 -07003457 (int64_t)GET_LMK_PROPERTY(int32, "downgrade_pressure", 100);
Suren Baghdasaryaneb7c5492017-12-08 13:17:06 -08003458 kill_heaviest_task =
Suren Baghdasaryand0a80042021-08-03 15:40:23 -07003459 GET_LMK_PROPERTY(bool, "kill_heaviest_task", false);
Suren Baghdasaryand1d59f82018-04-13 11:45:38 -07003460 low_ram_device = property_get_bool("ro.config.low_ram", false);
Suren Baghdasaryan30854e72018-01-17 17:28:01 -08003461 kill_timeout_ms =
Suren Baghdasaryand0a80042021-08-03 15:40:23 -07003462 (unsigned long)GET_LMK_PROPERTY(int32, "kill_timeout_ms", 100);
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07003463 use_minfree_levels =
Suren Baghdasaryand0a80042021-08-03 15:40:23 -07003464 GET_LMK_PROPERTY(bool, "use_minfree_levels", false);
Suren Baghdasaryan8389fdb2018-06-19 18:38:12 -07003465 per_app_memcg =
3466 property_get_bool("ro.config.per_app_memcg", low_ram_device);
Suren Baghdasaryand0a80042021-08-03 15:40:23 -07003467 swap_free_low_percentage = clamp(0, 100, GET_LMK_PROPERTY(int32, "swap_free_low_percentage",
Suren Baghdasaryanfb1f5922020-05-19 13:07:23 -07003468 DEF_LOW_SWAP));
Suren Baghdasaryand0a80042021-08-03 15:40:23 -07003469 psi_partial_stall_ms = GET_LMK_PROPERTY(int32, "psi_partial_stall_ms",
Suren Baghdasaryan2f88e152019-07-15 15:42:09 -07003470 low_ram_device ? DEF_PARTIAL_STALL_LOWRAM : DEF_PARTIAL_STALL);
Suren Baghdasaryand0a80042021-08-03 15:40:23 -07003471 psi_complete_stall_ms = GET_LMK_PROPERTY(int32, "psi_complete_stall_ms",
Suren Baghdasaryan2f88e152019-07-15 15:42:09 -07003472 DEF_COMPLETE_STALL);
Suren Baghdasaryand0a80042021-08-03 15:40:23 -07003473 thrashing_limit_pct = max(0, GET_LMK_PROPERTY(int32, "thrashing_limit",
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07003474 low_ram_device ? DEF_THRASHING_LOWRAM : DEF_THRASHING));
Suren Baghdasaryand0a80042021-08-03 15:40:23 -07003475 thrashing_limit_decay_pct = clamp(0, 100, GET_LMK_PROPERTY(int32, "thrashing_limit_decay",
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07003476 low_ram_device ? DEF_THRASHING_DECAY_LOWRAM : DEF_THRASHING_DECAY));
Suren Baghdasaryand0a80042021-08-03 15:40:23 -07003477 thrashing_critical_pct = max(0, GET_LMK_PROPERTY(int32, "thrashing_limit_critical",
Suren Baghdasaryan1ef47182021-07-22 20:59:31 +00003478 thrashing_limit_pct * 2));
Suren Baghdasaryand0a80042021-08-03 15:40:23 -07003479 swap_util_max = clamp(0, 100, GET_LMK_PROPERTY(int32, "swap_util_max", 100));
3480 filecache_min_kb = GET_LMK_PROPERTY(int64, "filecache_min_kb", 0);
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07003481}
3482
3483int main(int argc, char **argv) {
3484 if ((argc > 1) && argv[1] && !strcmp(argv[1], "--reinit")) {
Suren Baghdasaryan0e64ead2021-09-01 00:49:51 -07003485 if (property_set(LMKD_REINIT_PROP, "")) {
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07003486 ALOGE("Failed to reset " LMKD_REINIT_PROP " property");
3487 }
3488 return issue_reinit();
3489 }
3490
3491 update_props();
Robert Benea57397dc2017-07-31 17:15:20 -07003492
Suren Baghdasaryan12cacae2019-09-16 12:06:30 -07003493 ctx = create_android_logger(KILLINFO_LOG_TAG);
Suren Baghdasaryan08bfa982018-07-26 16:34:27 -07003494
Mark Salyzyn5cc80b32018-03-21 12:24:58 -07003495 if (!init()) {
3496 if (!use_inkernel_interface) {
3497 /*
3498 * MCL_ONFAULT pins pages as they fault instead of loading
3499 * everything immediately all at once. (Which would be bad,
3500 * because as of this writing, we have a lot of mapped pages we
3501 * never use.) Old kernels will see MCL_ONFAULT and fail with
3502 * EINVAL; we ignore this failure.
3503 *
3504 * N.B. read the man page for mlockall. MCL_CURRENT | MCL_ONFAULT
3505 * pins ⊆ MCL_CURRENT, converging to just MCL_CURRENT as we fault
3506 * in pages.
3507 */
Mark Salyzyna00ccd82018-04-09 09:50:32 -07003508 /* CAP_IPC_LOCK required */
Mark Salyzyn5cc80b32018-03-21 12:24:58 -07003509 if (mlockall(MCL_CURRENT | MCL_FUTURE | MCL_ONFAULT) && (errno != EINVAL)) {
3510 ALOGW("mlockall failed %s", strerror(errno));
3511 }
Daniel Colascione46648332018-01-03 12:01:02 -08003512
Mark Salyzyna00ccd82018-04-09 09:50:32 -07003513 /* CAP_NICE required */
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07003514 struct sched_param param = {
3515 .sched_priority = 1,
3516 };
Mark Salyzyna00ccd82018-04-09 09:50:32 -07003517 if (sched_setscheduler(0, SCHED_FIFO, &param)) {
3518 ALOGW("set SCHED_FIFO failed %s", strerror(errno));
3519 }
Mark Salyzyn5cc80b32018-03-21 12:24:58 -07003520 }
3521
Todd Poynorc58c5142013-07-09 19:35:14 -07003522 mainloop();
Mark Salyzyn5cc80b32018-03-21 12:24:58 -07003523 }
Todd Poynorc58c5142013-07-09 19:35:14 -07003524
Suren Baghdasaryan08bfa982018-07-26 16:34:27 -07003525 android_log_destroy(&ctx);
3526
Todd Poynorc58c5142013-07-09 19:35:14 -07003527 ALOGI("exiting");
3528 return 0;
3529}