blob: eb3f25a00cea6b18844b2840faf77f72029ebc82 [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>
Todd Poynorc58c5142013-07-09 19:35:14 -070043#include <cutils/sockets.h>
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -070044#include <liblmkd_utils.h>
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -080045#include <lmkd.h>
Mark Salyzyn6a63fde2017-01-10 13:19:54 -080046#include <log/log.h>
Suren Baghdasaryan08bfa982018-07-26 16:34:27 -070047#include <log/log_event_list.h>
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -070048#include <log/log_time.h>
Suren Baghdasaryan945658a2019-10-18 11:16:52 -070049#include <private/android_filesystem_config.h>
Wei Wang0195bcd2021-09-13 17:59:05 -070050#include <processgroup/processgroup.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 Wang0195bcd2021-09-13 17:59:05 -07002011static void set_process_group_and_prio(int pid, const std::vector<std::string>& profiles,
2012 int prio) {
Wei Wangf1ee2e12018-11-21 00:11:44 -08002013 DIR* d;
2014 char proc_path[PATH_MAX];
2015 struct dirent* de;
2016
2017 snprintf(proc_path, sizeof(proc_path), "/proc/%d/task", pid);
2018 if (!(d = opendir(proc_path))) {
2019 ALOGW("Failed to open %s; errno=%d: process pid(%d) might have died", proc_path, errno,
2020 pid);
2021 return;
2022 }
2023
2024 while ((de = readdir(d))) {
2025 int t_pid;
2026
2027 if (de->d_name[0] == '.') continue;
2028 t_pid = atoi(de->d_name);
2029
2030 if (!t_pid) {
2031 ALOGW("Failed to get t_pid for '%s' of pid(%d)", de->d_name, pid);
2032 continue;
2033 }
2034
2035 if (setpriority(PRIO_PROCESS, t_pid, prio) && errno != ESRCH) {
2036 ALOGW("Unable to raise priority of killing t_pid (%d): errno=%d", t_pid, errno);
2037 }
2038
Wei Wang0195bcd2021-09-13 17:59:05 -07002039 if (!SetTaskProfiles(t_pid, profiles)) {
2040 ALOGW("Failed to set task_profiles on pid(%d) t_pid(%d)", pid, t_pid);
Wei Wangf1ee2e12018-11-21 00:11:44 -08002041 continue;
2042 }
2043 }
2044 closedir(d);
2045}
2046
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002047static bool is_kill_pending(void) {
2048 char buf[24];
2049
2050 if (last_kill_pid_or_fd < 0) {
2051 return false;
2052 }
2053
2054 if (pidfd_supported) {
2055 return true;
2056 }
2057
2058 /* when pidfd is not supported base the decision on /proc/<pid> existence */
2059 snprintf(buf, sizeof(buf), "/proc/%d/", last_kill_pid_or_fd);
2060 if (access(buf, F_OK) == 0) {
2061 return true;
2062 }
2063
2064 return false;
2065}
2066
2067static bool is_waiting_for_kill(void) {
2068 return pidfd_supported && last_kill_pid_or_fd >= 0;
2069}
2070
2071static void stop_wait_for_proc_kill(bool finished) {
2072 struct epoll_event epev;
2073
2074 if (last_kill_pid_or_fd < 0) {
2075 return;
2076 }
2077
2078 if (debug_process_killing) {
2079 struct timespec curr_tm;
2080
2081 if (clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm) != 0) {
2082 /*
2083 * curr_tm is used here merely to report kill duration, so this failure is not fatal.
2084 * Log an error and continue.
2085 */
2086 ALOGE("Failed to get current time");
2087 }
2088
2089 if (finished) {
2090 ALOGI("Process got killed in %ldms",
2091 get_time_diff_ms(&last_kill_tm, &curr_tm));
2092 } else {
2093 ALOGI("Stop waiting for process kill after %ldms",
2094 get_time_diff_ms(&last_kill_tm, &curr_tm));
2095 }
2096 }
2097
2098 if (pidfd_supported) {
2099 /* unregister fd */
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07002100 if (epoll_ctl(epollfd, EPOLL_CTL_DEL, last_kill_pid_or_fd, &epev)) {
2101 // Log an error and keep going
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002102 ALOGE("epoll_ctl for last killed process failed; errno=%d", errno);
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002103 }
2104 maxevents--;
2105 close(last_kill_pid_or_fd);
2106 }
2107
2108 last_kill_pid_or_fd = -1;
2109}
2110
2111static void kill_done_handler(int data __unused, uint32_t events __unused,
2112 struct polling_params *poll_params) {
2113 stop_wait_for_proc_kill(true);
2114 poll_params->update = POLLING_RESUME;
2115}
2116
Suren Baghdasaryana10157c2019-07-19 10:55:39 -07002117static void start_wait_for_proc_kill(int pid_or_fd) {
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002118 static struct event_handler_info kill_done_hinfo = { 0, kill_done_handler };
2119 struct epoll_event epev;
2120
2121 if (last_kill_pid_or_fd >= 0) {
2122 /* Should not happen but if it does we should stop previous wait */
2123 ALOGE("Attempt to wait for a kill while another wait is in progress");
2124 stop_wait_for_proc_kill(false);
2125 }
2126
Suren Baghdasaryana10157c2019-07-19 10:55:39 -07002127 last_kill_pid_or_fd = pid_or_fd;
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002128
Suren Baghdasaryana10157c2019-07-19 10:55:39 -07002129 if (!pidfd_supported) {
2130 /* If pidfd is not supported just store PID and exit */
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002131 return;
2132 }
2133
2134 epev.events = EPOLLIN;
2135 epev.data.ptr = (void *)&kill_done_hinfo;
2136 if (epoll_ctl(epollfd, EPOLL_CTL_ADD, last_kill_pid_or_fd, &epev) != 0) {
2137 ALOGE("epoll_ctl for last kill failed; errno=%d", errno);
2138 close(last_kill_pid_or_fd);
2139 last_kill_pid_or_fd = -1;
2140 return;
2141 }
2142 maxevents++;
2143}
Tim Murraya79ec0f2018-10-25 17:05:41 -07002144
Ioannis Ilkos279268a2020-08-01 10:50:40 +01002145/* Kill one process specified by procp. Returns the size (in pages) of the process killed */
Suren Baghdasaryane1604752021-07-22 16:21:21 -07002146static int kill_one_process(struct proc* procp, int min_oom_score, struct kill_info *ki,
2147 union meminfo *mi, struct wakeup_info *wi, struct timespec *tm) {
Colin Cross3d57a512014-07-14 12:39:56 -07002148 int pid = procp->pid;
Suren Baghdasaryana10157c2019-07-19 10:55:39 -07002149 int pidfd = procp->pidfd;
Colin Cross3d57a512014-07-14 12:39:56 -07002150 uid_t uid = procp->uid;
2151 char *taskname;
Colin Cross3d57a512014-07-14 12:39:56 -07002152 int r;
Suren Baghdasaryan8b00c6d2018-10-12 11:28:33 -07002153 int result = -1;
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07002154 struct memory_stat *mem_st;
Suren Baghdasaryan3cc1f132020-09-09 20:19:02 -07002155 struct kill_stat kill_st;
Ioannis Ilkos279268a2020-08-01 10:50:40 +01002156 int64_t tgid;
2157 int64_t rss_kb;
2158 int64_t swap_kb;
2159 char buf[PAGE_SIZE];
Suren Baghdasaryan34928bb2021-07-29 17:02:51 -07002160 char desc[LINE_MAX];
Rajeev Kumar4aba9152018-01-31 17:54:56 -08002161
Ioannis Ilkos279268a2020-08-01 10:50:40 +01002162 if (!read_proc_status(pid, buf, sizeof(buf))) {
2163 goto out;
2164 }
2165 if (!parse_status_tag(buf, PROC_STATUS_TGID_FIELD, &tgid)) {
2166 ALOGE("Unable to parse tgid from /proc/%d/status", pid);
2167 goto out;
2168 }
2169 if (tgid != pid) {
2170 ALOGE("Possible pid reuse detected (pid %d, tgid %" PRId64 ")!", pid, tgid);
2171 goto out;
2172 }
2173 // Zombie processes will not have RSS / Swap fields.
2174 if (!parse_status_tag(buf, PROC_STATUS_RSS_FIELD, &rss_kb)) {
2175 goto out;
2176 }
2177 if (!parse_status_tag(buf, PROC_STATUS_SWAP_FIELD, &swap_kb)) {
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -07002178 goto out;
2179 }
2180
Suren Baghdasaryan632f1c52019-10-04 16:06:55 -07002181 taskname = proc_get_name(pid, buf, sizeof(buf));
Ioannis Ilkos279268a2020-08-01 10:50:40 +01002182 // taskname will point inside buf, do not reuse buf onwards.
Colin Cross3d57a512014-07-14 12:39:56 -07002183 if (!taskname) {
Suren Baghdasaryan8b00c6d2018-10-12 11:28:33 -07002184 goto out;
Colin Cross3d57a512014-07-14 12:39:56 -07002185 }
2186
Ioannis Ilkos279268a2020-08-01 10:50:40 +01002187 mem_st = stats_read_memory_stat(per_app_memcg, pid, uid, rss_kb * 1024, swap_kb * 1024);
Rajeev Kumar4aba9152018-01-31 17:54:56 -08002188
George Burgess IVe849f142021-08-05 06:59:42 +00002189 snprintf(desc, sizeof(desc), "lmk,%d,%d,%d,%d,%d", pid, ki ? (int)ki->kill_reason : -1,
2190 procp->oomadj, min_oom_score, ki ? ki->max_thrashing : -1);
Suren Baghdasaryan34928bb2021-07-29 17:02:51 -07002191 trace_kill_start(pid, desc);
Suren Baghdasaryan03e19872018-01-04 10:43:58 -08002192
Mark Salyzyna00ccd82018-04-09 09:50:32 -07002193 /* CAP_KILL required */
Suren Baghdasaryana10157c2019-07-19 10:55:39 -07002194 if (pidfd < 0) {
2195 start_wait_for_proc_kill(pid);
2196 r = kill(pid, SIGKILL);
2197 } else {
2198 start_wait_for_proc_kill(pidfd);
Josh Gao84623be2021-03-18 17:16:08 -07002199 r = pidfd_send_signal(pidfd, SIGKILL, NULL, 0);
Suren Baghdasaryana10157c2019-07-19 10:55:39 -07002200 }
Wei Wangf1ee2e12018-11-21 00:11:44 -08002201
Suren Baghdasaryan34928bb2021-07-29 17:02:51 -07002202 trace_kill_end();
Suren Baghdasaryanc2e05b62019-09-04 16:44:47 -07002203
2204 if (r) {
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002205 stop_wait_for_proc_kill(false);
Suren Baghdasaryanc2e05b62019-09-04 16:44:47 -07002206 ALOGE("kill(%d): errno=%d", pid, errno);
2207 /* Delete process record even when we fail to kill so that we don't get stuck on it */
2208 goto out;
2209 }
2210
Wei Wang0195bcd2021-09-13 17:59:05 -07002211 set_process_group_and_prio(pid, {"CPUSET_SP_BACKGROUND", "SCHED_SP_FOREGROUND"},
2212 ANDROID_PRIORITY_HIGHEST);
Wei Wangf1ee2e12018-11-21 00:11:44 -08002213
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002214 last_kill_tm = *tm;
2215
Suren Baghdasaryana7394ea2018-10-12 11:07:40 -07002216 inc_killcnt(procp->oomadj);
Suren Baghdasaryan12cacae2019-09-16 12:06:30 -07002217
Suren Baghdasaryane1604752021-07-22 16:21:21 -07002218 if (ki) {
2219 kill_st.kill_reason = ki->kill_reason;
2220 kill_st.thrashing = ki->thrashing;
2221 kill_st.max_thrashing = ki->max_thrashing;
Ioannis Ilkos48848902021-02-18 19:53:33 +00002222 ALOGI("Kill '%s' (%d), uid %d, oom_score_adj %d to free %" PRId64 "kB rss, %" PRId64
Suren Baghdasaryane1604752021-07-22 16:21:21 -07002223 "kB swap; reason: %s", taskname, pid, uid, procp->oomadj, rss_kb, swap_kb,
2224 ki->kill_desc);
Suren Baghdasaryan89454e62019-07-15 15:50:17 -07002225 } else {
Suren Baghdasaryane1604752021-07-22 16:21:21 -07002226 kill_st.kill_reason = NONE;
2227 kill_st.thrashing = 0;
2228 kill_st.max_thrashing = 0;
Ioannis Ilkos48848902021-02-18 19:53:33 +00002229 ALOGI("Kill '%s' (%d), uid %d, oom_score_adj %d to free %" PRId64 "kB rss, %" PRId64
2230 "kb swap", taskname, pid, uid, procp->oomadj, rss_kb, swap_kb);
Suren Baghdasaryan89454e62019-07-15 15:50:17 -07002231 }
Suren Baghdasaryan39b54802021-08-09 15:10:25 -07002232 killinfo_log(procp, min_oom_score, rss_kb, swap_kb, ki, mi, wi, tm);
Colin Cross3d57a512014-07-14 12:39:56 -07002233
Suren Baghdasaryan3cc1f132020-09-09 20:19:02 -07002234 kill_st.uid = static_cast<int32_t>(uid);
2235 kill_st.taskname = taskname;
Suren Baghdasaryan3cc1f132020-09-09 20:19:02 -07002236 kill_st.oom_score = procp->oomadj;
2237 kill_st.min_oom_score = min_oom_score;
2238 kill_st.free_mem_kb = mi->field.nr_free_pages * page_k;
2239 kill_st.free_swap_kb = mi->field.free_swap * page_k;
2240 stats_write_lmk_kill_occurred(&kill_st, mem_st);
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07002241
Jing Ji5c480962019-12-04 09:22:05 -08002242 ctrl_data_write_lmk_kill_occurred((pid_t)pid, uid);
2243
Ioannis Ilkos279268a2020-08-01 10:50:40 +01002244 result = rss_kb / page_k;
Mark Salyzyn1d5fdf32018-02-04 15:27:23 -08002245
Suren Baghdasaryan8b00c6d2018-10-12 11:28:33 -07002246out:
2247 /*
2248 * WARNING: After pid_remove() procp is freed and can't be used!
2249 * Therefore placed at the end of the function.
2250 */
2251 pid_remove(pid);
2252 return result;
Colin Cross3d57a512014-07-14 12:39:56 -07002253}
2254
2255/*
Chris Morin74b4df92021-02-26 00:00:35 -08002256 * Find one process to kill at or above the given oom_score_adj level.
Suren Baghdasaryan85c31b52018-10-26 11:32:15 -07002257 * Returns size of the killed process.
Colin Cross3d57a512014-07-14 12:39:56 -07002258 */
Suren Baghdasaryane1604752021-07-22 16:21:21 -07002259static int find_and_kill_process(int min_score_adj, struct kill_info *ki, union meminfo *mi,
Suren Baghdasaryan3cc1f132020-09-09 20:19:02 -07002260 struct wakeup_info *wi, struct timespec *tm) {
Colin Cross3d57a512014-07-14 12:39:56 -07002261 int i;
Suren Baghdasaryan85c31b52018-10-26 11:32:15 -07002262 int killed_size = 0;
Yang Lu5dfffbc2018-05-15 04:59:44 +00002263 bool lmk_state_change_start = false;
Suren Baghdasaryan858e8c62021-03-03 11:05:09 -08002264 bool choose_heaviest_task = kill_heaviest_task;
Rajeev Kumar4aba9152018-01-31 17:54:56 -08002265
Chong Zhang1cd12b52015-10-14 16:19:53 -07002266 for (i = OOM_SCORE_ADJ_MAX; i >= min_score_adj; i--) {
Colin Cross3d57a512014-07-14 12:39:56 -07002267 struct proc *procp;
2268
Suren Baghdasaryan858e8c62021-03-03 11:05:09 -08002269 if (!choose_heaviest_task && i <= PERCEPTIBLE_APP_ADJ) {
2270 /*
2271 * If we have to choose a perceptible process, choose the heaviest one to
2272 * hopefully minimize the number of victims.
2273 */
2274 choose_heaviest_task = true;
2275 }
2276
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002277 while (true) {
Suren Baghdasaryan858e8c62021-03-03 11:05:09 -08002278 procp = choose_heaviest_task ?
Suren Baghdasaryan36b2c492018-04-13 11:49:54 -07002279 proc_get_heaviest(i) : proc_adj_lru(i);
Colin Cross3d57a512014-07-14 12:39:56 -07002280
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002281 if (!procp)
2282 break;
2283
Suren Baghdasaryane1604752021-07-22 16:21:21 -07002284 killed_size = kill_one_process(procp, min_score_adj, ki, mi, wi, tm);
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002285 if (killed_size >= 0) {
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07002286 if (!lmk_state_change_start) {
Yang Lu5dfffbc2018-05-15 04:59:44 +00002287 lmk_state_change_start = true;
Vova Sharaienkoa92b76b2021-04-24 00:30:06 +00002288 stats_write_lmk_state_changed(STATE_START);
Yang Lu5dfffbc2018-05-15 04:59:44 +00002289 }
Suren Baghdasaryan85c31b52018-10-26 11:32:15 -07002290 break;
Colin Cross3d57a512014-07-14 12:39:56 -07002291 }
2292 }
Suren Baghdasaryan85c31b52018-10-26 11:32:15 -07002293 if (killed_size) {
2294 break;
2295 }
Colin Cross3d57a512014-07-14 12:39:56 -07002296 }
2297
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07002298 if (lmk_state_change_start) {
Vova Sharaienkoa92b76b2021-04-24 00:30:06 +00002299 stats_write_lmk_state_changed(STATE_STOP);
Rajeev Kumar4aba9152018-01-31 17:54:56 -08002300 }
Rajeev Kumar4aba9152018-01-31 17:54:56 -08002301
Suren Baghdasaryan85c31b52018-10-26 11:32:15 -07002302 return killed_size;
Colin Cross3d57a512014-07-14 12:39:56 -07002303}
2304
Suren Baghdasaryan87966742018-04-13 12:43:41 -07002305static int64_t get_memory_usage(struct reread_data *file_data) {
Robert Beneac72b2932017-08-21 15:18:31 -07002306 int64_t mem_usage;
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -07002307 char *buf;
Suren Baghdasaryan87966742018-04-13 12:43:41 -07002308
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -07002309 if ((buf = reread_file(file_data)) == NULL) {
Robert Beneac72b2932017-08-21 15:18:31 -07002310 return -1;
2311 }
2312
Suren Baghdasaryan87966742018-04-13 12:43:41 -07002313 if (!parse_int64(buf, &mem_usage)) {
2314 ALOGE("%s parse error", file_data->filename);
Robert Beneac72b2932017-08-21 15:18:31 -07002315 return -1;
2316 }
Robert Beneac72b2932017-08-21 15:18:31 -07002317 if (mem_usage == 0) {
2318 ALOGE("No memory!");
2319 return -1;
2320 }
2321 return mem_usage;
2322}
2323
Suren Baghdasaryane0f3dd12018-04-13 13:41:12 -07002324void record_low_pressure_levels(union meminfo *mi) {
2325 if (low_pressure_mem.min_nr_free_pages == -1 ||
2326 low_pressure_mem.min_nr_free_pages > mi->field.nr_free_pages) {
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002327 if (debug_process_killing) {
Suren Baghdasaryane0f3dd12018-04-13 13:41:12 -07002328 ALOGI("Low pressure min memory update from %" PRId64 " to %" PRId64,
2329 low_pressure_mem.min_nr_free_pages, mi->field.nr_free_pages);
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002330 }
Suren Baghdasaryane0f3dd12018-04-13 13:41:12 -07002331 low_pressure_mem.min_nr_free_pages = mi->field.nr_free_pages;
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002332 }
2333 /*
2334 * Free memory at low vmpressure events occasionally gets spikes,
2335 * possibly a stale low vmpressure event with memory already
2336 * freed up (no memory pressure should have been reported).
Suren Baghdasaryane0f3dd12018-04-13 13:41:12 -07002337 * Ignore large jumps in max_nr_free_pages that would mess up our stats.
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002338 */
Suren Baghdasaryane0f3dd12018-04-13 13:41:12 -07002339 if (low_pressure_mem.max_nr_free_pages == -1 ||
2340 (low_pressure_mem.max_nr_free_pages < mi->field.nr_free_pages &&
2341 mi->field.nr_free_pages - low_pressure_mem.max_nr_free_pages <
2342 low_pressure_mem.max_nr_free_pages * 0.1)) {
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002343 if (debug_process_killing) {
Suren Baghdasaryane0f3dd12018-04-13 13:41:12 -07002344 ALOGI("Low pressure max memory update from %" PRId64 " to %" PRId64,
2345 low_pressure_mem.max_nr_free_pages, mi->field.nr_free_pages);
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002346 }
Suren Baghdasaryane0f3dd12018-04-13 13:41:12 -07002347 low_pressure_mem.max_nr_free_pages = mi->field.nr_free_pages;
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002348 }
2349}
2350
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08002351enum vmpressure_level upgrade_level(enum vmpressure_level level) {
2352 return (enum vmpressure_level)((level < VMPRESS_LEVEL_CRITICAL) ?
2353 level + 1 : level);
2354}
2355
2356enum vmpressure_level downgrade_level(enum vmpressure_level level) {
2357 return (enum vmpressure_level)((level > VMPRESS_LEVEL_LOW) ?
2358 level - 1 : level);
2359}
2360
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002361enum zone_watermark {
2362 WMARK_MIN = 0,
2363 WMARK_LOW,
2364 WMARK_HIGH,
2365 WMARK_NONE
2366};
2367
Suren Baghdasaryan81c75b22019-08-14 09:48:35 -07002368struct zone_watermarks {
2369 long high_wmark;
2370 long low_wmark;
2371 long min_wmark;
2372};
2373
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002374/*
2375 * Returns lowest breached watermark or WMARK_NONE.
2376 */
Suren Baghdasaryan81c75b22019-08-14 09:48:35 -07002377static enum zone_watermark get_lowest_watermark(union meminfo *mi,
2378 struct zone_watermarks *watermarks)
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002379{
Suren Baghdasaryan81c75b22019-08-14 09:48:35 -07002380 int64_t nr_free_pages = mi->field.nr_free_pages - mi->field.cma_free;
2381
2382 if (nr_free_pages < watermarks->min_wmark) {
2383 return WMARK_MIN;
2384 }
2385 if (nr_free_pages < watermarks->low_wmark) {
2386 return WMARK_LOW;
2387 }
2388 if (nr_free_pages < watermarks->high_wmark) {
2389 return WMARK_HIGH;
2390 }
2391 return WMARK_NONE;
2392}
2393
2394void calc_zone_watermarks(struct zoneinfo *zi, struct zone_watermarks *watermarks) {
2395 memset(watermarks, 0, sizeof(struct zone_watermarks));
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002396
2397 for (int node_idx = 0; node_idx < zi->node_count; node_idx++) {
2398 struct zoneinfo_node *node = &zi->nodes[node_idx];
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002399 for (int zone_idx = 0; zone_idx < node->zone_count; zone_idx++) {
2400 struct zoneinfo_zone *zone = &node->zones[zone_idx];
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002401
2402 if (!zone->fields.field.present) {
2403 continue;
2404 }
2405
Suren Baghdasaryan81c75b22019-08-14 09:48:35 -07002406 watermarks->high_wmark += zone->max_protection + zone->fields.field.high;
2407 watermarks->low_wmark += zone->max_protection + zone->fields.field.low;
2408 watermarks->min_wmark += zone->max_protection + zone->fields.field.min;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002409 }
2410 }
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002411}
2412
Suren Baghdasaryan51ee4c52020-04-21 12:27:01 -07002413static int calc_swap_utilization(union meminfo *mi) {
2414 int64_t swap_used = mi->field.total_swap - mi->field.free_swap;
2415 int64_t total_swappable = mi->field.active_anon + mi->field.inactive_anon +
2416 mi->field.shmem + swap_used;
2417 return total_swappable > 0 ? (swap_used * 100) / total_swappable : 0;
2418}
2419
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002420static void mp_event_psi(int data, uint32_t events, struct polling_params *poll_params) {
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002421 enum reclaim_state {
2422 NO_RECLAIM = 0,
2423 KSWAPD_RECLAIM,
2424 DIRECT_RECLAIM,
2425 };
2426 static int64_t init_ws_refault;
Martin Liu1f72f5f2020-08-21 13:18:50 +08002427 static int64_t prev_workingset_refault;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002428 static int64_t base_file_lru;
2429 static int64_t init_pgscan_kswapd;
2430 static int64_t init_pgscan_direct;
2431 static int64_t swap_low_threshold;
2432 static bool killing;
Martin Liu1f72f5f2020-08-21 13:18:50 +08002433 static int thrashing_limit = thrashing_limit_pct;
Suren Baghdasaryan81c75b22019-08-14 09:48:35 -07002434 static struct zone_watermarks watermarks;
2435 static struct timespec wmark_update_tm;
Suren Baghdasaryand7b4fcb2020-07-23 18:00:43 -07002436 static struct wakeup_info wi;
Martin Liu1f72f5f2020-08-21 13:18:50 +08002437 static struct timespec thrashing_reset_tm;
2438 static int64_t prev_thrash_growth = 0;
Suren Baghdasaryan11221d42021-07-14 17:57:52 -07002439 static bool check_filecache = false;
Suren Baghdasaryane1604752021-07-22 16:21:21 -07002440 static int max_thrashing = 0;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002441
2442 union meminfo mi;
2443 union vmstat vs;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002444 struct timespec curr_tm;
2445 int64_t thrashing = 0;
2446 bool swap_is_low = false;
2447 enum vmpressure_level level = (enum vmpressure_level)data;
2448 enum kill_reasons kill_reason = NONE;
2449 bool cycle_after_kill = false;
2450 enum reclaim_state reclaim = NO_RECLAIM;
2451 enum zone_watermark wmark = WMARK_NONE;
Suren Baghdasaryan89454e62019-07-15 15:50:17 -07002452 char kill_desc[LINE_MAX];
Suren Baghdasaryan970a26a2019-09-19 15:27:21 -07002453 bool cut_thrashing_limit = false;
2454 int min_score_adj = 0;
Suren Baghdasaryan51ee4c52020-04-21 12:27:01 -07002455 int swap_util = 0;
Martin Liu1f72f5f2020-08-21 13:18:50 +08002456 long since_thrashing_reset_ms;
Suren Baghdasaryandc60f972020-12-14 13:38:48 -08002457 int64_t workingset_refault_file;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002458
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002459 if (clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm) != 0) {
2460 ALOGE("Failed to get current time");
2461 return;
2462 }
2463
Suren Baghdasaryand7b4fcb2020-07-23 18:00:43 -07002464 record_wakeup_time(&curr_tm, events ? Event : Polling, &wi);
2465
Suren Baghdasaryan03dccf32020-04-28 16:02:13 -07002466 bool kill_pending = is_kill_pending();
Suren Baghdasaryaned715a32020-05-11 16:31:57 -07002467 if (kill_pending && (kill_timeout_ms == 0 ||
2468 get_time_diff_ms(&last_kill_tm, &curr_tm) < static_cast<long>(kill_timeout_ms))) {
Suren Baghdasaryan03dccf32020-04-28 16:02:13 -07002469 /* Skip while still killing a process */
Suren Baghdasaryand7b4fcb2020-07-23 18:00:43 -07002470 wi.skipped_wakeups++;
Suren Baghdasaryan03dccf32020-04-28 16:02:13 -07002471 goto no_kill;
2472 }
2473 /*
2474 * Process is dead or kill timeout is over, stop waiting. This has no effect if pidfds are
2475 * supported and death notification already caused waiting to stop.
2476 */
2477 stop_wait_for_proc_kill(!kill_pending);
2478
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002479 if (vmstat_parse(&vs) < 0) {
2480 ALOGE("Failed to parse vmstat!");
2481 return;
2482 }
Suren Baghdasaryandc60f972020-12-14 13:38:48 -08002483 /* Starting 5.9 kernel workingset_refault vmstat field was renamed workingset_refault_file */
2484 workingset_refault_file = vs.field.workingset_refault ? : vs.field.workingset_refault_file;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002485
2486 if (meminfo_parse(&mi) < 0) {
2487 ALOGE("Failed to parse meminfo!");
2488 return;
2489 }
2490
2491 /* Reset states after process got killed */
2492 if (killing) {
2493 killing = false;
2494 cycle_after_kill = true;
2495 /* Reset file-backed pagecache size and refault amounts after a kill */
2496 base_file_lru = vs.field.nr_inactive_file + vs.field.nr_active_file;
Suren Baghdasaryandc60f972020-12-14 13:38:48 -08002497 init_ws_refault = workingset_refault_file;
Martin Liu1f72f5f2020-08-21 13:18:50 +08002498 thrashing_reset_tm = curr_tm;
2499 prev_thrash_growth = 0;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002500 }
2501
2502 /* Check free swap levels */
2503 if (swap_free_low_percentage) {
2504 if (!swap_low_threshold) {
2505 swap_low_threshold = mi.field.total_swap * swap_free_low_percentage / 100;
2506 }
2507 swap_is_low = mi.field.free_swap < swap_low_threshold;
2508 }
2509
2510 /* Identify reclaim state */
2511 if (vs.field.pgscan_direct > init_pgscan_direct) {
2512 init_pgscan_direct = vs.field.pgscan_direct;
2513 init_pgscan_kswapd = vs.field.pgscan_kswapd;
2514 reclaim = DIRECT_RECLAIM;
2515 } else if (vs.field.pgscan_kswapd > init_pgscan_kswapd) {
2516 init_pgscan_kswapd = vs.field.pgscan_kswapd;
2517 reclaim = KSWAPD_RECLAIM;
Suren Baghdasaryandc60f972020-12-14 13:38:48 -08002518 } else if (workingset_refault_file == prev_workingset_refault) {
Suren Baghdasaryan11221d42021-07-14 17:57:52 -07002519 /*
2520 * Device is not thrashing and not reclaiming, bail out early until we see these stats
2521 * changing
2522 */
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002523 goto no_kill;
2524 }
2525
Suren Baghdasaryandc60f972020-12-14 13:38:48 -08002526 prev_workingset_refault = workingset_refault_file;
Martin Liu1f72f5f2020-08-21 13:18:50 +08002527
2528 /*
2529 * It's possible we fail to find an eligible process to kill (ex. no process is
2530 * above oom_adj_min). When this happens, we should retry to find a new process
2531 * for a kill whenever a new eligible process is available. This is especially
2532 * important for a slow growing refault case. While retrying, we should keep
2533 * monitoring new thrashing counter as someone could release the memory to mitigate
2534 * the thrashing. Thus, when thrashing reset window comes, we decay the prev thrashing
Suren Baghdasaryan11221d42021-07-14 17:57:52 -07002535 * counter by window counts. If the counter is still greater than thrashing limit,
Martin Liu1f72f5f2020-08-21 13:18:50 +08002536 * we preserve the current prev_thrash counter so we will retry kill again. Otherwise,
2537 * we reset the prev_thrash counter so we will stop retrying.
2538 */
2539 since_thrashing_reset_ms = get_time_diff_ms(&thrashing_reset_tm, &curr_tm);
2540 if (since_thrashing_reset_ms > THRASHING_RESET_INTERVAL_MS) {
2541 long windows_passed;
2542 /* Calculate prev_thrash_growth if we crossed THRASHING_RESET_INTERVAL_MS */
Suren Baghdasaryandc60f972020-12-14 13:38:48 -08002543 prev_thrash_growth = (workingset_refault_file - init_ws_refault) * 100
Martin Liuc3108412020-09-03 22:12:14 +08002544 / (base_file_lru + 1);
Martin Liu1f72f5f2020-08-21 13:18:50 +08002545 windows_passed = (since_thrashing_reset_ms / THRASHING_RESET_INTERVAL_MS);
2546 /*
2547 * Decay prev_thrashing unless over-the-limit thrashing was registered in the window we
2548 * just crossed, which means there were no eligible processes to kill. We preserve the
2549 * counter in that case to ensure a kill if a new eligible process appears.
2550 */
2551 if (windows_passed > 1 || prev_thrash_growth < thrashing_limit) {
2552 prev_thrash_growth >>= windows_passed;
2553 }
2554
2555 /* Record file-backed pagecache size when crossing THRASHING_RESET_INTERVAL_MS */
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002556 base_file_lru = vs.field.nr_inactive_file + vs.field.nr_active_file;
Suren Baghdasaryandc60f972020-12-14 13:38:48 -08002557 init_ws_refault = workingset_refault_file;
Martin Liu1f72f5f2020-08-21 13:18:50 +08002558 thrashing_reset_tm = curr_tm;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002559 thrashing_limit = thrashing_limit_pct;
2560 } else {
2561 /* Calculate what % of the file-backed pagecache refaulted so far */
Suren Baghdasaryandc60f972020-12-14 13:38:48 -08002562 thrashing = (workingset_refault_file - init_ws_refault) * 100 / (base_file_lru + 1);
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002563 }
Martin Liu1f72f5f2020-08-21 13:18:50 +08002564 /* Add previous cycle's decayed thrashing amount */
2565 thrashing += prev_thrash_growth;
Suren Baghdasaryane1604752021-07-22 16:21:21 -07002566 if (max_thrashing < thrashing) {
2567 max_thrashing = thrashing;
2568 }
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002569
Suren Baghdasaryan81c75b22019-08-14 09:48:35 -07002570 /*
2571 * Refresh watermarks once per min in case user updated one of the margins.
2572 * TODO: b/140521024 replace this periodic update with an API for AMS to notify LMKD
2573 * that zone watermarks were changed by the system software.
2574 */
2575 if (watermarks.high_wmark == 0 || get_time_diff_ms(&wmark_update_tm, &curr_tm) > 60000) {
2576 struct zoneinfo zi;
2577
2578 if (zoneinfo_parse(&zi) < 0) {
2579 ALOGE("Failed to parse zoneinfo!");
2580 return;
2581 }
2582
2583 calc_zone_watermarks(&zi, &watermarks);
2584 wmark_update_tm = curr_tm;
Martin Liu1f72f5f2020-08-21 13:18:50 +08002585 }
Suren Baghdasaryan81c75b22019-08-14 09:48:35 -07002586
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002587 /* Find out which watermark is breached if any */
Suren Baghdasaryan81c75b22019-08-14 09:48:35 -07002588 wmark = get_lowest_watermark(&mi, &watermarks);
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002589
2590 /*
2591 * TODO: move this logic into a separate function
2592 * Decide if killing a process is necessary and record the reason
2593 */
2594 if (cycle_after_kill && wmark < WMARK_LOW) {
2595 /*
2596 * Prevent kills not freeing enough memory which might lead to OOM kill.
2597 * This might happen when a process is consuming memory faster than reclaim can
2598 * free even after a kill. Mostly happens when running memory stress tests.
2599 */
2600 kill_reason = PRESSURE_AFTER_KILL;
Suren Baghdasaryan89454e62019-07-15 15:50:17 -07002601 strncpy(kill_desc, "min watermark is breached even after kill", sizeof(kill_desc));
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002602 } else if (level == VMPRESS_LEVEL_CRITICAL && events != 0) {
2603 /*
2604 * Device is too busy reclaiming memory which might lead to ANR.
2605 * Critical level is triggered when PSI complete stall (all tasks are blocked because
2606 * of the memory congestion) breaches the configured threshold.
2607 */
2608 kill_reason = NOT_RESPONDING;
Suren Baghdasaryan89454e62019-07-15 15:50:17 -07002609 strncpy(kill_desc, "device is not responding", sizeof(kill_desc));
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002610 } else if (swap_is_low && thrashing > thrashing_limit_pct) {
2611 /* Page cache is thrashing while swap is low */
2612 kill_reason = LOW_SWAP_AND_THRASHING;
Suren Baghdasaryan89454e62019-07-15 15:50:17 -07002613 snprintf(kill_desc, sizeof(kill_desc), "device is low on swap (%" PRId64
2614 "kB < %" PRId64 "kB) and thrashing (%" PRId64 "%%)",
2615 mi.field.free_swap * page_k, swap_low_threshold * page_k, thrashing);
Suren Baghdasaryan0142b3c2021-03-03 11:11:09 -08002616 /* Do not kill perceptible apps unless below min watermark or heavily thrashing */
2617 if (wmark > WMARK_MIN && thrashing < thrashing_critical_pct) {
Suren Baghdasaryan48135c42020-05-19 12:59:18 -07002618 min_score_adj = PERCEPTIBLE_APP_ADJ + 1;
2619 }
Suren Baghdasaryan11221d42021-07-14 17:57:52 -07002620 check_filecache = true;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002621 } else if (swap_is_low && wmark < WMARK_HIGH) {
2622 /* Both free memory and swap are low */
2623 kill_reason = LOW_MEM_AND_SWAP;
Suren Baghdasaryan89454e62019-07-15 15:50:17 -07002624 snprintf(kill_desc, sizeof(kill_desc), "%s watermark is breached and swap is low (%"
Suren Baghdasaryan23678182021-03-02 18:33:09 -08002625 PRId64 "kB < %" PRId64 "kB)", wmark < WMARK_LOW ? "min" : "low",
Suren Baghdasaryan89454e62019-07-15 15:50:17 -07002626 mi.field.free_swap * page_k, swap_low_threshold * page_k);
Suren Baghdasaryan0142b3c2021-03-03 11:11:09 -08002627 /* Do not kill perceptible apps unless below min watermark or heavily thrashing */
2628 if (wmark > WMARK_MIN && thrashing < thrashing_critical_pct) {
Suren Baghdasaryan48135c42020-05-19 12:59:18 -07002629 min_score_adj = PERCEPTIBLE_APP_ADJ + 1;
2630 }
Suren Baghdasaryan51ee4c52020-04-21 12:27:01 -07002631 } else if (wmark < WMARK_HIGH && swap_util_max < 100 &&
2632 (swap_util = calc_swap_utilization(&mi)) > swap_util_max) {
2633 /*
2634 * Too much anon memory is swapped out but swap is not low.
2635 * Non-swappable allocations created memory pressure.
2636 */
2637 kill_reason = LOW_MEM_AND_SWAP_UTIL;
2638 snprintf(kill_desc, sizeof(kill_desc), "%s watermark is breached and swap utilization"
Suren Baghdasaryan23678182021-03-02 18:33:09 -08002639 " is high (%d%% > %d%%)", wmark < WMARK_LOW ? "min" : "low",
Suren Baghdasaryan51ee4c52020-04-21 12:27:01 -07002640 swap_util, swap_util_max);
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002641 } else if (wmark < WMARK_HIGH && thrashing > thrashing_limit) {
2642 /* Page cache is thrashing while memory is low */
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002643 kill_reason = LOW_MEM_AND_THRASHING;
Suren Baghdasaryan89454e62019-07-15 15:50:17 -07002644 snprintf(kill_desc, sizeof(kill_desc), "%s watermark is breached and thrashing (%"
Suren Baghdasaryan23678182021-03-02 18:33:09 -08002645 PRId64 "%%)", wmark < WMARK_LOW ? "min" : "low", thrashing);
Suren Baghdasaryan970a26a2019-09-19 15:27:21 -07002646 cut_thrashing_limit = true;
Suren Baghdasaryan0142b3c2021-03-03 11:11:09 -08002647 /* Do not kill perceptible apps unless thrashing at critical levels */
2648 if (thrashing < thrashing_critical_pct) {
2649 min_score_adj = PERCEPTIBLE_APP_ADJ + 1;
2650 }
Suren Baghdasaryan11221d42021-07-14 17:57:52 -07002651 check_filecache = true;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002652 } else if (reclaim == DIRECT_RECLAIM && thrashing > thrashing_limit) {
2653 /* Page cache is thrashing while in direct reclaim (mostly happens on lowram devices) */
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002654 kill_reason = DIRECT_RECL_AND_THRASHING;
Suren Baghdasaryan89454e62019-07-15 15:50:17 -07002655 snprintf(kill_desc, sizeof(kill_desc), "device is in direct reclaim and thrashing (%"
2656 PRId64 "%%)", thrashing);
Suren Baghdasaryan970a26a2019-09-19 15:27:21 -07002657 cut_thrashing_limit = true;
Suren Baghdasaryan0142b3c2021-03-03 11:11:09 -08002658 /* Do not kill perceptible apps unless thrashing at critical levels */
2659 if (thrashing < thrashing_critical_pct) {
2660 min_score_adj = PERCEPTIBLE_APP_ADJ + 1;
2661 }
Suren Baghdasaryan11221d42021-07-14 17:57:52 -07002662 check_filecache = true;
2663 } else if (check_filecache) {
2664 int64_t file_lru_kb = (vs.field.nr_inactive_file + vs.field.nr_active_file) * page_k;
2665
2666 if (file_lru_kb < filecache_min_kb) {
2667 /* File cache is too low after thrashing, keep killing background processes */
2668 kill_reason = LOW_FILECACHE_AFTER_THRASHING;
2669 snprintf(kill_desc, sizeof(kill_desc),
2670 "filecache is low (%" PRId64 "kB < %" PRId64 "kB) after thrashing",
2671 file_lru_kb, filecache_min_kb);
2672 min_score_adj = PERCEPTIBLE_APP_ADJ + 1;
2673 } else {
2674 /* File cache is big enough, stop checking */
2675 check_filecache = false;
2676 }
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002677 }
2678
2679 /* Kill a process if necessary */
2680 if (kill_reason != NONE) {
Suren Baghdasaryane1604752021-07-22 16:21:21 -07002681 struct kill_info ki = {
2682 .kill_reason = kill_reason,
2683 .kill_desc = kill_desc,
2684 .thrashing = (int)thrashing,
2685 .max_thrashing = max_thrashing,
2686 };
2687 int pages_freed = find_and_kill_process(min_score_adj, &ki, &mi, &wi, &curr_tm);
Suren Baghdasaryan970a26a2019-09-19 15:27:21 -07002688 if (pages_freed > 0) {
2689 killing = true;
Suren Baghdasaryane1604752021-07-22 16:21:21 -07002690 max_thrashing = 0;
Suren Baghdasaryan970a26a2019-09-19 15:27:21 -07002691 if (cut_thrashing_limit) {
2692 /*
2693 * Cut thrasing limit by thrashing_limit_decay_pct percentage of the current
2694 * thrashing limit until the system stops thrashing.
2695 */
2696 thrashing_limit = (thrashing_limit * (100 - thrashing_limit_decay_pct)) / 100;
2697 }
2698 }
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002699 }
2700
2701no_kill:
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002702 /* Do not poll if kernel supports pidfd waiting */
2703 if (is_waiting_for_kill()) {
2704 /* Pause polling if we are waiting for process death notification */
2705 poll_params->update = POLLING_PAUSE;
2706 return;
2707 }
2708
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002709 /*
2710 * Start polling after initial PSI event;
2711 * extend polling while device is in direct reclaim or process is being killed;
2712 * do not extend when kswapd reclaims because that might go on for a long time
2713 * without causing memory pressure
2714 */
2715 if (events || killing || reclaim == DIRECT_RECLAIM) {
2716 poll_params->update = POLLING_START;
2717 }
2718
2719 /* Decide the polling interval */
2720 if (swap_is_low || killing) {
2721 /* Fast polling during and after a kill or when swap is low */
2722 poll_params->polling_interval_ms = PSI_POLL_PERIOD_SHORT_MS;
2723 } else {
2724 /* By default use long intervals */
2725 poll_params->polling_interval_ms = PSI_POLL_PERIOD_LONG_MS;
2726 }
2727}
2728
Suren Baghdasaryane12a0672019-07-15 14:50:49 -07002729static void mp_event_common(int data, uint32_t events, struct polling_params *poll_params) {
Todd Poynorc58c5142013-07-09 19:35:14 -07002730 unsigned long long evcount;
Robert Beneac72b2932017-08-21 15:18:31 -07002731 int64_t mem_usage, memsw_usage;
Robert Benea3be16142017-09-13 15:20:30 -07002732 int64_t mem_pressure;
Suren Baghdasaryane0f3dd12018-04-13 13:41:12 -07002733 union meminfo mi;
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07002734 struct zoneinfo zi;
Suren Baghdasaryan53be36e2018-09-05 15:46:32 -07002735 struct timespec curr_tm;
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -07002736 static unsigned long kill_skip_count = 0;
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08002737 enum vmpressure_level level = (enum vmpressure_level)data;
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07002738 long other_free = 0, other_file = 0;
2739 int min_score_adj;
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07002740 int minfree = 0;
Suren Baghdasaryan87966742018-04-13 12:43:41 -07002741 static struct reread_data mem_usage_file_data = {
2742 .filename = MEMCG_MEMORY_USAGE,
2743 .fd = -1,
2744 };
2745 static struct reread_data memsw_usage_file_data = {
2746 .filename = MEMCG_MEMORYSW_USAGE,
2747 .fd = -1,
2748 };
Suren Baghdasaryand7b4fcb2020-07-23 18:00:43 -07002749 static struct wakeup_info wi;
Todd Poynorc58c5142013-07-09 19:35:14 -07002750
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08002751 if (debug_process_killing) {
2752 ALOGI("%s memory pressure event is triggered", level_name[level]);
2753 }
2754
2755 if (!use_psi_monitors) {
2756 /*
2757 * Check all event counters from low to critical
2758 * and upgrade to the highest priority one. By reading
2759 * eventfd we also reset the event counters.
2760 */
Tom Cherry43f3d2b2019-12-04 12:46:57 -08002761 for (int lvl = VMPRESS_LEVEL_LOW; lvl < VMPRESS_LEVEL_COUNT; lvl++) {
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08002762 if (mpevfd[lvl] != -1 &&
2763 TEMP_FAILURE_RETRY(read(mpevfd[lvl],
2764 &evcount, sizeof(evcount))) > 0 &&
2765 evcount > 0 && lvl > level) {
Tom Cherry43f3d2b2019-12-04 12:46:57 -08002766 level = static_cast<vmpressure_level>(lvl);
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08002767 }
Suren Baghdasaryan3e1a8492018-01-04 09:16:21 -08002768 }
2769 }
Todd Poynorc58c5142013-07-09 19:35:14 -07002770
Suren Baghdasaryane12a0672019-07-15 14:50:49 -07002771 /* Start polling after initial PSI event */
2772 if (use_psi_monitors && events) {
2773 /* Override polling params only if current event is more critical */
2774 if (!poll_params->poll_handler || data > poll_params->poll_handler->data) {
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002775 poll_params->polling_interval_ms = PSI_POLL_PERIOD_SHORT_MS;
Suren Baghdasaryane12a0672019-07-15 14:50:49 -07002776 poll_params->update = POLLING_START;
2777 }
2778 }
2779
Suren Baghdasaryan53be36e2018-09-05 15:46:32 -07002780 if (clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm) != 0) {
2781 ALOGE("Failed to get current time");
2782 return;
2783 }
2784
Suren Baghdasaryand7b4fcb2020-07-23 18:00:43 -07002785 record_wakeup_time(&curr_tm, events ? Event : Polling, &wi);
2786
Suren Baghdasaryaned715a32020-05-11 16:31:57 -07002787 if (kill_timeout_ms &&
2788 get_time_diff_ms(&last_kill_tm, &curr_tm) < static_cast<long>(kill_timeout_ms)) {
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002789 /*
2790 * If we're within the no-kill timeout, see if there's pending reclaim work
2791 * from the last killed process. If so, skip killing for now.
2792 */
2793 if (is_kill_pending()) {
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -07002794 kill_skip_count++;
Suren Baghdasaryand7b4fcb2020-07-23 18:00:43 -07002795 wi.skipped_wakeups++;
Suren Baghdasaryan30854e72018-01-17 17:28:01 -08002796 return;
2797 }
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002798 /*
2799 * Process is dead, stop waiting. This has no effect if pidfds are supported and
2800 * death notification already caused waiting to stop.
2801 */
2802 stop_wait_for_proc_kill(true);
2803 } else {
2804 /*
2805 * Killing took longer than no-kill timeout. Stop waiting for the last process
2806 * to die because we are ready to kill again.
2807 */
2808 stop_wait_for_proc_kill(false);
Suren Baghdasaryan30854e72018-01-17 17:28:01 -08002809 }
2810
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -07002811 if (kill_skip_count > 0) {
Suren Baghdasaryaneff82332018-05-10 16:10:56 -07002812 ALOGI("%lu memory pressure events were skipped after a kill!",
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -07002813 kill_skip_count);
2814 kill_skip_count = 0;
Suren Baghdasaryan30854e72018-01-17 17:28:01 -08002815 }
2816
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07002817 if (meminfo_parse(&mi) < 0 || zoneinfo_parse(&zi) < 0) {
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002818 ALOGE("Failed to get free memory!");
2819 return;
2820 }
2821
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07002822 if (use_minfree_levels) {
2823 int i;
2824
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07002825 other_free = mi.field.nr_free_pages - zi.totalreserve_pages;
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07002826 if (mi.field.nr_file_pages > (mi.field.shmem + mi.field.unevictable + mi.field.swap_cached)) {
2827 other_file = (mi.field.nr_file_pages - mi.field.shmem -
2828 mi.field.unevictable - mi.field.swap_cached);
2829 } else {
2830 other_file = 0;
2831 }
2832
2833 min_score_adj = OOM_SCORE_ADJ_MAX + 1;
2834 for (i = 0; i < lowmem_targets_size; i++) {
2835 minfree = lowmem_minfree[i];
2836 if (other_free < minfree && other_file < minfree) {
2837 min_score_adj = lowmem_adj[i];
2838 break;
2839 }
2840 }
2841
Suren Baghdasaryanb0bda552018-05-18 14:42:00 -07002842 if (min_score_adj == OOM_SCORE_ADJ_MAX + 1) {
2843 if (debug_process_killing) {
2844 ALOGI("Ignore %s memory pressure event "
2845 "(free memory=%ldkB, cache=%ldkB, limit=%ldkB)",
2846 level_name[level], other_free * page_k, other_file * page_k,
2847 (long)lowmem_minfree[lowmem_targets_size - 1] * page_k);
2848 }
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07002849 return;
Suren Baghdasaryanb0bda552018-05-18 14:42:00 -07002850 }
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07002851
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07002852 goto do_kill;
2853 }
2854
Suren Baghdasaryane0f3dd12018-04-13 13:41:12 -07002855 if (level == VMPRESS_LEVEL_LOW) {
2856 record_low_pressure_levels(&mi);
2857 }
2858
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002859 if (level_oomadj[level] > OOM_SCORE_ADJ_MAX) {
2860 /* Do not monitor this pressure level */
2861 return;
2862 }
2863
Suren Baghdasaryan87966742018-04-13 12:43:41 -07002864 if ((mem_usage = get_memory_usage(&mem_usage_file_data)) < 0) {
2865 goto do_kill;
2866 }
2867 if ((memsw_usage = get_memory_usage(&memsw_usage_file_data)) < 0) {
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08002868 goto do_kill;
Robert Benea3be16142017-09-13 15:20:30 -07002869 }
Robert Beneac72b2932017-08-21 15:18:31 -07002870
Robert Benea3be16142017-09-13 15:20:30 -07002871 // Calculate percent for swappinness.
2872 mem_pressure = (mem_usage * 100) / memsw_usage;
2873
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08002874 if (enable_pressure_upgrade && level != VMPRESS_LEVEL_CRITICAL) {
Robert Benea3be16142017-09-13 15:20:30 -07002875 // We are swapping too much.
2876 if (mem_pressure < upgrade_pressure) {
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08002877 level = upgrade_level(level);
2878 if (debug_process_killing) {
2879 ALOGI("Event upgraded to %s", level_name[level]);
2880 }
Robert Beneac72b2932017-08-21 15:18:31 -07002881 }
2882 }
2883
Vic Yang65680692018-08-07 10:18:22 -07002884 // If we still have enough swap space available, check if we want to
2885 // ignore/downgrade pressure events.
2886 if (mi.field.free_swap >=
2887 mi.field.total_swap * swap_free_low_percentage / 100) {
2888 // If the pressure is larger than downgrade_pressure lmk will not
2889 // kill any process, since enough memory is available.
2890 if (mem_pressure > downgrade_pressure) {
2891 if (debug_process_killing) {
2892 ALOGI("Ignore %s memory pressure", level_name[level]);
2893 }
2894 return;
2895 } else if (level == VMPRESS_LEVEL_CRITICAL && mem_pressure > upgrade_pressure) {
2896 if (debug_process_killing) {
2897 ALOGI("Downgrade critical memory pressure");
2898 }
2899 // Downgrade event, since enough memory available.
2900 level = downgrade_level(level);
Robert Benea3be16142017-09-13 15:20:30 -07002901 }
Robert Benea3be16142017-09-13 15:20:30 -07002902 }
2903
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08002904do_kill:
Suren Baghdasaryand1d59f82018-04-13 11:45:38 -07002905 if (low_ram_device) {
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002906 /* For Go devices kill only one task */
Suren Baghdasaryane1604752021-07-22 16:21:21 -07002907 if (find_and_kill_process(level_oomadj[level], NULL, &mi, &wi, &curr_tm) == 0) {
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002908 if (debug_process_killing) {
2909 ALOGI("Nothing to kill");
2910 }
2911 }
2912 } else {
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07002913 int pages_freed;
Suren Baghdasaryan53be36e2018-09-05 15:46:32 -07002914 static struct timespec last_report_tm;
2915 static unsigned long report_skip_count = 0;
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07002916
2917 if (!use_minfree_levels) {
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07002918 /* Free up enough memory to downgrate the memory pressure to low level */
Suren Baghdasaryan85c31b52018-10-26 11:32:15 -07002919 if (mi.field.nr_free_pages >= low_pressure_mem.max_nr_free_pages) {
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07002920 if (debug_process_killing) {
2921 ALOGI("Ignoring pressure since more memory is "
2922 "available (%" PRId64 ") than watermark (%" PRId64 ")",
2923 mi.field.nr_free_pages, low_pressure_mem.max_nr_free_pages);
2924 }
2925 return;
2926 }
2927 min_score_adj = level_oomadj[level];
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002928 }
2929
Suren Baghdasaryane1604752021-07-22 16:21:21 -07002930 pages_freed = find_and_kill_process(min_score_adj, NULL, &mi, &wi, &curr_tm);
Suren Baghdasaryaneff82332018-05-10 16:10:56 -07002931
Suren Baghdasaryan53be36e2018-09-05 15:46:32 -07002932 if (pages_freed == 0) {
2933 /* Rate limit kill reports when nothing was reclaimed */
2934 if (get_time_diff_ms(&last_report_tm, &curr_tm) < FAIL_REPORT_RLIMIT_MS) {
2935 report_skip_count++;
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -07002936 return;
2937 }
Robert Benea7f68a3f2017-08-11 16:03:20 -07002938 }
Suren Baghdasaryan53be36e2018-09-05 15:46:32 -07002939
Suren Baghdasaryan12cacae2019-09-16 12:06:30 -07002940 /* Log whenever we kill or when report rate limit allows */
Suren Baghdasaryan53be36e2018-09-05 15:46:32 -07002941 if (use_minfree_levels) {
Chris Morin74b4df92021-02-26 00:00:35 -08002942 ALOGI("Reclaimed %ldkB, cache(%ldkB) and free(%" PRId64 "kB)-reserved(%" PRId64 "kB) "
2943 "below min(%ldkB) for oom_score_adj %d",
Suren Baghdasaryan85c31b52018-10-26 11:32:15 -07002944 pages_freed * page_k,
Suren Baghdasaryan53be36e2018-09-05 15:46:32 -07002945 other_file * page_k, mi.field.nr_free_pages * page_k,
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07002946 zi.totalreserve_pages * page_k,
Suren Baghdasaryan53be36e2018-09-05 15:46:32 -07002947 minfree * page_k, min_score_adj);
2948 } else {
Chris Morin74b4df92021-02-26 00:00:35 -08002949 ALOGI("Reclaimed %ldkB at oom_score_adj %d", pages_freed * page_k, min_score_adj);
Suren Baghdasaryan53be36e2018-09-05 15:46:32 -07002950 }
2951
2952 if (report_skip_count > 0) {
2953 ALOGI("Suppressed %lu failed kill reports", report_skip_count);
2954 report_skip_count = 0;
2955 }
2956
2957 last_report_tm = curr_tm;
Colin Cross01db2712014-07-11 17:16:56 -07002958 }
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002959 if (is_waiting_for_kill()) {
2960 /* pause polling if we are waiting for process death notification */
2961 poll_params->update = POLLING_PAUSE;
2962 }
Todd Poynorc58c5142013-07-09 19:35:14 -07002963}
2964
Suren Baghdasaryan2f88e152019-07-15 15:42:09 -07002965static bool init_mp_psi(enum vmpressure_level level, bool use_new_strategy) {
2966 int fd;
2967
2968 /* Do not register a handler if threshold_ms is not set */
2969 if (!psi_thresholds[level].threshold_ms) {
2970 return true;
2971 }
2972
2973 fd = init_psi_monitor(psi_thresholds[level].stall_type,
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08002974 psi_thresholds[level].threshold_ms * US_PER_MS,
2975 PSI_WINDOW_SIZE_MS * US_PER_MS);
2976
2977 if (fd < 0) {
2978 return false;
2979 }
2980
Suren Baghdasaryan2f88e152019-07-15 15:42:09 -07002981 vmpressure_hinfo[level].handler = use_new_strategy ? mp_event_psi : mp_event_common;
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08002982 vmpressure_hinfo[level].data = level;
2983 if (register_psi_monitor(epollfd, fd, &vmpressure_hinfo[level]) < 0) {
2984 destroy_psi_monitor(fd);
2985 return false;
2986 }
2987 maxevents++;
2988 mpevfd[level] = fd;
2989
2990 return true;
2991}
2992
2993static void destroy_mp_psi(enum vmpressure_level level) {
2994 int fd = mpevfd[level];
2995
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07002996 if (fd < 0) {
2997 return;
2998 }
2999
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08003000 if (unregister_psi_monitor(epollfd, fd) < 0) {
3001 ALOGE("Failed to unregister psi monitor for %s memory pressure; errno=%d",
3002 level_name[level], errno);
3003 }
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07003004 maxevents--;
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08003005 destroy_psi_monitor(fd);
3006 mpevfd[level] = -1;
3007}
3008
3009static bool init_psi_monitors() {
Suren Baghdasaryan2f88e152019-07-15 15:42:09 -07003010 /*
3011 * When PSI is used on low-ram devices or on high-end devices without memfree levels
3012 * use new kill strategy based on zone watermarks, free swap and thrashing stats
3013 */
3014 bool use_new_strategy =
Suren Baghdasaryand0a80042021-08-03 15:40:23 -07003015 GET_LMK_PROPERTY(bool, "use_new_strategy", low_ram_device || !use_minfree_levels);
Suren Baghdasaryan2f88e152019-07-15 15:42:09 -07003016
3017 /* In default PSI mode override stall amounts using system properties */
3018 if (use_new_strategy) {
3019 /* Do not use low pressure level */
3020 psi_thresholds[VMPRESS_LEVEL_LOW].threshold_ms = 0;
3021 psi_thresholds[VMPRESS_LEVEL_MEDIUM].threshold_ms = psi_partial_stall_ms;
3022 psi_thresholds[VMPRESS_LEVEL_CRITICAL].threshold_ms = psi_complete_stall_ms;
3023 }
3024
3025 if (!init_mp_psi(VMPRESS_LEVEL_LOW, use_new_strategy)) {
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08003026 return false;
3027 }
Suren Baghdasaryan2f88e152019-07-15 15:42:09 -07003028 if (!init_mp_psi(VMPRESS_LEVEL_MEDIUM, use_new_strategy)) {
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08003029 destroy_mp_psi(VMPRESS_LEVEL_LOW);
3030 return false;
3031 }
Suren Baghdasaryan2f88e152019-07-15 15:42:09 -07003032 if (!init_mp_psi(VMPRESS_LEVEL_CRITICAL, use_new_strategy)) {
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08003033 destroy_mp_psi(VMPRESS_LEVEL_MEDIUM);
3034 destroy_mp_psi(VMPRESS_LEVEL_LOW);
3035 return false;
3036 }
3037 return true;
3038}
3039
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003040static bool init_mp_common(enum vmpressure_level level) {
Todd Poynorc58c5142013-07-09 19:35:14 -07003041 int mpfd;
3042 int evfd;
3043 int evctlfd;
3044 char buf[256];
3045 struct epoll_event epev;
3046 int ret;
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003047 int level_idx = (int)level;
3048 const char *levelstr = level_name[level_idx];
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08003049
Mark Salyzyna00ccd82018-04-09 09:50:32 -07003050 /* gid containing AID_SYSTEM required */
Nick Kralevich148d8dd2015-12-18 20:52:37 -08003051 mpfd = open(MEMCG_SYSFS_PATH "memory.pressure_level", O_RDONLY | O_CLOEXEC);
Todd Poynorc58c5142013-07-09 19:35:14 -07003052 if (mpfd < 0) {
3053 ALOGI("No kernel memory.pressure_level support (errno=%d)", errno);
3054 goto err_open_mpfd;
3055 }
3056
Nick Kralevich148d8dd2015-12-18 20:52:37 -08003057 evctlfd = open(MEMCG_SYSFS_PATH "cgroup.event_control", O_WRONLY | O_CLOEXEC);
Todd Poynorc58c5142013-07-09 19:35:14 -07003058 if (evctlfd < 0) {
3059 ALOGI("No kernel memory cgroup event control (errno=%d)", errno);
3060 goto err_open_evctlfd;
3061 }
3062
Nick Kralevich148d8dd2015-12-18 20:52:37 -08003063 evfd = eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC);
Todd Poynorc58c5142013-07-09 19:35:14 -07003064 if (evfd < 0) {
3065 ALOGE("eventfd failed for level %s; errno=%d", levelstr, errno);
3066 goto err_eventfd;
3067 }
3068
3069 ret = snprintf(buf, sizeof(buf), "%d %d %s", evfd, mpfd, levelstr);
3070 if (ret >= (ssize_t)sizeof(buf)) {
3071 ALOGE("cgroup.event_control line overflow for level %s", levelstr);
3072 goto err;
3073 }
3074
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003075 ret = TEMP_FAILURE_RETRY(write(evctlfd, buf, strlen(buf) + 1));
Todd Poynorc58c5142013-07-09 19:35:14 -07003076 if (ret == -1) {
3077 ALOGE("cgroup.event_control write failed for level %s; errno=%d",
3078 levelstr, errno);
3079 goto err;
3080 }
3081
3082 epev.events = EPOLLIN;
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003083 /* use data to store event level */
3084 vmpressure_hinfo[level_idx].data = level_idx;
3085 vmpressure_hinfo[level_idx].handler = mp_event_common;
3086 epev.data.ptr = (void *)&vmpressure_hinfo[level_idx];
Todd Poynorc58c5142013-07-09 19:35:14 -07003087 ret = epoll_ctl(epollfd, EPOLL_CTL_ADD, evfd, &epev);
3088 if (ret == -1) {
3089 ALOGE("epoll_ctl for level %s failed; errno=%d", levelstr, errno);
3090 goto err;
3091 }
3092 maxevents++;
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08003093 mpevfd[level] = evfd;
Suren Baghdasaryanceffaf22018-01-04 08:54:53 -08003094 close(evctlfd);
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08003095 return true;
Todd Poynorc58c5142013-07-09 19:35:14 -07003096
3097err:
3098 close(evfd);
3099err_eventfd:
3100 close(evctlfd);
3101err_open_evctlfd:
3102 close(mpfd);
3103err_open_mpfd:
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08003104 return false;
Robert Benea58d6a132017-06-01 16:32:31 -07003105}
3106
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07003107static void destroy_mp_common(enum vmpressure_level level) {
3108 struct epoll_event epev;
3109 int fd = mpevfd[level];
3110
3111 if (fd < 0) {
3112 return;
3113 }
3114
3115 if (epoll_ctl(epollfd, EPOLL_CTL_DEL, fd, &epev)) {
3116 // Log an error and keep going
3117 ALOGE("epoll_ctl for level %s failed; errno=%d", level_name[level], errno);
3118 }
3119 maxevents--;
3120 close(fd);
3121 mpevfd[level] = -1;
3122}
3123
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07003124static void kernel_event_handler(int data __unused, uint32_t events __unused,
3125 struct polling_params *poll_params __unused) {
Jing Ji5c480962019-12-04 09:22:05 -08003126 poll_kernel(kpoll_fd);
Jim Blackler700b7192019-04-26 11:18:29 +01003127}
3128
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07003129static bool init_monitors() {
3130 /* Try to use psi monitor first if kernel has it */
Suren Baghdasaryand0a80042021-08-03 15:40:23 -07003131 use_psi_monitors = GET_LMK_PROPERTY(bool, "use_psi", true) &&
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07003132 init_psi_monitors();
3133 /* Fall back to vmpressure */
3134 if (!use_psi_monitors &&
3135 (!init_mp_common(VMPRESS_LEVEL_LOW) ||
3136 !init_mp_common(VMPRESS_LEVEL_MEDIUM) ||
3137 !init_mp_common(VMPRESS_LEVEL_CRITICAL))) {
3138 ALOGE("Kernel does not support memory pressure events or in-kernel low memory killer");
3139 return false;
3140 }
3141 if (use_psi_monitors) {
3142 ALOGI("Using psi monitors for memory pressure detection");
3143 } else {
3144 ALOGI("Using vmpressure for memory pressure detection");
3145 }
3146 return true;
3147}
3148
3149static void destroy_monitors() {
3150 if (use_psi_monitors) {
3151 destroy_mp_psi(VMPRESS_LEVEL_CRITICAL);
3152 destroy_mp_psi(VMPRESS_LEVEL_MEDIUM);
3153 destroy_mp_psi(VMPRESS_LEVEL_LOW);
3154 } else {
3155 destroy_mp_common(VMPRESS_LEVEL_CRITICAL);
3156 destroy_mp_common(VMPRESS_LEVEL_MEDIUM);
3157 destroy_mp_common(VMPRESS_LEVEL_LOW);
3158 }
3159}
3160
Todd Poynorc58c5142013-07-09 19:35:14 -07003161static int init(void) {
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07003162 static struct event_handler_info kernel_poll_hinfo = { 0, kernel_event_handler };
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -07003163 struct reread_data file_data = {
3164 .filename = ZONEINFO_PATH,
3165 .fd = -1,
3166 };
Todd Poynorc58c5142013-07-09 19:35:14 -07003167 struct epoll_event epev;
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003168 int pidfd;
Todd Poynorc58c5142013-07-09 19:35:14 -07003169 int i;
3170 int ret;
3171
3172 page_k = sysconf(_SC_PAGESIZE);
3173 if (page_k == -1)
3174 page_k = PAGE_SIZE;
3175 page_k /= 1024;
3176
3177 epollfd = epoll_create(MAX_EPOLL_EVENTS);
3178 if (epollfd == -1) {
3179 ALOGE("epoll_create failed (errno=%d)", errno);
3180 return -1;
3181 }
3182
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003183 // mark data connections as not connected
3184 for (int i = 0; i < MAX_DATA_CONN; i++) {
3185 data_sock[i].sock = -1;
3186 }
3187
3188 ctrl_sock.sock = android_get_control_socket("lmkd");
3189 if (ctrl_sock.sock < 0) {
Todd Poynorc58c5142013-07-09 19:35:14 -07003190 ALOGE("get lmkd control socket failed");
3191 return -1;
3192 }
3193
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003194 ret = listen(ctrl_sock.sock, MAX_DATA_CONN);
Todd Poynorc58c5142013-07-09 19:35:14 -07003195 if (ret < 0) {
3196 ALOGE("lmkd control socket listen failed (errno=%d)", errno);
3197 return -1;
3198 }
3199
3200 epev.events = EPOLLIN;
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003201 ctrl_sock.handler_info.handler = ctrl_connect_handler;
3202 epev.data.ptr = (void *)&(ctrl_sock.handler_info);
3203 if (epoll_ctl(epollfd, EPOLL_CTL_ADD, ctrl_sock.sock, &epev) == -1) {
Todd Poynorc58c5142013-07-09 19:35:14 -07003204 ALOGE("epoll_ctl for lmkd control socket failed (errno=%d)", errno);
3205 return -1;
3206 }
3207 maxevents++;
3208
Robert Benea7878c9b2017-09-11 16:53:28 -07003209 has_inkernel_module = !access(INKERNEL_MINFREE_PATH, W_OK);
Suren Baghdasaryane6613ea2018-01-18 17:27:30 -08003210 use_inkernel_interface = has_inkernel_module;
Todd Poynorc58c5142013-07-09 19:35:14 -07003211
3212 if (use_inkernel_interface) {
3213 ALOGI("Using in-kernel low memory killer interface");
Jing Ji5c480962019-12-04 09:22:05 -08003214 if (init_poll_kernel()) {
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07003215 epev.events = EPOLLIN;
3216 epev.data.ptr = (void*)&kernel_poll_hinfo;
Jing Ji5c480962019-12-04 09:22:05 -08003217 if (epoll_ctl(epollfd, EPOLL_CTL_ADD, kpoll_fd, &epev) != 0) {
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07003218 ALOGE("epoll_ctl for lmk events failed (errno=%d)", errno);
Jing Ji5c480962019-12-04 09:22:05 -08003219 close(kpoll_fd);
3220 kpoll_fd = -1;
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07003221 } else {
3222 maxevents++;
Jing Ji5c480962019-12-04 09:22:05 -08003223 /* let the others know it does support reporting kills */
3224 property_set("sys.lmk.reportkills", "1");
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07003225 }
Jim Blackler700b7192019-04-26 11:18:29 +01003226 }
Todd Poynorc58c5142013-07-09 19:35:14 -07003227 } else {
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07003228 if (!init_monitors()) {
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08003229 return -1;
3230 }
Jing Ji5c480962019-12-04 09:22:05 -08003231 /* let the others know it does support reporting kills */
3232 property_set("sys.lmk.reportkills", "1");
Todd Poynorc58c5142013-07-09 19:35:14 -07003233 }
3234
Chong Zhang1cd12b52015-10-14 16:19:53 -07003235 for (i = 0; i <= ADJTOSLOT(OOM_SCORE_ADJ_MAX); i++) {
Todd Poynorc58c5142013-07-09 19:35:14 -07003236 procadjslot_list[i].next = &procadjslot_list[i];
3237 procadjslot_list[i].prev = &procadjslot_list[i];
3238 }
3239
Suren Baghdasaryana7394ea2018-10-12 11:07:40 -07003240 memset(killcnt_idx, KILLCNT_INVALID_IDX, sizeof(killcnt_idx));
3241
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -07003242 /*
3243 * Read zoneinfo as the biggest file we read to create and size the initial
3244 * read buffer and avoid memory re-allocations during memory pressure
3245 */
3246 if (reread_file(&file_data) == NULL) {
3247 ALOGE("Failed to read %s: %s", file_data.filename, strerror(errno));
3248 }
3249
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003250 /* check if kernel supports pidfd_open syscall */
Josh Gao84623be2021-03-18 17:16:08 -07003251 pidfd = TEMP_FAILURE_RETRY(pidfd_open(getpid(), 0));
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003252 if (pidfd < 0) {
3253 pidfd_supported = (errno != ENOSYS);
3254 } else {
3255 pidfd_supported = true;
3256 close(pidfd);
3257 }
3258 ALOGI("Process polling is %s", pidfd_supported ? "supported" : "not supported" );
3259
Todd Poynorc58c5142013-07-09 19:35:14 -07003260 return 0;
3261}
3262
Suren Baghdasaryan03dccf32020-04-28 16:02:13 -07003263static bool polling_paused(struct polling_params *poll_params) {
3264 return poll_params->paused_handler != NULL;
3265}
3266
3267static void resume_polling(struct polling_params *poll_params, struct timespec curr_tm) {
3268 poll_params->poll_start_tm = curr_tm;
3269 poll_params->poll_handler = poll_params->paused_handler;
Martin Liu589b5752020-09-02 23:15:18 +08003270 poll_params->polling_interval_ms = PSI_POLL_PERIOD_SHORT_MS;
3271 poll_params->paused_handler = NULL;
Suren Baghdasaryan03dccf32020-04-28 16:02:13 -07003272}
3273
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003274static void call_handler(struct event_handler_info* handler_info,
3275 struct polling_params *poll_params, uint32_t events) {
3276 struct timespec curr_tm;
3277
Suren Baghdasaryan9ca53342020-04-24 16:54:55 -07003278 poll_params->update = POLLING_DO_NOT_CHANGE;
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003279 handler_info->handler(handler_info->data, events, poll_params);
3280 clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm);
Suren Baghdasaryan9ca53342020-04-24 16:54:55 -07003281 if (poll_params->poll_handler == handler_info) {
3282 poll_params->last_poll_tm = curr_tm;
3283 }
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003284
3285 switch (poll_params->update) {
3286 case POLLING_START:
3287 /*
3288 * Poll for the duration of PSI_WINDOW_SIZE_MS after the
3289 * initial PSI event because psi events are rate-limited
3290 * at one per sec.
3291 */
3292 poll_params->poll_start_tm = curr_tm;
Greg Kaiser5e80ed52019-10-10 06:52:23 -07003293 poll_params->poll_handler = handler_info;
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003294 break;
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003295 case POLLING_PAUSE:
3296 poll_params->paused_handler = handler_info;
3297 poll_params->poll_handler = NULL;
3298 break;
3299 case POLLING_RESUME:
Suren Baghdasaryan03dccf32020-04-28 16:02:13 -07003300 resume_polling(poll_params, curr_tm);
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003301 break;
3302 case POLLING_DO_NOT_CHANGE:
3303 if (get_time_diff_ms(&poll_params->poll_start_tm, &curr_tm) > PSI_WINDOW_SIZE_MS) {
3304 /* Polled for the duration of PSI window, time to stop */
3305 poll_params->poll_handler = NULL;
3306 }
Suren Baghdasaryan9ca53342020-04-24 16:54:55 -07003307 break;
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003308 }
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003309}
3310
Todd Poynorc58c5142013-07-09 19:35:14 -07003311static void mainloop(void) {
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003312 struct event_handler_info* handler_info;
Suren Baghdasaryane12a0672019-07-15 14:50:49 -07003313 struct polling_params poll_params;
3314 struct timespec curr_tm;
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003315 struct epoll_event *evt;
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08003316 long delay = -1;
Suren Baghdasaryane12a0672019-07-15 14:50:49 -07003317
3318 poll_params.poll_handler = NULL;
Suren Baghdasaryan9ca53342020-04-24 16:54:55 -07003319 poll_params.paused_handler = NULL;
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003320
Todd Poynorc58c5142013-07-09 19:35:14 -07003321 while (1) {
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07003322 struct epoll_event events[MAX_EPOLL_EVENTS];
Todd Poynorc58c5142013-07-09 19:35:14 -07003323 int nevents;
3324 int i;
3325
Suren Baghdasaryane12a0672019-07-15 14:50:49 -07003326 if (poll_params.poll_handler) {
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003327 bool poll_now;
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08003328
3329 clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm);
Martin Liu589b5752020-09-02 23:15:18 +08003330 if (poll_params.update == POLLING_RESUME) {
3331 /* Just transitioned into POLLING_RESUME, poll immediately. */
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003332 poll_now = true;
3333 nevents = 0;
3334 } else {
3335 /* Calculate next timeout */
3336 delay = get_time_diff_ms(&poll_params.last_poll_tm, &curr_tm);
3337 delay = (delay < poll_params.polling_interval_ms) ?
3338 poll_params.polling_interval_ms - delay : poll_params.polling_interval_ms;
Suren Baghdasaryane12a0672019-07-15 14:50:49 -07003339
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003340 /* Wait for events until the next polling timeout */
3341 nevents = epoll_wait(epollfd, events, maxevents, delay);
3342
3343 /* Update current time after wait */
3344 clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm);
3345 poll_now = (get_time_diff_ms(&poll_params.last_poll_tm, &curr_tm) >=
3346 poll_params.polling_interval_ms);
3347 }
3348 if (poll_now) {
3349 call_handler(poll_params.poll_handler, &poll_params, 0);
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08003350 }
3351 } else {
Suren Baghdasaryan03dccf32020-04-28 16:02:13 -07003352 if (kill_timeout_ms && is_waiting_for_kill()) {
3353 clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm);
3354 delay = kill_timeout_ms - get_time_diff_ms(&last_kill_tm, &curr_tm);
3355 /* Wait for pidfds notification or kill timeout to expire */
3356 nevents = (delay > 0) ? epoll_wait(epollfd, events, maxevents, delay) : 0;
3357 if (nevents == 0) {
3358 /* Kill notification timed out */
3359 stop_wait_for_proc_kill(false);
3360 if (polling_paused(&poll_params)) {
3361 clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm);
Martin Liu589b5752020-09-02 23:15:18 +08003362 poll_params.update = POLLING_RESUME;
Suren Baghdasaryan03dccf32020-04-28 16:02:13 -07003363 resume_polling(&poll_params, curr_tm);
3364 }
3365 }
3366 } else {
3367 /* Wait for events with no timeout */
3368 nevents = epoll_wait(epollfd, events, maxevents, -1);
3369 }
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08003370 }
Todd Poynorc58c5142013-07-09 19:35:14 -07003371
3372 if (nevents == -1) {
3373 if (errno == EINTR)
3374 continue;
3375 ALOGE("epoll_wait failed (errno=%d)", errno);
3376 continue;
3377 }
3378
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003379 /*
3380 * First pass to see if any data socket connections were dropped.
3381 * Dropped connection should be handled before any other events
3382 * to deallocate data connection and correctly handle cases when
3383 * connection gets dropped and reestablished in the same epoll cycle.
3384 * In such cases it's essential to handle connection closures first.
3385 */
3386 for (i = 0, evt = &events[0]; i < nevents; ++i, evt++) {
3387 if ((evt->events & EPOLLHUP) && evt->data.ptr) {
3388 ALOGI("lmkd data connection dropped");
3389 handler_info = (struct event_handler_info*)evt->data.ptr;
3390 ctrl_data_close(handler_info->data);
3391 }
3392 }
3393
3394 /* Second pass to handle all other events */
3395 for (i = 0, evt = &events[0]; i < nevents; ++i, evt++) {
Suren Baghdasaryane12a0672019-07-15 14:50:49 -07003396 if (evt->events & EPOLLERR) {
Todd Poynorc58c5142013-07-09 19:35:14 -07003397 ALOGD("EPOLLERR on event #%d", i);
Suren Baghdasaryane12a0672019-07-15 14:50:49 -07003398 }
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003399 if (evt->events & EPOLLHUP) {
3400 /* This case was handled in the first pass */
3401 continue;
3402 }
3403 if (evt->data.ptr) {
3404 handler_info = (struct event_handler_info*)evt->data.ptr;
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003405 call_handler(handler_info, &poll_params, evt->events);
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003406 }
Todd Poynorc58c5142013-07-09 19:35:14 -07003407 }
3408 }
3409}
3410
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07003411int issue_reinit() {
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07003412 int sock;
Colin Crossd5b510e2014-07-14 14:31:15 -07003413
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07003414 sock = lmkd_connect();
3415 if (sock < 0) {
3416 ALOGE("failed to connect to lmkd: %s", strerror(errno));
3417 return -1;
3418 }
3419
3420 enum update_props_result res = lmkd_update_props(sock);
3421 switch (res) {
3422 case UPDATE_PROPS_SUCCESS:
3423 ALOGI("lmkd updated properties successfully");
3424 break;
3425 case UPDATE_PROPS_SEND_ERR:
3426 ALOGE("failed to send lmkd request: %s", strerror(errno));
3427 break;
3428 case UPDATE_PROPS_RECV_ERR:
3429 ALOGE("failed to receive lmkd reply: %s", strerror(errno));
3430 break;
3431 case UPDATE_PROPS_FORMAT_ERR:
3432 ALOGE("lmkd reply is invalid");
3433 break;
3434 case UPDATE_PROPS_FAIL:
3435 ALOGE("lmkd failed to update its properties");
3436 break;
3437 }
3438
3439 close(sock);
3440 return res == UPDATE_PROPS_SUCCESS ? 0 : -1;
3441}
3442
3443static void update_props() {
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08003444 /* By default disable low level vmpressure events */
3445 level_oomadj[VMPRESS_LEVEL_LOW] =
Suren Baghdasaryand0a80042021-08-03 15:40:23 -07003446 GET_LMK_PROPERTY(int32, "low", OOM_SCORE_ADJ_MAX + 1);
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08003447 level_oomadj[VMPRESS_LEVEL_MEDIUM] =
Suren Baghdasaryand0a80042021-08-03 15:40:23 -07003448 GET_LMK_PROPERTY(int32, "medium", 800);
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08003449 level_oomadj[VMPRESS_LEVEL_CRITICAL] =
Suren Baghdasaryand0a80042021-08-03 15:40:23 -07003450 GET_LMK_PROPERTY(int32, "critical", 0);
3451 debug_process_killing = GET_LMK_PROPERTY(bool, "debug", false);
Suren Baghdasaryan3faa3032017-12-08 13:08:41 -08003452
3453 /* By default disable upgrade/downgrade logic */
3454 enable_pressure_upgrade =
Suren Baghdasaryand0a80042021-08-03 15:40:23 -07003455 GET_LMK_PROPERTY(bool, "critical_upgrade", false);
Suren Baghdasaryan3faa3032017-12-08 13:08:41 -08003456 upgrade_pressure =
Suren Baghdasaryand0a80042021-08-03 15:40:23 -07003457 (int64_t)GET_LMK_PROPERTY(int32, "upgrade_pressure", 100);
Suren Baghdasaryan3faa3032017-12-08 13:08:41 -08003458 downgrade_pressure =
Suren Baghdasaryand0a80042021-08-03 15:40:23 -07003459 (int64_t)GET_LMK_PROPERTY(int32, "downgrade_pressure", 100);
Suren Baghdasaryaneb7c5492017-12-08 13:17:06 -08003460 kill_heaviest_task =
Suren Baghdasaryand0a80042021-08-03 15:40:23 -07003461 GET_LMK_PROPERTY(bool, "kill_heaviest_task", false);
Suren Baghdasaryand1d59f82018-04-13 11:45:38 -07003462 low_ram_device = property_get_bool("ro.config.low_ram", false);
Suren Baghdasaryan30854e72018-01-17 17:28:01 -08003463 kill_timeout_ms =
Suren Baghdasaryand0a80042021-08-03 15:40:23 -07003464 (unsigned long)GET_LMK_PROPERTY(int32, "kill_timeout_ms", 100);
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07003465 use_minfree_levels =
Suren Baghdasaryand0a80042021-08-03 15:40:23 -07003466 GET_LMK_PROPERTY(bool, "use_minfree_levels", false);
Suren Baghdasaryan8389fdb2018-06-19 18:38:12 -07003467 per_app_memcg =
3468 property_get_bool("ro.config.per_app_memcg", low_ram_device);
Suren Baghdasaryand0a80042021-08-03 15:40:23 -07003469 swap_free_low_percentage = clamp(0, 100, GET_LMK_PROPERTY(int32, "swap_free_low_percentage",
Suren Baghdasaryanfb1f5922020-05-19 13:07:23 -07003470 DEF_LOW_SWAP));
Suren Baghdasaryand0a80042021-08-03 15:40:23 -07003471 psi_partial_stall_ms = GET_LMK_PROPERTY(int32, "psi_partial_stall_ms",
Suren Baghdasaryan2f88e152019-07-15 15:42:09 -07003472 low_ram_device ? DEF_PARTIAL_STALL_LOWRAM : DEF_PARTIAL_STALL);
Suren Baghdasaryand0a80042021-08-03 15:40:23 -07003473 psi_complete_stall_ms = GET_LMK_PROPERTY(int32, "psi_complete_stall_ms",
Suren Baghdasaryan2f88e152019-07-15 15:42:09 -07003474 DEF_COMPLETE_STALL);
Suren Baghdasaryand0a80042021-08-03 15:40:23 -07003475 thrashing_limit_pct = max(0, GET_LMK_PROPERTY(int32, "thrashing_limit",
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07003476 low_ram_device ? DEF_THRASHING_LOWRAM : DEF_THRASHING));
Suren Baghdasaryand0a80042021-08-03 15:40:23 -07003477 thrashing_limit_decay_pct = clamp(0, 100, GET_LMK_PROPERTY(int32, "thrashing_limit_decay",
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07003478 low_ram_device ? DEF_THRASHING_DECAY_LOWRAM : DEF_THRASHING_DECAY));
Suren Baghdasaryand0a80042021-08-03 15:40:23 -07003479 thrashing_critical_pct = max(0, GET_LMK_PROPERTY(int32, "thrashing_limit_critical",
Suren Baghdasaryan1ef47182021-07-22 20:59:31 +00003480 thrashing_limit_pct * 2));
Suren Baghdasaryand0a80042021-08-03 15:40:23 -07003481 swap_util_max = clamp(0, 100, GET_LMK_PROPERTY(int32, "swap_util_max", 100));
3482 filecache_min_kb = GET_LMK_PROPERTY(int64, "filecache_min_kb", 0);
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07003483}
3484
3485int main(int argc, char **argv) {
3486 if ((argc > 1) && argv[1] && !strcmp(argv[1], "--reinit")) {
Suren Baghdasaryan0e64ead2021-09-01 00:49:51 -07003487 if (property_set(LMKD_REINIT_PROP, "")) {
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07003488 ALOGE("Failed to reset " LMKD_REINIT_PROP " property");
3489 }
3490 return issue_reinit();
3491 }
3492
3493 update_props();
Robert Benea57397dc2017-07-31 17:15:20 -07003494
Suren Baghdasaryan12cacae2019-09-16 12:06:30 -07003495 ctx = create_android_logger(KILLINFO_LOG_TAG);
Suren Baghdasaryan08bfa982018-07-26 16:34:27 -07003496
Mark Salyzyn5cc80b32018-03-21 12:24:58 -07003497 if (!init()) {
3498 if (!use_inkernel_interface) {
3499 /*
3500 * MCL_ONFAULT pins pages as they fault instead of loading
3501 * everything immediately all at once. (Which would be bad,
3502 * because as of this writing, we have a lot of mapped pages we
3503 * never use.) Old kernels will see MCL_ONFAULT and fail with
3504 * EINVAL; we ignore this failure.
3505 *
3506 * N.B. read the man page for mlockall. MCL_CURRENT | MCL_ONFAULT
3507 * pins ⊆ MCL_CURRENT, converging to just MCL_CURRENT as we fault
3508 * in pages.
3509 */
Mark Salyzyna00ccd82018-04-09 09:50:32 -07003510 /* CAP_IPC_LOCK required */
Mark Salyzyn5cc80b32018-03-21 12:24:58 -07003511 if (mlockall(MCL_CURRENT | MCL_FUTURE | MCL_ONFAULT) && (errno != EINVAL)) {
3512 ALOGW("mlockall failed %s", strerror(errno));
3513 }
Daniel Colascione46648332018-01-03 12:01:02 -08003514
Mark Salyzyna00ccd82018-04-09 09:50:32 -07003515 /* CAP_NICE required */
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07003516 struct sched_param param = {
3517 .sched_priority = 1,
3518 };
Mark Salyzyna00ccd82018-04-09 09:50:32 -07003519 if (sched_setscheduler(0, SCHED_FIFO, &param)) {
3520 ALOGW("set SCHED_FIFO failed %s", strerror(errno));
3521 }
Mark Salyzyn5cc80b32018-03-21 12:24:58 -07003522 }
3523
Todd Poynorc58c5142013-07-09 19:35:14 -07003524 mainloop();
Mark Salyzyn5cc80b32018-03-21 12:24:58 -07003525 }
Todd Poynorc58c5142013-07-09 19:35:14 -07003526
Suren Baghdasaryan08bfa982018-07-26 16:34:27 -07003527 android_log_destroy(&ctx);
3528
Todd Poynorc58c5142013-07-09 19:35:14 -07003529 ALOGI("exiting");
3530 return 0;
3531}