blob: 2136ab08e742ff29b4167b1cf75daacd6ec02163 [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>
Muhammad Qureshied8fe842019-12-09 17:38:47 -080025#include <statslog_lmkd.h>
Suren Baghdasaryanf584fff2018-03-20 13:53:17 -070026#include <stdbool.h>
Todd Poynorc58c5142013-07-09 19:35:14 -070027#include <stdlib.h>
28#include <string.h>
Mark Salyzyneb062742014-04-30 13:36:35 -070029#include <sys/cdefs.h>
Todd Poynorc58c5142013-07-09 19:35:14 -070030#include <sys/epoll.h>
31#include <sys/eventfd.h>
Colin Crossc4059002014-07-11 17:15:44 -070032#include <sys/mman.h>
Josh Gao84623be2021-03-18 17:16:08 -070033#include <sys/pidfd.h>
Wei Wangf1ee2e12018-11-21 00:11:44 -080034#include <sys/resource.h>
Todd Poynorc58c5142013-07-09 19:35:14 -070035#include <sys/socket.h>
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -070036#include <sys/syscall.h>
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -080037#include <sys/sysinfo.h>
Wei Wangf1ee2e12018-11-21 00:11:44 -080038#include <sys/time.h>
Mark Salyzyn5cc80b32018-03-21 12:24:58 -070039#include <sys/types.h>
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -070040#include <time.h>
Mark Salyzyneb062742014-04-30 13:36:35 -070041#include <unistd.h>
42
Robert Benea57397dc2017-07-31 17:15:20 -070043#include <cutils/properties.h>
Wei Wangf1ee2e12018-11-21 00:11:44 -080044#include <cutils/sched_policy.h>
Todd Poynorc58c5142013-07-09 19:35:14 -070045#include <cutils/sockets.h>
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -070046#include <liblmkd_utils.h>
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -080047#include <lmkd.h>
Mark Salyzyn6a63fde2017-01-10 13:19:54 -080048#include <log/log.h>
Suren Baghdasaryan08bfa982018-07-26 16:34:27 -070049#include <log/log_event_list.h>
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -070050#include <log/log_time.h>
Suren Baghdasaryan945658a2019-10-18 11:16:52 -070051#include <private/android_filesystem_config.h>
Suren Baghdasaryan55e31502019-01-08 12:54:48 -080052#include <psi/psi.h>
Wei Wangf1ee2e12018-11-21 00:11:44 -080053#include <system/thread_defs.h>
Mark Salyzyneb062742014-04-30 13:36:35 -070054
Yao Chen337606c2018-05-02 11:19:27 -070055#include "statslog.h"
Rajeev Kumar4aba9152018-01-31 17:54:56 -080056
Suren Baghdasaryan03e19872018-01-04 10:43:58 -080057/*
58 * Define LMKD_TRACE_KILLS to record lmkd kills in kernel traces
59 * to profile and correlate with OOM kills
60 */
61#ifdef LMKD_TRACE_KILLS
62
63#define ATRACE_TAG ATRACE_TAG_ALWAYS
64#include <cutils/trace.h>
65
66#define TRACE_KILL_START(pid) ATRACE_INT(__FUNCTION__, pid);
67#define TRACE_KILL_END() ATRACE_INT(__FUNCTION__, 0);
68
69#else /* LMKD_TRACE_KILLS */
70
Daniel Colascione56b95d72018-02-12 11:24:47 -080071#define TRACE_KILL_START(pid) ((void)(pid))
72#define TRACE_KILL_END() ((void)0)
Suren Baghdasaryan03e19872018-01-04 10:43:58 -080073
74#endif /* LMKD_TRACE_KILLS */
75
Mark Salyzyneb062742014-04-30 13:36:35 -070076#ifndef __unused
77#define __unused __attribute__((__unused__))
78#endif
Todd Poynorc58c5142013-07-09 19:35:14 -070079
80#define MEMCG_SYSFS_PATH "/dev/memcg/"
Robert Beneac72b2932017-08-21 15:18:31 -070081#define MEMCG_MEMORY_USAGE "/dev/memcg/memory.usage_in_bytes"
82#define MEMCG_MEMORYSW_USAGE "/dev/memcg/memory.memsw.usage_in_bytes"
Suren Baghdasaryand28a9732018-04-13 13:11:51 -070083#define ZONEINFO_PATH "/proc/zoneinfo"
84#define MEMINFO_PATH "/proc/meminfo"
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -070085#define VMSTAT_PATH "/proc/vmstat"
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -070086#define PROC_STATUS_TGID_FIELD "Tgid:"
Ioannis Ilkos279268a2020-08-01 10:50:40 +010087#define PROC_STATUS_RSS_FIELD "VmRSS:"
88#define PROC_STATUS_SWAP_FIELD "VmSwap:"
Todd Poynorc58c5142013-07-09 19:35:14 -070089#define LINE_MAX 128
90
Suren Baghdasaryan970a26a2019-09-19 15:27:21 -070091#define PERCEPTIBLE_APP_ADJ 200
92
Suren Baghdasaryan08bfa982018-07-26 16:34:27 -070093/* Android Logger event logtags (see event.logtags) */
Suren Baghdasaryan12cacae2019-09-16 12:06:30 -070094#define KILLINFO_LOG_TAG 10195355
Suren Baghdasaryan08bfa982018-07-26 16:34:27 -070095
Mark Salyzyna00ccd82018-04-09 09:50:32 -070096/* gid containing AID_SYSTEM required */
Todd Poynorc58c5142013-07-09 19:35:14 -070097#define INKERNEL_MINFREE_PATH "/sys/module/lowmemorykiller/parameters/minfree"
98#define INKERNEL_ADJ_PATH "/sys/module/lowmemorykiller/parameters/adj"
99
100#define ARRAY_SIZE(x) (sizeof(x) / sizeof(*(x)))
Robert Benea58d6a132017-06-01 16:32:31 -0700101#define EIGHT_MEGA (1 << 23)
Todd Poynorc58c5142013-07-09 19:35:14 -0700102
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -0700103#define TARGET_UPDATE_MIN_INTERVAL_MS 1000
Martin Liu1f72f5f2020-08-21 13:18:50 +0800104#define THRASHING_RESET_INTERVAL_MS 1000
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -0700105
106#define NS_PER_MS (NS_PER_SEC / MS_PER_SEC)
Suren Baghdasaryan55e31502019-01-08 12:54:48 -0800107#define US_PER_MS (US_PER_SEC / MS_PER_SEC)
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -0700108
Suren Baghdasaryanbb7747b2018-03-20 16:03:29 -0700109/* Defined as ProcessList.SYSTEM_ADJ in ProcessList.java */
110#define SYSTEM_ADJ (-900)
111
Greg Kaiserf5b1d142018-03-23 14:16:12 -0700112#define STRINGIFY(x) STRINGIFY_INTERNAL(x)
113#define STRINGIFY_INTERNAL(x) #x
114
Suren Baghdasaryan55e31502019-01-08 12:54:48 -0800115/*
116 * PSI monitor tracking window size.
117 * PSI monitor generates events at most once per window,
118 * therefore we poll memory state for the duration of
119 * PSI_WINDOW_SIZE_MS after the event happens.
120 */
121#define PSI_WINDOW_SIZE_MS 1000
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -0700122/* Polling period after PSI signal when pressure is high */
123#define PSI_POLL_PERIOD_SHORT_MS 10
124/* Polling period after PSI signal when pressure is low */
125#define PSI_POLL_PERIOD_LONG_MS 100
Suren Baghdasaryan55e31502019-01-08 12:54:48 -0800126
Suren Baghdasaryan08bfa982018-07-26 16:34:27 -0700127#define min(a, b) (((a) < (b)) ? (a) : (b))
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -0700128#define max(a, b) (((a) > (b)) ? (a) : (b))
Suren Baghdasaryan08bfa982018-07-26 16:34:27 -0700129
Suren Baghdasaryan53be36e2018-09-05 15:46:32 -0700130#define FAIL_REPORT_RLIMIT_MS 1000
131
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -0700132/*
133 * System property defaults
134 */
135/* ro.lmk.swap_free_low_percentage property defaults */
Suren Baghdasaryanfb1f5922020-05-19 13:07:23 -0700136#define DEF_LOW_SWAP 10
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -0700137/* ro.lmk.thrashing_limit property defaults */
138#define DEF_THRASHING_LOWRAM 30
139#define DEF_THRASHING 100
140/* ro.lmk.thrashing_limit_decay property defaults */
141#define DEF_THRASHING_DECAY_LOWRAM 50
142#define DEF_THRASHING_DECAY 10
Suren Baghdasaryan2f88e152019-07-15 15:42:09 -0700143/* ro.lmk.psi_partial_stall_ms property defaults */
144#define DEF_PARTIAL_STALL_LOWRAM 200
145#define DEF_PARTIAL_STALL 70
146/* ro.lmk.psi_complete_stall_ms property defaults */
147#define DEF_COMPLETE_STALL 700
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -0700148
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -0700149#define LMKD_REINIT_PROP "lmkd.reinit"
150
Todd Poynorc58c5142013-07-09 19:35:14 -0700151/* default to old in-kernel interface if no memory pressure events */
Mark Salyzyn5cc80b32018-03-21 12:24:58 -0700152static bool use_inkernel_interface = true;
Robert Benea7878c9b2017-09-11 16:53:28 -0700153static bool has_inkernel_module;
Todd Poynorc58c5142013-07-09 19:35:14 -0700154
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -0800155/* memory pressure levels */
156enum vmpressure_level {
157 VMPRESS_LEVEL_LOW = 0,
158 VMPRESS_LEVEL_MEDIUM,
159 VMPRESS_LEVEL_CRITICAL,
160 VMPRESS_LEVEL_COUNT
161};
Todd Poynorc58c5142013-07-09 19:35:14 -0700162
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -0800163static const char *level_name[] = {
164 "low",
165 "medium",
166 "critical"
167};
168
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -0800169struct {
Suren Baghdasaryane0f3dd12018-04-13 13:41:12 -0700170 int64_t min_nr_free_pages; /* recorded but not used yet */
171 int64_t max_nr_free_pages;
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -0800172} low_pressure_mem = { -1, -1 };
173
Suren Baghdasaryan55e31502019-01-08 12:54:48 -0800174struct psi_threshold {
175 enum psi_stall_type stall_type;
176 int threshold_ms;
177};
178
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -0800179static int level_oomadj[VMPRESS_LEVEL_COUNT];
Suren Baghdasaryan3e1a8492018-01-04 09:16:21 -0800180static int mpevfd[VMPRESS_LEVEL_COUNT] = { -1, -1, -1 };
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -0700181static bool pidfd_supported;
182static int last_kill_pid_or_fd = -1;
183static struct timespec last_kill_tm;
184
185/* lmkd configurable parameters */
Robert Beneac72b2932017-08-21 15:18:31 -0700186static bool debug_process_killing;
187static bool enable_pressure_upgrade;
188static int64_t upgrade_pressure;
Robert Benea3be16142017-09-13 15:20:30 -0700189static int64_t downgrade_pressure;
Suren Baghdasaryand1d59f82018-04-13 11:45:38 -0700190static bool low_ram_device;
Suren Baghdasaryaneb7c5492017-12-08 13:17:06 -0800191static bool kill_heaviest_task;
Suren Baghdasaryan30854e72018-01-17 17:28:01 -0800192static unsigned long kill_timeout_ms;
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -0700193static bool use_minfree_levels;
Suren Baghdasaryan8389fdb2018-06-19 18:38:12 -0700194static bool per_app_memcg;
Vic Yang65680692018-08-07 10:18:22 -0700195static int swap_free_low_percentage;
Suren Baghdasaryan2f88e152019-07-15 15:42:09 -0700196static int psi_partial_stall_ms;
197static int psi_complete_stall_ms;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -0700198static int thrashing_limit_pct;
199static int thrashing_limit_decay_pct;
Suren Baghdasaryan51ee4c52020-04-21 12:27:01 -0700200static int swap_util_max;
Suren Baghdasaryan55e31502019-01-08 12:54:48 -0800201static bool use_psi_monitors = false;
Jing Ji5c480962019-12-04 09:22:05 -0800202static int kpoll_fd;
Suren Baghdasaryan55e31502019-01-08 12:54:48 -0800203static struct psi_threshold psi_thresholds[VMPRESS_LEVEL_COUNT] = {
204 { PSI_SOME, 70 }, /* 70ms out of 1sec for partial stall */
205 { PSI_SOME, 100 }, /* 100ms out of 1sec for partial stall */
206 { PSI_FULL, 70 }, /* 70ms out of 1sec for complete stall */
207};
Robert Benea57397dc2017-07-31 17:15:20 -0700208
Suren Baghdasaryan08bfa982018-07-26 16:34:27 -0700209static android_log_context ctx;
210
Suren Baghdasaryane12a0672019-07-15 14:50:49 -0700211enum polling_update {
212 POLLING_DO_NOT_CHANGE,
213 POLLING_START,
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -0700214 POLLING_PAUSE,
215 POLLING_RESUME,
Suren Baghdasaryane12a0672019-07-15 14:50:49 -0700216};
217
218/*
219 * Data used for periodic polling for the memory state of the device.
220 * Note that when system is not polling poll_handler is set to NULL,
221 * when polling starts poll_handler gets set and is reset back to
222 * NULL when polling stops.
223 */
224struct polling_params {
225 struct event_handler_info* poll_handler;
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -0700226 struct event_handler_info* paused_handler;
Suren Baghdasaryane12a0672019-07-15 14:50:49 -0700227 struct timespec poll_start_tm;
228 struct timespec last_poll_tm;
229 int polling_interval_ms;
230 enum polling_update update;
231};
232
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -0800233/* data required to handle events */
234struct event_handler_info {
235 int data;
Suren Baghdasaryane12a0672019-07-15 14:50:49 -0700236 void (*handler)(int data, uint32_t events, struct polling_params *poll_params);
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -0800237};
Todd Poynorc58c5142013-07-09 19:35:14 -0700238
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -0800239/* data required to handle socket events */
240struct sock_event_handler_info {
241 int sock;
Suren Baghdasaryan945658a2019-10-18 11:16:52 -0700242 pid_t pid;
Suren Baghdasaryan36baf442019-12-23 11:37:34 -0800243 uint32_t async_event_mask;
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -0800244 struct event_handler_info handler_info;
245};
246
Suren Baghdasaryanf2cbefd2019-10-21 17:59:22 -0700247/* max supported number of data connections (AMS, init, tests) */
248#define MAX_DATA_CONN 3
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -0800249
250/* socket event handler data */
251static struct sock_event_handler_info ctrl_sock;
252static struct sock_event_handler_info data_sock[MAX_DATA_CONN];
253
254/* vmpressure event handler data */
255static struct event_handler_info vmpressure_hinfo[VMPRESS_LEVEL_COUNT];
256
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -0700257/*
Suren Baghdasaryanf2cbefd2019-10-21 17:59:22 -0700258 * 1 ctrl listen socket, 3 ctrl data socket, 3 memory pressure levels,
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -0700259 * 1 lmk events + 1 fd to wait for process death
260 */
261#define MAX_EPOLL_EVENTS (1 + MAX_DATA_CONN + VMPRESS_LEVEL_COUNT + 1 + 1)
Todd Poynorc58c5142013-07-09 19:35:14 -0700262static int epollfd;
263static int maxevents;
264
Chong Zhang1cd12b52015-10-14 16:19:53 -0700265/* OOM score values used by both kernel and framework */
Todd Poynora08c1722013-09-16 19:26:47 -0700266#define OOM_SCORE_ADJ_MIN (-1000)
267#define OOM_SCORE_ADJ_MAX 1000
268
Todd Poynorc58c5142013-07-09 19:35:14 -0700269static int lowmem_adj[MAX_TARGETS];
270static int lowmem_minfree[MAX_TARGETS];
271static int lowmem_targets_size;
272
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700273/* Fields to parse in /proc/zoneinfo */
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -0700274/* zoneinfo per-zone fields */
275enum zoneinfo_zone_field {
276 ZI_ZONE_NR_FREE_PAGES = 0,
277 ZI_ZONE_MIN,
278 ZI_ZONE_LOW,
279 ZI_ZONE_HIGH,
280 ZI_ZONE_PRESENT,
281 ZI_ZONE_NR_FREE_CMA,
282 ZI_ZONE_FIELD_COUNT
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700283};
284
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -0700285static const char* const zoneinfo_zone_field_names[ZI_ZONE_FIELD_COUNT] = {
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700286 "nr_free_pages",
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -0700287 "min",
288 "low",
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700289 "high",
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -0700290 "present",
291 "nr_free_cma",
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700292};
293
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -0700294/* zoneinfo per-zone special fields */
295enum zoneinfo_zone_spec_field {
296 ZI_ZONE_SPEC_PROTECTION = 0,
297 ZI_ZONE_SPEC_PAGESETS,
298 ZI_ZONE_SPEC_FIELD_COUNT,
299};
300
301static const char* const zoneinfo_zone_spec_field_names[ZI_ZONE_SPEC_FIELD_COUNT] = {
302 "protection:",
303 "pagesets",
304};
305
306/* see __MAX_NR_ZONES definition in kernel mmzone.h */
307#define MAX_NR_ZONES 6
308
309union zoneinfo_zone_fields {
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700310 struct {
311 int64_t nr_free_pages;
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -0700312 int64_t min;
313 int64_t low;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700314 int64_t high;
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -0700315 int64_t present;
316 int64_t nr_free_cma;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700317 } field;
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -0700318 int64_t arr[ZI_ZONE_FIELD_COUNT];
319};
320
321struct zoneinfo_zone {
322 union zoneinfo_zone_fields fields;
323 int64_t protection[MAX_NR_ZONES];
324 int64_t max_protection;
325};
326
327/* zoneinfo per-node fields */
328enum zoneinfo_node_field {
329 ZI_NODE_NR_INACTIVE_FILE = 0,
330 ZI_NODE_NR_ACTIVE_FILE,
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -0700331 ZI_NODE_FIELD_COUNT
332};
333
334static const char* const zoneinfo_node_field_names[ZI_NODE_FIELD_COUNT] = {
335 "nr_inactive_file",
336 "nr_active_file",
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -0700337};
338
339union zoneinfo_node_fields {
340 struct {
341 int64_t nr_inactive_file;
342 int64_t nr_active_file;
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -0700343 } field;
344 int64_t arr[ZI_NODE_FIELD_COUNT];
345};
346
347struct zoneinfo_node {
348 int id;
349 int zone_count;
350 struct zoneinfo_zone zones[MAX_NR_ZONES];
351 union zoneinfo_node_fields fields;
352};
353
354/* for now two memory nodes is more than enough */
355#define MAX_NR_NODES 2
356
357struct zoneinfo {
358 int node_count;
359 struct zoneinfo_node nodes[MAX_NR_NODES];
360 int64_t totalreserve_pages;
361 int64_t total_inactive_file;
362 int64_t total_active_file;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700363};
364
365/* Fields to parse in /proc/meminfo */
366enum meminfo_field {
367 MI_NR_FREE_PAGES = 0,
368 MI_CACHED,
369 MI_SWAP_CACHED,
370 MI_BUFFERS,
371 MI_SHMEM,
372 MI_UNEVICTABLE,
Vic Yang65680692018-08-07 10:18:22 -0700373 MI_TOTAL_SWAP,
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700374 MI_FREE_SWAP,
Suren Baghdasaryan08bfa982018-07-26 16:34:27 -0700375 MI_ACTIVE_ANON,
376 MI_INACTIVE_ANON,
377 MI_ACTIVE_FILE,
378 MI_INACTIVE_FILE,
379 MI_SRECLAIMABLE,
380 MI_SUNRECLAIM,
381 MI_KERNEL_STACK,
382 MI_PAGE_TABLES,
383 MI_ION_HELP,
384 MI_ION_HELP_POOL,
385 MI_CMA_FREE,
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700386 MI_FIELD_COUNT
387};
388
389static const char* const meminfo_field_names[MI_FIELD_COUNT] = {
390 "MemFree:",
391 "Cached:",
392 "SwapCached:",
393 "Buffers:",
394 "Shmem:",
395 "Unevictable:",
Vic Yang65680692018-08-07 10:18:22 -0700396 "SwapTotal:",
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700397 "SwapFree:",
Suren Baghdasaryan08bfa982018-07-26 16:34:27 -0700398 "Active(anon):",
399 "Inactive(anon):",
400 "Active(file):",
401 "Inactive(file):",
402 "SReclaimable:",
403 "SUnreclaim:",
404 "KernelStack:",
405 "PageTables:",
406 "ION_heap:",
407 "ION_heap_pool:",
408 "CmaFree:",
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700409};
410
411union meminfo {
412 struct {
413 int64_t nr_free_pages;
414 int64_t cached;
415 int64_t swap_cached;
416 int64_t buffers;
417 int64_t shmem;
418 int64_t unevictable;
Vic Yang65680692018-08-07 10:18:22 -0700419 int64_t total_swap;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700420 int64_t free_swap;
Suren Baghdasaryan08bfa982018-07-26 16:34:27 -0700421 int64_t active_anon;
422 int64_t inactive_anon;
423 int64_t active_file;
424 int64_t inactive_file;
425 int64_t sreclaimable;
426 int64_t sunreclaimable;
427 int64_t kernel_stack;
428 int64_t page_tables;
429 int64_t ion_heap;
430 int64_t ion_heap_pool;
431 int64_t cma_free;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700432 /* fields below are calculated rather than read from the file */
433 int64_t nr_file_pages;
434 } field;
435 int64_t arr[MI_FIELD_COUNT];
436};
437
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -0700438/* Fields to parse in /proc/vmstat */
439enum vmstat_field {
440 VS_FREE_PAGES,
441 VS_INACTIVE_FILE,
442 VS_ACTIVE_FILE,
443 VS_WORKINGSET_REFAULT,
Suren Baghdasaryandc60f972020-12-14 13:38:48 -0800444 VS_WORKINGSET_REFAULT_FILE,
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -0700445 VS_PGSCAN_KSWAPD,
446 VS_PGSCAN_DIRECT,
447 VS_PGSCAN_DIRECT_THROTTLE,
448 VS_FIELD_COUNT
449};
450
451static const char* const vmstat_field_names[MI_FIELD_COUNT] = {
452 "nr_free_pages",
453 "nr_inactive_file",
454 "nr_active_file",
455 "workingset_refault",
Suren Baghdasaryandc60f972020-12-14 13:38:48 -0800456 "workingset_refault_file",
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -0700457 "pgscan_kswapd",
458 "pgscan_direct",
459 "pgscan_direct_throttle",
460};
461
462union vmstat {
463 struct {
464 int64_t nr_free_pages;
465 int64_t nr_inactive_file;
466 int64_t nr_active_file;
467 int64_t workingset_refault;
Suren Baghdasaryandc60f972020-12-14 13:38:48 -0800468 int64_t workingset_refault_file;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -0700469 int64_t pgscan_kswapd;
470 int64_t pgscan_direct;
471 int64_t pgscan_direct_throttle;
472 } field;
473 int64_t arr[VS_FIELD_COUNT];
474};
475
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700476enum field_match_result {
477 NO_MATCH,
478 PARSE_FAIL,
479 PARSE_SUCCESS
480};
481
Todd Poynorc58c5142013-07-09 19:35:14 -0700482struct adjslot_list {
483 struct adjslot_list *next;
484 struct adjslot_list *prev;
485};
486
487struct proc {
488 struct adjslot_list asl;
489 int pid;
Suren Baghdasaryana10157c2019-07-19 10:55:39 -0700490 int pidfd;
Colin Cross748d2182014-06-13 14:52:43 -0700491 uid_t uid;
Todd Poynorc58c5142013-07-09 19:35:14 -0700492 int oomadj;
Suren Baghdasaryan945658a2019-10-18 11:16:52 -0700493 pid_t reg_pid; /* PID of the process that registered this record */
Todd Poynorc58c5142013-07-09 19:35:14 -0700494 struct proc *pidhash_next;
495};
496
Suren Baghdasaryan87966742018-04-13 12:43:41 -0700497struct reread_data {
498 const char* const filename;
499 int fd;
500};
501
Todd Poynorc58c5142013-07-09 19:35:14 -0700502#define PIDHASH_SZ 1024
503static struct proc *pidhash[PIDHASH_SZ];
504#define pid_hashfn(x) ((((x) >> 8) ^ (x)) & (PIDHASH_SZ - 1))
505
Chih-Hung Hsieheefa2462016-05-19 16:02:22 -0700506#define ADJTOSLOT(adj) ((adj) + -OOM_SCORE_ADJ_MIN)
Suren Baghdasaryana7394ea2018-10-12 11:07:40 -0700507#define ADJTOSLOT_COUNT (ADJTOSLOT(OOM_SCORE_ADJ_MAX) + 1)
508static struct adjslot_list procadjslot_list[ADJTOSLOT_COUNT];
509
510#define MAX_DISTINCT_OOM_ADJ 32
511#define KILLCNT_INVALID_IDX 0xFF
512/*
513 * Because killcnt array is sparse a two-level indirection is used
514 * to keep the size small. killcnt_idx stores index of the element in
515 * killcnt array. Index KILLCNT_INVALID_IDX indicates an unused slot.
516 */
517static uint8_t killcnt_idx[ADJTOSLOT_COUNT];
518static uint16_t killcnt[MAX_DISTINCT_OOM_ADJ];
519static int killcnt_free_idx = 0;
520static uint32_t killcnt_total = 0;
Todd Poynorc58c5142013-07-09 19:35:14 -0700521
Todd Poynorc58c5142013-07-09 19:35:14 -0700522/* PAGE_SIZE / 1024 */
523static long page_k;
524
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -0700525static void update_props();
526static bool init_monitors();
527static void destroy_monitors();
528
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -0700529static int clamp(int low, int high, int value) {
530 return max(min(value, high), low);
531}
532
Suren Baghdasaryan87966742018-04-13 12:43:41 -0700533static bool parse_int64(const char* str, int64_t* ret) {
534 char* endptr;
535 long long val = strtoll(str, &endptr, 10);
536 if (str == endptr || val > INT64_MAX) {
537 return false;
538 }
539 *ret = (int64_t)val;
540 return true;
541}
542
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -0700543static int find_field(const char* name, const char* const field_names[], int field_count) {
544 for (int i = 0; i < field_count; i++) {
545 if (!strcmp(name, field_names[i])) {
546 return i;
547 }
548 }
549 return -1;
550}
551
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700552static enum field_match_result match_field(const char* cp, const char* ap,
553 const char* const field_names[],
554 int field_count, int64_t* field,
555 int *field_idx) {
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -0700556 int i = find_field(cp, field_names, field_count);
557 if (i < 0) {
558 return NO_MATCH;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700559 }
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -0700560 *field_idx = i;
561 return parse_int64(ap, field) ? PARSE_SUCCESS : PARSE_FAIL;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700562}
563
Suren Baghdasaryan87966742018-04-13 12:43:41 -0700564/*
565 * Read file content from the beginning up to max_len bytes or EOF
566 * whichever happens first.
567 */
Colin Crossdba1cc62014-07-11 17:53:27 -0700568static ssize_t read_all(int fd, char *buf, size_t max_len)
569{
570 ssize_t ret = 0;
Suren Baghdasaryan87966742018-04-13 12:43:41 -0700571 off_t offset = 0;
Colin Crossdba1cc62014-07-11 17:53:27 -0700572
573 while (max_len > 0) {
Suren Baghdasaryan87966742018-04-13 12:43:41 -0700574 ssize_t r = TEMP_FAILURE_RETRY(pread(fd, buf, max_len, offset));
Colin Crossdba1cc62014-07-11 17:53:27 -0700575 if (r == 0) {
576 break;
577 }
578 if (r == -1) {
579 return -1;
580 }
581 ret += r;
582 buf += r;
Suren Baghdasaryan87966742018-04-13 12:43:41 -0700583 offset += r;
Colin Crossdba1cc62014-07-11 17:53:27 -0700584 max_len -= r;
585 }
586
587 return ret;
588}
589
Suren Baghdasaryan87966742018-04-13 12:43:41 -0700590/*
591 * Read a new or already opened file from the beginning.
592 * If the file has not been opened yet data->fd should be set to -1.
593 * To be used with files which are read often and possibly during high
594 * memory pressure to minimize file opening which by itself requires kernel
595 * memory allocation and might result in a stall on memory stressed system.
596 */
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -0700597static char *reread_file(struct reread_data *data) {
598 /* start with page-size buffer and increase if needed */
599 static ssize_t buf_size = PAGE_SIZE;
600 static char *new_buf, *buf = NULL;
Suren Baghdasaryan87966742018-04-13 12:43:41 -0700601 ssize_t size;
602
603 if (data->fd == -1) {
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -0700604 /* First-time buffer initialization */
Tom Cherry43f3d2b2019-12-04 12:46:57 -0800605 if (!buf && (buf = static_cast<char*>(malloc(buf_size))) == nullptr) {
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -0700606 return NULL;
607 }
608
609 data->fd = TEMP_FAILURE_RETRY(open(data->filename, O_RDONLY | O_CLOEXEC));
610 if (data->fd < 0) {
Suren Baghdasaryan87966742018-04-13 12:43:41 -0700611 ALOGE("%s open: %s", data->filename, strerror(errno));
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -0700612 return NULL;
Suren Baghdasaryan87966742018-04-13 12:43:41 -0700613 }
614 }
615
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -0700616 while (true) {
617 size = read_all(data->fd, buf, buf_size - 1);
618 if (size < 0) {
619 ALOGE("%s read: %s", data->filename, strerror(errno));
620 close(data->fd);
621 data->fd = -1;
622 return NULL;
623 }
624 if (size < buf_size - 1) {
625 break;
626 }
627 /*
628 * Since we are reading /proc files we can't use fstat to find out
629 * the real size of the file. Double the buffer size and keep retrying.
630 */
Tom Cherry43f3d2b2019-12-04 12:46:57 -0800631 if ((new_buf = static_cast<char*>(realloc(buf, buf_size * 2))) == nullptr) {
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -0700632 errno = ENOMEM;
633 return NULL;
634 }
635 buf = new_buf;
636 buf_size *= 2;
Suren Baghdasaryan87966742018-04-13 12:43:41 -0700637 }
Suren Baghdasaryan87966742018-04-13 12:43:41 -0700638 buf[size] = 0;
639
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -0700640 return buf;
Suren Baghdasaryan87966742018-04-13 12:43:41 -0700641}
642
Jing Ji5c480962019-12-04 09:22:05 -0800643static bool claim_record(struct proc* procp, pid_t pid) {
644 if (procp->reg_pid == pid) {
645 /* Record already belongs to the registrant */
646 return true;
647 }
648 if (procp->reg_pid == 0) {
649 /* Old registrant is gone, claim the record */
650 procp->reg_pid = pid;
651 return true;
652 }
653 /* The record is owned by another registrant */
654 return false;
655}
656
657static void remove_claims(pid_t pid) {
658 int i;
659
660 for (i = 0; i < PIDHASH_SZ; i++) {
661 struct proc* procp = pidhash[i];
662 while (procp) {
663 if (procp->reg_pid == pid) {
664 procp->reg_pid = 0;
665 }
666 procp = procp->pidhash_next;
667 }
668 }
669}
670
671static void ctrl_data_close(int dsock_idx) {
672 struct epoll_event epev;
673
674 ALOGI("closing lmkd data connection");
675 if (epoll_ctl(epollfd, EPOLL_CTL_DEL, data_sock[dsock_idx].sock, &epev) == -1) {
676 // Log a warning and keep going
677 ALOGW("epoll_ctl for data connection socket failed; errno=%d", errno);
678 }
679 maxevents--;
680
681 close(data_sock[dsock_idx].sock);
682 data_sock[dsock_idx].sock = -1;
683
684 /* Mark all records of the old registrant as unclaimed */
685 remove_claims(data_sock[dsock_idx].pid);
686}
687
688static ssize_t ctrl_data_read(int dsock_idx, char* buf, size_t bufsz, struct ucred* sender_cred) {
689 struct iovec iov = {buf, bufsz};
690 char control[CMSG_SPACE(sizeof(struct ucred))];
691 struct msghdr hdr = {
692 NULL, 0, &iov, 1, control, sizeof(control), 0,
693 };
694 ssize_t ret;
695 ret = TEMP_FAILURE_RETRY(recvmsg(data_sock[dsock_idx].sock, &hdr, 0));
696 if (ret == -1) {
697 ALOGE("control data socket read failed; %s", strerror(errno));
698 return -1;
699 }
700 if (ret == 0) {
701 ALOGE("Got EOF on control data socket");
702 return -1;
703 }
704
705 struct ucred* cred = NULL;
706 struct cmsghdr* cmsg = CMSG_FIRSTHDR(&hdr);
707 while (cmsg != NULL) {
708 if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_CREDENTIALS) {
709 cred = (struct ucred*)CMSG_DATA(cmsg);
710 break;
711 }
712 cmsg = CMSG_NXTHDR(&hdr, cmsg);
713 }
714
715 if (cred == NULL) {
716 ALOGE("Failed to retrieve sender credentials");
717 /* Close the connection */
718 ctrl_data_close(dsock_idx);
719 return -1;
720 }
721
722 memcpy(sender_cred, cred, sizeof(struct ucred));
723
724 /* Store PID of the peer */
725 data_sock[dsock_idx].pid = cred->pid;
726
727 return ret;
728}
729
730static int ctrl_data_write(int dsock_idx, char* buf, size_t bufsz) {
731 int ret = 0;
732
733 ret = TEMP_FAILURE_RETRY(write(data_sock[dsock_idx].sock, buf, bufsz));
734
735 if (ret == -1) {
736 ALOGE("control data socket write failed; errno=%d", errno);
737 } else if (ret == 0) {
738 ALOGE("Got EOF on control data socket");
739 ret = -1;
740 }
741
742 return ret;
743}
744
745/*
746 * Write the pid/uid pair over the data socket, note: all active clients
747 * will receive this unsolicited notification.
748 */
749static void ctrl_data_write_lmk_kill_occurred(pid_t pid, uid_t uid) {
750 LMKD_CTRL_PACKET packet;
751 size_t len = lmkd_pack_set_prockills(packet, pid, uid);
752
753 for (int i = 0; i < MAX_DATA_CONN; i++) {
Suren Baghdasaryan36baf442019-12-23 11:37:34 -0800754 if (data_sock[i].sock >= 0 && data_sock[i].async_event_mask & 1 << LMK_ASYNC_EVENT_KILL) {
Jing Ji5c480962019-12-04 09:22:05 -0800755 ctrl_data_write(i, (char*)packet, len);
756 }
757 }
758}
759
760static void poll_kernel(int poll_fd) {
761 if (poll_fd == -1) {
762 // not waiting
763 return;
764 }
765
766 while (1) {
767 char rd_buf[256];
768 int bytes_read = TEMP_FAILURE_RETRY(pread(poll_fd, (void*)rd_buf, sizeof(rd_buf), 0));
769 if (bytes_read <= 0) break;
770 rd_buf[bytes_read] = '\0';
771
772 int64_t pid;
773 int64_t uid;
774 int64_t group_leader_pid;
775 int64_t rss_in_pages;
776 struct memory_stat mem_st = {};
777 int16_t oom_score_adj;
778 int16_t min_score_adj;
779 int64_t starttime;
780 char* taskname = 0;
781
782 int fields_read =
783 sscanf(rd_buf,
784 "%" SCNd64 " %" SCNd64 " %" SCNd64 " %" SCNd64 " %" SCNd64 " %" SCNd64
785 " %" SCNd16 " %" SCNd16 " %" SCNd64 "\n%m[^\n]",
786 &pid, &uid, &group_leader_pid, &mem_st.pgfault, &mem_st.pgmajfault,
787 &rss_in_pages, &oom_score_adj, &min_score_adj, &starttime, &taskname);
788
789 /* only the death of the group leader process is logged */
790 if (fields_read == 10 && group_leader_pid == pid) {
791 ctrl_data_write_lmk_kill_occurred((pid_t)pid, (uid_t)uid);
792 mem_st.process_start_time_ns = starttime * (NS_PER_SEC / sysconf(_SC_CLK_TCK));
793 mem_st.rss_in_bytes = rss_in_pages * PAGE_SIZE;
Suren Baghdasaryan3cc1f132020-09-09 20:19:02 -0700794
795 struct kill_stat kill_st = {
796 .uid = static_cast<int32_t>(uid),
797 .kill_reason = NONE,
798 .oom_score = oom_score_adj,
799 .min_oom_score = min_score_adj,
800 .free_mem_kb = 0,
801 .free_swap_kb = 0,
802 };
803 stats_write_lmk_kill_occurred_pid(pid, &kill_st, &mem_st);
Jing Ji5c480962019-12-04 09:22:05 -0800804 }
805
806 free(taskname);
807 }
808}
809
810static bool init_poll_kernel() {
811 kpoll_fd = TEMP_FAILURE_RETRY(open("/proc/lowmemorykiller", O_RDONLY | O_NONBLOCK | O_CLOEXEC));
812
813 if (kpoll_fd < 0) {
814 ALOGE("kernel lmk event file could not be opened; errno=%d", errno);
815 return false;
816 }
817
818 return true;
819}
820
Todd Poynorc58c5142013-07-09 19:35:14 -0700821static struct proc *pid_lookup(int pid) {
822 struct proc *procp;
823
824 for (procp = pidhash[pid_hashfn(pid)]; procp && procp->pid != pid;
825 procp = procp->pidhash_next)
826 ;
827
828 return procp;
829}
830
Tom Cherry43f3d2b2019-12-04 12:46:57 -0800831static void adjslot_insert(struct adjslot_list *head, struct adjslot_list *new_element)
Todd Poynorc58c5142013-07-09 19:35:14 -0700832{
833 struct adjslot_list *next = head->next;
Tom Cherry43f3d2b2019-12-04 12:46:57 -0800834 new_element->prev = head;
835 new_element->next = next;
836 next->prev = new_element;
837 head->next = new_element;
Todd Poynorc58c5142013-07-09 19:35:14 -0700838}
839
840static void adjslot_remove(struct adjslot_list *old)
841{
842 struct adjslot_list *prev = old->prev;
843 struct adjslot_list *next = old->next;
844 next->prev = prev;
845 prev->next = next;
846}
847
848static struct adjslot_list *adjslot_tail(struct adjslot_list *head) {
849 struct adjslot_list *asl = head->prev;
850
851 return asl == head ? NULL : asl;
852}
853
854static void proc_slot(struct proc *procp) {
855 int adjslot = ADJTOSLOT(procp->oomadj);
856
857 adjslot_insert(&procadjslot_list[adjslot], &procp->asl);
858}
859
860static void proc_unslot(struct proc *procp) {
861 adjslot_remove(&procp->asl);
862}
863
864static void proc_insert(struct proc *procp) {
865 int hval = pid_hashfn(procp->pid);
866
867 procp->pidhash_next = pidhash[hval];
868 pidhash[hval] = procp;
869 proc_slot(procp);
870}
871
872static int pid_remove(int pid) {
873 int hval = pid_hashfn(pid);
874 struct proc *procp;
875 struct proc *prevp;
876
877 for (procp = pidhash[hval], prevp = NULL; procp && procp->pid != pid;
878 procp = procp->pidhash_next)
879 prevp = procp;
880
881 if (!procp)
882 return -1;
883
884 if (!prevp)
885 pidhash[hval] = procp->pidhash_next;
886 else
887 prevp->pidhash_next = procp->pidhash_next;
888
889 proc_unslot(procp);
Suren Baghdasaryana10157c2019-07-19 10:55:39 -0700890 /*
891 * Close pidfd here if we are not waiting for corresponding process to die,
892 * in which case stop_wait_for_proc_kill() will close the pidfd later
893 */
894 if (procp->pidfd >= 0 && procp->pidfd != last_kill_pid_or_fd) {
895 close(procp->pidfd);
896 }
Todd Poynorc58c5142013-07-09 19:35:14 -0700897 free(procp);
898 return 0;
899}
900
Suren Baghdasaryanf584fff2018-03-20 13:53:17 -0700901/*
902 * Write a string to a file.
903 * Returns false if the file does not exist.
904 */
905static bool writefilestring(const char *path, const char *s,
906 bool err_if_missing) {
Nick Kralevich148d8dd2015-12-18 20:52:37 -0800907 int fd = open(path, O_WRONLY | O_CLOEXEC);
Suren Baghdasaryanf584fff2018-03-20 13:53:17 -0700908 ssize_t len = strlen(s);
909 ssize_t ret;
Todd Poynorc58c5142013-07-09 19:35:14 -0700910
911 if (fd < 0) {
Suren Baghdasaryanf584fff2018-03-20 13:53:17 -0700912 if (err_if_missing) {
913 ALOGE("Error opening %s; errno=%d", path, errno);
914 }
915 return false;
Todd Poynorc58c5142013-07-09 19:35:14 -0700916 }
917
Suren Baghdasaryanf584fff2018-03-20 13:53:17 -0700918 ret = TEMP_FAILURE_RETRY(write(fd, s, len));
Todd Poynorc58c5142013-07-09 19:35:14 -0700919 if (ret < 0) {
920 ALOGE("Error writing %s; errno=%d", path, errno);
921 } else if (ret < len) {
Suren Baghdasaryanf584fff2018-03-20 13:53:17 -0700922 ALOGE("Short write on %s; length=%zd", path, ret);
Todd Poynorc58c5142013-07-09 19:35:14 -0700923 }
924
925 close(fd);
Suren Baghdasaryanf584fff2018-03-20 13:53:17 -0700926 return true;
Todd Poynorc58c5142013-07-09 19:35:14 -0700927}
928
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -0700929static inline long get_time_diff_ms(struct timespec *from,
930 struct timespec *to) {
931 return (to->tv_sec - from->tv_sec) * (long)MS_PER_SEC +
932 (to->tv_nsec - from->tv_nsec) / (long)NS_PER_MS;
933}
934
Ioannis Ilkos279268a2020-08-01 10:50:40 +0100935/* Reads /proc/pid/status into buf. */
936static bool read_proc_status(int pid, char *buf, size_t buf_sz) {
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -0700937 char path[PATH_MAX];
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -0700938 int fd;
939 ssize_t size;
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -0700940
941 snprintf(path, PATH_MAX, "/proc/%d/status", pid);
942 fd = open(path, O_RDONLY | O_CLOEXEC);
943 if (fd < 0) {
Ioannis Ilkos279268a2020-08-01 10:50:40 +0100944 return false;
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -0700945 }
946
Ioannis Ilkos279268a2020-08-01 10:50:40 +0100947 size = read_all(fd, buf, buf_sz - 1);
948 close(fd);
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -0700949 if (size < 0) {
Ioannis Ilkos279268a2020-08-01 10:50:40 +0100950 return false;
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -0700951 }
952 buf[size] = 0;
Ioannis Ilkos279268a2020-08-01 10:50:40 +0100953 return true;
954}
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -0700955
Ioannis Ilkos279268a2020-08-01 10:50:40 +0100956/* Looks for tag in buf and parses the first integer */
957static bool parse_status_tag(char *buf, const char *tag, int64_t *out) {
958 char *pos = buf;
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -0700959 while (true) {
Ioannis Ilkos279268a2020-08-01 10:50:40 +0100960 pos = strstr(pos, tag);
961 /* Stop if tag not found or found at the line beginning */
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -0700962 if (pos == NULL || pos == buf || pos[-1] == '\n') {
963 break;
964 }
965 pos++;
966 }
967
968 if (pos == NULL) {
Ioannis Ilkos279268a2020-08-01 10:50:40 +0100969 return false;
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -0700970 }
971
Ioannis Ilkos279268a2020-08-01 10:50:40 +0100972 pos += strlen(tag);
973 while (*pos == ' ') ++pos;
974 return parse_int64(pos, out);
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -0700975}
976
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -0700977static int proc_get_size(int pid) {
978 char path[PATH_MAX];
979 char line[LINE_MAX];
980 int fd;
981 int rss = 0;
982 int total;
983 ssize_t ret;
984
985 /* gid containing AID_READPROC required */
986 snprintf(path, PATH_MAX, "/proc/%d/statm", pid);
987 fd = open(path, O_RDONLY | O_CLOEXEC);
988 if (fd == -1)
989 return -1;
990
991 ret = read_all(fd, line, sizeof(line) - 1);
992 if (ret < 0) {
993 close(fd);
994 return -1;
995 }
Suren Baghdasaryan632f1c52019-10-04 16:06:55 -0700996 line[ret] = '\0';
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -0700997
998 sscanf(line, "%d %d ", &total, &rss);
999 close(fd);
1000 return rss;
1001}
1002
Suren Baghdasaryan632f1c52019-10-04 16:06:55 -07001003static char *proc_get_name(int pid, char *buf, size_t buf_size) {
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07001004 char path[PATH_MAX];
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07001005 int fd;
1006 char *cp;
1007 ssize_t ret;
1008
1009 /* gid containing AID_READPROC required */
1010 snprintf(path, PATH_MAX, "/proc/%d/cmdline", pid);
1011 fd = open(path, O_RDONLY | O_CLOEXEC);
1012 if (fd == -1) {
1013 return NULL;
1014 }
Suren Baghdasaryan632f1c52019-10-04 16:06:55 -07001015 ret = read_all(fd, buf, buf_size - 1);
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07001016 close(fd);
1017 if (ret < 0) {
1018 return NULL;
1019 }
Suren Baghdasaryan632f1c52019-10-04 16:06:55 -07001020 buf[ret] = '\0';
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07001021
Suren Baghdasaryan632f1c52019-10-04 16:06:55 -07001022 cp = strchr(buf, ' ');
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07001023 if (cp) {
1024 *cp = '\0';
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07001025 }
1026
Suren Baghdasaryan632f1c52019-10-04 16:06:55 -07001027 return buf;
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07001028}
1029
Suren Baghdasaryana93503e2019-10-22 17:12:01 -07001030static void cmd_procprio(LMKD_CTRL_PACKET packet, int field_count, struct ucred *cred) {
Todd Poynorc58c5142013-07-09 19:35:14 -07001031 struct proc *procp;
Suren Baghdasaryan632f1c52019-10-04 16:06:55 -07001032 char path[LINE_MAX];
Todd Poynorc58c5142013-07-09 19:35:14 -07001033 char val[20];
Robert Benea58d6a132017-06-01 16:32:31 -07001034 int soft_limit_mult;
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -08001035 struct lmk_procprio params;
Suren Baghdasaryanbb7747b2018-03-20 16:03:29 -07001036 bool is_system_server;
1037 struct passwd *pwdrec;
Ioannis Ilkos279268a2020-08-01 10:50:40 +01001038 int64_t tgid;
1039 char buf[PAGE_SIZE];
Todd Poynorc58c5142013-07-09 19:35:14 -07001040
Suren Baghdasaryana93503e2019-10-22 17:12:01 -07001041 lmkd_pack_get_procprio(packet, field_count, &params);
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -08001042
1043 if (params.oomadj < OOM_SCORE_ADJ_MIN ||
1044 params.oomadj > OOM_SCORE_ADJ_MAX) {
1045 ALOGE("Invalid PROCPRIO oomadj argument %d", params.oomadj);
Todd Poynorc58c5142013-07-09 19:35:14 -07001046 return;
1047 }
1048
Suren Baghdasaryana93503e2019-10-22 17:12:01 -07001049 if (params.ptype < PROC_TYPE_FIRST || params.ptype >= PROC_TYPE_COUNT) {
1050 ALOGE("Invalid PROCPRIO process type argument %d", params.ptype);
1051 return;
1052 }
1053
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -07001054 /* Check if registered process is a thread group leader */
Ioannis Ilkos279268a2020-08-01 10:50:40 +01001055 if (read_proc_status(params.pid, buf, sizeof(buf))) {
1056 if (parse_status_tag(buf, PROC_STATUS_TGID_FIELD, &tgid) && tgid != params.pid) {
1057 ALOGE("Attempt to register a task that is not a thread group leader "
1058 "(tid %d, tgid %" PRId64 ")", params.pid, tgid);
1059 return;
1060 }
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -07001061 }
1062
Mark Salyzyna00ccd82018-04-09 09:50:32 -07001063 /* gid containing AID_READPROC required */
1064 /* CAP_SYS_RESOURCE required */
1065 /* CAP_DAC_OVERRIDE required */
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -08001066 snprintf(path, sizeof(path), "/proc/%d/oom_score_adj", params.pid);
1067 snprintf(val, sizeof(val), "%d", params.oomadj);
Suren Baghdasaryanf584fff2018-03-20 13:53:17 -07001068 if (!writefilestring(path, val, false)) {
1069 ALOGW("Failed to open %s; errno=%d: process %d might have been killed",
1070 path, errno, params.pid);
1071 /* If this file does not exist the process is dead. */
1072 return;
1073 }
Todd Poynorc58c5142013-07-09 19:35:14 -07001074
Mark Salyzyn5cc80b32018-03-21 12:24:58 -07001075 if (use_inkernel_interface) {
Jing Ji5c480962019-12-04 09:22:05 -08001076 stats_store_taskname(params.pid, proc_get_name(params.pid, path, sizeof(path)));
Todd Poynorc58c5142013-07-09 19:35:14 -07001077 return;
Mark Salyzyn5cc80b32018-03-21 12:24:58 -07001078 }
Todd Poynorc58c5142013-07-09 19:35:14 -07001079
Suren Baghdasaryana93503e2019-10-22 17:12:01 -07001080 /* lmkd should not change soft limits for services */
1081 if (params.ptype == PROC_TYPE_APP && per_app_memcg) {
Suren Baghdasaryanb0bda552018-05-18 14:42:00 -07001082 if (params.oomadj >= 900) {
1083 soft_limit_mult = 0;
1084 } else if (params.oomadj >= 800) {
1085 soft_limit_mult = 0;
1086 } else if (params.oomadj >= 700) {
1087 soft_limit_mult = 0;
1088 } else if (params.oomadj >= 600) {
1089 // Launcher should be perceptible, don't kill it.
1090 params.oomadj = 200;
1091 soft_limit_mult = 1;
1092 } else if (params.oomadj >= 500) {
1093 soft_limit_mult = 0;
1094 } else if (params.oomadj >= 400) {
1095 soft_limit_mult = 0;
1096 } else if (params.oomadj >= 300) {
1097 soft_limit_mult = 1;
1098 } else if (params.oomadj >= 200) {
Srinivas Paladugua453f0b2018-10-09 14:21:10 -07001099 soft_limit_mult = 8;
Suren Baghdasaryanb0bda552018-05-18 14:42:00 -07001100 } else if (params.oomadj >= 100) {
1101 soft_limit_mult = 10;
1102 } else if (params.oomadj >= 0) {
1103 soft_limit_mult = 20;
1104 } else {
1105 // Persistent processes will have a large
1106 // soft limit 512MB.
1107 soft_limit_mult = 64;
1108 }
Robert Benea58d6a132017-06-01 16:32:31 -07001109
Suren Baghdasaryanbf919ff2018-05-21 19:48:47 -07001110 snprintf(path, sizeof(path), MEMCG_SYSFS_PATH
1111 "apps/uid_%d/pid_%d/memory.soft_limit_in_bytes",
1112 params.uid, params.pid);
Suren Baghdasaryanb0bda552018-05-18 14:42:00 -07001113 snprintf(val, sizeof(val), "%d", soft_limit_mult * EIGHT_MEGA);
Suren Baghdasaryanbf919ff2018-05-21 19:48:47 -07001114
1115 /*
1116 * system_server process has no memcg under /dev/memcg/apps but should be
1117 * registered with lmkd. This is the best way so far to identify it.
1118 */
1119 is_system_server = (params.oomadj == SYSTEM_ADJ &&
1120 (pwdrec = getpwnam("system")) != NULL &&
1121 params.uid == pwdrec->pw_uid);
1122 writefilestring(path, val, !is_system_server);
Robert Benea58d6a132017-06-01 16:32:31 -07001123 }
1124
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -08001125 procp = pid_lookup(params.pid);
Todd Poynorc58c5142013-07-09 19:35:14 -07001126 if (!procp) {
Suren Baghdasaryana10157c2019-07-19 10:55:39 -07001127 int pidfd = -1;
1128
1129 if (pidfd_supported) {
Josh Gao84623be2021-03-18 17:16:08 -07001130 pidfd = TEMP_FAILURE_RETRY(pidfd_open(params.pid, 0));
Suren Baghdasaryana10157c2019-07-19 10:55:39 -07001131 if (pidfd < 0) {
1132 ALOGE("pidfd_open for pid %d failed; errno=%d", params.pid, errno);
Todd Poynorc58c5142013-07-09 19:35:14 -07001133 return;
1134 }
Suren Baghdasaryana10157c2019-07-19 10:55:39 -07001135 }
Todd Poynorc58c5142013-07-09 19:35:14 -07001136
Tom Cherry43f3d2b2019-12-04 12:46:57 -08001137 procp = static_cast<struct proc*>(calloc(1, sizeof(struct proc)));
Suren Baghdasaryana10157c2019-07-19 10:55:39 -07001138 if (!procp) {
1139 // Oh, the irony. May need to rebuild our state.
1140 return;
1141 }
1142
1143 procp->pid = params.pid;
1144 procp->pidfd = pidfd;
1145 procp->uid = params.uid;
Suren Baghdasaryan945658a2019-10-18 11:16:52 -07001146 procp->reg_pid = cred->pid;
Suren Baghdasaryana10157c2019-07-19 10:55:39 -07001147 procp->oomadj = params.oomadj;
1148 proc_insert(procp);
Todd Poynorc58c5142013-07-09 19:35:14 -07001149 } else {
Suren Baghdasaryan945658a2019-10-18 11:16:52 -07001150 if (!claim_record(procp, cred->pid)) {
1151 char buf[LINE_MAX];
1152 /* Only registrant of the record can remove it */
1153 ALOGE("%s (%d, %d) attempts to modify a process registered by another client",
1154 proc_get_name(cred->pid, buf, sizeof(buf)), cred->uid, cred->pid);
1155 return;
1156 }
Todd Poynorc58c5142013-07-09 19:35:14 -07001157 proc_unslot(procp);
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -08001158 procp->oomadj = params.oomadj;
Todd Poynorc58c5142013-07-09 19:35:14 -07001159 proc_slot(procp);
1160 }
1161}
1162
Suren Baghdasaryan945658a2019-10-18 11:16:52 -07001163static void cmd_procremove(LMKD_CTRL_PACKET packet, struct ucred *cred) {
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -08001164 struct lmk_procremove params;
Suren Baghdasaryan945658a2019-10-18 11:16:52 -07001165 struct proc *procp;
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -08001166
George Burgess IV3b36b902019-10-02 11:22:55 -07001167 lmkd_pack_get_procremove(packet, &params);
Suren Baghdasaryan945658a2019-10-18 11:16:52 -07001168
Mark Salyzyn5cc80b32018-03-21 12:24:58 -07001169 if (use_inkernel_interface) {
Jing Ji5c480962019-12-04 09:22:05 -08001170 /*
1171 * Perform an extra check before the pid is removed, after which it
1172 * will be impossible for poll_kernel to get the taskname. poll_kernel()
1173 * is potentially a long-running blocking function; however this method
1174 * handles AMS requests but does not block AMS.
1175 */
1176 poll_kernel(kpoll_fd);
1177
1178 stats_remove_taskname(params.pid);
Todd Poynorc58c5142013-07-09 19:35:14 -07001179 return;
Mark Salyzyn5cc80b32018-03-21 12:24:58 -07001180 }
Todd Poynorc58c5142013-07-09 19:35:14 -07001181
Suren Baghdasaryan945658a2019-10-18 11:16:52 -07001182 procp = pid_lookup(params.pid);
1183 if (!procp) {
1184 return;
1185 }
1186
1187 if (!claim_record(procp, cred->pid)) {
1188 char buf[LINE_MAX];
1189 /* Only registrant of the record can remove it */
1190 ALOGE("%s (%d, %d) attempts to unregister a process registered by another client",
1191 proc_get_name(cred->pid, buf, sizeof(buf)), cred->uid, cred->pid);
1192 return;
1193 }
1194
Suren Baghdasaryan8b00c6d2018-10-12 11:28:33 -07001195 /*
1196 * WARNING: After pid_remove() procp is freed and can't be used!
1197 * Therefore placed at the end of the function.
1198 */
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -08001199 pid_remove(params.pid);
Todd Poynorc58c5142013-07-09 19:35:14 -07001200}
1201
Suren Baghdasaryan945658a2019-10-18 11:16:52 -07001202static void cmd_procpurge(struct ucred *cred) {
Suren Baghdasaryan83df0082018-10-10 14:17:17 -07001203 int i;
1204 struct proc *procp;
1205 struct proc *next;
1206
1207 if (use_inkernel_interface) {
Jim Blackler90853b62019-09-10 15:30:05 +01001208 stats_purge_tasknames();
Suren Baghdasaryan83df0082018-10-10 14:17:17 -07001209 return;
1210 }
1211
Suren Baghdasaryan83df0082018-10-10 14:17:17 -07001212 for (i = 0; i < PIDHASH_SZ; i++) {
1213 procp = pidhash[i];
1214 while (procp) {
1215 next = procp->pidhash_next;
Suren Baghdasaryan945658a2019-10-18 11:16:52 -07001216 /* Purge only records created by the requestor */
1217 if (claim_record(procp, cred->pid)) {
1218 pid_remove(procp->pid);
1219 }
Suren Baghdasaryan83df0082018-10-10 14:17:17 -07001220 procp = next;
1221 }
1222 }
Suren Baghdasaryan83df0082018-10-10 14:17:17 -07001223}
1224
Suren Baghdasaryan36baf442019-12-23 11:37:34 -08001225static void cmd_subscribe(int dsock_idx, LMKD_CTRL_PACKET packet) {
1226 struct lmk_subscribe params;
1227
1228 lmkd_pack_get_subscribe(packet, &params);
1229 data_sock[dsock_idx].async_event_mask |= 1 << params.evt_type;
1230}
1231
Suren Baghdasaryana7394ea2018-10-12 11:07:40 -07001232static void inc_killcnt(int oomadj) {
1233 int slot = ADJTOSLOT(oomadj);
1234 uint8_t idx = killcnt_idx[slot];
1235
1236 if (idx == KILLCNT_INVALID_IDX) {
1237 /* index is not assigned for this oomadj */
1238 if (killcnt_free_idx < MAX_DISTINCT_OOM_ADJ) {
1239 killcnt_idx[slot] = killcnt_free_idx;
1240 killcnt[killcnt_free_idx] = 1;
1241 killcnt_free_idx++;
1242 } else {
1243 ALOGW("Number of distinct oomadj levels exceeds %d",
1244 MAX_DISTINCT_OOM_ADJ);
1245 }
1246 } else {
1247 /*
1248 * wraparound is highly unlikely and is detectable using total
1249 * counter because it has to be equal to the sum of all counters
1250 */
1251 killcnt[idx]++;
1252 }
1253 /* increment total kill counter */
1254 killcnt_total++;
1255}
1256
1257static int get_killcnt(int min_oomadj, int max_oomadj) {
1258 int slot;
1259 int count = 0;
1260
1261 if (min_oomadj > max_oomadj)
1262 return 0;
1263
1264 /* special case to get total kill count */
1265 if (min_oomadj > OOM_SCORE_ADJ_MAX)
1266 return killcnt_total;
1267
1268 while (min_oomadj <= max_oomadj &&
1269 (slot = ADJTOSLOT(min_oomadj)) < ADJTOSLOT_COUNT) {
1270 uint8_t idx = killcnt_idx[slot];
1271 if (idx != KILLCNT_INVALID_IDX) {
1272 count += killcnt[idx];
1273 }
1274 min_oomadj++;
1275 }
1276
1277 return count;
1278}
1279
1280static int cmd_getkillcnt(LMKD_CTRL_PACKET packet) {
1281 struct lmk_getkillcnt params;
1282
1283 if (use_inkernel_interface) {
1284 /* kernel driver does not expose this information */
1285 return 0;
1286 }
1287
1288 lmkd_pack_get_getkillcnt(packet, &params);
1289
1290 return get_killcnt(params.min_oomadj, params.max_oomadj);
1291}
1292
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -08001293static void cmd_target(int ntargets, LMKD_CTRL_PACKET packet) {
Todd Poynorc58c5142013-07-09 19:35:14 -07001294 int i;
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -08001295 struct lmk_target target;
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -07001296 char minfree_str[PROPERTY_VALUE_MAX];
1297 char *pstr = minfree_str;
1298 char *pend = minfree_str + sizeof(minfree_str);
1299 static struct timespec last_req_tm;
1300 struct timespec curr_tm;
Todd Poynorc58c5142013-07-09 19:35:14 -07001301
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -07001302 if (ntargets < 1 || ntargets > (int)ARRAY_SIZE(lowmem_adj))
Todd Poynorc58c5142013-07-09 19:35:14 -07001303 return;
1304
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -07001305 /*
1306 * Ratelimit minfree updates to once per TARGET_UPDATE_MIN_INTERVAL_MS
1307 * to prevent DoS attacks
1308 */
1309 if (clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm) != 0) {
1310 ALOGE("Failed to get current time");
1311 return;
1312 }
1313
1314 if (get_time_diff_ms(&last_req_tm, &curr_tm) <
1315 TARGET_UPDATE_MIN_INTERVAL_MS) {
1316 ALOGE("Ignoring frequent updated to lmkd limits");
1317 return;
1318 }
1319
1320 last_req_tm = curr_tm;
1321
Todd Poynorc58c5142013-07-09 19:35:14 -07001322 for (i = 0; i < ntargets; i++) {
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -08001323 lmkd_pack_get_target(packet, i, &target);
1324 lowmem_minfree[i] = target.minfree;
1325 lowmem_adj[i] = target.oom_adj_score;
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -07001326
1327 pstr += snprintf(pstr, pend - pstr, "%d:%d,", target.minfree,
1328 target.oom_adj_score);
1329 if (pstr >= pend) {
1330 /* if no more space in the buffer then terminate the loop */
1331 pstr = pend;
1332 break;
1333 }
Todd Poynorc58c5142013-07-09 19:35:14 -07001334 }
1335
1336 lowmem_targets_size = ntargets;
1337
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -07001338 /* Override the last extra comma */
1339 pstr[-1] = '\0';
1340 property_set("sys.lmk.minfree_levels", minfree_str);
1341
Robert Benea7878c9b2017-09-11 16:53:28 -07001342 if (has_inkernel_module) {
Todd Poynorc58c5142013-07-09 19:35:14 -07001343 char minfreestr[128];
1344 char killpriostr[128];
1345
1346 minfreestr[0] = '\0';
1347 killpriostr[0] = '\0';
1348
1349 for (i = 0; i < lowmem_targets_size; i++) {
1350 char val[40];
1351
1352 if (i) {
1353 strlcat(minfreestr, ",", sizeof(minfreestr));
1354 strlcat(killpriostr, ",", sizeof(killpriostr));
1355 }
1356
Robert Benea7878c9b2017-09-11 16:53:28 -07001357 snprintf(val, sizeof(val), "%d", use_inkernel_interface ? lowmem_minfree[i] : 0);
Todd Poynorc58c5142013-07-09 19:35:14 -07001358 strlcat(minfreestr, val, sizeof(minfreestr));
Robert Benea7878c9b2017-09-11 16:53:28 -07001359 snprintf(val, sizeof(val), "%d", use_inkernel_interface ? lowmem_adj[i] : 0);
Todd Poynorc58c5142013-07-09 19:35:14 -07001360 strlcat(killpriostr, val, sizeof(killpriostr));
1361 }
1362
Suren Baghdasaryanf584fff2018-03-20 13:53:17 -07001363 writefilestring(INKERNEL_MINFREE_PATH, minfreestr, true);
1364 writefilestring(INKERNEL_ADJ_PATH, killpriostr, true);
Todd Poynorc58c5142013-07-09 19:35:14 -07001365 }
1366}
1367
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08001368static void ctrl_command_handler(int dsock_idx) {
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -08001369 LMKD_CTRL_PACKET packet;
Suren Baghdasaryan945658a2019-10-18 11:16:52 -07001370 struct ucred cred;
Todd Poynorc58c5142013-07-09 19:35:14 -07001371 int len;
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -08001372 enum lmk_cmd cmd;
Todd Poynorc58c5142013-07-09 19:35:14 -07001373 int nargs;
1374 int targets;
Suren Baghdasaryana7394ea2018-10-12 11:07:40 -07001375 int kill_cnt;
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07001376 int result;
Todd Poynorc58c5142013-07-09 19:35:14 -07001377
Suren Baghdasaryan945658a2019-10-18 11:16:52 -07001378 len = ctrl_data_read(dsock_idx, (char *)packet, CTRL_PACKET_MAX_SIZE, &cred);
Todd Poynorc58c5142013-07-09 19:35:14 -07001379 if (len <= 0)
1380 return;
1381
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -08001382 if (len < (int)sizeof(int)) {
1383 ALOGE("Wrong control socket read length len=%d", len);
1384 return;
1385 }
1386
1387 cmd = lmkd_pack_get_cmd(packet);
Todd Poynorc58c5142013-07-09 19:35:14 -07001388 nargs = len / sizeof(int) - 1;
1389 if (nargs < 0)
1390 goto wronglen;
1391
Todd Poynorc58c5142013-07-09 19:35:14 -07001392 switch(cmd) {
1393 case LMK_TARGET:
1394 targets = nargs / 2;
1395 if (nargs & 0x1 || targets > (int)ARRAY_SIZE(lowmem_adj))
1396 goto wronglen;
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -08001397 cmd_target(targets, packet);
Todd Poynorc58c5142013-07-09 19:35:14 -07001398 break;
1399 case LMK_PROCPRIO:
Suren Baghdasaryana93503e2019-10-22 17:12:01 -07001400 /* process type field is optional for backward compatibility */
1401 if (nargs < 3 || nargs > 4)
Todd Poynorc58c5142013-07-09 19:35:14 -07001402 goto wronglen;
Suren Baghdasaryana93503e2019-10-22 17:12:01 -07001403 cmd_procprio(packet, nargs, &cred);
Todd Poynorc58c5142013-07-09 19:35:14 -07001404 break;
1405 case LMK_PROCREMOVE:
1406 if (nargs != 1)
1407 goto wronglen;
Suren Baghdasaryan945658a2019-10-18 11:16:52 -07001408 cmd_procremove(packet, &cred);
Todd Poynorc58c5142013-07-09 19:35:14 -07001409 break;
Suren Baghdasaryan83df0082018-10-10 14:17:17 -07001410 case LMK_PROCPURGE:
1411 if (nargs != 0)
1412 goto wronglen;
Suren Baghdasaryan945658a2019-10-18 11:16:52 -07001413 cmd_procpurge(&cred);
Suren Baghdasaryan83df0082018-10-10 14:17:17 -07001414 break;
Suren Baghdasaryana7394ea2018-10-12 11:07:40 -07001415 case LMK_GETKILLCNT:
1416 if (nargs != 2)
1417 goto wronglen;
1418 kill_cnt = cmd_getkillcnt(packet);
1419 len = lmkd_pack_set_getkillcnt_repl(packet, kill_cnt);
1420 if (ctrl_data_write(dsock_idx, (char *)packet, len) != len)
1421 return;
1422 break;
Suren Baghdasaryan36baf442019-12-23 11:37:34 -08001423 case LMK_SUBSCRIBE:
1424 if (nargs != 1)
1425 goto wronglen;
1426 cmd_subscribe(dsock_idx, packet);
1427 break;
Jing Ji5c480962019-12-04 09:22:05 -08001428 case LMK_PROCKILL:
1429 /* This command code is NOT expected at all */
1430 ALOGE("Received unexpected command code %d", cmd);
1431 break;
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07001432 case LMK_UPDATE_PROPS:
1433 if (nargs != 0)
1434 goto wronglen;
1435 update_props();
1436 if (!use_inkernel_interface) {
1437 /* Reinitialize monitors to apply new settings */
1438 destroy_monitors();
1439 result = init_monitors() ? 0 : -1;
1440 } else {
1441 result = 0;
1442 }
1443 len = lmkd_pack_set_update_props_repl(packet, result);
1444 if (ctrl_data_write(dsock_idx, (char *)packet, len) != len) {
1445 ALOGE("Failed to report operation results");
1446 }
1447 if (!result) {
1448 ALOGI("Properties reinitilized");
1449 } else {
1450 /* New settings can't be supported, crash to be restarted */
1451 ALOGE("New configuration is not supported. Exiting...");
1452 exit(1);
1453 }
1454 break;
Todd Poynorc58c5142013-07-09 19:35:14 -07001455 default:
1456 ALOGE("Received unknown command code %d", cmd);
1457 return;
1458 }
1459
1460 return;
1461
1462wronglen:
1463 ALOGE("Wrong control socket read length cmd=%d len=%d", cmd, len);
1464}
1465
Suren Baghdasaryane12a0672019-07-15 14:50:49 -07001466static void ctrl_data_handler(int data, uint32_t events,
1467 struct polling_params *poll_params __unused) {
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08001468 if (events & EPOLLIN) {
1469 ctrl_command_handler(data);
Todd Poynorc58c5142013-07-09 19:35:14 -07001470 }
1471}
1472
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08001473static int get_free_dsock() {
1474 for (int i = 0; i < MAX_DATA_CONN; i++) {
1475 if (data_sock[i].sock < 0) {
1476 return i;
1477 }
1478 }
1479 return -1;
1480}
Todd Poynorc58c5142013-07-09 19:35:14 -07001481
Suren Baghdasaryane12a0672019-07-15 14:50:49 -07001482static void ctrl_connect_handler(int data __unused, uint32_t events __unused,
1483 struct polling_params *poll_params __unused) {
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08001484 struct epoll_event epev;
1485 int free_dscock_idx = get_free_dsock();
1486
1487 if (free_dscock_idx < 0) {
1488 /*
1489 * Number of data connections exceeded max supported. This should not
1490 * happen but if it does we drop all existing connections and accept
1491 * the new one. This prevents inactive connections from monopolizing
1492 * data socket and if we drop ActivityManager connection it will
1493 * immediately reconnect.
1494 */
1495 for (int i = 0; i < MAX_DATA_CONN; i++) {
1496 ctrl_data_close(i);
1497 }
1498 free_dscock_idx = 0;
Todd Poynorc58c5142013-07-09 19:35:14 -07001499 }
1500
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08001501 data_sock[free_dscock_idx].sock = accept(ctrl_sock.sock, NULL, NULL);
1502 if (data_sock[free_dscock_idx].sock < 0) {
Todd Poynorc58c5142013-07-09 19:35:14 -07001503 ALOGE("lmkd control socket accept failed; errno=%d", errno);
1504 return;
1505 }
1506
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08001507 ALOGI("lmkd data connection established");
1508 /* use data to store data connection idx */
1509 data_sock[free_dscock_idx].handler_info.data = free_dscock_idx;
1510 data_sock[free_dscock_idx].handler_info.handler = ctrl_data_handler;
Suren Baghdasaryan36baf442019-12-23 11:37:34 -08001511 data_sock[free_dscock_idx].async_event_mask = 0;
Todd Poynorc58c5142013-07-09 19:35:14 -07001512 epev.events = EPOLLIN;
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08001513 epev.data.ptr = (void *)&(data_sock[free_dscock_idx].handler_info);
1514 if (epoll_ctl(epollfd, EPOLL_CTL_ADD, data_sock[free_dscock_idx].sock, &epev) == -1) {
Todd Poynorc58c5142013-07-09 19:35:14 -07001515 ALOGE("epoll_ctl for data connection socket failed; errno=%d", errno);
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08001516 ctrl_data_close(free_dscock_idx);
Todd Poynorc58c5142013-07-09 19:35:14 -07001517 return;
1518 }
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08001519 maxevents++;
Todd Poynorc58c5142013-07-09 19:35:14 -07001520}
1521
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001522/*
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07001523 * /proc/zoneinfo parsing routines
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001524 * Expected file format is:
1525 *
1526 * Node <node_id>, zone <zone_name>
1527 * (
1528 * per-node stats
1529 * (<per-node field name> <value>)+
1530 * )?
1531 * (pages free <value>
1532 * (<per-zone field name> <value>)+
1533 * pagesets
1534 * (<unused fields>)*
1535 * )+
1536 * ...
1537 */
1538static void zoneinfo_parse_protection(char *buf, struct zoneinfo_zone *zone) {
1539 int zone_idx;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001540 int64_t max = 0;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001541 char *save_ptr;
1542
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001543 for (buf = strtok_r(buf, "(), ", &save_ptr), zone_idx = 0;
1544 buf && zone_idx < MAX_NR_ZONES;
1545 buf = strtok_r(NULL, "), ", &save_ptr), zone_idx++) {
1546 long long zoneval = strtoll(buf, &buf, 0);
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001547 if (zoneval > max) {
1548 max = (zoneval > INT64_MAX) ? INT64_MAX : zoneval;
1549 }
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001550 zone->protection[zone_idx] = zoneval;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001551 }
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001552 zone->max_protection = max;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001553}
1554
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001555static int zoneinfo_parse_zone(char **buf, struct zoneinfo_zone *zone) {
1556 for (char *line = strtok_r(NULL, "\n", buf); line;
1557 line = strtok_r(NULL, "\n", buf)) {
1558 char *cp;
1559 char *ap;
1560 char *save_ptr;
1561 int64_t val;
1562 int field_idx;
1563 enum field_match_result match_res;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001564
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001565 cp = strtok_r(line, " ", &save_ptr);
1566 if (!cp) {
1567 return false;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001568 }
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001569
1570 field_idx = find_field(cp, zoneinfo_zone_spec_field_names, ZI_ZONE_SPEC_FIELD_COUNT);
1571 if (field_idx >= 0) {
1572 /* special field */
1573 if (field_idx == ZI_ZONE_SPEC_PAGESETS) {
1574 /* no mode fields we are interested in */
1575 return true;
1576 }
1577
1578 /* protection field */
1579 ap = strtok_r(NULL, ")", &save_ptr);
1580 if (ap) {
1581 zoneinfo_parse_protection(ap, zone);
1582 }
1583 continue;
1584 }
1585
1586 ap = strtok_r(NULL, " ", &save_ptr);
1587 if (!ap) {
1588 continue;
1589 }
1590
1591 match_res = match_field(cp, ap, zoneinfo_zone_field_names, ZI_ZONE_FIELD_COUNT,
1592 &val, &field_idx);
1593 if (match_res == PARSE_FAIL) {
1594 return false;
1595 }
1596 if (match_res == PARSE_SUCCESS) {
1597 zone->fields.arr[field_idx] = val;
1598 }
1599 if (field_idx == ZI_ZONE_PRESENT && val == 0) {
1600 /* zone is not populated, stop parsing it */
1601 return true;
1602 }
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001603 }
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001604 return false;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001605}
1606
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001607static int zoneinfo_parse_node(char **buf, struct zoneinfo_node *node) {
1608 int fields_to_match = ZI_NODE_FIELD_COUNT;
1609
1610 for (char *line = strtok_r(NULL, "\n", buf); line;
1611 line = strtok_r(NULL, "\n", buf)) {
1612 char *cp;
1613 char *ap;
1614 char *save_ptr;
1615 int64_t val;
1616 int field_idx;
1617 enum field_match_result match_res;
1618
1619 cp = strtok_r(line, " ", &save_ptr);
1620 if (!cp) {
1621 return false;
1622 }
1623
1624 ap = strtok_r(NULL, " ", &save_ptr);
1625 if (!ap) {
1626 return false;
1627 }
1628
1629 match_res = match_field(cp, ap, zoneinfo_node_field_names, ZI_NODE_FIELD_COUNT,
1630 &val, &field_idx);
1631 if (match_res == PARSE_FAIL) {
1632 return false;
1633 }
1634 if (match_res == PARSE_SUCCESS) {
1635 node->fields.arr[field_idx] = val;
1636 fields_to_match--;
1637 if (!fields_to_match) {
1638 return true;
1639 }
1640 }
1641 }
1642 return false;
1643}
1644
1645static int zoneinfo_parse(struct zoneinfo *zi) {
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001646 static struct reread_data file_data = {
1647 .filename = ZONEINFO_PATH,
1648 .fd = -1,
1649 };
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -07001650 char *buf;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001651 char *save_ptr;
1652 char *line;
Greg Kaiser259984f2019-10-02 07:07:32 -07001653 char zone_name[LINE_MAX + 1];
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001654 struct zoneinfo_node *node = NULL;
1655 int node_idx = 0;
1656 int zone_idx = 0;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001657
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001658 memset(zi, 0, sizeof(struct zoneinfo));
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001659
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -07001660 if ((buf = reread_file(&file_data)) == NULL) {
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001661 return -1;
1662 }
1663
1664 for (line = strtok_r(buf, "\n", &save_ptr); line;
1665 line = strtok_r(NULL, "\n", &save_ptr)) {
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001666 int node_id;
1667 if (sscanf(line, "Node %d, zone %" STRINGIFY(LINE_MAX) "s", &node_id, zone_name) == 2) {
1668 if (!node || node->id != node_id) {
1669 /* new node is found */
1670 if (node) {
1671 node->zone_count = zone_idx + 1;
1672 node_idx++;
1673 if (node_idx == MAX_NR_NODES) {
1674 /* max node count exceeded */
1675 ALOGE("%s parse error", file_data.filename);
1676 return -1;
1677 }
1678 }
1679 node = &zi->nodes[node_idx];
1680 node->id = node_id;
1681 zone_idx = 0;
1682 if (!zoneinfo_parse_node(&save_ptr, node)) {
1683 ALOGE("%s parse error", file_data.filename);
1684 return -1;
1685 }
1686 } else {
1687 /* new zone is found */
1688 zone_idx++;
1689 }
1690 if (!zoneinfo_parse_zone(&save_ptr, &node->zones[zone_idx])) {
1691 ALOGE("%s parse error", file_data.filename);
1692 return -1;
1693 }
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001694 }
1695 }
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001696 if (!node) {
1697 ALOGE("%s parse error", file_data.filename);
1698 return -1;
1699 }
1700 node->zone_count = zone_idx + 1;
1701 zi->node_count = node_idx + 1;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001702
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001703 /* calculate totals fields */
1704 for (node_idx = 0; node_idx < zi->node_count; node_idx++) {
1705 node = &zi->nodes[node_idx];
1706 for (zone_idx = 0; zone_idx < node->zone_count; zone_idx++) {
1707 struct zoneinfo_zone *zone = &zi->nodes[node_idx].zones[zone_idx];
1708 zi->totalreserve_pages += zone->max_protection + zone->fields.field.high;
1709 }
1710 zi->total_inactive_file += node->fields.field.nr_inactive_file;
1711 zi->total_active_file += node->fields.field.nr_active_file;
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001712 }
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001713 return 0;
1714}
1715
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07001716/* /proc/meminfo parsing routines */
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001717static bool meminfo_parse_line(char *line, union meminfo *mi) {
1718 char *cp = line;
1719 char *ap;
1720 char *save_ptr;
1721 int64_t val;
1722 int field_idx;
1723 enum field_match_result match_res;
1724
1725 cp = strtok_r(line, " ", &save_ptr);
1726 if (!cp) {
1727 return false;
1728 }
1729
1730 ap = strtok_r(NULL, " ", &save_ptr);
1731 if (!ap) {
1732 return false;
1733 }
1734
1735 match_res = match_field(cp, ap, meminfo_field_names, MI_FIELD_COUNT,
1736 &val, &field_idx);
1737 if (match_res == PARSE_SUCCESS) {
1738 mi->arr[field_idx] = val / page_k;
1739 }
1740 return (match_res != PARSE_FAIL);
1741}
1742
1743static int meminfo_parse(union meminfo *mi) {
1744 static struct reread_data file_data = {
1745 .filename = MEMINFO_PATH,
1746 .fd = -1,
1747 };
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -07001748 char *buf;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001749 char *save_ptr;
1750 char *line;
1751
1752 memset(mi, 0, sizeof(union meminfo));
1753
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -07001754 if ((buf = reread_file(&file_data)) == NULL) {
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001755 return -1;
1756 }
1757
1758 for (line = strtok_r(buf, "\n", &save_ptr); line;
1759 line = strtok_r(NULL, "\n", &save_ptr)) {
1760 if (!meminfo_parse_line(line, mi)) {
1761 ALOGE("%s parse error", file_data.filename);
1762 return -1;
1763 }
1764 }
1765 mi->field.nr_file_pages = mi->field.cached + mi->field.swap_cached +
1766 mi->field.buffers;
1767
1768 return 0;
1769}
1770
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07001771/* /proc/vmstat parsing routines */
1772static bool vmstat_parse_line(char *line, union vmstat *vs) {
1773 char *cp;
1774 char *ap;
1775 char *save_ptr;
1776 int64_t val;
1777 int field_idx;
1778 enum field_match_result match_res;
1779
1780 cp = strtok_r(line, " ", &save_ptr);
1781 if (!cp) {
1782 return false;
1783 }
1784
1785 ap = strtok_r(NULL, " ", &save_ptr);
1786 if (!ap) {
1787 return false;
1788 }
1789
1790 match_res = match_field(cp, ap, vmstat_field_names, VS_FIELD_COUNT,
1791 &val, &field_idx);
1792 if (match_res == PARSE_SUCCESS) {
1793 vs->arr[field_idx] = val;
1794 }
1795 return (match_res != PARSE_FAIL);
1796}
1797
1798static int vmstat_parse(union vmstat *vs) {
1799 static struct reread_data file_data = {
1800 .filename = VMSTAT_PATH,
1801 .fd = -1,
1802 };
1803 char *buf;
1804 char *save_ptr;
1805 char *line;
1806
1807 memset(vs, 0, sizeof(union vmstat));
1808
1809 if ((buf = reread_file(&file_data)) == NULL) {
1810 return -1;
1811 }
1812
1813 for (line = strtok_r(buf, "\n", &save_ptr); line;
1814 line = strtok_r(NULL, "\n", &save_ptr)) {
1815 if (!vmstat_parse_line(line, vs)) {
1816 ALOGE("%s parse error", file_data.filename);
1817 return -1;
1818 }
1819 }
1820
1821 return 0;
1822}
1823
Suren Baghdasaryand7b4fcb2020-07-23 18:00:43 -07001824enum wakeup_reason {
1825 Event,
1826 Polling
1827};
1828
1829struct wakeup_info {
1830 struct timespec wakeup_tm;
1831 struct timespec prev_wakeup_tm;
1832 struct timespec last_event_tm;
1833 int wakeups_since_event;
1834 int skipped_wakeups;
1835};
1836
1837/*
1838 * After the initial memory pressure event is received lmkd schedules periodic wakeups to check
1839 * the memory conditions and kill if needed (polling). This is done because pressure events are
1840 * rate-limited and memory conditions can change in between events. Therefore after the initial
1841 * event there might be multiple wakeups. This function records the wakeup information such as the
1842 * timestamps of the last event and the last wakeup, the number of wakeups since the last event
1843 * and how many of those wakeups were skipped (some wakeups are skipped if previously killed
1844 * process is still freeing its memory).
1845 */
1846static void record_wakeup_time(struct timespec *tm, enum wakeup_reason reason,
1847 struct wakeup_info *wi) {
1848 wi->prev_wakeup_tm = wi->wakeup_tm;
1849 wi->wakeup_tm = *tm;
1850 if (reason == Event) {
1851 wi->last_event_tm = *tm;
1852 wi->wakeups_since_event = 0;
1853 wi->skipped_wakeups = 0;
1854 } else {
1855 wi->wakeups_since_event++;
1856 }
1857}
1858
Ioannis Ilkos279268a2020-08-01 10:50:40 +01001859static void killinfo_log(struct proc* procp, int min_oom_score, int rss_kb,
Ioannis Ilkos48848902021-02-18 19:53:33 +00001860 int swap_kb, int kill_reason, union meminfo *mi,
Suren Baghdasaryand7b4fcb2020-07-23 18:00:43 -07001861 struct wakeup_info *wi, struct timespec *tm) {
Suren Baghdasaryan12cacae2019-09-16 12:06:30 -07001862 /* log process information */
1863 android_log_write_int32(ctx, procp->pid);
1864 android_log_write_int32(ctx, procp->uid);
1865 android_log_write_int32(ctx, procp->oomadj);
1866 android_log_write_int32(ctx, min_oom_score);
Ioannis Ilkos279268a2020-08-01 10:50:40 +01001867 android_log_write_int32(ctx, (int32_t)min(rss_kb, INT32_MAX));
Suren Baghdasaryan12cacae2019-09-16 12:06:30 -07001868 android_log_write_int32(ctx, kill_reason);
1869
1870 /* log meminfo fields */
Suren Baghdasaryan08bfa982018-07-26 16:34:27 -07001871 for (int field_idx = 0; field_idx < MI_FIELD_COUNT; field_idx++) {
1872 android_log_write_int32(ctx, (int32_t)min(mi->arr[field_idx] * page_k, INT32_MAX));
1873 }
1874
Suren Baghdasaryand7b4fcb2020-07-23 18:00:43 -07001875 /* log lmkd wakeup information */
1876 android_log_write_int32(ctx, (int32_t)get_time_diff_ms(&wi->last_event_tm, tm));
1877 android_log_write_int32(ctx, (int32_t)get_time_diff_ms(&wi->prev_wakeup_tm, tm));
1878 android_log_write_int32(ctx, wi->wakeups_since_event);
1879 android_log_write_int32(ctx, wi->skipped_wakeups);
Ioannis Ilkos282437f2021-03-04 17:50:05 +00001880 android_log_write_int32(ctx, (int32_t)min(swap_kb, INT32_MAX));
Suren Baghdasaryand7b4fcb2020-07-23 18:00:43 -07001881
Suren Baghdasaryan08bfa982018-07-26 16:34:27 -07001882 android_log_write_list(ctx, LOG_ID_EVENTS);
1883 android_log_reset(ctx);
1884}
1885
Todd Poynorc58c5142013-07-09 19:35:14 -07001886static struct proc *proc_adj_lru(int oomadj) {
1887 return (struct proc *)adjslot_tail(&procadjslot_list[ADJTOSLOT(oomadj)]);
1888}
1889
Suren Baghdasaryaneb7c5492017-12-08 13:17:06 -08001890static struct proc *proc_get_heaviest(int oomadj) {
1891 struct adjslot_list *head = &procadjslot_list[ADJTOSLOT(oomadj)];
1892 struct adjslot_list *curr = head->next;
1893 struct proc *maxprocp = NULL;
1894 int maxsize = 0;
1895 while (curr != head) {
1896 int pid = ((struct proc *)curr)->pid;
1897 int tasksize = proc_get_size(pid);
1898 if (tasksize <= 0) {
1899 struct adjslot_list *next = curr->next;
1900 pid_remove(pid);
1901 curr = next;
1902 } else {
1903 if (tasksize > maxsize) {
1904 maxsize = tasksize;
1905 maxprocp = (struct proc *)curr;
1906 }
1907 curr = curr->next;
1908 }
1909 }
1910 return maxprocp;
1911}
1912
Wei Wangf1ee2e12018-11-21 00:11:44 -08001913static void set_process_group_and_prio(int pid, SchedPolicy sp, int prio) {
1914 DIR* d;
1915 char proc_path[PATH_MAX];
1916 struct dirent* de;
1917
1918 snprintf(proc_path, sizeof(proc_path), "/proc/%d/task", pid);
1919 if (!(d = opendir(proc_path))) {
1920 ALOGW("Failed to open %s; errno=%d: process pid(%d) might have died", proc_path, errno,
1921 pid);
1922 return;
1923 }
1924
1925 while ((de = readdir(d))) {
1926 int t_pid;
1927
1928 if (de->d_name[0] == '.') continue;
1929 t_pid = atoi(de->d_name);
1930
1931 if (!t_pid) {
1932 ALOGW("Failed to get t_pid for '%s' of pid(%d)", de->d_name, pid);
1933 continue;
1934 }
1935
1936 if (setpriority(PRIO_PROCESS, t_pid, prio) && errno != ESRCH) {
1937 ALOGW("Unable to raise priority of killing t_pid (%d): errno=%d", t_pid, errno);
1938 }
1939
1940 if (set_cpuset_policy(t_pid, sp)) {
1941 ALOGW("Failed to set_cpuset_policy on pid(%d) t_pid(%d) to %d", pid, t_pid, (int)sp);
1942 continue;
1943 }
1944 }
1945 closedir(d);
1946}
1947
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07001948static bool is_kill_pending(void) {
1949 char buf[24];
1950
1951 if (last_kill_pid_or_fd < 0) {
1952 return false;
1953 }
1954
1955 if (pidfd_supported) {
1956 return true;
1957 }
1958
1959 /* when pidfd is not supported base the decision on /proc/<pid> existence */
1960 snprintf(buf, sizeof(buf), "/proc/%d/", last_kill_pid_or_fd);
1961 if (access(buf, F_OK) == 0) {
1962 return true;
1963 }
1964
1965 return false;
1966}
1967
1968static bool is_waiting_for_kill(void) {
1969 return pidfd_supported && last_kill_pid_or_fd >= 0;
1970}
1971
1972static void stop_wait_for_proc_kill(bool finished) {
1973 struct epoll_event epev;
1974
1975 if (last_kill_pid_or_fd < 0) {
1976 return;
1977 }
1978
1979 if (debug_process_killing) {
1980 struct timespec curr_tm;
1981
1982 if (clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm) != 0) {
1983 /*
1984 * curr_tm is used here merely to report kill duration, so this failure is not fatal.
1985 * Log an error and continue.
1986 */
1987 ALOGE("Failed to get current time");
1988 }
1989
1990 if (finished) {
1991 ALOGI("Process got killed in %ldms",
1992 get_time_diff_ms(&last_kill_tm, &curr_tm));
1993 } else {
1994 ALOGI("Stop waiting for process kill after %ldms",
1995 get_time_diff_ms(&last_kill_tm, &curr_tm));
1996 }
1997 }
1998
1999 if (pidfd_supported) {
2000 /* unregister fd */
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07002001 if (epoll_ctl(epollfd, EPOLL_CTL_DEL, last_kill_pid_or_fd, &epev)) {
2002 // Log an error and keep going
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002003 ALOGE("epoll_ctl for last killed process failed; errno=%d", errno);
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002004 }
2005 maxevents--;
2006 close(last_kill_pid_or_fd);
2007 }
2008
2009 last_kill_pid_or_fd = -1;
2010}
2011
2012static void kill_done_handler(int data __unused, uint32_t events __unused,
2013 struct polling_params *poll_params) {
2014 stop_wait_for_proc_kill(true);
2015 poll_params->update = POLLING_RESUME;
2016}
2017
Suren Baghdasaryana10157c2019-07-19 10:55:39 -07002018static void start_wait_for_proc_kill(int pid_or_fd) {
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002019 static struct event_handler_info kill_done_hinfo = { 0, kill_done_handler };
2020 struct epoll_event epev;
2021
2022 if (last_kill_pid_or_fd >= 0) {
2023 /* Should not happen but if it does we should stop previous wait */
2024 ALOGE("Attempt to wait for a kill while another wait is in progress");
2025 stop_wait_for_proc_kill(false);
2026 }
2027
Suren Baghdasaryana10157c2019-07-19 10:55:39 -07002028 last_kill_pid_or_fd = pid_or_fd;
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002029
Suren Baghdasaryana10157c2019-07-19 10:55:39 -07002030 if (!pidfd_supported) {
2031 /* If pidfd is not supported just store PID and exit */
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002032 return;
2033 }
2034
2035 epev.events = EPOLLIN;
2036 epev.data.ptr = (void *)&kill_done_hinfo;
2037 if (epoll_ctl(epollfd, EPOLL_CTL_ADD, last_kill_pid_or_fd, &epev) != 0) {
2038 ALOGE("epoll_ctl for last kill failed; errno=%d", errno);
2039 close(last_kill_pid_or_fd);
2040 last_kill_pid_or_fd = -1;
2041 return;
2042 }
2043 maxevents++;
2044}
Tim Murraya79ec0f2018-10-25 17:05:41 -07002045
Ioannis Ilkos279268a2020-08-01 10:50:40 +01002046/* Kill one process specified by procp. Returns the size (in pages) of the process killed */
Suren Baghdasaryan3cc1f132020-09-09 20:19:02 -07002047static int kill_one_process(struct proc* procp, int min_oom_score, enum kill_reasons kill_reason,
Suren Baghdasaryand7b4fcb2020-07-23 18:00:43 -07002048 const char *kill_desc, union meminfo *mi, struct wakeup_info *wi,
2049 struct timespec *tm) {
Colin Cross3d57a512014-07-14 12:39:56 -07002050 int pid = procp->pid;
Suren Baghdasaryana10157c2019-07-19 10:55:39 -07002051 int pidfd = procp->pidfd;
Colin Cross3d57a512014-07-14 12:39:56 -07002052 uid_t uid = procp->uid;
2053 char *taskname;
Colin Cross3d57a512014-07-14 12:39:56 -07002054 int r;
Suren Baghdasaryan8b00c6d2018-10-12 11:28:33 -07002055 int result = -1;
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07002056 struct memory_stat *mem_st;
Suren Baghdasaryan3cc1f132020-09-09 20:19:02 -07002057 struct kill_stat kill_st;
Ioannis Ilkos279268a2020-08-01 10:50:40 +01002058 int64_t tgid;
2059 int64_t rss_kb;
2060 int64_t swap_kb;
2061 char buf[PAGE_SIZE];
Rajeev Kumar4aba9152018-01-31 17:54:56 -08002062
Ioannis Ilkos279268a2020-08-01 10:50:40 +01002063 if (!read_proc_status(pid, buf, sizeof(buf))) {
2064 goto out;
2065 }
2066 if (!parse_status_tag(buf, PROC_STATUS_TGID_FIELD, &tgid)) {
2067 ALOGE("Unable to parse tgid from /proc/%d/status", pid);
2068 goto out;
2069 }
2070 if (tgid != pid) {
2071 ALOGE("Possible pid reuse detected (pid %d, tgid %" PRId64 ")!", pid, tgid);
2072 goto out;
2073 }
2074 // Zombie processes will not have RSS / Swap fields.
2075 if (!parse_status_tag(buf, PROC_STATUS_RSS_FIELD, &rss_kb)) {
2076 goto out;
2077 }
2078 if (!parse_status_tag(buf, PROC_STATUS_SWAP_FIELD, &swap_kb)) {
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -07002079 goto out;
2080 }
2081
Suren Baghdasaryan632f1c52019-10-04 16:06:55 -07002082 taskname = proc_get_name(pid, buf, sizeof(buf));
Ioannis Ilkos279268a2020-08-01 10:50:40 +01002083 // taskname will point inside buf, do not reuse buf onwards.
Colin Cross3d57a512014-07-14 12:39:56 -07002084 if (!taskname) {
Suren Baghdasaryan8b00c6d2018-10-12 11:28:33 -07002085 goto out;
Colin Cross3d57a512014-07-14 12:39:56 -07002086 }
2087
Ioannis Ilkos279268a2020-08-01 10:50:40 +01002088 mem_st = stats_read_memory_stat(per_app_memcg, pid, uid, rss_kb * 1024, swap_kb * 1024);
Rajeev Kumar4aba9152018-01-31 17:54:56 -08002089
Suren Baghdasaryan03e19872018-01-04 10:43:58 -08002090 TRACE_KILL_START(pid);
2091
Mark Salyzyna00ccd82018-04-09 09:50:32 -07002092 /* CAP_KILL required */
Suren Baghdasaryana10157c2019-07-19 10:55:39 -07002093 if (pidfd < 0) {
2094 start_wait_for_proc_kill(pid);
2095 r = kill(pid, SIGKILL);
2096 } else {
2097 start_wait_for_proc_kill(pidfd);
Josh Gao84623be2021-03-18 17:16:08 -07002098 r = pidfd_send_signal(pidfd, SIGKILL, NULL, 0);
Suren Baghdasaryana10157c2019-07-19 10:55:39 -07002099 }
Wei Wangf1ee2e12018-11-21 00:11:44 -08002100
Suren Baghdasaryanc2e05b62019-09-04 16:44:47 -07002101 TRACE_KILL_END();
2102
2103 if (r) {
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002104 stop_wait_for_proc_kill(false);
Suren Baghdasaryanc2e05b62019-09-04 16:44:47 -07002105 ALOGE("kill(%d): errno=%d", pid, errno);
2106 /* Delete process record even when we fail to kill so that we don't get stuck on it */
2107 goto out;
2108 }
2109
Wei Wangf1ee2e12018-11-21 00:11:44 -08002110 set_process_group_and_prio(pid, SP_FOREGROUND, ANDROID_PRIORITY_HIGHEST);
2111
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002112 last_kill_tm = *tm;
2113
Suren Baghdasaryana7394ea2018-10-12 11:07:40 -07002114 inc_killcnt(procp->oomadj);
Suren Baghdasaryan12cacae2019-09-16 12:06:30 -07002115
Ioannis Ilkos48848902021-02-18 19:53:33 +00002116 killinfo_log(procp, min_oom_score, rss_kb, swap_kb, kill_reason, mi, wi, tm);
Suren Baghdasaryan12cacae2019-09-16 12:06:30 -07002117
2118 if (kill_desc) {
Ioannis Ilkos48848902021-02-18 19:53:33 +00002119 ALOGI("Kill '%s' (%d), uid %d, oom_score_adj %d to free %" PRId64 "kB rss, %" PRId64
2120 "kB swap; reason: %s", taskname, pid, uid, procp->oomadj, rss_kb, swap_kb, kill_desc);
Suren Baghdasaryan89454e62019-07-15 15:50:17 -07002121 } else {
Ioannis Ilkos48848902021-02-18 19:53:33 +00002122 ALOGI("Kill '%s' (%d), uid %d, oom_score_adj %d to free %" PRId64 "kB rss, %" PRId64
2123 "kb swap", taskname, pid, uid, procp->oomadj, rss_kb, swap_kb);
Suren Baghdasaryan89454e62019-07-15 15:50:17 -07002124 }
Colin Cross3d57a512014-07-14 12:39:56 -07002125
Suren Baghdasaryan3cc1f132020-09-09 20:19:02 -07002126 kill_st.uid = static_cast<int32_t>(uid);
2127 kill_st.taskname = taskname;
2128 kill_st.kill_reason = kill_reason;
2129 kill_st.oom_score = procp->oomadj;
2130 kill_st.min_oom_score = min_oom_score;
2131 kill_st.free_mem_kb = mi->field.nr_free_pages * page_k;
2132 kill_st.free_swap_kb = mi->field.free_swap * page_k;
2133 stats_write_lmk_kill_occurred(&kill_st, mem_st);
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07002134
Jing Ji5c480962019-12-04 09:22:05 -08002135 ctrl_data_write_lmk_kill_occurred((pid_t)pid, uid);
2136
Ioannis Ilkos279268a2020-08-01 10:50:40 +01002137 result = rss_kb / page_k;
Mark Salyzyn1d5fdf32018-02-04 15:27:23 -08002138
Suren Baghdasaryan8b00c6d2018-10-12 11:28:33 -07002139out:
2140 /*
2141 * WARNING: After pid_remove() procp is freed and can't be used!
2142 * Therefore placed at the end of the function.
2143 */
2144 pid_remove(pid);
2145 return result;
Colin Cross3d57a512014-07-14 12:39:56 -07002146}
2147
2148/*
Chris Morin74b4df92021-02-26 00:00:35 -08002149 * Find one process to kill at or above the given oom_score_adj level.
Suren Baghdasaryan85c31b52018-10-26 11:32:15 -07002150 * Returns size of the killed process.
Colin Cross3d57a512014-07-14 12:39:56 -07002151 */
Suren Baghdasaryan3cc1f132020-09-09 20:19:02 -07002152static int find_and_kill_process(int min_score_adj, enum kill_reasons kill_reason,
2153 const char *kill_desc, union meminfo *mi,
2154 struct wakeup_info *wi, struct timespec *tm) {
Colin Cross3d57a512014-07-14 12:39:56 -07002155 int i;
Suren Baghdasaryan85c31b52018-10-26 11:32:15 -07002156 int killed_size = 0;
Yang Lu5dfffbc2018-05-15 04:59:44 +00002157 bool lmk_state_change_start = false;
Suren Baghdasaryan858e8c62021-03-03 11:05:09 -08002158 bool choose_heaviest_task = kill_heaviest_task;
Rajeev Kumar4aba9152018-01-31 17:54:56 -08002159
Chong Zhang1cd12b52015-10-14 16:19:53 -07002160 for (i = OOM_SCORE_ADJ_MAX; i >= min_score_adj; i--) {
Colin Cross3d57a512014-07-14 12:39:56 -07002161 struct proc *procp;
2162
Suren Baghdasaryan858e8c62021-03-03 11:05:09 -08002163 if (!choose_heaviest_task && i <= PERCEPTIBLE_APP_ADJ) {
2164 /*
2165 * If we have to choose a perceptible process, choose the heaviest one to
2166 * hopefully minimize the number of victims.
2167 */
2168 choose_heaviest_task = true;
2169 }
2170
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002171 while (true) {
Suren Baghdasaryan858e8c62021-03-03 11:05:09 -08002172 procp = choose_heaviest_task ?
Suren Baghdasaryan36b2c492018-04-13 11:49:54 -07002173 proc_get_heaviest(i) : proc_adj_lru(i);
Colin Cross3d57a512014-07-14 12:39:56 -07002174
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002175 if (!procp)
2176 break;
2177
Suren Baghdasaryand7b4fcb2020-07-23 18:00:43 -07002178 killed_size = kill_one_process(procp, min_score_adj, kill_reason, kill_desc,
2179 mi, wi, tm);
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002180 if (killed_size >= 0) {
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07002181 if (!lmk_state_change_start) {
Yang Lu5dfffbc2018-05-15 04:59:44 +00002182 lmk_state_change_start = true;
Muhammad Qureshied8fe842019-12-09 17:38:47 -08002183 stats_write_lmk_state_changed(
2184 android::lmkd::stats::LMK_STATE_CHANGED__STATE__START);
Yang Lu5dfffbc2018-05-15 04:59:44 +00002185 }
Suren Baghdasaryan85c31b52018-10-26 11:32:15 -07002186 break;
Colin Cross3d57a512014-07-14 12:39:56 -07002187 }
2188 }
Suren Baghdasaryan85c31b52018-10-26 11:32:15 -07002189 if (killed_size) {
2190 break;
2191 }
Colin Cross3d57a512014-07-14 12:39:56 -07002192 }
2193
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07002194 if (lmk_state_change_start) {
Muhammad Qureshied8fe842019-12-09 17:38:47 -08002195 stats_write_lmk_state_changed(android::lmkd::stats::LMK_STATE_CHANGED__STATE__STOP);
Rajeev Kumar4aba9152018-01-31 17:54:56 -08002196 }
Rajeev Kumar4aba9152018-01-31 17:54:56 -08002197
Suren Baghdasaryan85c31b52018-10-26 11:32:15 -07002198 return killed_size;
Colin Cross3d57a512014-07-14 12:39:56 -07002199}
2200
Suren Baghdasaryan87966742018-04-13 12:43:41 -07002201static int64_t get_memory_usage(struct reread_data *file_data) {
Robert Beneac72b2932017-08-21 15:18:31 -07002202 int64_t mem_usage;
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -07002203 char *buf;
Suren Baghdasaryan87966742018-04-13 12:43:41 -07002204
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -07002205 if ((buf = reread_file(file_data)) == NULL) {
Robert Beneac72b2932017-08-21 15:18:31 -07002206 return -1;
2207 }
2208
Suren Baghdasaryan87966742018-04-13 12:43:41 -07002209 if (!parse_int64(buf, &mem_usage)) {
2210 ALOGE("%s parse error", file_data->filename);
Robert Beneac72b2932017-08-21 15:18:31 -07002211 return -1;
2212 }
Robert Beneac72b2932017-08-21 15:18:31 -07002213 if (mem_usage == 0) {
2214 ALOGE("No memory!");
2215 return -1;
2216 }
2217 return mem_usage;
2218}
2219
Suren Baghdasaryane0f3dd12018-04-13 13:41:12 -07002220void record_low_pressure_levels(union meminfo *mi) {
2221 if (low_pressure_mem.min_nr_free_pages == -1 ||
2222 low_pressure_mem.min_nr_free_pages > mi->field.nr_free_pages) {
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002223 if (debug_process_killing) {
Suren Baghdasaryane0f3dd12018-04-13 13:41:12 -07002224 ALOGI("Low pressure min memory update from %" PRId64 " to %" PRId64,
2225 low_pressure_mem.min_nr_free_pages, mi->field.nr_free_pages);
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002226 }
Suren Baghdasaryane0f3dd12018-04-13 13:41:12 -07002227 low_pressure_mem.min_nr_free_pages = mi->field.nr_free_pages;
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002228 }
2229 /*
2230 * Free memory at low vmpressure events occasionally gets spikes,
2231 * possibly a stale low vmpressure event with memory already
2232 * freed up (no memory pressure should have been reported).
Suren Baghdasaryane0f3dd12018-04-13 13:41:12 -07002233 * Ignore large jumps in max_nr_free_pages that would mess up our stats.
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002234 */
Suren Baghdasaryane0f3dd12018-04-13 13:41:12 -07002235 if (low_pressure_mem.max_nr_free_pages == -1 ||
2236 (low_pressure_mem.max_nr_free_pages < mi->field.nr_free_pages &&
2237 mi->field.nr_free_pages - low_pressure_mem.max_nr_free_pages <
2238 low_pressure_mem.max_nr_free_pages * 0.1)) {
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002239 if (debug_process_killing) {
Suren Baghdasaryane0f3dd12018-04-13 13:41:12 -07002240 ALOGI("Low pressure max memory update from %" PRId64 " to %" PRId64,
2241 low_pressure_mem.max_nr_free_pages, mi->field.nr_free_pages);
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002242 }
Suren Baghdasaryane0f3dd12018-04-13 13:41:12 -07002243 low_pressure_mem.max_nr_free_pages = mi->field.nr_free_pages;
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002244 }
2245}
2246
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08002247enum vmpressure_level upgrade_level(enum vmpressure_level level) {
2248 return (enum vmpressure_level)((level < VMPRESS_LEVEL_CRITICAL) ?
2249 level + 1 : level);
2250}
2251
2252enum vmpressure_level downgrade_level(enum vmpressure_level level) {
2253 return (enum vmpressure_level)((level > VMPRESS_LEVEL_LOW) ?
2254 level - 1 : level);
2255}
2256
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002257enum zone_watermark {
2258 WMARK_MIN = 0,
2259 WMARK_LOW,
2260 WMARK_HIGH,
2261 WMARK_NONE
2262};
2263
Suren Baghdasaryan81c75b22019-08-14 09:48:35 -07002264struct zone_watermarks {
2265 long high_wmark;
2266 long low_wmark;
2267 long min_wmark;
2268};
2269
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002270/*
2271 * Returns lowest breached watermark or WMARK_NONE.
2272 */
Suren Baghdasaryan81c75b22019-08-14 09:48:35 -07002273static enum zone_watermark get_lowest_watermark(union meminfo *mi,
2274 struct zone_watermarks *watermarks)
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002275{
Suren Baghdasaryan81c75b22019-08-14 09:48:35 -07002276 int64_t nr_free_pages = mi->field.nr_free_pages - mi->field.cma_free;
2277
2278 if (nr_free_pages < watermarks->min_wmark) {
2279 return WMARK_MIN;
2280 }
2281 if (nr_free_pages < watermarks->low_wmark) {
2282 return WMARK_LOW;
2283 }
2284 if (nr_free_pages < watermarks->high_wmark) {
2285 return WMARK_HIGH;
2286 }
2287 return WMARK_NONE;
2288}
2289
2290void calc_zone_watermarks(struct zoneinfo *zi, struct zone_watermarks *watermarks) {
2291 memset(watermarks, 0, sizeof(struct zone_watermarks));
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002292
2293 for (int node_idx = 0; node_idx < zi->node_count; node_idx++) {
2294 struct zoneinfo_node *node = &zi->nodes[node_idx];
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002295 for (int zone_idx = 0; zone_idx < node->zone_count; zone_idx++) {
2296 struct zoneinfo_zone *zone = &node->zones[zone_idx];
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002297
2298 if (!zone->fields.field.present) {
2299 continue;
2300 }
2301
Suren Baghdasaryan81c75b22019-08-14 09:48:35 -07002302 watermarks->high_wmark += zone->max_protection + zone->fields.field.high;
2303 watermarks->low_wmark += zone->max_protection + zone->fields.field.low;
2304 watermarks->min_wmark += zone->max_protection + zone->fields.field.min;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002305 }
2306 }
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002307}
2308
Suren Baghdasaryan51ee4c52020-04-21 12:27:01 -07002309static int calc_swap_utilization(union meminfo *mi) {
2310 int64_t swap_used = mi->field.total_swap - mi->field.free_swap;
2311 int64_t total_swappable = mi->field.active_anon + mi->field.inactive_anon +
2312 mi->field.shmem + swap_used;
2313 return total_swappable > 0 ? (swap_used * 100) / total_swappable : 0;
2314}
2315
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002316static void mp_event_psi(int data, uint32_t events, struct polling_params *poll_params) {
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002317 enum reclaim_state {
2318 NO_RECLAIM = 0,
2319 KSWAPD_RECLAIM,
2320 DIRECT_RECLAIM,
2321 };
2322 static int64_t init_ws_refault;
Martin Liu1f72f5f2020-08-21 13:18:50 +08002323 static int64_t prev_workingset_refault;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002324 static int64_t base_file_lru;
2325 static int64_t init_pgscan_kswapd;
2326 static int64_t init_pgscan_direct;
2327 static int64_t swap_low_threshold;
2328 static bool killing;
Martin Liu1f72f5f2020-08-21 13:18:50 +08002329 static int thrashing_limit = thrashing_limit_pct;
Suren Baghdasaryan81c75b22019-08-14 09:48:35 -07002330 static struct zone_watermarks watermarks;
2331 static struct timespec wmark_update_tm;
Suren Baghdasaryand7b4fcb2020-07-23 18:00:43 -07002332 static struct wakeup_info wi;
Martin Liu1f72f5f2020-08-21 13:18:50 +08002333 static struct timespec thrashing_reset_tm;
2334 static int64_t prev_thrash_growth = 0;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002335
2336 union meminfo mi;
2337 union vmstat vs;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002338 struct timespec curr_tm;
2339 int64_t thrashing = 0;
2340 bool swap_is_low = false;
2341 enum vmpressure_level level = (enum vmpressure_level)data;
2342 enum kill_reasons kill_reason = NONE;
2343 bool cycle_after_kill = false;
2344 enum reclaim_state reclaim = NO_RECLAIM;
2345 enum zone_watermark wmark = WMARK_NONE;
Suren Baghdasaryan89454e62019-07-15 15:50:17 -07002346 char kill_desc[LINE_MAX];
Suren Baghdasaryan970a26a2019-09-19 15:27:21 -07002347 bool cut_thrashing_limit = false;
2348 int min_score_adj = 0;
Suren Baghdasaryan51ee4c52020-04-21 12:27:01 -07002349 int swap_util = 0;
Martin Liu1f72f5f2020-08-21 13:18:50 +08002350 long since_thrashing_reset_ms;
Suren Baghdasaryandc60f972020-12-14 13:38:48 -08002351 int64_t workingset_refault_file;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002352
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002353 if (clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm) != 0) {
2354 ALOGE("Failed to get current time");
2355 return;
2356 }
2357
Suren Baghdasaryand7b4fcb2020-07-23 18:00:43 -07002358 record_wakeup_time(&curr_tm, events ? Event : Polling, &wi);
2359
Suren Baghdasaryan03dccf32020-04-28 16:02:13 -07002360 bool kill_pending = is_kill_pending();
Suren Baghdasaryaned715a32020-05-11 16:31:57 -07002361 if (kill_pending && (kill_timeout_ms == 0 ||
2362 get_time_diff_ms(&last_kill_tm, &curr_tm) < static_cast<long>(kill_timeout_ms))) {
Suren Baghdasaryan03dccf32020-04-28 16:02:13 -07002363 /* Skip while still killing a process */
Suren Baghdasaryand7b4fcb2020-07-23 18:00:43 -07002364 wi.skipped_wakeups++;
Suren Baghdasaryan03dccf32020-04-28 16:02:13 -07002365 goto no_kill;
2366 }
2367 /*
2368 * Process is dead or kill timeout is over, stop waiting. This has no effect if pidfds are
2369 * supported and death notification already caused waiting to stop.
2370 */
2371 stop_wait_for_proc_kill(!kill_pending);
2372
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002373 if (vmstat_parse(&vs) < 0) {
2374 ALOGE("Failed to parse vmstat!");
2375 return;
2376 }
Suren Baghdasaryandc60f972020-12-14 13:38:48 -08002377 /* Starting 5.9 kernel workingset_refault vmstat field was renamed workingset_refault_file */
2378 workingset_refault_file = vs.field.workingset_refault ? : vs.field.workingset_refault_file;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002379
2380 if (meminfo_parse(&mi) < 0) {
2381 ALOGE("Failed to parse meminfo!");
2382 return;
2383 }
2384
2385 /* Reset states after process got killed */
2386 if (killing) {
2387 killing = false;
2388 cycle_after_kill = true;
2389 /* Reset file-backed pagecache size and refault amounts after a kill */
2390 base_file_lru = vs.field.nr_inactive_file + vs.field.nr_active_file;
Suren Baghdasaryandc60f972020-12-14 13:38:48 -08002391 init_ws_refault = workingset_refault_file;
Martin Liu1f72f5f2020-08-21 13:18:50 +08002392 thrashing_reset_tm = curr_tm;
2393 prev_thrash_growth = 0;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002394 }
2395
2396 /* Check free swap levels */
2397 if (swap_free_low_percentage) {
2398 if (!swap_low_threshold) {
2399 swap_low_threshold = mi.field.total_swap * swap_free_low_percentage / 100;
2400 }
2401 swap_is_low = mi.field.free_swap < swap_low_threshold;
2402 }
2403
2404 /* Identify reclaim state */
2405 if (vs.field.pgscan_direct > init_pgscan_direct) {
2406 init_pgscan_direct = vs.field.pgscan_direct;
2407 init_pgscan_kswapd = vs.field.pgscan_kswapd;
2408 reclaim = DIRECT_RECLAIM;
2409 } else if (vs.field.pgscan_kswapd > init_pgscan_kswapd) {
2410 init_pgscan_kswapd = vs.field.pgscan_kswapd;
2411 reclaim = KSWAPD_RECLAIM;
Suren Baghdasaryandc60f972020-12-14 13:38:48 -08002412 } else if (workingset_refault_file == prev_workingset_refault) {
Martin Liu1f72f5f2020-08-21 13:18:50 +08002413 /* Device is not thrashing and not reclaiming, bail out early until we see these stats changing*/
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002414 goto no_kill;
2415 }
2416
Suren Baghdasaryandc60f972020-12-14 13:38:48 -08002417 prev_workingset_refault = workingset_refault_file;
Martin Liu1f72f5f2020-08-21 13:18:50 +08002418
2419 /*
2420 * It's possible we fail to find an eligible process to kill (ex. no process is
2421 * above oom_adj_min). When this happens, we should retry to find a new process
2422 * for a kill whenever a new eligible process is available. This is especially
2423 * important for a slow growing refault case. While retrying, we should keep
2424 * monitoring new thrashing counter as someone could release the memory to mitigate
2425 * the thrashing. Thus, when thrashing reset window comes, we decay the prev thrashing
2426 * counter by window counts. if the counter is still greater than thrashing limit,
2427 * we preserve the current prev_thrash counter so we will retry kill again. Otherwise,
2428 * we reset the prev_thrash counter so we will stop retrying.
2429 */
2430 since_thrashing_reset_ms = get_time_diff_ms(&thrashing_reset_tm, &curr_tm);
2431 if (since_thrashing_reset_ms > THRASHING_RESET_INTERVAL_MS) {
2432 long windows_passed;
2433 /* Calculate prev_thrash_growth if we crossed THRASHING_RESET_INTERVAL_MS */
Suren Baghdasaryandc60f972020-12-14 13:38:48 -08002434 prev_thrash_growth = (workingset_refault_file - init_ws_refault) * 100
Martin Liuc3108412020-09-03 22:12:14 +08002435 / (base_file_lru + 1);
Martin Liu1f72f5f2020-08-21 13:18:50 +08002436 windows_passed = (since_thrashing_reset_ms / THRASHING_RESET_INTERVAL_MS);
2437 /*
2438 * Decay prev_thrashing unless over-the-limit thrashing was registered in the window we
2439 * just crossed, which means there were no eligible processes to kill. We preserve the
2440 * counter in that case to ensure a kill if a new eligible process appears.
2441 */
2442 if (windows_passed > 1 || prev_thrash_growth < thrashing_limit) {
2443 prev_thrash_growth >>= windows_passed;
2444 }
2445
2446 /* Record file-backed pagecache size when crossing THRASHING_RESET_INTERVAL_MS */
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002447 base_file_lru = vs.field.nr_inactive_file + vs.field.nr_active_file;
Suren Baghdasaryandc60f972020-12-14 13:38:48 -08002448 init_ws_refault = workingset_refault_file;
Martin Liu1f72f5f2020-08-21 13:18:50 +08002449 thrashing_reset_tm = curr_tm;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002450 thrashing_limit = thrashing_limit_pct;
2451 } else {
2452 /* Calculate what % of the file-backed pagecache refaulted so far */
Suren Baghdasaryandc60f972020-12-14 13:38:48 -08002453 thrashing = (workingset_refault_file - init_ws_refault) * 100 / (base_file_lru + 1);
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002454 }
Martin Liu1f72f5f2020-08-21 13:18:50 +08002455 /* Add previous cycle's decayed thrashing amount */
2456 thrashing += prev_thrash_growth;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002457
Suren Baghdasaryan81c75b22019-08-14 09:48:35 -07002458 /*
2459 * Refresh watermarks once per min in case user updated one of the margins.
2460 * TODO: b/140521024 replace this periodic update with an API for AMS to notify LMKD
2461 * that zone watermarks were changed by the system software.
2462 */
2463 if (watermarks.high_wmark == 0 || get_time_diff_ms(&wmark_update_tm, &curr_tm) > 60000) {
2464 struct zoneinfo zi;
2465
2466 if (zoneinfo_parse(&zi) < 0) {
2467 ALOGE("Failed to parse zoneinfo!");
2468 return;
2469 }
2470
2471 calc_zone_watermarks(&zi, &watermarks);
2472 wmark_update_tm = curr_tm;
Martin Liu1f72f5f2020-08-21 13:18:50 +08002473 }
Suren Baghdasaryan81c75b22019-08-14 09:48:35 -07002474
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002475 /* Find out which watermark is breached if any */
Suren Baghdasaryan81c75b22019-08-14 09:48:35 -07002476 wmark = get_lowest_watermark(&mi, &watermarks);
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002477
2478 /*
2479 * TODO: move this logic into a separate function
2480 * Decide if killing a process is necessary and record the reason
2481 */
2482 if (cycle_after_kill && wmark < WMARK_LOW) {
2483 /*
2484 * Prevent kills not freeing enough memory which might lead to OOM kill.
2485 * This might happen when a process is consuming memory faster than reclaim can
2486 * free even after a kill. Mostly happens when running memory stress tests.
2487 */
2488 kill_reason = PRESSURE_AFTER_KILL;
Suren Baghdasaryan89454e62019-07-15 15:50:17 -07002489 strncpy(kill_desc, "min watermark is breached even after kill", sizeof(kill_desc));
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002490 } else if (level == VMPRESS_LEVEL_CRITICAL && events != 0) {
2491 /*
2492 * Device is too busy reclaiming memory which might lead to ANR.
2493 * Critical level is triggered when PSI complete stall (all tasks are blocked because
2494 * of the memory congestion) breaches the configured threshold.
2495 */
2496 kill_reason = NOT_RESPONDING;
Suren Baghdasaryan89454e62019-07-15 15:50:17 -07002497 strncpy(kill_desc, "device is not responding", sizeof(kill_desc));
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002498 } else if (swap_is_low && thrashing > thrashing_limit_pct) {
2499 /* Page cache is thrashing while swap is low */
2500 kill_reason = LOW_SWAP_AND_THRASHING;
Suren Baghdasaryan89454e62019-07-15 15:50:17 -07002501 snprintf(kill_desc, sizeof(kill_desc), "device is low on swap (%" PRId64
2502 "kB < %" PRId64 "kB) and thrashing (%" PRId64 "%%)",
2503 mi.field.free_swap * page_k, swap_low_threshold * page_k, thrashing);
Suren Baghdasaryan48135c42020-05-19 12:59:18 -07002504 /* Do not kill perceptible apps unless below min watermark */
Martin Liu3185c2d2020-06-02 13:05:51 +08002505 if (wmark > WMARK_MIN) {
Suren Baghdasaryan48135c42020-05-19 12:59:18 -07002506 min_score_adj = PERCEPTIBLE_APP_ADJ + 1;
2507 }
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002508 } else if (swap_is_low && wmark < WMARK_HIGH) {
2509 /* Both free memory and swap are low */
2510 kill_reason = LOW_MEM_AND_SWAP;
Suren Baghdasaryan89454e62019-07-15 15:50:17 -07002511 snprintf(kill_desc, sizeof(kill_desc), "%s watermark is breached and swap is low (%"
Suren Baghdasaryan23678182021-03-02 18:33:09 -08002512 PRId64 "kB < %" PRId64 "kB)", wmark < WMARK_LOW ? "min" : "low",
Suren Baghdasaryan89454e62019-07-15 15:50:17 -07002513 mi.field.free_swap * page_k, swap_low_threshold * page_k);
Suren Baghdasaryan48135c42020-05-19 12:59:18 -07002514 /* Do not kill perceptible apps unless below min watermark */
Martin Liu3185c2d2020-06-02 13:05:51 +08002515 if (wmark > WMARK_MIN) {
Suren Baghdasaryan48135c42020-05-19 12:59:18 -07002516 min_score_adj = PERCEPTIBLE_APP_ADJ + 1;
2517 }
Suren Baghdasaryan51ee4c52020-04-21 12:27:01 -07002518 } else if (wmark < WMARK_HIGH && swap_util_max < 100 &&
2519 (swap_util = calc_swap_utilization(&mi)) > swap_util_max) {
2520 /*
2521 * Too much anon memory is swapped out but swap is not low.
2522 * Non-swappable allocations created memory pressure.
2523 */
2524 kill_reason = LOW_MEM_AND_SWAP_UTIL;
2525 snprintf(kill_desc, sizeof(kill_desc), "%s watermark is breached and swap utilization"
Suren Baghdasaryan23678182021-03-02 18:33:09 -08002526 " is high (%d%% > %d%%)", wmark < WMARK_LOW ? "min" : "low",
Suren Baghdasaryan51ee4c52020-04-21 12:27:01 -07002527 swap_util, swap_util_max);
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002528 } else if (wmark < WMARK_HIGH && thrashing > thrashing_limit) {
2529 /* Page cache is thrashing while memory is low */
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002530 kill_reason = LOW_MEM_AND_THRASHING;
Suren Baghdasaryan89454e62019-07-15 15:50:17 -07002531 snprintf(kill_desc, sizeof(kill_desc), "%s watermark is breached and thrashing (%"
Suren Baghdasaryan23678182021-03-02 18:33:09 -08002532 PRId64 "%%)", wmark < WMARK_LOW ? "min" : "low", thrashing);
Suren Baghdasaryan970a26a2019-09-19 15:27:21 -07002533 cut_thrashing_limit = true;
2534 /* Do not kill perceptible apps because of thrashing */
Suren Baghdasaryan5c039b52020-05-19 12:44:31 -07002535 min_score_adj = PERCEPTIBLE_APP_ADJ + 1;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002536 } else if (reclaim == DIRECT_RECLAIM && thrashing > thrashing_limit) {
2537 /* Page cache is thrashing while in direct reclaim (mostly happens on lowram devices) */
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002538 kill_reason = DIRECT_RECL_AND_THRASHING;
Suren Baghdasaryan89454e62019-07-15 15:50:17 -07002539 snprintf(kill_desc, sizeof(kill_desc), "device is in direct reclaim and thrashing (%"
2540 PRId64 "%%)", thrashing);
Suren Baghdasaryan970a26a2019-09-19 15:27:21 -07002541 cut_thrashing_limit = true;
2542 /* Do not kill perceptible apps because of thrashing */
Suren Baghdasaryan5c039b52020-05-19 12:44:31 -07002543 min_score_adj = PERCEPTIBLE_APP_ADJ + 1;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002544 }
2545
2546 /* Kill a process if necessary */
2547 if (kill_reason != NONE) {
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002548 int pages_freed = find_and_kill_process(min_score_adj, kill_reason, kill_desc, &mi,
Suren Baghdasaryand7b4fcb2020-07-23 18:00:43 -07002549 &wi, &curr_tm);
Suren Baghdasaryan970a26a2019-09-19 15:27:21 -07002550 if (pages_freed > 0) {
2551 killing = true;
2552 if (cut_thrashing_limit) {
2553 /*
2554 * Cut thrasing limit by thrashing_limit_decay_pct percentage of the current
2555 * thrashing limit until the system stops thrashing.
2556 */
2557 thrashing_limit = (thrashing_limit * (100 - thrashing_limit_decay_pct)) / 100;
2558 }
2559 }
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002560 }
2561
2562no_kill:
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002563 /* Do not poll if kernel supports pidfd waiting */
2564 if (is_waiting_for_kill()) {
2565 /* Pause polling if we are waiting for process death notification */
2566 poll_params->update = POLLING_PAUSE;
2567 return;
2568 }
2569
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002570 /*
2571 * Start polling after initial PSI event;
2572 * extend polling while device is in direct reclaim or process is being killed;
2573 * do not extend when kswapd reclaims because that might go on for a long time
2574 * without causing memory pressure
2575 */
2576 if (events || killing || reclaim == DIRECT_RECLAIM) {
2577 poll_params->update = POLLING_START;
2578 }
2579
2580 /* Decide the polling interval */
2581 if (swap_is_low || killing) {
2582 /* Fast polling during and after a kill or when swap is low */
2583 poll_params->polling_interval_ms = PSI_POLL_PERIOD_SHORT_MS;
2584 } else {
2585 /* By default use long intervals */
2586 poll_params->polling_interval_ms = PSI_POLL_PERIOD_LONG_MS;
2587 }
2588}
2589
Suren Baghdasaryane12a0672019-07-15 14:50:49 -07002590static void mp_event_common(int data, uint32_t events, struct polling_params *poll_params) {
Todd Poynorc58c5142013-07-09 19:35:14 -07002591 unsigned long long evcount;
Robert Beneac72b2932017-08-21 15:18:31 -07002592 int64_t mem_usage, memsw_usage;
Robert Benea3be16142017-09-13 15:20:30 -07002593 int64_t mem_pressure;
Suren Baghdasaryane0f3dd12018-04-13 13:41:12 -07002594 union meminfo mi;
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07002595 struct zoneinfo zi;
Suren Baghdasaryan53be36e2018-09-05 15:46:32 -07002596 struct timespec curr_tm;
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -07002597 static unsigned long kill_skip_count = 0;
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08002598 enum vmpressure_level level = (enum vmpressure_level)data;
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07002599 long other_free = 0, other_file = 0;
2600 int min_score_adj;
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07002601 int minfree = 0;
Suren Baghdasaryan87966742018-04-13 12:43:41 -07002602 static struct reread_data mem_usage_file_data = {
2603 .filename = MEMCG_MEMORY_USAGE,
2604 .fd = -1,
2605 };
2606 static struct reread_data memsw_usage_file_data = {
2607 .filename = MEMCG_MEMORYSW_USAGE,
2608 .fd = -1,
2609 };
Suren Baghdasaryand7b4fcb2020-07-23 18:00:43 -07002610 static struct wakeup_info wi;
Todd Poynorc58c5142013-07-09 19:35:14 -07002611
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08002612 if (debug_process_killing) {
2613 ALOGI("%s memory pressure event is triggered", level_name[level]);
2614 }
2615
2616 if (!use_psi_monitors) {
2617 /*
2618 * Check all event counters from low to critical
2619 * and upgrade to the highest priority one. By reading
2620 * eventfd we also reset the event counters.
2621 */
Tom Cherry43f3d2b2019-12-04 12:46:57 -08002622 for (int lvl = VMPRESS_LEVEL_LOW; lvl < VMPRESS_LEVEL_COUNT; lvl++) {
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08002623 if (mpevfd[lvl] != -1 &&
2624 TEMP_FAILURE_RETRY(read(mpevfd[lvl],
2625 &evcount, sizeof(evcount))) > 0 &&
2626 evcount > 0 && lvl > level) {
Tom Cherry43f3d2b2019-12-04 12:46:57 -08002627 level = static_cast<vmpressure_level>(lvl);
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08002628 }
Suren Baghdasaryan3e1a8492018-01-04 09:16:21 -08002629 }
2630 }
Todd Poynorc58c5142013-07-09 19:35:14 -07002631
Suren Baghdasaryane12a0672019-07-15 14:50:49 -07002632 /* Start polling after initial PSI event */
2633 if (use_psi_monitors && events) {
2634 /* Override polling params only if current event is more critical */
2635 if (!poll_params->poll_handler || data > poll_params->poll_handler->data) {
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002636 poll_params->polling_interval_ms = PSI_POLL_PERIOD_SHORT_MS;
Suren Baghdasaryane12a0672019-07-15 14:50:49 -07002637 poll_params->update = POLLING_START;
2638 }
2639 }
2640
Suren Baghdasaryan53be36e2018-09-05 15:46:32 -07002641 if (clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm) != 0) {
2642 ALOGE("Failed to get current time");
2643 return;
2644 }
2645
Suren Baghdasaryand7b4fcb2020-07-23 18:00:43 -07002646 record_wakeup_time(&curr_tm, events ? Event : Polling, &wi);
2647
Suren Baghdasaryaned715a32020-05-11 16:31:57 -07002648 if (kill_timeout_ms &&
2649 get_time_diff_ms(&last_kill_tm, &curr_tm) < static_cast<long>(kill_timeout_ms)) {
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002650 /*
2651 * If we're within the no-kill timeout, see if there's pending reclaim work
2652 * from the last killed process. If so, skip killing for now.
2653 */
2654 if (is_kill_pending()) {
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -07002655 kill_skip_count++;
Suren Baghdasaryand7b4fcb2020-07-23 18:00:43 -07002656 wi.skipped_wakeups++;
Suren Baghdasaryan30854e72018-01-17 17:28:01 -08002657 return;
2658 }
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002659 /*
2660 * Process is dead, stop waiting. This has no effect if pidfds are supported and
2661 * death notification already caused waiting to stop.
2662 */
2663 stop_wait_for_proc_kill(true);
2664 } else {
2665 /*
2666 * Killing took longer than no-kill timeout. Stop waiting for the last process
2667 * to die because we are ready to kill again.
2668 */
2669 stop_wait_for_proc_kill(false);
Suren Baghdasaryan30854e72018-01-17 17:28:01 -08002670 }
2671
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -07002672 if (kill_skip_count > 0) {
Suren Baghdasaryaneff82332018-05-10 16:10:56 -07002673 ALOGI("%lu memory pressure events were skipped after a kill!",
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -07002674 kill_skip_count);
2675 kill_skip_count = 0;
Suren Baghdasaryan30854e72018-01-17 17:28:01 -08002676 }
2677
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07002678 if (meminfo_parse(&mi) < 0 || zoneinfo_parse(&zi) < 0) {
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002679 ALOGE("Failed to get free memory!");
2680 return;
2681 }
2682
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07002683 if (use_minfree_levels) {
2684 int i;
2685
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07002686 other_free = mi.field.nr_free_pages - zi.totalreserve_pages;
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07002687 if (mi.field.nr_file_pages > (mi.field.shmem + mi.field.unevictable + mi.field.swap_cached)) {
2688 other_file = (mi.field.nr_file_pages - mi.field.shmem -
2689 mi.field.unevictable - mi.field.swap_cached);
2690 } else {
2691 other_file = 0;
2692 }
2693
2694 min_score_adj = OOM_SCORE_ADJ_MAX + 1;
2695 for (i = 0; i < lowmem_targets_size; i++) {
2696 minfree = lowmem_minfree[i];
2697 if (other_free < minfree && other_file < minfree) {
2698 min_score_adj = lowmem_adj[i];
2699 break;
2700 }
2701 }
2702
Suren Baghdasaryanb0bda552018-05-18 14:42:00 -07002703 if (min_score_adj == OOM_SCORE_ADJ_MAX + 1) {
2704 if (debug_process_killing) {
2705 ALOGI("Ignore %s memory pressure event "
2706 "(free memory=%ldkB, cache=%ldkB, limit=%ldkB)",
2707 level_name[level], other_free * page_k, other_file * page_k,
2708 (long)lowmem_minfree[lowmem_targets_size - 1] * page_k);
2709 }
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07002710 return;
Suren Baghdasaryanb0bda552018-05-18 14:42:00 -07002711 }
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07002712
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07002713 goto do_kill;
2714 }
2715
Suren Baghdasaryane0f3dd12018-04-13 13:41:12 -07002716 if (level == VMPRESS_LEVEL_LOW) {
2717 record_low_pressure_levels(&mi);
2718 }
2719
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002720 if (level_oomadj[level] > OOM_SCORE_ADJ_MAX) {
2721 /* Do not monitor this pressure level */
2722 return;
2723 }
2724
Suren Baghdasaryan87966742018-04-13 12:43:41 -07002725 if ((mem_usage = get_memory_usage(&mem_usage_file_data)) < 0) {
2726 goto do_kill;
2727 }
2728 if ((memsw_usage = get_memory_usage(&memsw_usage_file_data)) < 0) {
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08002729 goto do_kill;
Robert Benea3be16142017-09-13 15:20:30 -07002730 }
Robert Beneac72b2932017-08-21 15:18:31 -07002731
Robert Benea3be16142017-09-13 15:20:30 -07002732 // Calculate percent for swappinness.
2733 mem_pressure = (mem_usage * 100) / memsw_usage;
2734
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08002735 if (enable_pressure_upgrade && level != VMPRESS_LEVEL_CRITICAL) {
Robert Benea3be16142017-09-13 15:20:30 -07002736 // We are swapping too much.
2737 if (mem_pressure < upgrade_pressure) {
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08002738 level = upgrade_level(level);
2739 if (debug_process_killing) {
2740 ALOGI("Event upgraded to %s", level_name[level]);
2741 }
Robert Beneac72b2932017-08-21 15:18:31 -07002742 }
2743 }
2744
Vic Yang65680692018-08-07 10:18:22 -07002745 // If we still have enough swap space available, check if we want to
2746 // ignore/downgrade pressure events.
2747 if (mi.field.free_swap >=
2748 mi.field.total_swap * swap_free_low_percentage / 100) {
2749 // If the pressure is larger than downgrade_pressure lmk will not
2750 // kill any process, since enough memory is available.
2751 if (mem_pressure > downgrade_pressure) {
2752 if (debug_process_killing) {
2753 ALOGI("Ignore %s memory pressure", level_name[level]);
2754 }
2755 return;
2756 } else if (level == VMPRESS_LEVEL_CRITICAL && mem_pressure > upgrade_pressure) {
2757 if (debug_process_killing) {
2758 ALOGI("Downgrade critical memory pressure");
2759 }
2760 // Downgrade event, since enough memory available.
2761 level = downgrade_level(level);
Robert Benea3be16142017-09-13 15:20:30 -07002762 }
Robert Benea3be16142017-09-13 15:20:30 -07002763 }
2764
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08002765do_kill:
Suren Baghdasaryand1d59f82018-04-13 11:45:38 -07002766 if (low_ram_device) {
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002767 /* For Go devices kill only one task */
Suren Baghdasaryan3cc1f132020-09-09 20:19:02 -07002768 if (find_and_kill_process(level_oomadj[level], NONE, NULL, &mi, &wi, &curr_tm) == 0) {
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002769 if (debug_process_killing) {
2770 ALOGI("Nothing to kill");
2771 }
2772 }
2773 } else {
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07002774 int pages_freed;
Suren Baghdasaryan53be36e2018-09-05 15:46:32 -07002775 static struct timespec last_report_tm;
2776 static unsigned long report_skip_count = 0;
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07002777
2778 if (!use_minfree_levels) {
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07002779 /* Free up enough memory to downgrate the memory pressure to low level */
Suren Baghdasaryan85c31b52018-10-26 11:32:15 -07002780 if (mi.field.nr_free_pages >= low_pressure_mem.max_nr_free_pages) {
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07002781 if (debug_process_killing) {
2782 ALOGI("Ignoring pressure since more memory is "
2783 "available (%" PRId64 ") than watermark (%" PRId64 ")",
2784 mi.field.nr_free_pages, low_pressure_mem.max_nr_free_pages);
2785 }
2786 return;
2787 }
2788 min_score_adj = level_oomadj[level];
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002789 }
2790
Suren Baghdasaryan3cc1f132020-09-09 20:19:02 -07002791 pages_freed = find_and_kill_process(min_score_adj, NONE, NULL, &mi, &wi, &curr_tm);
Suren Baghdasaryaneff82332018-05-10 16:10:56 -07002792
Suren Baghdasaryan53be36e2018-09-05 15:46:32 -07002793 if (pages_freed == 0) {
2794 /* Rate limit kill reports when nothing was reclaimed */
2795 if (get_time_diff_ms(&last_report_tm, &curr_tm) < FAIL_REPORT_RLIMIT_MS) {
2796 report_skip_count++;
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -07002797 return;
2798 }
Robert Benea7f68a3f2017-08-11 16:03:20 -07002799 }
Suren Baghdasaryan53be36e2018-09-05 15:46:32 -07002800
Suren Baghdasaryan12cacae2019-09-16 12:06:30 -07002801 /* Log whenever we kill or when report rate limit allows */
Suren Baghdasaryan53be36e2018-09-05 15:46:32 -07002802 if (use_minfree_levels) {
Chris Morin74b4df92021-02-26 00:00:35 -08002803 ALOGI("Reclaimed %ldkB, cache(%ldkB) and free(%" PRId64 "kB)-reserved(%" PRId64 "kB) "
2804 "below min(%ldkB) for oom_score_adj %d",
Suren Baghdasaryan85c31b52018-10-26 11:32:15 -07002805 pages_freed * page_k,
Suren Baghdasaryan53be36e2018-09-05 15:46:32 -07002806 other_file * page_k, mi.field.nr_free_pages * page_k,
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07002807 zi.totalreserve_pages * page_k,
Suren Baghdasaryan53be36e2018-09-05 15:46:32 -07002808 minfree * page_k, min_score_adj);
2809 } else {
Chris Morin74b4df92021-02-26 00:00:35 -08002810 ALOGI("Reclaimed %ldkB at oom_score_adj %d", pages_freed * page_k, min_score_adj);
Suren Baghdasaryan53be36e2018-09-05 15:46:32 -07002811 }
2812
2813 if (report_skip_count > 0) {
2814 ALOGI("Suppressed %lu failed kill reports", report_skip_count);
2815 report_skip_count = 0;
2816 }
2817
2818 last_report_tm = curr_tm;
Colin Cross01db2712014-07-11 17:16:56 -07002819 }
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002820 if (is_waiting_for_kill()) {
2821 /* pause polling if we are waiting for process death notification */
2822 poll_params->update = POLLING_PAUSE;
2823 }
Todd Poynorc58c5142013-07-09 19:35:14 -07002824}
2825
Suren Baghdasaryan2f88e152019-07-15 15:42:09 -07002826static bool init_mp_psi(enum vmpressure_level level, bool use_new_strategy) {
2827 int fd;
2828
2829 /* Do not register a handler if threshold_ms is not set */
2830 if (!psi_thresholds[level].threshold_ms) {
2831 return true;
2832 }
2833
2834 fd = init_psi_monitor(psi_thresholds[level].stall_type,
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08002835 psi_thresholds[level].threshold_ms * US_PER_MS,
2836 PSI_WINDOW_SIZE_MS * US_PER_MS);
2837
2838 if (fd < 0) {
2839 return false;
2840 }
2841
Suren Baghdasaryan2f88e152019-07-15 15:42:09 -07002842 vmpressure_hinfo[level].handler = use_new_strategy ? mp_event_psi : mp_event_common;
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08002843 vmpressure_hinfo[level].data = level;
2844 if (register_psi_monitor(epollfd, fd, &vmpressure_hinfo[level]) < 0) {
2845 destroy_psi_monitor(fd);
2846 return false;
2847 }
2848 maxevents++;
2849 mpevfd[level] = fd;
2850
2851 return true;
2852}
2853
2854static void destroy_mp_psi(enum vmpressure_level level) {
2855 int fd = mpevfd[level];
2856
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07002857 if (fd < 0) {
2858 return;
2859 }
2860
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08002861 if (unregister_psi_monitor(epollfd, fd) < 0) {
2862 ALOGE("Failed to unregister psi monitor for %s memory pressure; errno=%d",
2863 level_name[level], errno);
2864 }
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07002865 maxevents--;
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08002866 destroy_psi_monitor(fd);
2867 mpevfd[level] = -1;
2868}
2869
2870static bool init_psi_monitors() {
Suren Baghdasaryan2f88e152019-07-15 15:42:09 -07002871 /*
2872 * When PSI is used on low-ram devices or on high-end devices without memfree levels
2873 * use new kill strategy based on zone watermarks, free swap and thrashing stats
2874 */
2875 bool use_new_strategy =
2876 property_get_bool("ro.lmk.use_new_strategy", low_ram_device || !use_minfree_levels);
2877
2878 /* In default PSI mode override stall amounts using system properties */
2879 if (use_new_strategy) {
2880 /* Do not use low pressure level */
2881 psi_thresholds[VMPRESS_LEVEL_LOW].threshold_ms = 0;
2882 psi_thresholds[VMPRESS_LEVEL_MEDIUM].threshold_ms = psi_partial_stall_ms;
2883 psi_thresholds[VMPRESS_LEVEL_CRITICAL].threshold_ms = psi_complete_stall_ms;
2884 }
2885
2886 if (!init_mp_psi(VMPRESS_LEVEL_LOW, use_new_strategy)) {
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08002887 return false;
2888 }
Suren Baghdasaryan2f88e152019-07-15 15:42:09 -07002889 if (!init_mp_psi(VMPRESS_LEVEL_MEDIUM, use_new_strategy)) {
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08002890 destroy_mp_psi(VMPRESS_LEVEL_LOW);
2891 return false;
2892 }
Suren Baghdasaryan2f88e152019-07-15 15:42:09 -07002893 if (!init_mp_psi(VMPRESS_LEVEL_CRITICAL, use_new_strategy)) {
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08002894 destroy_mp_psi(VMPRESS_LEVEL_MEDIUM);
2895 destroy_mp_psi(VMPRESS_LEVEL_LOW);
2896 return false;
2897 }
2898 return true;
2899}
2900
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08002901static bool init_mp_common(enum vmpressure_level level) {
Todd Poynorc58c5142013-07-09 19:35:14 -07002902 int mpfd;
2903 int evfd;
2904 int evctlfd;
2905 char buf[256];
2906 struct epoll_event epev;
2907 int ret;
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08002908 int level_idx = (int)level;
2909 const char *levelstr = level_name[level_idx];
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08002910
Mark Salyzyna00ccd82018-04-09 09:50:32 -07002911 /* gid containing AID_SYSTEM required */
Nick Kralevich148d8dd2015-12-18 20:52:37 -08002912 mpfd = open(MEMCG_SYSFS_PATH "memory.pressure_level", O_RDONLY | O_CLOEXEC);
Todd Poynorc58c5142013-07-09 19:35:14 -07002913 if (mpfd < 0) {
2914 ALOGI("No kernel memory.pressure_level support (errno=%d)", errno);
2915 goto err_open_mpfd;
2916 }
2917
Nick Kralevich148d8dd2015-12-18 20:52:37 -08002918 evctlfd = open(MEMCG_SYSFS_PATH "cgroup.event_control", O_WRONLY | O_CLOEXEC);
Todd Poynorc58c5142013-07-09 19:35:14 -07002919 if (evctlfd < 0) {
2920 ALOGI("No kernel memory cgroup event control (errno=%d)", errno);
2921 goto err_open_evctlfd;
2922 }
2923
Nick Kralevich148d8dd2015-12-18 20:52:37 -08002924 evfd = eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC);
Todd Poynorc58c5142013-07-09 19:35:14 -07002925 if (evfd < 0) {
2926 ALOGE("eventfd failed for level %s; errno=%d", levelstr, errno);
2927 goto err_eventfd;
2928 }
2929
2930 ret = snprintf(buf, sizeof(buf), "%d %d %s", evfd, mpfd, levelstr);
2931 if (ret >= (ssize_t)sizeof(buf)) {
2932 ALOGE("cgroup.event_control line overflow for level %s", levelstr);
2933 goto err;
2934 }
2935
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08002936 ret = TEMP_FAILURE_RETRY(write(evctlfd, buf, strlen(buf) + 1));
Todd Poynorc58c5142013-07-09 19:35:14 -07002937 if (ret == -1) {
2938 ALOGE("cgroup.event_control write failed for level %s; errno=%d",
2939 levelstr, errno);
2940 goto err;
2941 }
2942
2943 epev.events = EPOLLIN;
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08002944 /* use data to store event level */
2945 vmpressure_hinfo[level_idx].data = level_idx;
2946 vmpressure_hinfo[level_idx].handler = mp_event_common;
2947 epev.data.ptr = (void *)&vmpressure_hinfo[level_idx];
Todd Poynorc58c5142013-07-09 19:35:14 -07002948 ret = epoll_ctl(epollfd, EPOLL_CTL_ADD, evfd, &epev);
2949 if (ret == -1) {
2950 ALOGE("epoll_ctl for level %s failed; errno=%d", levelstr, errno);
2951 goto err;
2952 }
2953 maxevents++;
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08002954 mpevfd[level] = evfd;
Suren Baghdasaryanceffaf22018-01-04 08:54:53 -08002955 close(evctlfd);
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08002956 return true;
Todd Poynorc58c5142013-07-09 19:35:14 -07002957
2958err:
2959 close(evfd);
2960err_eventfd:
2961 close(evctlfd);
2962err_open_evctlfd:
2963 close(mpfd);
2964err_open_mpfd:
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08002965 return false;
Robert Benea58d6a132017-06-01 16:32:31 -07002966}
2967
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07002968static void destroy_mp_common(enum vmpressure_level level) {
2969 struct epoll_event epev;
2970 int fd = mpevfd[level];
2971
2972 if (fd < 0) {
2973 return;
2974 }
2975
2976 if (epoll_ctl(epollfd, EPOLL_CTL_DEL, fd, &epev)) {
2977 // Log an error and keep going
2978 ALOGE("epoll_ctl for level %s failed; errno=%d", level_name[level], errno);
2979 }
2980 maxevents--;
2981 close(fd);
2982 mpevfd[level] = -1;
2983}
2984
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07002985static void kernel_event_handler(int data __unused, uint32_t events __unused,
2986 struct polling_params *poll_params __unused) {
Jing Ji5c480962019-12-04 09:22:05 -08002987 poll_kernel(kpoll_fd);
Jim Blackler700b7192019-04-26 11:18:29 +01002988}
2989
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07002990static bool init_monitors() {
2991 /* Try to use psi monitor first if kernel has it */
2992 use_psi_monitors = property_get_bool("ro.lmk.use_psi", true) &&
2993 init_psi_monitors();
2994 /* Fall back to vmpressure */
2995 if (!use_psi_monitors &&
2996 (!init_mp_common(VMPRESS_LEVEL_LOW) ||
2997 !init_mp_common(VMPRESS_LEVEL_MEDIUM) ||
2998 !init_mp_common(VMPRESS_LEVEL_CRITICAL))) {
2999 ALOGE("Kernel does not support memory pressure events or in-kernel low memory killer");
3000 return false;
3001 }
3002 if (use_psi_monitors) {
3003 ALOGI("Using psi monitors for memory pressure detection");
3004 } else {
3005 ALOGI("Using vmpressure for memory pressure detection");
3006 }
3007 return true;
3008}
3009
3010static void destroy_monitors() {
3011 if (use_psi_monitors) {
3012 destroy_mp_psi(VMPRESS_LEVEL_CRITICAL);
3013 destroy_mp_psi(VMPRESS_LEVEL_MEDIUM);
3014 destroy_mp_psi(VMPRESS_LEVEL_LOW);
3015 } else {
3016 destroy_mp_common(VMPRESS_LEVEL_CRITICAL);
3017 destroy_mp_common(VMPRESS_LEVEL_MEDIUM);
3018 destroy_mp_common(VMPRESS_LEVEL_LOW);
3019 }
3020}
3021
Todd Poynorc58c5142013-07-09 19:35:14 -07003022static int init(void) {
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07003023 static struct event_handler_info kernel_poll_hinfo = { 0, kernel_event_handler };
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -07003024 struct reread_data file_data = {
3025 .filename = ZONEINFO_PATH,
3026 .fd = -1,
3027 };
Todd Poynorc58c5142013-07-09 19:35:14 -07003028 struct epoll_event epev;
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003029 int pidfd;
Todd Poynorc58c5142013-07-09 19:35:14 -07003030 int i;
3031 int ret;
3032
3033 page_k = sysconf(_SC_PAGESIZE);
3034 if (page_k == -1)
3035 page_k = PAGE_SIZE;
3036 page_k /= 1024;
3037
3038 epollfd = epoll_create(MAX_EPOLL_EVENTS);
3039 if (epollfd == -1) {
3040 ALOGE("epoll_create failed (errno=%d)", errno);
3041 return -1;
3042 }
3043
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003044 // mark data connections as not connected
3045 for (int i = 0; i < MAX_DATA_CONN; i++) {
3046 data_sock[i].sock = -1;
3047 }
3048
3049 ctrl_sock.sock = android_get_control_socket("lmkd");
3050 if (ctrl_sock.sock < 0) {
Todd Poynorc58c5142013-07-09 19:35:14 -07003051 ALOGE("get lmkd control socket failed");
3052 return -1;
3053 }
3054
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003055 ret = listen(ctrl_sock.sock, MAX_DATA_CONN);
Todd Poynorc58c5142013-07-09 19:35:14 -07003056 if (ret < 0) {
3057 ALOGE("lmkd control socket listen failed (errno=%d)", errno);
3058 return -1;
3059 }
3060
3061 epev.events = EPOLLIN;
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003062 ctrl_sock.handler_info.handler = ctrl_connect_handler;
3063 epev.data.ptr = (void *)&(ctrl_sock.handler_info);
3064 if (epoll_ctl(epollfd, EPOLL_CTL_ADD, ctrl_sock.sock, &epev) == -1) {
Todd Poynorc58c5142013-07-09 19:35:14 -07003065 ALOGE("epoll_ctl for lmkd control socket failed (errno=%d)", errno);
3066 return -1;
3067 }
3068 maxevents++;
3069
Robert Benea7878c9b2017-09-11 16:53:28 -07003070 has_inkernel_module = !access(INKERNEL_MINFREE_PATH, W_OK);
Suren Baghdasaryane6613ea2018-01-18 17:27:30 -08003071 use_inkernel_interface = has_inkernel_module;
Todd Poynorc58c5142013-07-09 19:35:14 -07003072
3073 if (use_inkernel_interface) {
3074 ALOGI("Using in-kernel low memory killer interface");
Jing Ji5c480962019-12-04 09:22:05 -08003075 if (init_poll_kernel()) {
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07003076 epev.events = EPOLLIN;
3077 epev.data.ptr = (void*)&kernel_poll_hinfo;
Jing Ji5c480962019-12-04 09:22:05 -08003078 if (epoll_ctl(epollfd, EPOLL_CTL_ADD, kpoll_fd, &epev) != 0) {
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07003079 ALOGE("epoll_ctl for lmk events failed (errno=%d)", errno);
Jing Ji5c480962019-12-04 09:22:05 -08003080 close(kpoll_fd);
3081 kpoll_fd = -1;
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07003082 } else {
3083 maxevents++;
Jing Ji5c480962019-12-04 09:22:05 -08003084 /* let the others know it does support reporting kills */
3085 property_set("sys.lmk.reportkills", "1");
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07003086 }
Jim Blackler700b7192019-04-26 11:18:29 +01003087 }
Todd Poynorc58c5142013-07-09 19:35:14 -07003088 } else {
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07003089 if (!init_monitors()) {
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08003090 return -1;
3091 }
Jing Ji5c480962019-12-04 09:22:05 -08003092 /* let the others know it does support reporting kills */
3093 property_set("sys.lmk.reportkills", "1");
Todd Poynorc58c5142013-07-09 19:35:14 -07003094 }
3095
Chong Zhang1cd12b52015-10-14 16:19:53 -07003096 for (i = 0; i <= ADJTOSLOT(OOM_SCORE_ADJ_MAX); i++) {
Todd Poynorc58c5142013-07-09 19:35:14 -07003097 procadjslot_list[i].next = &procadjslot_list[i];
3098 procadjslot_list[i].prev = &procadjslot_list[i];
3099 }
3100
Suren Baghdasaryana7394ea2018-10-12 11:07:40 -07003101 memset(killcnt_idx, KILLCNT_INVALID_IDX, sizeof(killcnt_idx));
3102
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -07003103 /*
3104 * Read zoneinfo as the biggest file we read to create and size the initial
3105 * read buffer and avoid memory re-allocations during memory pressure
3106 */
3107 if (reread_file(&file_data) == NULL) {
3108 ALOGE("Failed to read %s: %s", file_data.filename, strerror(errno));
3109 }
3110
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003111 /* check if kernel supports pidfd_open syscall */
Josh Gao84623be2021-03-18 17:16:08 -07003112 pidfd = TEMP_FAILURE_RETRY(pidfd_open(getpid(), 0));
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003113 if (pidfd < 0) {
3114 pidfd_supported = (errno != ENOSYS);
3115 } else {
3116 pidfd_supported = true;
3117 close(pidfd);
3118 }
3119 ALOGI("Process polling is %s", pidfd_supported ? "supported" : "not supported" );
3120
Todd Poynorc58c5142013-07-09 19:35:14 -07003121 return 0;
3122}
3123
Suren Baghdasaryan03dccf32020-04-28 16:02:13 -07003124static bool polling_paused(struct polling_params *poll_params) {
3125 return poll_params->paused_handler != NULL;
3126}
3127
3128static void resume_polling(struct polling_params *poll_params, struct timespec curr_tm) {
3129 poll_params->poll_start_tm = curr_tm;
3130 poll_params->poll_handler = poll_params->paused_handler;
Martin Liu589b5752020-09-02 23:15:18 +08003131 poll_params->polling_interval_ms = PSI_POLL_PERIOD_SHORT_MS;
3132 poll_params->paused_handler = NULL;
Suren Baghdasaryan03dccf32020-04-28 16:02:13 -07003133}
3134
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003135static void call_handler(struct event_handler_info* handler_info,
3136 struct polling_params *poll_params, uint32_t events) {
3137 struct timespec curr_tm;
3138
Suren Baghdasaryan9ca53342020-04-24 16:54:55 -07003139 poll_params->update = POLLING_DO_NOT_CHANGE;
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003140 handler_info->handler(handler_info->data, events, poll_params);
3141 clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm);
Suren Baghdasaryan9ca53342020-04-24 16:54:55 -07003142 if (poll_params->poll_handler == handler_info) {
3143 poll_params->last_poll_tm = curr_tm;
3144 }
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003145
3146 switch (poll_params->update) {
3147 case POLLING_START:
3148 /*
3149 * Poll for the duration of PSI_WINDOW_SIZE_MS after the
3150 * initial PSI event because psi events are rate-limited
3151 * at one per sec.
3152 */
3153 poll_params->poll_start_tm = curr_tm;
Greg Kaiser5e80ed52019-10-10 06:52:23 -07003154 poll_params->poll_handler = handler_info;
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003155 break;
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003156 case POLLING_PAUSE:
3157 poll_params->paused_handler = handler_info;
3158 poll_params->poll_handler = NULL;
3159 break;
3160 case POLLING_RESUME:
Suren Baghdasaryan03dccf32020-04-28 16:02:13 -07003161 resume_polling(poll_params, curr_tm);
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003162 break;
3163 case POLLING_DO_NOT_CHANGE:
3164 if (get_time_diff_ms(&poll_params->poll_start_tm, &curr_tm) > PSI_WINDOW_SIZE_MS) {
3165 /* Polled for the duration of PSI window, time to stop */
3166 poll_params->poll_handler = NULL;
3167 }
Suren Baghdasaryan9ca53342020-04-24 16:54:55 -07003168 break;
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003169 }
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003170}
3171
Todd Poynorc58c5142013-07-09 19:35:14 -07003172static void mainloop(void) {
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003173 struct event_handler_info* handler_info;
Suren Baghdasaryane12a0672019-07-15 14:50:49 -07003174 struct polling_params poll_params;
3175 struct timespec curr_tm;
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003176 struct epoll_event *evt;
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08003177 long delay = -1;
Suren Baghdasaryane12a0672019-07-15 14:50:49 -07003178
3179 poll_params.poll_handler = NULL;
Suren Baghdasaryan9ca53342020-04-24 16:54:55 -07003180 poll_params.paused_handler = NULL;
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003181
Todd Poynorc58c5142013-07-09 19:35:14 -07003182 while (1) {
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07003183 struct epoll_event events[MAX_EPOLL_EVENTS];
Todd Poynorc58c5142013-07-09 19:35:14 -07003184 int nevents;
3185 int i;
3186
Suren Baghdasaryane12a0672019-07-15 14:50:49 -07003187 if (poll_params.poll_handler) {
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003188 bool poll_now;
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08003189
3190 clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm);
Martin Liu589b5752020-09-02 23:15:18 +08003191 if (poll_params.update == POLLING_RESUME) {
3192 /* Just transitioned into POLLING_RESUME, poll immediately. */
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003193 poll_now = true;
3194 nevents = 0;
3195 } else {
3196 /* Calculate next timeout */
3197 delay = get_time_diff_ms(&poll_params.last_poll_tm, &curr_tm);
3198 delay = (delay < poll_params.polling_interval_ms) ?
3199 poll_params.polling_interval_ms - delay : poll_params.polling_interval_ms;
Suren Baghdasaryane12a0672019-07-15 14:50:49 -07003200
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003201 /* Wait for events until the next polling timeout */
3202 nevents = epoll_wait(epollfd, events, maxevents, delay);
3203
3204 /* Update current time after wait */
3205 clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm);
3206 poll_now = (get_time_diff_ms(&poll_params.last_poll_tm, &curr_tm) >=
3207 poll_params.polling_interval_ms);
3208 }
3209 if (poll_now) {
3210 call_handler(poll_params.poll_handler, &poll_params, 0);
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08003211 }
3212 } else {
Suren Baghdasaryan03dccf32020-04-28 16:02:13 -07003213 if (kill_timeout_ms && is_waiting_for_kill()) {
3214 clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm);
3215 delay = kill_timeout_ms - get_time_diff_ms(&last_kill_tm, &curr_tm);
3216 /* Wait for pidfds notification or kill timeout to expire */
3217 nevents = (delay > 0) ? epoll_wait(epollfd, events, maxevents, delay) : 0;
3218 if (nevents == 0) {
3219 /* Kill notification timed out */
3220 stop_wait_for_proc_kill(false);
3221 if (polling_paused(&poll_params)) {
3222 clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm);
Martin Liu589b5752020-09-02 23:15:18 +08003223 poll_params.update = POLLING_RESUME;
Suren Baghdasaryan03dccf32020-04-28 16:02:13 -07003224 resume_polling(&poll_params, curr_tm);
3225 }
3226 }
3227 } else {
3228 /* Wait for events with no timeout */
3229 nevents = epoll_wait(epollfd, events, maxevents, -1);
3230 }
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08003231 }
Todd Poynorc58c5142013-07-09 19:35:14 -07003232
3233 if (nevents == -1) {
3234 if (errno == EINTR)
3235 continue;
3236 ALOGE("epoll_wait failed (errno=%d)", errno);
3237 continue;
3238 }
3239
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003240 /*
3241 * First pass to see if any data socket connections were dropped.
3242 * Dropped connection should be handled before any other events
3243 * to deallocate data connection and correctly handle cases when
3244 * connection gets dropped and reestablished in the same epoll cycle.
3245 * In such cases it's essential to handle connection closures first.
3246 */
3247 for (i = 0, evt = &events[0]; i < nevents; ++i, evt++) {
3248 if ((evt->events & EPOLLHUP) && evt->data.ptr) {
3249 ALOGI("lmkd data connection dropped");
3250 handler_info = (struct event_handler_info*)evt->data.ptr;
3251 ctrl_data_close(handler_info->data);
3252 }
3253 }
3254
3255 /* Second pass to handle all other events */
3256 for (i = 0, evt = &events[0]; i < nevents; ++i, evt++) {
Suren Baghdasaryane12a0672019-07-15 14:50:49 -07003257 if (evt->events & EPOLLERR) {
Todd Poynorc58c5142013-07-09 19:35:14 -07003258 ALOGD("EPOLLERR on event #%d", i);
Suren Baghdasaryane12a0672019-07-15 14:50:49 -07003259 }
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003260 if (evt->events & EPOLLHUP) {
3261 /* This case was handled in the first pass */
3262 continue;
3263 }
3264 if (evt->data.ptr) {
3265 handler_info = (struct event_handler_info*)evt->data.ptr;
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003266 call_handler(handler_info, &poll_params, evt->events);
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003267 }
Todd Poynorc58c5142013-07-09 19:35:14 -07003268 }
3269 }
3270}
3271
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07003272int issue_reinit() {
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07003273 int sock;
Colin Crossd5b510e2014-07-14 14:31:15 -07003274
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07003275 sock = lmkd_connect();
3276 if (sock < 0) {
3277 ALOGE("failed to connect to lmkd: %s", strerror(errno));
3278 return -1;
3279 }
3280
3281 enum update_props_result res = lmkd_update_props(sock);
3282 switch (res) {
3283 case UPDATE_PROPS_SUCCESS:
3284 ALOGI("lmkd updated properties successfully");
3285 break;
3286 case UPDATE_PROPS_SEND_ERR:
3287 ALOGE("failed to send lmkd request: %s", strerror(errno));
3288 break;
3289 case UPDATE_PROPS_RECV_ERR:
3290 ALOGE("failed to receive lmkd reply: %s", strerror(errno));
3291 break;
3292 case UPDATE_PROPS_FORMAT_ERR:
3293 ALOGE("lmkd reply is invalid");
3294 break;
3295 case UPDATE_PROPS_FAIL:
3296 ALOGE("lmkd failed to update its properties");
3297 break;
3298 }
3299
3300 close(sock);
3301 return res == UPDATE_PROPS_SUCCESS ? 0 : -1;
3302}
3303
3304static void update_props() {
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08003305 /* By default disable low level vmpressure events */
3306 level_oomadj[VMPRESS_LEVEL_LOW] =
3307 property_get_int32("ro.lmk.low", OOM_SCORE_ADJ_MAX + 1);
3308 level_oomadj[VMPRESS_LEVEL_MEDIUM] =
3309 property_get_int32("ro.lmk.medium", 800);
3310 level_oomadj[VMPRESS_LEVEL_CRITICAL] =
3311 property_get_int32("ro.lmk.critical", 0);
Robert Benea7f68a3f2017-08-11 16:03:20 -07003312 debug_process_killing = property_get_bool("ro.lmk.debug", false);
Suren Baghdasaryan3faa3032017-12-08 13:08:41 -08003313
3314 /* By default disable upgrade/downgrade logic */
3315 enable_pressure_upgrade =
3316 property_get_bool("ro.lmk.critical_upgrade", false);
3317 upgrade_pressure =
3318 (int64_t)property_get_int32("ro.lmk.upgrade_pressure", 100);
3319 downgrade_pressure =
3320 (int64_t)property_get_int32("ro.lmk.downgrade_pressure", 100);
Suren Baghdasaryaneb7c5492017-12-08 13:17:06 -08003321 kill_heaviest_task =
Suren Baghdasaryan36b2c492018-04-13 11:49:54 -07003322 property_get_bool("ro.lmk.kill_heaviest_task", false);
Suren Baghdasaryand1d59f82018-04-13 11:45:38 -07003323 low_ram_device = property_get_bool("ro.config.low_ram", false);
Suren Baghdasaryan30854e72018-01-17 17:28:01 -08003324 kill_timeout_ms =
Suren Baghdasaryan7d1f4f02020-07-08 11:40:10 -07003325 (unsigned long)property_get_int32("ro.lmk.kill_timeout_ms", 100);
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07003326 use_minfree_levels =
3327 property_get_bool("ro.lmk.use_minfree_levels", false);
Suren Baghdasaryan8389fdb2018-06-19 18:38:12 -07003328 per_app_memcg =
3329 property_get_bool("ro.config.per_app_memcg", low_ram_device);
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07003330 swap_free_low_percentage = clamp(0, 100, property_get_int32("ro.lmk.swap_free_low_percentage",
Suren Baghdasaryanfb1f5922020-05-19 13:07:23 -07003331 DEF_LOW_SWAP));
Suren Baghdasaryan2f88e152019-07-15 15:42:09 -07003332 psi_partial_stall_ms = property_get_int32("ro.lmk.psi_partial_stall_ms",
3333 low_ram_device ? DEF_PARTIAL_STALL_LOWRAM : DEF_PARTIAL_STALL);
3334 psi_complete_stall_ms = property_get_int32("ro.lmk.psi_complete_stall_ms",
3335 DEF_COMPLETE_STALL);
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07003336 thrashing_limit_pct = max(0, property_get_int32("ro.lmk.thrashing_limit",
3337 low_ram_device ? DEF_THRASHING_LOWRAM : DEF_THRASHING));
3338 thrashing_limit_decay_pct = clamp(0, 100, property_get_int32("ro.lmk.thrashing_limit_decay",
3339 low_ram_device ? DEF_THRASHING_DECAY_LOWRAM : DEF_THRASHING_DECAY));
Suren Baghdasaryan51ee4c52020-04-21 12:27:01 -07003340 swap_util_max = clamp(0, 100, property_get_int32("ro.lmk.swap_util_max", 100));
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07003341}
3342
3343int main(int argc, char **argv) {
3344 if ((argc > 1) && argv[1] && !strcmp(argv[1], "--reinit")) {
3345 if (property_set(LMKD_REINIT_PROP, "0")) {
3346 ALOGE("Failed to reset " LMKD_REINIT_PROP " property");
3347 }
3348 return issue_reinit();
3349 }
3350
3351 update_props();
Robert Benea57397dc2017-07-31 17:15:20 -07003352
Suren Baghdasaryan12cacae2019-09-16 12:06:30 -07003353 ctx = create_android_logger(KILLINFO_LOG_TAG);
Suren Baghdasaryan08bfa982018-07-26 16:34:27 -07003354
Mark Salyzyn5cc80b32018-03-21 12:24:58 -07003355 if (!init()) {
3356 if (!use_inkernel_interface) {
3357 /*
3358 * MCL_ONFAULT pins pages as they fault instead of loading
3359 * everything immediately all at once. (Which would be bad,
3360 * because as of this writing, we have a lot of mapped pages we
3361 * never use.) Old kernels will see MCL_ONFAULT and fail with
3362 * EINVAL; we ignore this failure.
3363 *
3364 * N.B. read the man page for mlockall. MCL_CURRENT | MCL_ONFAULT
3365 * pins ⊆ MCL_CURRENT, converging to just MCL_CURRENT as we fault
3366 * in pages.
3367 */
Mark Salyzyna00ccd82018-04-09 09:50:32 -07003368 /* CAP_IPC_LOCK required */
Mark Salyzyn5cc80b32018-03-21 12:24:58 -07003369 if (mlockall(MCL_CURRENT | MCL_FUTURE | MCL_ONFAULT) && (errno != EINVAL)) {
3370 ALOGW("mlockall failed %s", strerror(errno));
3371 }
Daniel Colascione46648332018-01-03 12:01:02 -08003372
Mark Salyzyna00ccd82018-04-09 09:50:32 -07003373 /* CAP_NICE required */
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07003374 struct sched_param param = {
3375 .sched_priority = 1,
3376 };
Mark Salyzyna00ccd82018-04-09 09:50:32 -07003377 if (sched_setscheduler(0, SCHED_FIFO, &param)) {
3378 ALOGW("set SCHED_FIFO failed %s", strerror(errno));
3379 }
Mark Salyzyn5cc80b32018-03-21 12:24:58 -07003380 }
3381
Todd Poynorc58c5142013-07-09 19:35:14 -07003382 mainloop();
Mark Salyzyn5cc80b32018-03-21 12:24:58 -07003383 }
Todd Poynorc58c5142013-07-09 19:35:14 -07003384
Suren Baghdasaryan08bfa982018-07-26 16:34:27 -07003385 android_log_destroy(&ctx);
3386
Todd Poynorc58c5142013-07-09 19:35:14 -07003387 ALOGI("exiting");
3388 return 0;
3389}