blob: 741e89168cc1838ccb2d30ed8bae0d2978b0f773 [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
19#include <errno.h>
Robert Beneac72b2932017-08-21 15:18:31 -070020#include <inttypes.h>
Suren Baghdasaryanbb7747b2018-03-20 16:03:29 -070021#include <pwd.h>
Mark Salyzyna1f5b862016-10-17 14:28:00 -070022#include <sched.h>
Suren Baghdasaryanf584fff2018-03-20 13:53:17 -070023#include <stdbool.h>
Todd Poynorc58c5142013-07-09 19:35:14 -070024#include <stdlib.h>
25#include <string.h>
Mark Salyzyneb062742014-04-30 13:36:35 -070026#include <sys/cdefs.h>
Todd Poynorc58c5142013-07-09 19:35:14 -070027#include <sys/epoll.h>
28#include <sys/eventfd.h>
Colin Crossc4059002014-07-11 17:15:44 -070029#include <sys/mman.h>
Josh Gao84623be2021-03-18 17:16:08 -070030#include <sys/pidfd.h>
Todd Poynorc58c5142013-07-09 19:35:14 -070031#include <sys/socket.h>
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -070032#include <sys/syscall.h>
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -080033#include <sys/sysinfo.h>
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -070034#include <time.h>
Mark Salyzyneb062742014-04-30 13:36:35 -070035#include <unistd.h>
36
Bart Van Assche80a3dba2022-02-02 23:51:35 +000037#include <algorithm>
Bart Van Assche54506792022-02-02 23:57:01 +000038#include <array>
Suren Baghdasaryanaf1b0e02021-11-16 11:50:29 -080039#include <shared_mutex>
40
Robert Benea57397dc2017-07-31 17:15:20 -070041#include <cutils/properties.h>
Todd Poynorc58c5142013-07-09 19:35:14 -070042#include <cutils/sockets.h>
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -070043#include <liblmkd_utils.h>
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -080044#include <lmkd.h>
Mark Salyzyn6a63fde2017-01-10 13:19:54 -080045#include <log/log.h>
Suren Baghdasaryan08bfa982018-07-26 16:34:27 -070046#include <log/log_event_list.h>
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -070047#include <log/log_time.h>
Suren Baghdasaryan945658a2019-10-18 11:16:52 -070048#include <private/android_filesystem_config.h>
Bart Van Asscheb4d26bb2022-02-17 21:31:51 +000049#include <processgroup/processgroup.h>
Suren Baghdasaryan55e31502019-01-08 12:54:48 -080050#include <psi/psi.h>
Mark Salyzyneb062742014-04-30 13:36:35 -070051
Suren Baghdasaryan7c3addb2021-06-11 12:12:56 -070052#include "reaper.h"
Yao Chen337606c2018-05-02 11:19:27 -070053#include "statslog.h"
Suren Baghdasaryanaf1b0e02021-11-16 11:50:29 -080054#include "watchdog.h"
Rajeev Kumar4aba9152018-01-31 17:54:56 -080055
Suren Baghdasaryan940e7cf2021-05-27 18:15:44 -070056#define BPF_FD_JUST_USE_INT
57#include "BpfSyscallWrappers.h"
58
Suren Baghdasaryan03e19872018-01-04 10:43:58 -080059/*
60 * Define LMKD_TRACE_KILLS to record lmkd kills in kernel traces
61 * to profile and correlate with OOM kills
62 */
63#ifdef LMKD_TRACE_KILLS
64
65#define ATRACE_TAG ATRACE_TAG_ALWAYS
66#include <cutils/trace.h>
67
Suren Baghdasaryan34928bb2021-07-29 17:02:51 -070068static inline void trace_kill_start(int pid, const char *desc) {
69 ATRACE_INT("kill_one_process", pid);
70 ATRACE_BEGIN(desc);
71}
72
73static inline void trace_kill_end() {
74 ATRACE_END();
75 ATRACE_INT("kill_one_process", 0);
76}
Suren Baghdasaryan03e19872018-01-04 10:43:58 -080077
78#else /* LMKD_TRACE_KILLS */
79
Suren Baghdasaryan34928bb2021-07-29 17:02:51 -070080static inline void trace_kill_start(int, const char *) {}
81static inline void trace_kill_end() {}
Suren Baghdasaryan03e19872018-01-04 10:43:58 -080082
83#endif /* LMKD_TRACE_KILLS */
84
Mark Salyzyneb062742014-04-30 13:36:35 -070085#ifndef __unused
86#define __unused __attribute__((__unused__))
87#endif
Todd Poynorc58c5142013-07-09 19:35:14 -070088
Suren Baghdasaryand28a9732018-04-13 13:11:51 -070089#define ZONEINFO_PATH "/proc/zoneinfo"
90#define MEMINFO_PATH "/proc/meminfo"
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -070091#define VMSTAT_PATH "/proc/vmstat"
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -070092#define PROC_STATUS_TGID_FIELD "Tgid:"
Ioannis Ilkos279268a2020-08-01 10:50:40 +010093#define PROC_STATUS_RSS_FIELD "VmRSS:"
94#define PROC_STATUS_SWAP_FIELD "VmSwap:"
Todd Poynorc58c5142013-07-09 19:35:14 -070095#define LINE_MAX 128
96
Suren Baghdasaryan970a26a2019-09-19 15:27:21 -070097#define PERCEPTIBLE_APP_ADJ 200
98
Suren Baghdasaryan08bfa982018-07-26 16:34:27 -070099/* Android Logger event logtags (see event.logtags) */
Suren Baghdasaryan12cacae2019-09-16 12:06:30 -0700100#define KILLINFO_LOG_TAG 10195355
Suren Baghdasaryan08bfa982018-07-26 16:34:27 -0700101
Mark Salyzyna00ccd82018-04-09 09:50:32 -0700102/* gid containing AID_SYSTEM required */
Todd Poynorc58c5142013-07-09 19:35:14 -0700103#define INKERNEL_MINFREE_PATH "/sys/module/lowmemorykiller/parameters/minfree"
104#define INKERNEL_ADJ_PATH "/sys/module/lowmemorykiller/parameters/adj"
105
Robert Benea58d6a132017-06-01 16:32:31 -0700106#define EIGHT_MEGA (1 << 23)
Todd Poynorc58c5142013-07-09 19:35:14 -0700107
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -0700108#define TARGET_UPDATE_MIN_INTERVAL_MS 1000
Martin Liu1f72f5f2020-08-21 13:18:50 +0800109#define THRASHING_RESET_INTERVAL_MS 1000
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -0700110
111#define NS_PER_MS (NS_PER_SEC / MS_PER_SEC)
Suren Baghdasaryan55e31502019-01-08 12:54:48 -0800112#define US_PER_MS (US_PER_SEC / MS_PER_SEC)
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -0700113
Suren Baghdasaryanbb7747b2018-03-20 16:03:29 -0700114/* Defined as ProcessList.SYSTEM_ADJ in ProcessList.java */
115#define SYSTEM_ADJ (-900)
116
Greg Kaiserf5b1d142018-03-23 14:16:12 -0700117#define STRINGIFY(x) STRINGIFY_INTERNAL(x)
118#define STRINGIFY_INTERNAL(x) #x
119
Suren Baghdasaryan55e31502019-01-08 12:54:48 -0800120/*
Suren Baghdasaryand0a80042021-08-03 15:40:23 -0700121 * Read lmk property with persist.device_config.lmkd_native.<name> overriding ro.lmk.<name>
122 * persist.device_config.lmkd_native.* properties are being set by experiments. If a new property
123 * can be controlled by an experiment then use GET_LMK_PROPERTY instead of property_get_xxx and
124 * add "on property" triggers in lmkd.rc to react to the experiment flag changes.
125 */
126#define GET_LMK_PROPERTY(type, name, def) \
127 property_get_##type("persist.device_config.lmkd_native." name, \
128 property_get_##type("ro.lmk." name, def))
129
130/*
Suren Baghdasaryan55e31502019-01-08 12:54:48 -0800131 * PSI monitor tracking window size.
132 * PSI monitor generates events at most once per window,
133 * therefore we poll memory state for the duration of
134 * PSI_WINDOW_SIZE_MS after the event happens.
135 */
136#define PSI_WINDOW_SIZE_MS 1000
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -0700137/* Polling period after PSI signal when pressure is high */
138#define PSI_POLL_PERIOD_SHORT_MS 10
139/* Polling period after PSI signal when pressure is low */
140#define PSI_POLL_PERIOD_LONG_MS 100
Suren Baghdasaryan55e31502019-01-08 12:54:48 -0800141
Suren Baghdasaryan53be36e2018-09-05 15:46:32 -0700142#define FAIL_REPORT_RLIMIT_MS 1000
143
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -0700144/*
145 * System property defaults
146 */
147/* ro.lmk.swap_free_low_percentage property defaults */
Suren Baghdasaryanfb1f5922020-05-19 13:07:23 -0700148#define DEF_LOW_SWAP 10
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -0700149/* ro.lmk.thrashing_limit property defaults */
150#define DEF_THRASHING_LOWRAM 30
151#define DEF_THRASHING 100
152/* ro.lmk.thrashing_limit_decay property defaults */
153#define DEF_THRASHING_DECAY_LOWRAM 50
154#define DEF_THRASHING_DECAY 10
Suren Baghdasaryan2f88e152019-07-15 15:42:09 -0700155/* ro.lmk.psi_partial_stall_ms property defaults */
156#define DEF_PARTIAL_STALL_LOWRAM 200
157#define DEF_PARTIAL_STALL 70
158/* ro.lmk.psi_complete_stall_ms property defaults */
159#define DEF_COMPLETE_STALL 700
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -0700160
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -0700161#define LMKD_REINIT_PROP "lmkd.reinit"
162
Suren Baghdasaryanaf1b0e02021-11-16 11:50:29 -0800163#define WATCHDOG_TIMEOUT_SEC 2
164
Todd Poynorc58c5142013-07-09 19:35:14 -0700165/* default to old in-kernel interface if no memory pressure events */
Mark Salyzyn5cc80b32018-03-21 12:24:58 -0700166static bool use_inkernel_interface = true;
Robert Benea7878c9b2017-09-11 16:53:28 -0700167static bool has_inkernel_module;
Todd Poynorc58c5142013-07-09 19:35:14 -0700168
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -0800169/* memory pressure levels */
170enum vmpressure_level {
171 VMPRESS_LEVEL_LOW = 0,
172 VMPRESS_LEVEL_MEDIUM,
173 VMPRESS_LEVEL_CRITICAL,
174 VMPRESS_LEVEL_COUNT
175};
Todd Poynorc58c5142013-07-09 19:35:14 -0700176
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -0800177static const char *level_name[] = {
178 "low",
179 "medium",
180 "critical"
181};
182
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -0800183struct {
Suren Baghdasaryane0f3dd12018-04-13 13:41:12 -0700184 int64_t min_nr_free_pages; /* recorded but not used yet */
185 int64_t max_nr_free_pages;
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -0800186} low_pressure_mem = { -1, -1 };
187
Suren Baghdasaryan55e31502019-01-08 12:54:48 -0800188struct psi_threshold {
189 enum psi_stall_type stall_type;
190 int threshold_ms;
191};
192
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -0800193static int level_oomadj[VMPRESS_LEVEL_COUNT];
Suren Baghdasaryan3e1a8492018-01-04 09:16:21 -0800194static int mpevfd[VMPRESS_LEVEL_COUNT] = { -1, -1, -1 };
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -0700195static bool pidfd_supported;
196static int last_kill_pid_or_fd = -1;
197static struct timespec last_kill_tm;
198
199/* lmkd configurable parameters */
Robert Beneac72b2932017-08-21 15:18:31 -0700200static bool debug_process_killing;
201static bool enable_pressure_upgrade;
202static int64_t upgrade_pressure;
Robert Benea3be16142017-09-13 15:20:30 -0700203static int64_t downgrade_pressure;
Suren Baghdasaryand1d59f82018-04-13 11:45:38 -0700204static bool low_ram_device;
Suren Baghdasaryaneb7c5492017-12-08 13:17:06 -0800205static bool kill_heaviest_task;
Suren Baghdasaryan30854e72018-01-17 17:28:01 -0800206static unsigned long kill_timeout_ms;
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -0700207static bool use_minfree_levels;
Suren Baghdasaryan8389fdb2018-06-19 18:38:12 -0700208static bool per_app_memcg;
Vic Yang65680692018-08-07 10:18:22 -0700209static int swap_free_low_percentage;
Suren Baghdasaryan2f88e152019-07-15 15:42:09 -0700210static int psi_partial_stall_ms;
211static int psi_complete_stall_ms;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -0700212static int thrashing_limit_pct;
213static int thrashing_limit_decay_pct;
Suren Baghdasaryan0142b3c2021-03-03 11:11:09 -0800214static int thrashing_critical_pct;
Suren Baghdasaryan51ee4c52020-04-21 12:27:01 -0700215static int swap_util_max;
Suren Baghdasaryan11221d42021-07-14 17:57:52 -0700216static int64_t filecache_min_kb;
Suren Baghdasaryan5ae47a92022-02-10 21:10:23 -0800217static int64_t stall_limit_critical;
Suren Baghdasaryan55e31502019-01-08 12:54:48 -0800218static bool use_psi_monitors = false;
Jing Ji5c480962019-12-04 09:22:05 -0800219static int kpoll_fd;
Suren Baghdasaryan55e31502019-01-08 12:54:48 -0800220static struct psi_threshold psi_thresholds[VMPRESS_LEVEL_COUNT] = {
221 { PSI_SOME, 70 }, /* 70ms out of 1sec for partial stall */
222 { PSI_SOME, 100 }, /* 100ms out of 1sec for partial stall */
223 { PSI_FULL, 70 }, /* 70ms out of 1sec for complete stall */
224};
Robert Benea57397dc2017-07-31 17:15:20 -0700225
Suren Baghdasaryan08bfa982018-07-26 16:34:27 -0700226static android_log_context ctx;
Suren Baghdasaryan7c3addb2021-06-11 12:12:56 -0700227static Reaper reaper;
228static int reaper_comm_fd[2];
Suren Baghdasaryan08bfa982018-07-26 16:34:27 -0700229
Suren Baghdasaryane12a0672019-07-15 14:50:49 -0700230enum polling_update {
231 POLLING_DO_NOT_CHANGE,
232 POLLING_START,
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -0700233 POLLING_PAUSE,
234 POLLING_RESUME,
Suren Baghdasaryane12a0672019-07-15 14:50:49 -0700235};
236
237/*
238 * Data used for periodic polling for the memory state of the device.
239 * Note that when system is not polling poll_handler is set to NULL,
240 * when polling starts poll_handler gets set and is reset back to
241 * NULL when polling stops.
242 */
243struct polling_params {
244 struct event_handler_info* poll_handler;
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -0700245 struct event_handler_info* paused_handler;
Suren Baghdasaryane12a0672019-07-15 14:50:49 -0700246 struct timespec poll_start_tm;
247 struct timespec last_poll_tm;
248 int polling_interval_ms;
249 enum polling_update update;
250};
251
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -0800252/* data required to handle events */
253struct event_handler_info {
254 int data;
Suren Baghdasaryane12a0672019-07-15 14:50:49 -0700255 void (*handler)(int data, uint32_t events, struct polling_params *poll_params);
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -0800256};
Todd Poynorc58c5142013-07-09 19:35:14 -0700257
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -0800258/* data required to handle socket events */
259struct sock_event_handler_info {
260 int sock;
Suren Baghdasaryan945658a2019-10-18 11:16:52 -0700261 pid_t pid;
Suren Baghdasaryan36baf442019-12-23 11:37:34 -0800262 uint32_t async_event_mask;
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -0800263 struct event_handler_info handler_info;
264};
265
Suren Baghdasaryanf2cbefd2019-10-21 17:59:22 -0700266/* max supported number of data connections (AMS, init, tests) */
267#define MAX_DATA_CONN 3
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -0800268
269/* socket event handler data */
270static struct sock_event_handler_info ctrl_sock;
271static struct sock_event_handler_info data_sock[MAX_DATA_CONN];
272
273/* vmpressure event handler data */
274static struct event_handler_info vmpressure_hinfo[VMPRESS_LEVEL_COUNT];
275
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -0700276/*
Suren Baghdasaryanf2cbefd2019-10-21 17:59:22 -0700277 * 1 ctrl listen socket, 3 ctrl data socket, 3 memory pressure levels,
Suren Baghdasaryan7c3addb2021-06-11 12:12:56 -0700278 * 1 lmk events + 1 fd to wait for process death + 1 fd to receive kill failure notifications
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -0700279 */
Suren Baghdasaryan7c3addb2021-06-11 12:12:56 -0700280#define MAX_EPOLL_EVENTS (1 + MAX_DATA_CONN + VMPRESS_LEVEL_COUNT + 1 + 1 + 1)
Todd Poynorc58c5142013-07-09 19:35:14 -0700281static int epollfd;
282static int maxevents;
283
Chong Zhang1cd12b52015-10-14 16:19:53 -0700284/* OOM score values used by both kernel and framework */
Todd Poynora08c1722013-09-16 19:26:47 -0700285#define OOM_SCORE_ADJ_MIN (-1000)
286#define OOM_SCORE_ADJ_MAX 1000
287
Bart Van Assche54506792022-02-02 23:57:01 +0000288static std::array<int, MAX_TARGETS> lowmem_adj;
289static std::array<int, MAX_TARGETS> lowmem_minfree;
Todd Poynorc58c5142013-07-09 19:35:14 -0700290static int lowmem_targets_size;
291
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700292/* Fields to parse in /proc/zoneinfo */
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -0700293/* zoneinfo per-zone fields */
294enum zoneinfo_zone_field {
295 ZI_ZONE_NR_FREE_PAGES = 0,
296 ZI_ZONE_MIN,
297 ZI_ZONE_LOW,
298 ZI_ZONE_HIGH,
299 ZI_ZONE_PRESENT,
300 ZI_ZONE_NR_FREE_CMA,
301 ZI_ZONE_FIELD_COUNT
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700302};
303
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -0700304static const char* const zoneinfo_zone_field_names[ZI_ZONE_FIELD_COUNT] = {
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700305 "nr_free_pages",
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -0700306 "min",
307 "low",
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700308 "high",
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -0700309 "present",
310 "nr_free_cma",
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700311};
312
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -0700313/* zoneinfo per-zone special fields */
314enum zoneinfo_zone_spec_field {
315 ZI_ZONE_SPEC_PROTECTION = 0,
316 ZI_ZONE_SPEC_PAGESETS,
317 ZI_ZONE_SPEC_FIELD_COUNT,
318};
319
320static const char* const zoneinfo_zone_spec_field_names[ZI_ZONE_SPEC_FIELD_COUNT] = {
321 "protection:",
322 "pagesets",
323};
324
325/* see __MAX_NR_ZONES definition in kernel mmzone.h */
326#define MAX_NR_ZONES 6
327
328union zoneinfo_zone_fields {
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700329 struct {
330 int64_t nr_free_pages;
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -0700331 int64_t min;
332 int64_t low;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700333 int64_t high;
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -0700334 int64_t present;
335 int64_t nr_free_cma;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700336 } field;
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -0700337 int64_t arr[ZI_ZONE_FIELD_COUNT];
338};
339
340struct zoneinfo_zone {
341 union zoneinfo_zone_fields fields;
342 int64_t protection[MAX_NR_ZONES];
343 int64_t max_protection;
344};
345
346/* zoneinfo per-node fields */
347enum zoneinfo_node_field {
348 ZI_NODE_NR_INACTIVE_FILE = 0,
349 ZI_NODE_NR_ACTIVE_FILE,
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -0700350 ZI_NODE_FIELD_COUNT
351};
352
353static const char* const zoneinfo_node_field_names[ZI_NODE_FIELD_COUNT] = {
354 "nr_inactive_file",
355 "nr_active_file",
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -0700356};
357
358union zoneinfo_node_fields {
359 struct {
360 int64_t nr_inactive_file;
361 int64_t nr_active_file;
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -0700362 } field;
363 int64_t arr[ZI_NODE_FIELD_COUNT];
364};
365
366struct zoneinfo_node {
367 int id;
368 int zone_count;
369 struct zoneinfo_zone zones[MAX_NR_ZONES];
370 union zoneinfo_node_fields fields;
371};
372
373/* for now two memory nodes is more than enough */
374#define MAX_NR_NODES 2
375
376struct zoneinfo {
377 int node_count;
378 struct zoneinfo_node nodes[MAX_NR_NODES];
379 int64_t totalreserve_pages;
380 int64_t total_inactive_file;
381 int64_t total_active_file;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700382};
383
384/* Fields to parse in /proc/meminfo */
385enum meminfo_field {
386 MI_NR_FREE_PAGES = 0,
387 MI_CACHED,
388 MI_SWAP_CACHED,
389 MI_BUFFERS,
390 MI_SHMEM,
391 MI_UNEVICTABLE,
Vic Yang65680692018-08-07 10:18:22 -0700392 MI_TOTAL_SWAP,
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700393 MI_FREE_SWAP,
Suren Baghdasaryan08bfa982018-07-26 16:34:27 -0700394 MI_ACTIVE_ANON,
395 MI_INACTIVE_ANON,
396 MI_ACTIVE_FILE,
397 MI_INACTIVE_FILE,
398 MI_SRECLAIMABLE,
399 MI_SUNRECLAIM,
400 MI_KERNEL_STACK,
401 MI_PAGE_TABLES,
402 MI_ION_HELP,
403 MI_ION_HELP_POOL,
404 MI_CMA_FREE,
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700405 MI_FIELD_COUNT
406};
407
408static const char* const meminfo_field_names[MI_FIELD_COUNT] = {
409 "MemFree:",
410 "Cached:",
411 "SwapCached:",
412 "Buffers:",
413 "Shmem:",
414 "Unevictable:",
Vic Yang65680692018-08-07 10:18:22 -0700415 "SwapTotal:",
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700416 "SwapFree:",
Suren Baghdasaryan08bfa982018-07-26 16:34:27 -0700417 "Active(anon):",
418 "Inactive(anon):",
419 "Active(file):",
420 "Inactive(file):",
421 "SReclaimable:",
422 "SUnreclaim:",
423 "KernelStack:",
424 "PageTables:",
425 "ION_heap:",
426 "ION_heap_pool:",
427 "CmaFree:",
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700428};
429
430union meminfo {
431 struct {
432 int64_t nr_free_pages;
433 int64_t cached;
434 int64_t swap_cached;
435 int64_t buffers;
436 int64_t shmem;
437 int64_t unevictable;
Vic Yang65680692018-08-07 10:18:22 -0700438 int64_t total_swap;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700439 int64_t free_swap;
Suren Baghdasaryan08bfa982018-07-26 16:34:27 -0700440 int64_t active_anon;
441 int64_t inactive_anon;
442 int64_t active_file;
443 int64_t inactive_file;
444 int64_t sreclaimable;
445 int64_t sunreclaimable;
446 int64_t kernel_stack;
447 int64_t page_tables;
448 int64_t ion_heap;
449 int64_t ion_heap_pool;
450 int64_t cma_free;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700451 /* fields below are calculated rather than read from the file */
452 int64_t nr_file_pages;
Suren Baghdasaryan940e7cf2021-05-27 18:15:44 -0700453 int64_t total_gpu_kb;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700454 } field;
455 int64_t arr[MI_FIELD_COUNT];
456};
457
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -0700458/* Fields to parse in /proc/vmstat */
459enum vmstat_field {
460 VS_FREE_PAGES,
461 VS_INACTIVE_FILE,
462 VS_ACTIVE_FILE,
463 VS_WORKINGSET_REFAULT,
Suren Baghdasaryandc60f972020-12-14 13:38:48 -0800464 VS_WORKINGSET_REFAULT_FILE,
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -0700465 VS_PGSCAN_KSWAPD,
466 VS_PGSCAN_DIRECT,
467 VS_PGSCAN_DIRECT_THROTTLE,
468 VS_FIELD_COUNT
469};
470
471static const char* const vmstat_field_names[MI_FIELD_COUNT] = {
472 "nr_free_pages",
473 "nr_inactive_file",
474 "nr_active_file",
475 "workingset_refault",
Suren Baghdasaryandc60f972020-12-14 13:38:48 -0800476 "workingset_refault_file",
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -0700477 "pgscan_kswapd",
478 "pgscan_direct",
479 "pgscan_direct_throttle",
480};
481
482union vmstat {
483 struct {
484 int64_t nr_free_pages;
485 int64_t nr_inactive_file;
486 int64_t nr_active_file;
487 int64_t workingset_refault;
Suren Baghdasaryandc60f972020-12-14 13:38:48 -0800488 int64_t workingset_refault_file;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -0700489 int64_t pgscan_kswapd;
490 int64_t pgscan_direct;
491 int64_t pgscan_direct_throttle;
492 } field;
493 int64_t arr[VS_FIELD_COUNT];
494};
495
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700496enum field_match_result {
497 NO_MATCH,
498 PARSE_FAIL,
499 PARSE_SUCCESS
500};
501
Todd Poynorc58c5142013-07-09 19:35:14 -0700502struct adjslot_list {
503 struct adjslot_list *next;
504 struct adjslot_list *prev;
505};
506
507struct proc {
508 struct adjslot_list asl;
509 int pid;
Suren Baghdasaryana10157c2019-07-19 10:55:39 -0700510 int pidfd;
Colin Cross748d2182014-06-13 14:52:43 -0700511 uid_t uid;
Todd Poynorc58c5142013-07-09 19:35:14 -0700512 int oomadj;
Suren Baghdasaryan945658a2019-10-18 11:16:52 -0700513 pid_t reg_pid; /* PID of the process that registered this record */
Todd Poynorc58c5142013-07-09 19:35:14 -0700514 struct proc *pidhash_next;
515};
516
Suren Baghdasaryan87966742018-04-13 12:43:41 -0700517struct reread_data {
518 const char* const filename;
519 int fd;
520};
521
Todd Poynorc58c5142013-07-09 19:35:14 -0700522#define PIDHASH_SZ 1024
523static struct proc *pidhash[PIDHASH_SZ];
524#define pid_hashfn(x) ((((x) >> 8) ^ (x)) & (PIDHASH_SZ - 1))
525
Chih-Hung Hsieheefa2462016-05-19 16:02:22 -0700526#define ADJTOSLOT(adj) ((adj) + -OOM_SCORE_ADJ_MIN)
Suren Baghdasaryana7394ea2018-10-12 11:07:40 -0700527#define ADJTOSLOT_COUNT (ADJTOSLOT(OOM_SCORE_ADJ_MAX) + 1)
Suren Baghdasaryanaf1b0e02021-11-16 11:50:29 -0800528
529// protects procadjslot_list from concurrent access
530static std::shared_mutex adjslot_list_lock;
531// procadjslot_list should be modified only from the main thread while exclusively holding
532// adjslot_list_lock. Readers from non-main threads should hold adjslot_list_lock shared lock.
Suren Baghdasaryana7394ea2018-10-12 11:07:40 -0700533static struct adjslot_list procadjslot_list[ADJTOSLOT_COUNT];
534
535#define MAX_DISTINCT_OOM_ADJ 32
536#define KILLCNT_INVALID_IDX 0xFF
537/*
538 * Because killcnt array is sparse a two-level indirection is used
539 * to keep the size small. killcnt_idx stores index of the element in
540 * killcnt array. Index KILLCNT_INVALID_IDX indicates an unused slot.
541 */
542static uint8_t killcnt_idx[ADJTOSLOT_COUNT];
543static uint16_t killcnt[MAX_DISTINCT_OOM_ADJ];
544static int killcnt_free_idx = 0;
545static uint32_t killcnt_total = 0;
Todd Poynorc58c5142013-07-09 19:35:14 -0700546
Todd Poynorc58c5142013-07-09 19:35:14 -0700547/* PAGE_SIZE / 1024 */
548static long page_k;
549
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -0700550static void update_props();
551static bool init_monitors();
552static void destroy_monitors();
553
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -0700554static int clamp(int low, int high, int value) {
Bart Van Assche80a3dba2022-02-02 23:51:35 +0000555 return std::max(std::min(value, high), low);
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -0700556}
557
Suren Baghdasaryan87966742018-04-13 12:43:41 -0700558static bool parse_int64(const char* str, int64_t* ret) {
559 char* endptr;
560 long long val = strtoll(str, &endptr, 10);
561 if (str == endptr || val > INT64_MAX) {
562 return false;
563 }
564 *ret = (int64_t)val;
565 return true;
566}
567
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -0700568static int find_field(const char* name, const char* const field_names[], int field_count) {
569 for (int i = 0; i < field_count; i++) {
570 if (!strcmp(name, field_names[i])) {
571 return i;
572 }
573 }
574 return -1;
575}
576
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700577static enum field_match_result match_field(const char* cp, const char* ap,
578 const char* const field_names[],
579 int field_count, int64_t* field,
580 int *field_idx) {
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -0700581 int i = find_field(cp, field_names, field_count);
582 if (i < 0) {
583 return NO_MATCH;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700584 }
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -0700585 *field_idx = i;
586 return parse_int64(ap, field) ? PARSE_SUCCESS : PARSE_FAIL;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700587}
588
Suren Baghdasaryan87966742018-04-13 12:43:41 -0700589/*
590 * Read file content from the beginning up to max_len bytes or EOF
591 * whichever happens first.
592 */
Colin Crossdba1cc62014-07-11 17:53:27 -0700593static ssize_t read_all(int fd, char *buf, size_t max_len)
594{
595 ssize_t ret = 0;
Suren Baghdasaryan87966742018-04-13 12:43:41 -0700596 off_t offset = 0;
Colin Crossdba1cc62014-07-11 17:53:27 -0700597
598 while (max_len > 0) {
Suren Baghdasaryan87966742018-04-13 12:43:41 -0700599 ssize_t r = TEMP_FAILURE_RETRY(pread(fd, buf, max_len, offset));
Colin Crossdba1cc62014-07-11 17:53:27 -0700600 if (r == 0) {
601 break;
602 }
603 if (r == -1) {
604 return -1;
605 }
606 ret += r;
607 buf += r;
Suren Baghdasaryan87966742018-04-13 12:43:41 -0700608 offset += r;
Colin Crossdba1cc62014-07-11 17:53:27 -0700609 max_len -= r;
610 }
611
612 return ret;
613}
614
Suren Baghdasaryan87966742018-04-13 12:43:41 -0700615/*
616 * Read a new or already opened file from the beginning.
617 * If the file has not been opened yet data->fd should be set to -1.
618 * To be used with files which are read often and possibly during high
619 * memory pressure to minimize file opening which by itself requires kernel
620 * memory allocation and might result in a stall on memory stressed system.
621 */
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -0700622static char *reread_file(struct reread_data *data) {
623 /* start with page-size buffer and increase if needed */
624 static ssize_t buf_size = PAGE_SIZE;
625 static char *new_buf, *buf = NULL;
Suren Baghdasaryan87966742018-04-13 12:43:41 -0700626 ssize_t size;
627
628 if (data->fd == -1) {
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -0700629 /* First-time buffer initialization */
Tom Cherry43f3d2b2019-12-04 12:46:57 -0800630 if (!buf && (buf = static_cast<char*>(malloc(buf_size))) == nullptr) {
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -0700631 return NULL;
632 }
633
634 data->fd = TEMP_FAILURE_RETRY(open(data->filename, O_RDONLY | O_CLOEXEC));
635 if (data->fd < 0) {
Suren Baghdasaryan87966742018-04-13 12:43:41 -0700636 ALOGE("%s open: %s", data->filename, strerror(errno));
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -0700637 return NULL;
Suren Baghdasaryan87966742018-04-13 12:43:41 -0700638 }
639 }
640
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -0700641 while (true) {
642 size = read_all(data->fd, buf, buf_size - 1);
643 if (size < 0) {
644 ALOGE("%s read: %s", data->filename, strerror(errno));
645 close(data->fd);
646 data->fd = -1;
647 return NULL;
648 }
649 if (size < buf_size - 1) {
650 break;
651 }
652 /*
653 * Since we are reading /proc files we can't use fstat to find out
654 * the real size of the file. Double the buffer size and keep retrying.
655 */
Tom Cherry43f3d2b2019-12-04 12:46:57 -0800656 if ((new_buf = static_cast<char*>(realloc(buf, buf_size * 2))) == nullptr) {
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -0700657 errno = ENOMEM;
658 return NULL;
659 }
660 buf = new_buf;
661 buf_size *= 2;
Suren Baghdasaryan87966742018-04-13 12:43:41 -0700662 }
Suren Baghdasaryan87966742018-04-13 12:43:41 -0700663 buf[size] = 0;
664
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -0700665 return buf;
Suren Baghdasaryan87966742018-04-13 12:43:41 -0700666}
667
Jing Ji5c480962019-12-04 09:22:05 -0800668static bool claim_record(struct proc* procp, pid_t pid) {
669 if (procp->reg_pid == pid) {
670 /* Record already belongs to the registrant */
671 return true;
672 }
673 if (procp->reg_pid == 0) {
674 /* Old registrant is gone, claim the record */
675 procp->reg_pid = pid;
676 return true;
677 }
678 /* The record is owned by another registrant */
679 return false;
680}
681
682static void remove_claims(pid_t pid) {
683 int i;
684
685 for (i = 0; i < PIDHASH_SZ; i++) {
686 struct proc* procp = pidhash[i];
687 while (procp) {
688 if (procp->reg_pid == pid) {
689 procp->reg_pid = 0;
690 }
691 procp = procp->pidhash_next;
692 }
693 }
694}
695
696static void ctrl_data_close(int dsock_idx) {
697 struct epoll_event epev;
698
699 ALOGI("closing lmkd data connection");
700 if (epoll_ctl(epollfd, EPOLL_CTL_DEL, data_sock[dsock_idx].sock, &epev) == -1) {
701 // Log a warning and keep going
702 ALOGW("epoll_ctl for data connection socket failed; errno=%d", errno);
703 }
704 maxevents--;
705
706 close(data_sock[dsock_idx].sock);
707 data_sock[dsock_idx].sock = -1;
708
709 /* Mark all records of the old registrant as unclaimed */
710 remove_claims(data_sock[dsock_idx].pid);
711}
712
713static ssize_t ctrl_data_read(int dsock_idx, char* buf, size_t bufsz, struct ucred* sender_cred) {
714 struct iovec iov = {buf, bufsz};
715 char control[CMSG_SPACE(sizeof(struct ucred))];
716 struct msghdr hdr = {
717 NULL, 0, &iov, 1, control, sizeof(control), 0,
718 };
719 ssize_t ret;
720 ret = TEMP_FAILURE_RETRY(recvmsg(data_sock[dsock_idx].sock, &hdr, 0));
721 if (ret == -1) {
722 ALOGE("control data socket read failed; %s", strerror(errno));
723 return -1;
724 }
725 if (ret == 0) {
726 ALOGE("Got EOF on control data socket");
727 return -1;
728 }
729
730 struct ucred* cred = NULL;
731 struct cmsghdr* cmsg = CMSG_FIRSTHDR(&hdr);
732 while (cmsg != NULL) {
733 if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_CREDENTIALS) {
734 cred = (struct ucred*)CMSG_DATA(cmsg);
735 break;
736 }
737 cmsg = CMSG_NXTHDR(&hdr, cmsg);
738 }
739
740 if (cred == NULL) {
741 ALOGE("Failed to retrieve sender credentials");
742 /* Close the connection */
743 ctrl_data_close(dsock_idx);
744 return -1;
745 }
746
747 memcpy(sender_cred, cred, sizeof(struct ucred));
748
749 /* Store PID of the peer */
750 data_sock[dsock_idx].pid = cred->pid;
751
752 return ret;
753}
754
755static int ctrl_data_write(int dsock_idx, char* buf, size_t bufsz) {
756 int ret = 0;
757
758 ret = TEMP_FAILURE_RETRY(write(data_sock[dsock_idx].sock, buf, bufsz));
759
760 if (ret == -1) {
761 ALOGE("control data socket write failed; errno=%d", errno);
762 } else if (ret == 0) {
763 ALOGE("Got EOF on control data socket");
764 ret = -1;
765 }
766
767 return ret;
768}
769
770/*
771 * Write the pid/uid pair over the data socket, note: all active clients
772 * will receive this unsolicited notification.
773 */
774static void ctrl_data_write_lmk_kill_occurred(pid_t pid, uid_t uid) {
775 LMKD_CTRL_PACKET packet;
776 size_t len = lmkd_pack_set_prockills(packet, pid, uid);
777
778 for (int i = 0; i < MAX_DATA_CONN; i++) {
Suren Baghdasaryan36baf442019-12-23 11:37:34 -0800779 if (data_sock[i].sock >= 0 && data_sock[i].async_event_mask & 1 << LMK_ASYNC_EVENT_KILL) {
Jing Ji5c480962019-12-04 09:22:05 -0800780 ctrl_data_write(i, (char*)packet, len);
781 }
782 }
783}
784
Vova Sharaienkoa92b76b2021-04-24 00:30:06 +0000785/*
786 * Write the kill_stat/memory_stat over the data socket to be propagated via AMS to statsd
787 */
788static void stats_write_lmk_kill_occurred(struct kill_stat *kill_st,
789 struct memory_stat *mem_st) {
790 LMK_KILL_OCCURRED_PACKET packet;
791 const size_t len = lmkd_pack_set_kill_occurred(packet, kill_st, mem_st);
792 if (len == 0) {
793 return;
794 }
795
796 for (int i = 0; i < MAX_DATA_CONN; i++) {
797 if (data_sock[i].sock >= 0 && data_sock[i].async_event_mask & 1 << LMK_ASYNC_EVENT_STAT) {
798 ctrl_data_write(i, packet, len);
799 }
800 }
801
802}
803
804static void stats_write_lmk_kill_occurred_pid(int pid, struct kill_stat *kill_st,
805 struct memory_stat *mem_st) {
806 kill_st->taskname = stats_get_task_name(pid);
807 if (kill_st->taskname != NULL) {
808 stats_write_lmk_kill_occurred(kill_st, mem_st);
809 }
810}
811
812/*
813 * Write the state_changed over the data socket to be propagated via AMS to statsd
814 */
815static void stats_write_lmk_state_changed(enum lmk_state state) {
816 LMKD_CTRL_PACKET packet_state_changed;
817 const size_t len = lmkd_pack_set_state_changed(packet_state_changed, state);
818 if (len == 0) {
819 return;
820 }
821 for (int i = 0; i < MAX_DATA_CONN; i++) {
822 if (data_sock[i].sock >= 0 && data_sock[i].async_event_mask & 1 << LMK_ASYNC_EVENT_STAT) {
823 ctrl_data_write(i, (char*)packet_state_changed, len);
824 }
825 }
826}
827
Jing Ji5c480962019-12-04 09:22:05 -0800828static void poll_kernel(int poll_fd) {
829 if (poll_fd == -1) {
830 // not waiting
831 return;
832 }
833
834 while (1) {
835 char rd_buf[256];
Bart Van Assche5ebc4e82022-02-03 00:05:19 +0000836 int bytes_read = TEMP_FAILURE_RETRY(pread(poll_fd, (void*)rd_buf, sizeof(rd_buf) - 1, 0));
Jing Ji5c480962019-12-04 09:22:05 -0800837 if (bytes_read <= 0) break;
838 rd_buf[bytes_read] = '\0';
839
840 int64_t pid;
841 int64_t uid;
842 int64_t group_leader_pid;
843 int64_t rss_in_pages;
844 struct memory_stat mem_st = {};
845 int16_t oom_score_adj;
846 int16_t min_score_adj;
847 int64_t starttime;
848 char* taskname = 0;
849
850 int fields_read =
851 sscanf(rd_buf,
852 "%" SCNd64 " %" SCNd64 " %" SCNd64 " %" SCNd64 " %" SCNd64 " %" SCNd64
853 " %" SCNd16 " %" SCNd16 " %" SCNd64 "\n%m[^\n]",
854 &pid, &uid, &group_leader_pid, &mem_st.pgfault, &mem_st.pgmajfault,
855 &rss_in_pages, &oom_score_adj, &min_score_adj, &starttime, &taskname);
856
857 /* only the death of the group leader process is logged */
858 if (fields_read == 10 && group_leader_pid == pid) {
859 ctrl_data_write_lmk_kill_occurred((pid_t)pid, (uid_t)uid);
860 mem_st.process_start_time_ns = starttime * (NS_PER_SEC / sysconf(_SC_CLK_TCK));
861 mem_st.rss_in_bytes = rss_in_pages * PAGE_SIZE;
Suren Baghdasaryan3cc1f132020-09-09 20:19:02 -0700862
863 struct kill_stat kill_st = {
864 .uid = static_cast<int32_t>(uid),
865 .kill_reason = NONE,
866 .oom_score = oom_score_adj,
867 .min_oom_score = min_score_adj,
868 .free_mem_kb = 0,
869 .free_swap_kb = 0,
870 };
871 stats_write_lmk_kill_occurred_pid(pid, &kill_st, &mem_st);
Jing Ji5c480962019-12-04 09:22:05 -0800872 }
873
874 free(taskname);
875 }
876}
877
878static bool init_poll_kernel() {
879 kpoll_fd = TEMP_FAILURE_RETRY(open("/proc/lowmemorykiller", O_RDONLY | O_NONBLOCK | O_CLOEXEC));
880
881 if (kpoll_fd < 0) {
882 ALOGE("kernel lmk event file could not be opened; errno=%d", errno);
883 return false;
884 }
885
886 return true;
887}
888
Todd Poynorc58c5142013-07-09 19:35:14 -0700889static struct proc *pid_lookup(int pid) {
890 struct proc *procp;
891
892 for (procp = pidhash[pid_hashfn(pid)]; procp && procp->pid != pid;
893 procp = procp->pidhash_next)
894 ;
895
896 return procp;
897}
898
Tom Cherry43f3d2b2019-12-04 12:46:57 -0800899static void adjslot_insert(struct adjslot_list *head, struct adjslot_list *new_element)
Todd Poynorc58c5142013-07-09 19:35:14 -0700900{
901 struct adjslot_list *next = head->next;
Tom Cherry43f3d2b2019-12-04 12:46:57 -0800902 new_element->prev = head;
903 new_element->next = next;
904 next->prev = new_element;
905 head->next = new_element;
Todd Poynorc58c5142013-07-09 19:35:14 -0700906}
907
908static void adjslot_remove(struct adjslot_list *old)
909{
910 struct adjslot_list *prev = old->prev;
911 struct adjslot_list *next = old->next;
912 next->prev = prev;
913 prev->next = next;
914}
915
916static struct adjslot_list *adjslot_tail(struct adjslot_list *head) {
917 struct adjslot_list *asl = head->prev;
918
919 return asl == head ? NULL : asl;
920}
921
Suren Baghdasaryanaf1b0e02021-11-16 11:50:29 -0800922// Should be modified only from the main thread.
Todd Poynorc58c5142013-07-09 19:35:14 -0700923static void proc_slot(struct proc *procp) {
924 int adjslot = ADJTOSLOT(procp->oomadj);
Suren Baghdasaryanaf1b0e02021-11-16 11:50:29 -0800925 std::scoped_lock lock(adjslot_list_lock);
Todd Poynorc58c5142013-07-09 19:35:14 -0700926
927 adjslot_insert(&procadjslot_list[adjslot], &procp->asl);
928}
929
Suren Baghdasaryanaf1b0e02021-11-16 11:50:29 -0800930// Should be modified only from the main thread.
Todd Poynorc58c5142013-07-09 19:35:14 -0700931static void proc_unslot(struct proc *procp) {
Suren Baghdasaryanaf1b0e02021-11-16 11:50:29 -0800932 std::scoped_lock lock(adjslot_list_lock);
933
Todd Poynorc58c5142013-07-09 19:35:14 -0700934 adjslot_remove(&procp->asl);
935}
936
937static void proc_insert(struct proc *procp) {
938 int hval = pid_hashfn(procp->pid);
939
940 procp->pidhash_next = pidhash[hval];
941 pidhash[hval] = procp;
942 proc_slot(procp);
943}
944
945static int pid_remove(int pid) {
946 int hval = pid_hashfn(pid);
947 struct proc *procp;
948 struct proc *prevp;
949
950 for (procp = pidhash[hval], prevp = NULL; procp && procp->pid != pid;
951 procp = procp->pidhash_next)
952 prevp = procp;
953
954 if (!procp)
955 return -1;
956
957 if (!prevp)
958 pidhash[hval] = procp->pidhash_next;
959 else
960 prevp->pidhash_next = procp->pidhash_next;
961
962 proc_unslot(procp);
Suren Baghdasaryana10157c2019-07-19 10:55:39 -0700963 /*
964 * Close pidfd here if we are not waiting for corresponding process to die,
965 * in which case stop_wait_for_proc_kill() will close the pidfd later
966 */
967 if (procp->pidfd >= 0 && procp->pidfd != last_kill_pid_or_fd) {
968 close(procp->pidfd);
969 }
Todd Poynorc58c5142013-07-09 19:35:14 -0700970 free(procp);
971 return 0;
972}
973
Suren Baghdasaryanf584fff2018-03-20 13:53:17 -0700974/*
975 * Write a string to a file.
976 * Returns false if the file does not exist.
977 */
978static bool writefilestring(const char *path, const char *s,
979 bool err_if_missing) {
Nick Kralevich148d8dd2015-12-18 20:52:37 -0800980 int fd = open(path, O_WRONLY | O_CLOEXEC);
Suren Baghdasaryanf584fff2018-03-20 13:53:17 -0700981 ssize_t len = strlen(s);
982 ssize_t ret;
Todd Poynorc58c5142013-07-09 19:35:14 -0700983
984 if (fd < 0) {
Suren Baghdasaryanf584fff2018-03-20 13:53:17 -0700985 if (err_if_missing) {
986 ALOGE("Error opening %s; errno=%d", path, errno);
987 }
988 return false;
Todd Poynorc58c5142013-07-09 19:35:14 -0700989 }
990
Suren Baghdasaryanf584fff2018-03-20 13:53:17 -0700991 ret = TEMP_FAILURE_RETRY(write(fd, s, len));
Todd Poynorc58c5142013-07-09 19:35:14 -0700992 if (ret < 0) {
993 ALOGE("Error writing %s; errno=%d", path, errno);
994 } else if (ret < len) {
Suren Baghdasaryanf584fff2018-03-20 13:53:17 -0700995 ALOGE("Short write on %s; length=%zd", path, ret);
Todd Poynorc58c5142013-07-09 19:35:14 -0700996 }
997
998 close(fd);
Suren Baghdasaryanf584fff2018-03-20 13:53:17 -0700999 return true;
Todd Poynorc58c5142013-07-09 19:35:14 -07001000}
1001
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -07001002static inline long get_time_diff_ms(struct timespec *from,
1003 struct timespec *to) {
1004 return (to->tv_sec - from->tv_sec) * (long)MS_PER_SEC +
1005 (to->tv_nsec - from->tv_nsec) / (long)NS_PER_MS;
1006}
1007
Ioannis Ilkos279268a2020-08-01 10:50:40 +01001008/* Reads /proc/pid/status into buf. */
1009static bool read_proc_status(int pid, char *buf, size_t buf_sz) {
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -07001010 char path[PATH_MAX];
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -07001011 int fd;
1012 ssize_t size;
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -07001013
1014 snprintf(path, PATH_MAX, "/proc/%d/status", pid);
1015 fd = open(path, O_RDONLY | O_CLOEXEC);
1016 if (fd < 0) {
Ioannis Ilkos279268a2020-08-01 10:50:40 +01001017 return false;
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -07001018 }
1019
Ioannis Ilkos279268a2020-08-01 10:50:40 +01001020 size = read_all(fd, buf, buf_sz - 1);
1021 close(fd);
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -07001022 if (size < 0) {
Ioannis Ilkos279268a2020-08-01 10:50:40 +01001023 return false;
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -07001024 }
1025 buf[size] = 0;
Ioannis Ilkos279268a2020-08-01 10:50:40 +01001026 return true;
1027}
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -07001028
Ioannis Ilkos279268a2020-08-01 10:50:40 +01001029/* Looks for tag in buf and parses the first integer */
1030static bool parse_status_tag(char *buf, const char *tag, int64_t *out) {
1031 char *pos = buf;
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -07001032 while (true) {
Ioannis Ilkos279268a2020-08-01 10:50:40 +01001033 pos = strstr(pos, tag);
1034 /* Stop if tag not found or found at the line beginning */
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -07001035 if (pos == NULL || pos == buf || pos[-1] == '\n') {
1036 break;
1037 }
1038 pos++;
1039 }
1040
1041 if (pos == NULL) {
Ioannis Ilkos279268a2020-08-01 10:50:40 +01001042 return false;
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -07001043 }
1044
Ioannis Ilkos279268a2020-08-01 10:50:40 +01001045 pos += strlen(tag);
1046 while (*pos == ' ') ++pos;
1047 return parse_int64(pos, out);
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -07001048}
1049
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07001050static int proc_get_size(int pid) {
1051 char path[PATH_MAX];
1052 char line[LINE_MAX];
1053 int fd;
1054 int rss = 0;
1055 int total;
1056 ssize_t ret;
1057
1058 /* gid containing AID_READPROC required */
1059 snprintf(path, PATH_MAX, "/proc/%d/statm", pid);
1060 fd = open(path, O_RDONLY | O_CLOEXEC);
1061 if (fd == -1)
1062 return -1;
1063
1064 ret = read_all(fd, line, sizeof(line) - 1);
1065 if (ret < 0) {
1066 close(fd);
1067 return -1;
1068 }
Suren Baghdasaryan632f1c52019-10-04 16:06:55 -07001069 line[ret] = '\0';
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07001070
1071 sscanf(line, "%d %d ", &total, &rss);
1072 close(fd);
1073 return rss;
1074}
1075
Suren Baghdasaryan632f1c52019-10-04 16:06:55 -07001076static char *proc_get_name(int pid, char *buf, size_t buf_size) {
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07001077 char path[PATH_MAX];
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07001078 int fd;
1079 char *cp;
1080 ssize_t ret;
1081
1082 /* gid containing AID_READPROC required */
1083 snprintf(path, PATH_MAX, "/proc/%d/cmdline", pid);
1084 fd = open(path, O_RDONLY | O_CLOEXEC);
1085 if (fd == -1) {
1086 return NULL;
1087 }
Suren Baghdasaryan632f1c52019-10-04 16:06:55 -07001088 ret = read_all(fd, buf, buf_size - 1);
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07001089 close(fd);
1090 if (ret < 0) {
1091 return NULL;
1092 }
Suren Baghdasaryan632f1c52019-10-04 16:06:55 -07001093 buf[ret] = '\0';
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07001094
Suren Baghdasaryan632f1c52019-10-04 16:06:55 -07001095 cp = strchr(buf, ' ');
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07001096 if (cp) {
1097 *cp = '\0';
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07001098 }
1099
Suren Baghdasaryan632f1c52019-10-04 16:06:55 -07001100 return buf;
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07001101}
1102
Suren Baghdasaryana93503e2019-10-22 17:12:01 -07001103static void cmd_procprio(LMKD_CTRL_PACKET packet, int field_count, struct ucred *cred) {
Todd Poynorc58c5142013-07-09 19:35:14 -07001104 struct proc *procp;
Suren Baghdasaryan632f1c52019-10-04 16:06:55 -07001105 char path[LINE_MAX];
Todd Poynorc58c5142013-07-09 19:35:14 -07001106 char val[20];
Robert Benea58d6a132017-06-01 16:32:31 -07001107 int soft_limit_mult;
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -08001108 struct lmk_procprio params;
Suren Baghdasaryanbb7747b2018-03-20 16:03:29 -07001109 bool is_system_server;
1110 struct passwd *pwdrec;
Ioannis Ilkos279268a2020-08-01 10:50:40 +01001111 int64_t tgid;
1112 char buf[PAGE_SIZE];
Todd Poynorc58c5142013-07-09 19:35:14 -07001113
Suren Baghdasaryana93503e2019-10-22 17:12:01 -07001114 lmkd_pack_get_procprio(packet, field_count, &params);
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -08001115
1116 if (params.oomadj < OOM_SCORE_ADJ_MIN ||
1117 params.oomadj > OOM_SCORE_ADJ_MAX) {
1118 ALOGE("Invalid PROCPRIO oomadj argument %d", params.oomadj);
Todd Poynorc58c5142013-07-09 19:35:14 -07001119 return;
1120 }
1121
Suren Baghdasaryana93503e2019-10-22 17:12:01 -07001122 if (params.ptype < PROC_TYPE_FIRST || params.ptype >= PROC_TYPE_COUNT) {
1123 ALOGE("Invalid PROCPRIO process type argument %d", params.ptype);
1124 return;
1125 }
1126
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -07001127 /* Check if registered process is a thread group leader */
Ioannis Ilkos279268a2020-08-01 10:50:40 +01001128 if (read_proc_status(params.pid, buf, sizeof(buf))) {
1129 if (parse_status_tag(buf, PROC_STATUS_TGID_FIELD, &tgid) && tgid != params.pid) {
1130 ALOGE("Attempt to register a task that is not a thread group leader "
1131 "(tid %d, tgid %" PRId64 ")", params.pid, tgid);
1132 return;
1133 }
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -07001134 }
1135
Mark Salyzyna00ccd82018-04-09 09:50:32 -07001136 /* gid containing AID_READPROC required */
1137 /* CAP_SYS_RESOURCE required */
1138 /* CAP_DAC_OVERRIDE required */
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -08001139 snprintf(path, sizeof(path), "/proc/%d/oom_score_adj", params.pid);
1140 snprintf(val, sizeof(val), "%d", params.oomadj);
Suren Baghdasaryanf584fff2018-03-20 13:53:17 -07001141 if (!writefilestring(path, val, false)) {
1142 ALOGW("Failed to open %s; errno=%d: process %d might have been killed",
1143 path, errno, params.pid);
1144 /* If this file does not exist the process is dead. */
1145 return;
1146 }
Todd Poynorc58c5142013-07-09 19:35:14 -07001147
Mark Salyzyn5cc80b32018-03-21 12:24:58 -07001148 if (use_inkernel_interface) {
Jing Ji5c480962019-12-04 09:22:05 -08001149 stats_store_taskname(params.pid, proc_get_name(params.pid, path, sizeof(path)));
Todd Poynorc58c5142013-07-09 19:35:14 -07001150 return;
Mark Salyzyn5cc80b32018-03-21 12:24:58 -07001151 }
Todd Poynorc58c5142013-07-09 19:35:14 -07001152
Suren Baghdasaryana93503e2019-10-22 17:12:01 -07001153 /* lmkd should not change soft limits for services */
1154 if (params.ptype == PROC_TYPE_APP && per_app_memcg) {
Suren Baghdasaryanb0bda552018-05-18 14:42:00 -07001155 if (params.oomadj >= 900) {
1156 soft_limit_mult = 0;
1157 } else if (params.oomadj >= 800) {
1158 soft_limit_mult = 0;
1159 } else if (params.oomadj >= 700) {
1160 soft_limit_mult = 0;
1161 } else if (params.oomadj >= 600) {
1162 // Launcher should be perceptible, don't kill it.
1163 params.oomadj = 200;
1164 soft_limit_mult = 1;
1165 } else if (params.oomadj >= 500) {
1166 soft_limit_mult = 0;
1167 } else if (params.oomadj >= 400) {
1168 soft_limit_mult = 0;
1169 } else if (params.oomadj >= 300) {
1170 soft_limit_mult = 1;
1171 } else if (params.oomadj >= 200) {
Srinivas Paladugua453f0b2018-10-09 14:21:10 -07001172 soft_limit_mult = 8;
Suren Baghdasaryanb0bda552018-05-18 14:42:00 -07001173 } else if (params.oomadj >= 100) {
1174 soft_limit_mult = 10;
1175 } else if (params.oomadj >= 0) {
1176 soft_limit_mult = 20;
1177 } else {
1178 // Persistent processes will have a large
1179 // soft limit 512MB.
1180 soft_limit_mult = 64;
1181 }
Robert Benea58d6a132017-06-01 16:32:31 -07001182
Bart Van Asscheb4d26bb2022-02-17 21:31:51 +00001183 std::string path;
1184 if (!CgroupGetAttributePathForTask("MemSoftLimit", params.pid, &path)) {
1185 ALOGE("Querying MemSoftLimit path failed");
1186 return;
1187 }
1188
Suren Baghdasaryanb0bda552018-05-18 14:42:00 -07001189 snprintf(val, sizeof(val), "%d", soft_limit_mult * EIGHT_MEGA);
Suren Baghdasaryanbf919ff2018-05-21 19:48:47 -07001190
1191 /*
1192 * system_server process has no memcg under /dev/memcg/apps but should be
1193 * registered with lmkd. This is the best way so far to identify it.
1194 */
1195 is_system_server = (params.oomadj == SYSTEM_ADJ &&
1196 (pwdrec = getpwnam("system")) != NULL &&
1197 params.uid == pwdrec->pw_uid);
Bart Van Asscheb4d26bb2022-02-17 21:31:51 +00001198 writefilestring(path.c_str(), val, !is_system_server);
Robert Benea58d6a132017-06-01 16:32:31 -07001199 }
1200
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -08001201 procp = pid_lookup(params.pid);
Todd Poynorc58c5142013-07-09 19:35:14 -07001202 if (!procp) {
Suren Baghdasaryana10157c2019-07-19 10:55:39 -07001203 int pidfd = -1;
1204
1205 if (pidfd_supported) {
Josh Gao84623be2021-03-18 17:16:08 -07001206 pidfd = TEMP_FAILURE_RETRY(pidfd_open(params.pid, 0));
Suren Baghdasaryana10157c2019-07-19 10:55:39 -07001207 if (pidfd < 0) {
1208 ALOGE("pidfd_open for pid %d failed; errno=%d", params.pid, errno);
Todd Poynorc58c5142013-07-09 19:35:14 -07001209 return;
1210 }
Suren Baghdasaryana10157c2019-07-19 10:55:39 -07001211 }
Todd Poynorc58c5142013-07-09 19:35:14 -07001212
Tom Cherry43f3d2b2019-12-04 12:46:57 -08001213 procp = static_cast<struct proc*>(calloc(1, sizeof(struct proc)));
Suren Baghdasaryana10157c2019-07-19 10:55:39 -07001214 if (!procp) {
1215 // Oh, the irony. May need to rebuild our state.
1216 return;
1217 }
1218
1219 procp->pid = params.pid;
1220 procp->pidfd = pidfd;
1221 procp->uid = params.uid;
Suren Baghdasaryan945658a2019-10-18 11:16:52 -07001222 procp->reg_pid = cred->pid;
Suren Baghdasaryana10157c2019-07-19 10:55:39 -07001223 procp->oomadj = params.oomadj;
1224 proc_insert(procp);
Todd Poynorc58c5142013-07-09 19:35:14 -07001225 } else {
Suren Baghdasaryan945658a2019-10-18 11:16:52 -07001226 if (!claim_record(procp, cred->pid)) {
1227 char buf[LINE_MAX];
Suren Baghdasaryan9f1be122021-04-23 13:39:37 -07001228 char *taskname = proc_get_name(cred->pid, buf, sizeof(buf));
Suren Baghdasaryan945658a2019-10-18 11:16:52 -07001229 /* Only registrant of the record can remove it */
1230 ALOGE("%s (%d, %d) attempts to modify a process registered by another client",
Suren Baghdasaryan9f1be122021-04-23 13:39:37 -07001231 taskname ? taskname : "A process ", cred->uid, cred->pid);
Suren Baghdasaryan945658a2019-10-18 11:16:52 -07001232 return;
1233 }
Todd Poynorc58c5142013-07-09 19:35:14 -07001234 proc_unslot(procp);
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -08001235 procp->oomadj = params.oomadj;
Todd Poynorc58c5142013-07-09 19:35:14 -07001236 proc_slot(procp);
1237 }
1238}
1239
Suren Baghdasaryan945658a2019-10-18 11:16:52 -07001240static void cmd_procremove(LMKD_CTRL_PACKET packet, struct ucred *cred) {
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -08001241 struct lmk_procremove params;
Suren Baghdasaryan945658a2019-10-18 11:16:52 -07001242 struct proc *procp;
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -08001243
George Burgess IV3b36b902019-10-02 11:22:55 -07001244 lmkd_pack_get_procremove(packet, &params);
Suren Baghdasaryan945658a2019-10-18 11:16:52 -07001245
Mark Salyzyn5cc80b32018-03-21 12:24:58 -07001246 if (use_inkernel_interface) {
Jing Ji5c480962019-12-04 09:22:05 -08001247 /*
1248 * Perform an extra check before the pid is removed, after which it
1249 * will be impossible for poll_kernel to get the taskname. poll_kernel()
1250 * is potentially a long-running blocking function; however this method
1251 * handles AMS requests but does not block AMS.
1252 */
1253 poll_kernel(kpoll_fd);
1254
1255 stats_remove_taskname(params.pid);
Todd Poynorc58c5142013-07-09 19:35:14 -07001256 return;
Mark Salyzyn5cc80b32018-03-21 12:24:58 -07001257 }
Todd Poynorc58c5142013-07-09 19:35:14 -07001258
Suren Baghdasaryan945658a2019-10-18 11:16:52 -07001259 procp = pid_lookup(params.pid);
1260 if (!procp) {
1261 return;
1262 }
1263
1264 if (!claim_record(procp, cred->pid)) {
1265 char buf[LINE_MAX];
Suren Baghdasaryan9f1be122021-04-23 13:39:37 -07001266 char *taskname = proc_get_name(cred->pid, buf, sizeof(buf));
Suren Baghdasaryan945658a2019-10-18 11:16:52 -07001267 /* Only registrant of the record can remove it */
1268 ALOGE("%s (%d, %d) attempts to unregister a process registered by another client",
Suren Baghdasaryan9f1be122021-04-23 13:39:37 -07001269 taskname ? taskname : "A process ", cred->uid, cred->pid);
Suren Baghdasaryan945658a2019-10-18 11:16:52 -07001270 return;
1271 }
1272
Suren Baghdasaryan8b00c6d2018-10-12 11:28:33 -07001273 /*
1274 * WARNING: After pid_remove() procp is freed and can't be used!
1275 * Therefore placed at the end of the function.
1276 */
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -08001277 pid_remove(params.pid);
Todd Poynorc58c5142013-07-09 19:35:14 -07001278}
1279
Suren Baghdasaryan945658a2019-10-18 11:16:52 -07001280static void cmd_procpurge(struct ucred *cred) {
Suren Baghdasaryan83df0082018-10-10 14:17:17 -07001281 int i;
1282 struct proc *procp;
1283 struct proc *next;
1284
1285 if (use_inkernel_interface) {
Jim Blackler90853b62019-09-10 15:30:05 +01001286 stats_purge_tasknames();
Suren Baghdasaryan83df0082018-10-10 14:17:17 -07001287 return;
1288 }
1289
Suren Baghdasaryan83df0082018-10-10 14:17:17 -07001290 for (i = 0; i < PIDHASH_SZ; i++) {
1291 procp = pidhash[i];
1292 while (procp) {
1293 next = procp->pidhash_next;
Suren Baghdasaryan945658a2019-10-18 11:16:52 -07001294 /* Purge only records created by the requestor */
1295 if (claim_record(procp, cred->pid)) {
1296 pid_remove(procp->pid);
1297 }
Suren Baghdasaryan83df0082018-10-10 14:17:17 -07001298 procp = next;
1299 }
1300 }
Suren Baghdasaryan83df0082018-10-10 14:17:17 -07001301}
1302
Suren Baghdasaryan36baf442019-12-23 11:37:34 -08001303static void cmd_subscribe(int dsock_idx, LMKD_CTRL_PACKET packet) {
1304 struct lmk_subscribe params;
1305
1306 lmkd_pack_get_subscribe(packet, &params);
1307 data_sock[dsock_idx].async_event_mask |= 1 << params.evt_type;
1308}
1309
Suren Baghdasaryana7394ea2018-10-12 11:07:40 -07001310static void inc_killcnt(int oomadj) {
1311 int slot = ADJTOSLOT(oomadj);
1312 uint8_t idx = killcnt_idx[slot];
1313
1314 if (idx == KILLCNT_INVALID_IDX) {
1315 /* index is not assigned for this oomadj */
1316 if (killcnt_free_idx < MAX_DISTINCT_OOM_ADJ) {
1317 killcnt_idx[slot] = killcnt_free_idx;
1318 killcnt[killcnt_free_idx] = 1;
1319 killcnt_free_idx++;
1320 } else {
1321 ALOGW("Number of distinct oomadj levels exceeds %d",
1322 MAX_DISTINCT_OOM_ADJ);
1323 }
1324 } else {
1325 /*
1326 * wraparound is highly unlikely and is detectable using total
1327 * counter because it has to be equal to the sum of all counters
1328 */
1329 killcnt[idx]++;
1330 }
1331 /* increment total kill counter */
1332 killcnt_total++;
1333}
1334
1335static int get_killcnt(int min_oomadj, int max_oomadj) {
1336 int slot;
1337 int count = 0;
1338
1339 if (min_oomadj > max_oomadj)
1340 return 0;
1341
1342 /* special case to get total kill count */
1343 if (min_oomadj > OOM_SCORE_ADJ_MAX)
1344 return killcnt_total;
1345
1346 while (min_oomadj <= max_oomadj &&
1347 (slot = ADJTOSLOT(min_oomadj)) < ADJTOSLOT_COUNT) {
1348 uint8_t idx = killcnt_idx[slot];
1349 if (idx != KILLCNT_INVALID_IDX) {
1350 count += killcnt[idx];
1351 }
1352 min_oomadj++;
1353 }
1354
1355 return count;
1356}
1357
1358static int cmd_getkillcnt(LMKD_CTRL_PACKET packet) {
1359 struct lmk_getkillcnt params;
1360
1361 if (use_inkernel_interface) {
1362 /* kernel driver does not expose this information */
1363 return 0;
1364 }
1365
1366 lmkd_pack_get_getkillcnt(packet, &params);
1367
1368 return get_killcnt(params.min_oomadj, params.max_oomadj);
1369}
1370
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -08001371static void cmd_target(int ntargets, LMKD_CTRL_PACKET packet) {
Todd Poynorc58c5142013-07-09 19:35:14 -07001372 int i;
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -08001373 struct lmk_target target;
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -07001374 char minfree_str[PROPERTY_VALUE_MAX];
1375 char *pstr = minfree_str;
1376 char *pend = minfree_str + sizeof(minfree_str);
1377 static struct timespec last_req_tm;
1378 struct timespec curr_tm;
Todd Poynorc58c5142013-07-09 19:35:14 -07001379
Bart Van Assche54506792022-02-02 23:57:01 +00001380 if (ntargets < 1 || ntargets > (int)lowmem_adj.size()) {
Todd Poynorc58c5142013-07-09 19:35:14 -07001381 return;
Bart Van Assche54506792022-02-02 23:57:01 +00001382 }
Todd Poynorc58c5142013-07-09 19:35:14 -07001383
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -07001384 /*
1385 * Ratelimit minfree updates to once per TARGET_UPDATE_MIN_INTERVAL_MS
1386 * to prevent DoS attacks
1387 */
1388 if (clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm) != 0) {
1389 ALOGE("Failed to get current time");
1390 return;
1391 }
1392
1393 if (get_time_diff_ms(&last_req_tm, &curr_tm) <
1394 TARGET_UPDATE_MIN_INTERVAL_MS) {
1395 ALOGE("Ignoring frequent updated to lmkd limits");
1396 return;
1397 }
1398
1399 last_req_tm = curr_tm;
1400
Todd Poynorc58c5142013-07-09 19:35:14 -07001401 for (i = 0; i < ntargets; i++) {
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -08001402 lmkd_pack_get_target(packet, i, &target);
1403 lowmem_minfree[i] = target.minfree;
1404 lowmem_adj[i] = target.oom_adj_score;
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -07001405
1406 pstr += snprintf(pstr, pend - pstr, "%d:%d,", target.minfree,
1407 target.oom_adj_score);
1408 if (pstr >= pend) {
1409 /* if no more space in the buffer then terminate the loop */
1410 pstr = pend;
1411 break;
1412 }
Todd Poynorc58c5142013-07-09 19:35:14 -07001413 }
1414
1415 lowmem_targets_size = ntargets;
1416
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -07001417 /* Override the last extra comma */
1418 pstr[-1] = '\0';
1419 property_set("sys.lmk.minfree_levels", minfree_str);
1420
Robert Benea7878c9b2017-09-11 16:53:28 -07001421 if (has_inkernel_module) {
Todd Poynorc58c5142013-07-09 19:35:14 -07001422 char minfreestr[128];
1423 char killpriostr[128];
1424
1425 minfreestr[0] = '\0';
1426 killpriostr[0] = '\0';
1427
1428 for (i = 0; i < lowmem_targets_size; i++) {
1429 char val[40];
1430
1431 if (i) {
1432 strlcat(minfreestr, ",", sizeof(minfreestr));
1433 strlcat(killpriostr, ",", sizeof(killpriostr));
1434 }
1435
Robert Benea7878c9b2017-09-11 16:53:28 -07001436 snprintf(val, sizeof(val), "%d", use_inkernel_interface ? lowmem_minfree[i] : 0);
Todd Poynorc58c5142013-07-09 19:35:14 -07001437 strlcat(minfreestr, val, sizeof(minfreestr));
Robert Benea7878c9b2017-09-11 16:53:28 -07001438 snprintf(val, sizeof(val), "%d", use_inkernel_interface ? lowmem_adj[i] : 0);
Todd Poynorc58c5142013-07-09 19:35:14 -07001439 strlcat(killpriostr, val, sizeof(killpriostr));
1440 }
1441
Suren Baghdasaryanf584fff2018-03-20 13:53:17 -07001442 writefilestring(INKERNEL_MINFREE_PATH, minfreestr, true);
1443 writefilestring(INKERNEL_ADJ_PATH, killpriostr, true);
Todd Poynorc58c5142013-07-09 19:35:14 -07001444 }
1445}
1446
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08001447static void ctrl_command_handler(int dsock_idx) {
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -08001448 LMKD_CTRL_PACKET packet;
Suren Baghdasaryan945658a2019-10-18 11:16:52 -07001449 struct ucred cred;
Todd Poynorc58c5142013-07-09 19:35:14 -07001450 int len;
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -08001451 enum lmk_cmd cmd;
Todd Poynorc58c5142013-07-09 19:35:14 -07001452 int nargs;
1453 int targets;
Suren Baghdasaryana7394ea2018-10-12 11:07:40 -07001454 int kill_cnt;
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07001455 int result;
Todd Poynorc58c5142013-07-09 19:35:14 -07001456
Suren Baghdasaryan945658a2019-10-18 11:16:52 -07001457 len = ctrl_data_read(dsock_idx, (char *)packet, CTRL_PACKET_MAX_SIZE, &cred);
Todd Poynorc58c5142013-07-09 19:35:14 -07001458 if (len <= 0)
1459 return;
1460
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -08001461 if (len < (int)sizeof(int)) {
1462 ALOGE("Wrong control socket read length len=%d", len);
1463 return;
1464 }
1465
1466 cmd = lmkd_pack_get_cmd(packet);
Todd Poynorc58c5142013-07-09 19:35:14 -07001467 nargs = len / sizeof(int) - 1;
1468 if (nargs < 0)
1469 goto wronglen;
1470
Todd Poynorc58c5142013-07-09 19:35:14 -07001471 switch(cmd) {
1472 case LMK_TARGET:
1473 targets = nargs / 2;
Bart Van Assche54506792022-02-02 23:57:01 +00001474 if (nargs & 0x1 || targets > (int)lowmem_adj.size()) {
Todd Poynorc58c5142013-07-09 19:35:14 -07001475 goto wronglen;
Bart Van Assche54506792022-02-02 23:57:01 +00001476 }
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -08001477 cmd_target(targets, packet);
Todd Poynorc58c5142013-07-09 19:35:14 -07001478 break;
1479 case LMK_PROCPRIO:
Suren Baghdasaryana93503e2019-10-22 17:12:01 -07001480 /* process type field is optional for backward compatibility */
1481 if (nargs < 3 || nargs > 4)
Todd Poynorc58c5142013-07-09 19:35:14 -07001482 goto wronglen;
Suren Baghdasaryana93503e2019-10-22 17:12:01 -07001483 cmd_procprio(packet, nargs, &cred);
Todd Poynorc58c5142013-07-09 19:35:14 -07001484 break;
1485 case LMK_PROCREMOVE:
1486 if (nargs != 1)
1487 goto wronglen;
Suren Baghdasaryan945658a2019-10-18 11:16:52 -07001488 cmd_procremove(packet, &cred);
Todd Poynorc58c5142013-07-09 19:35:14 -07001489 break;
Suren Baghdasaryan83df0082018-10-10 14:17:17 -07001490 case LMK_PROCPURGE:
1491 if (nargs != 0)
1492 goto wronglen;
Suren Baghdasaryan945658a2019-10-18 11:16:52 -07001493 cmd_procpurge(&cred);
Suren Baghdasaryan83df0082018-10-10 14:17:17 -07001494 break;
Suren Baghdasaryana7394ea2018-10-12 11:07:40 -07001495 case LMK_GETKILLCNT:
1496 if (nargs != 2)
1497 goto wronglen;
1498 kill_cnt = cmd_getkillcnt(packet);
1499 len = lmkd_pack_set_getkillcnt_repl(packet, kill_cnt);
1500 if (ctrl_data_write(dsock_idx, (char *)packet, len) != len)
1501 return;
1502 break;
Suren Baghdasaryan36baf442019-12-23 11:37:34 -08001503 case LMK_SUBSCRIBE:
1504 if (nargs != 1)
1505 goto wronglen;
1506 cmd_subscribe(dsock_idx, packet);
1507 break;
Jing Ji5c480962019-12-04 09:22:05 -08001508 case LMK_PROCKILL:
1509 /* This command code is NOT expected at all */
1510 ALOGE("Received unexpected command code %d", cmd);
1511 break;
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07001512 case LMK_UPDATE_PROPS:
1513 if (nargs != 0)
1514 goto wronglen;
1515 update_props();
1516 if (!use_inkernel_interface) {
1517 /* Reinitialize monitors to apply new settings */
1518 destroy_monitors();
1519 result = init_monitors() ? 0 : -1;
1520 } else {
1521 result = 0;
1522 }
1523 len = lmkd_pack_set_update_props_repl(packet, result);
1524 if (ctrl_data_write(dsock_idx, (char *)packet, len) != len) {
1525 ALOGE("Failed to report operation results");
1526 }
1527 if (!result) {
1528 ALOGI("Properties reinitilized");
1529 } else {
1530 /* New settings can't be supported, crash to be restarted */
1531 ALOGE("New configuration is not supported. Exiting...");
1532 exit(1);
1533 }
1534 break;
Todd Poynorc58c5142013-07-09 19:35:14 -07001535 default:
1536 ALOGE("Received unknown command code %d", cmd);
1537 return;
1538 }
1539
1540 return;
1541
1542wronglen:
1543 ALOGE("Wrong control socket read length cmd=%d len=%d", cmd, len);
1544}
1545
Suren Baghdasaryane12a0672019-07-15 14:50:49 -07001546static void ctrl_data_handler(int data, uint32_t events,
1547 struct polling_params *poll_params __unused) {
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08001548 if (events & EPOLLIN) {
1549 ctrl_command_handler(data);
Todd Poynorc58c5142013-07-09 19:35:14 -07001550 }
1551}
1552
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08001553static int get_free_dsock() {
1554 for (int i = 0; i < MAX_DATA_CONN; i++) {
1555 if (data_sock[i].sock < 0) {
1556 return i;
1557 }
1558 }
1559 return -1;
1560}
Todd Poynorc58c5142013-07-09 19:35:14 -07001561
Suren Baghdasaryane12a0672019-07-15 14:50:49 -07001562static void ctrl_connect_handler(int data __unused, uint32_t events __unused,
1563 struct polling_params *poll_params __unused) {
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08001564 struct epoll_event epev;
1565 int free_dscock_idx = get_free_dsock();
1566
1567 if (free_dscock_idx < 0) {
1568 /*
1569 * Number of data connections exceeded max supported. This should not
1570 * happen but if it does we drop all existing connections and accept
1571 * the new one. This prevents inactive connections from monopolizing
1572 * data socket and if we drop ActivityManager connection it will
1573 * immediately reconnect.
1574 */
1575 for (int i = 0; i < MAX_DATA_CONN; i++) {
1576 ctrl_data_close(i);
1577 }
1578 free_dscock_idx = 0;
Todd Poynorc58c5142013-07-09 19:35:14 -07001579 }
1580
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08001581 data_sock[free_dscock_idx].sock = accept(ctrl_sock.sock, NULL, NULL);
1582 if (data_sock[free_dscock_idx].sock < 0) {
Todd Poynorc58c5142013-07-09 19:35:14 -07001583 ALOGE("lmkd control socket accept failed; errno=%d", errno);
1584 return;
1585 }
1586
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08001587 ALOGI("lmkd data connection established");
1588 /* use data to store data connection idx */
1589 data_sock[free_dscock_idx].handler_info.data = free_dscock_idx;
1590 data_sock[free_dscock_idx].handler_info.handler = ctrl_data_handler;
Suren Baghdasaryan36baf442019-12-23 11:37:34 -08001591 data_sock[free_dscock_idx].async_event_mask = 0;
Todd Poynorc58c5142013-07-09 19:35:14 -07001592 epev.events = EPOLLIN;
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08001593 epev.data.ptr = (void *)&(data_sock[free_dscock_idx].handler_info);
1594 if (epoll_ctl(epollfd, EPOLL_CTL_ADD, data_sock[free_dscock_idx].sock, &epev) == -1) {
Todd Poynorc58c5142013-07-09 19:35:14 -07001595 ALOGE("epoll_ctl for data connection socket failed; errno=%d", errno);
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08001596 ctrl_data_close(free_dscock_idx);
Todd Poynorc58c5142013-07-09 19:35:14 -07001597 return;
1598 }
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08001599 maxevents++;
Todd Poynorc58c5142013-07-09 19:35:14 -07001600}
1601
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001602/*
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07001603 * /proc/zoneinfo parsing routines
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001604 * Expected file format is:
1605 *
1606 * Node <node_id>, zone <zone_name>
1607 * (
1608 * per-node stats
1609 * (<per-node field name> <value>)+
1610 * )?
1611 * (pages free <value>
1612 * (<per-zone field name> <value>)+
1613 * pagesets
1614 * (<unused fields>)*
1615 * )+
1616 * ...
1617 */
1618static void zoneinfo_parse_protection(char *buf, struct zoneinfo_zone *zone) {
1619 int zone_idx;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001620 int64_t max = 0;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001621 char *save_ptr;
1622
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001623 for (buf = strtok_r(buf, "(), ", &save_ptr), zone_idx = 0;
1624 buf && zone_idx < MAX_NR_ZONES;
1625 buf = strtok_r(NULL, "), ", &save_ptr), zone_idx++) {
1626 long long zoneval = strtoll(buf, &buf, 0);
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001627 if (zoneval > max) {
1628 max = (zoneval > INT64_MAX) ? INT64_MAX : zoneval;
1629 }
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001630 zone->protection[zone_idx] = zoneval;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001631 }
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001632 zone->max_protection = max;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001633}
1634
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001635static int zoneinfo_parse_zone(char **buf, struct zoneinfo_zone *zone) {
1636 for (char *line = strtok_r(NULL, "\n", buf); line;
1637 line = strtok_r(NULL, "\n", buf)) {
1638 char *cp;
1639 char *ap;
1640 char *save_ptr;
1641 int64_t val;
1642 int field_idx;
1643 enum field_match_result match_res;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001644
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001645 cp = strtok_r(line, " ", &save_ptr);
1646 if (!cp) {
1647 return false;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001648 }
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001649
1650 field_idx = find_field(cp, zoneinfo_zone_spec_field_names, ZI_ZONE_SPEC_FIELD_COUNT);
1651 if (field_idx >= 0) {
1652 /* special field */
1653 if (field_idx == ZI_ZONE_SPEC_PAGESETS) {
1654 /* no mode fields we are interested in */
1655 return true;
1656 }
1657
1658 /* protection field */
1659 ap = strtok_r(NULL, ")", &save_ptr);
1660 if (ap) {
1661 zoneinfo_parse_protection(ap, zone);
1662 }
1663 continue;
1664 }
1665
1666 ap = strtok_r(NULL, " ", &save_ptr);
1667 if (!ap) {
1668 continue;
1669 }
1670
1671 match_res = match_field(cp, ap, zoneinfo_zone_field_names, ZI_ZONE_FIELD_COUNT,
1672 &val, &field_idx);
1673 if (match_res == PARSE_FAIL) {
1674 return false;
1675 }
1676 if (match_res == PARSE_SUCCESS) {
1677 zone->fields.arr[field_idx] = val;
1678 }
1679 if (field_idx == ZI_ZONE_PRESENT && val == 0) {
1680 /* zone is not populated, stop parsing it */
1681 return true;
1682 }
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001683 }
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001684 return false;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001685}
1686
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001687static int zoneinfo_parse_node(char **buf, struct zoneinfo_node *node) {
1688 int fields_to_match = ZI_NODE_FIELD_COUNT;
1689
1690 for (char *line = strtok_r(NULL, "\n", buf); line;
1691 line = strtok_r(NULL, "\n", buf)) {
1692 char *cp;
1693 char *ap;
1694 char *save_ptr;
1695 int64_t val;
1696 int field_idx;
1697 enum field_match_result match_res;
1698
1699 cp = strtok_r(line, " ", &save_ptr);
1700 if (!cp) {
1701 return false;
1702 }
1703
1704 ap = strtok_r(NULL, " ", &save_ptr);
1705 if (!ap) {
1706 return false;
1707 }
1708
1709 match_res = match_field(cp, ap, zoneinfo_node_field_names, ZI_NODE_FIELD_COUNT,
1710 &val, &field_idx);
1711 if (match_res == PARSE_FAIL) {
1712 return false;
1713 }
1714 if (match_res == PARSE_SUCCESS) {
1715 node->fields.arr[field_idx] = val;
1716 fields_to_match--;
1717 if (!fields_to_match) {
1718 return true;
1719 }
1720 }
1721 }
1722 return false;
1723}
1724
1725static int zoneinfo_parse(struct zoneinfo *zi) {
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001726 static struct reread_data file_data = {
1727 .filename = ZONEINFO_PATH,
1728 .fd = -1,
1729 };
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -07001730 char *buf;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001731 char *save_ptr;
1732 char *line;
Greg Kaiser259984f2019-10-02 07:07:32 -07001733 char zone_name[LINE_MAX + 1];
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001734 struct zoneinfo_node *node = NULL;
1735 int node_idx = 0;
1736 int zone_idx = 0;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001737
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001738 memset(zi, 0, sizeof(struct zoneinfo));
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001739
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -07001740 if ((buf = reread_file(&file_data)) == NULL) {
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001741 return -1;
1742 }
1743
1744 for (line = strtok_r(buf, "\n", &save_ptr); line;
1745 line = strtok_r(NULL, "\n", &save_ptr)) {
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001746 int node_id;
1747 if (sscanf(line, "Node %d, zone %" STRINGIFY(LINE_MAX) "s", &node_id, zone_name) == 2) {
1748 if (!node || node->id != node_id) {
1749 /* new node is found */
1750 if (node) {
1751 node->zone_count = zone_idx + 1;
1752 node_idx++;
1753 if (node_idx == MAX_NR_NODES) {
1754 /* max node count exceeded */
1755 ALOGE("%s parse error", file_data.filename);
1756 return -1;
1757 }
1758 }
1759 node = &zi->nodes[node_idx];
1760 node->id = node_id;
1761 zone_idx = 0;
1762 if (!zoneinfo_parse_node(&save_ptr, node)) {
1763 ALOGE("%s parse error", file_data.filename);
1764 return -1;
1765 }
1766 } else {
1767 /* new zone is found */
1768 zone_idx++;
1769 }
1770 if (!zoneinfo_parse_zone(&save_ptr, &node->zones[zone_idx])) {
1771 ALOGE("%s parse error", file_data.filename);
1772 return -1;
1773 }
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001774 }
1775 }
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001776 if (!node) {
1777 ALOGE("%s parse error", file_data.filename);
1778 return -1;
1779 }
1780 node->zone_count = zone_idx + 1;
1781 zi->node_count = node_idx + 1;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001782
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001783 /* calculate totals fields */
1784 for (node_idx = 0; node_idx < zi->node_count; node_idx++) {
1785 node = &zi->nodes[node_idx];
1786 for (zone_idx = 0; zone_idx < node->zone_count; zone_idx++) {
1787 struct zoneinfo_zone *zone = &zi->nodes[node_idx].zones[zone_idx];
1788 zi->totalreserve_pages += zone->max_protection + zone->fields.field.high;
1789 }
1790 zi->total_inactive_file += node->fields.field.nr_inactive_file;
1791 zi->total_active_file += node->fields.field.nr_active_file;
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001792 }
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001793 return 0;
1794}
1795
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07001796/* /proc/meminfo parsing routines */
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001797static bool meminfo_parse_line(char *line, union meminfo *mi) {
1798 char *cp = line;
1799 char *ap;
1800 char *save_ptr;
1801 int64_t val;
1802 int field_idx;
1803 enum field_match_result match_res;
1804
1805 cp = strtok_r(line, " ", &save_ptr);
1806 if (!cp) {
1807 return false;
1808 }
1809
1810 ap = strtok_r(NULL, " ", &save_ptr);
1811 if (!ap) {
1812 return false;
1813 }
1814
1815 match_res = match_field(cp, ap, meminfo_field_names, MI_FIELD_COUNT,
1816 &val, &field_idx);
1817 if (match_res == PARSE_SUCCESS) {
1818 mi->arr[field_idx] = val / page_k;
1819 }
1820 return (match_res != PARSE_FAIL);
1821}
1822
Suren Baghdasaryan940e7cf2021-05-27 18:15:44 -07001823static int64_t read_gpu_total_kb() {
1824 static int fd = android::bpf::bpfFdGet(
1825 "/sys/fs/bpf/map_gpu_mem_gpu_mem_total_map", BPF_F_RDONLY);
1826 static constexpr uint64_t kBpfKeyGpuTotalUsage = 0;
1827 uint64_t value;
1828
1829 if (fd < 0) {
1830 return 0;
1831 }
1832
1833 return android::bpf::findMapEntry(fd, &kBpfKeyGpuTotalUsage, &value)
1834 ? 0
1835 : (int32_t)(value / 1024);
1836}
1837
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001838static int meminfo_parse(union meminfo *mi) {
1839 static struct reread_data file_data = {
1840 .filename = MEMINFO_PATH,
1841 .fd = -1,
1842 };
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -07001843 char *buf;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001844 char *save_ptr;
1845 char *line;
1846
1847 memset(mi, 0, sizeof(union meminfo));
1848
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -07001849 if ((buf = reread_file(&file_data)) == NULL) {
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001850 return -1;
1851 }
1852
1853 for (line = strtok_r(buf, "\n", &save_ptr); line;
1854 line = strtok_r(NULL, "\n", &save_ptr)) {
1855 if (!meminfo_parse_line(line, mi)) {
1856 ALOGE("%s parse error", file_data.filename);
1857 return -1;
1858 }
1859 }
1860 mi->field.nr_file_pages = mi->field.cached + mi->field.swap_cached +
1861 mi->field.buffers;
Suren Baghdasaryan940e7cf2021-05-27 18:15:44 -07001862 mi->field.total_gpu_kb = read_gpu_total_kb();
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001863
1864 return 0;
1865}
1866
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07001867/* /proc/vmstat parsing routines */
1868static bool vmstat_parse_line(char *line, union vmstat *vs) {
1869 char *cp;
1870 char *ap;
1871 char *save_ptr;
1872 int64_t val;
1873 int field_idx;
1874 enum field_match_result match_res;
1875
1876 cp = strtok_r(line, " ", &save_ptr);
1877 if (!cp) {
1878 return false;
1879 }
1880
1881 ap = strtok_r(NULL, " ", &save_ptr);
1882 if (!ap) {
1883 return false;
1884 }
1885
1886 match_res = match_field(cp, ap, vmstat_field_names, VS_FIELD_COUNT,
1887 &val, &field_idx);
1888 if (match_res == PARSE_SUCCESS) {
1889 vs->arr[field_idx] = val;
1890 }
1891 return (match_res != PARSE_FAIL);
1892}
1893
1894static int vmstat_parse(union vmstat *vs) {
1895 static struct reread_data file_data = {
1896 .filename = VMSTAT_PATH,
1897 .fd = -1,
1898 };
1899 char *buf;
1900 char *save_ptr;
1901 char *line;
1902
1903 memset(vs, 0, sizeof(union vmstat));
1904
1905 if ((buf = reread_file(&file_data)) == NULL) {
1906 return -1;
1907 }
1908
1909 for (line = strtok_r(buf, "\n", &save_ptr); line;
1910 line = strtok_r(NULL, "\n", &save_ptr)) {
1911 if (!vmstat_parse_line(line, vs)) {
1912 ALOGE("%s parse error", file_data.filename);
1913 return -1;
1914 }
1915 }
1916
1917 return 0;
1918}
1919
Suren Baghdasaryan5ae47a92022-02-10 21:10:23 -08001920static int psi_parse(struct reread_data *file_data, struct psi_stats stats[], bool full) {
1921 char *buf;
1922 char *save_ptr;
1923 char *line;
1924
1925 if ((buf = reread_file(file_data)) == NULL) {
1926 return -1;
1927 }
1928
1929 line = strtok_r(buf, "\n", &save_ptr);
1930 if (parse_psi_line(line, PSI_SOME, stats)) {
1931 return -1;
1932 }
1933 if (full) {
1934 line = strtok_r(NULL, "\n", &save_ptr);
1935 if (parse_psi_line(line, PSI_FULL, stats)) {
1936 return -1;
1937 }
1938 }
1939
1940 return 0;
1941}
1942
1943static int psi_parse_mem(struct psi_data *psi_data) {
1944 static struct reread_data file_data = {
1945 .filename = PSI_PATH_MEMORY,
1946 .fd = -1,
1947 };
1948 return psi_parse(&file_data, psi_data->mem_stats, true);
1949}
1950
Suren Baghdasaryan014dd712022-02-18 12:51:15 -08001951static int psi_parse_io(struct psi_data *psi_data) {
1952 static struct reread_data file_data = {
1953 .filename = PSI_PATH_IO,
1954 .fd = -1,
1955 };
1956 return psi_parse(&file_data, psi_data->io_stats, true);
1957}
1958
1959static int psi_parse_cpu(struct psi_data *psi_data) {
1960 static struct reread_data file_data = {
1961 .filename = PSI_PATH_CPU,
1962 .fd = -1,
1963 };
1964 return psi_parse(&file_data, psi_data->cpu_stats, false);
1965}
1966
Suren Baghdasaryand7b4fcb2020-07-23 18:00:43 -07001967enum wakeup_reason {
1968 Event,
1969 Polling
1970};
1971
1972struct wakeup_info {
1973 struct timespec wakeup_tm;
1974 struct timespec prev_wakeup_tm;
1975 struct timespec last_event_tm;
1976 int wakeups_since_event;
1977 int skipped_wakeups;
1978};
1979
1980/*
1981 * After the initial memory pressure event is received lmkd schedules periodic wakeups to check
1982 * the memory conditions and kill if needed (polling). This is done because pressure events are
1983 * rate-limited and memory conditions can change in between events. Therefore after the initial
1984 * event there might be multiple wakeups. This function records the wakeup information such as the
1985 * timestamps of the last event and the last wakeup, the number of wakeups since the last event
1986 * and how many of those wakeups were skipped (some wakeups are skipped if previously killed
1987 * process is still freeing its memory).
1988 */
1989static void record_wakeup_time(struct timespec *tm, enum wakeup_reason reason,
1990 struct wakeup_info *wi) {
1991 wi->prev_wakeup_tm = wi->wakeup_tm;
1992 wi->wakeup_tm = *tm;
1993 if (reason == Event) {
1994 wi->last_event_tm = *tm;
1995 wi->wakeups_since_event = 0;
1996 wi->skipped_wakeups = 0;
1997 } else {
1998 wi->wakeups_since_event++;
1999 }
2000}
2001
Suren Baghdasaryan39b54802021-08-09 15:10:25 -07002002struct kill_info {
2003 enum kill_reasons kill_reason;
2004 const char *kill_desc;
2005 int thrashing;
2006 int max_thrashing;
2007};
2008
Ioannis Ilkos279268a2020-08-01 10:50:40 +01002009static void killinfo_log(struct proc* procp, int min_oom_score, int rss_kb,
Suren Baghdasaryan39b54802021-08-09 15:10:25 -07002010 int swap_kb, struct kill_info *ki, union meminfo *mi,
Suren Baghdasaryan014dd712022-02-18 12:51:15 -08002011 struct wakeup_info *wi, struct timespec *tm, struct psi_data *pd) {
Suren Baghdasaryan12cacae2019-09-16 12:06:30 -07002012 /* log process information */
2013 android_log_write_int32(ctx, procp->pid);
2014 android_log_write_int32(ctx, procp->uid);
2015 android_log_write_int32(ctx, procp->oomadj);
2016 android_log_write_int32(ctx, min_oom_score);
Bart Van Assche80a3dba2022-02-02 23:51:35 +00002017 android_log_write_int32(ctx, std::min(rss_kb, (int)INT32_MAX));
Suren Baghdasaryan39b54802021-08-09 15:10:25 -07002018 android_log_write_int32(ctx, ki ? ki->kill_reason : NONE);
Suren Baghdasaryan12cacae2019-09-16 12:06:30 -07002019
2020 /* log meminfo fields */
Suren Baghdasaryan08bfa982018-07-26 16:34:27 -07002021 for (int field_idx = 0; field_idx < MI_FIELD_COUNT; field_idx++) {
Bart Van Assche80a3dba2022-02-02 23:51:35 +00002022 android_log_write_int32(ctx,
2023 mi ? std::min(mi->arr[field_idx] * page_k, (int64_t)INT32_MAX) : 0);
Suren Baghdasaryan08bfa982018-07-26 16:34:27 -07002024 }
2025
Suren Baghdasaryand7b4fcb2020-07-23 18:00:43 -07002026 /* log lmkd wakeup information */
Suren Baghdasaryanaf1b0e02021-11-16 11:50:29 -08002027 if (wi) {
2028 android_log_write_int32(ctx, (int32_t)get_time_diff_ms(&wi->last_event_tm, tm));
2029 android_log_write_int32(ctx, (int32_t)get_time_diff_ms(&wi->prev_wakeup_tm, tm));
2030 android_log_write_int32(ctx, wi->wakeups_since_event);
2031 android_log_write_int32(ctx, wi->skipped_wakeups);
2032 } else {
2033 android_log_write_int32(ctx, 0);
2034 android_log_write_int32(ctx, 0);
2035 android_log_write_int32(ctx, 0);
2036 android_log_write_int32(ctx, 0);
2037 }
2038
Bart Van Assche80a3dba2022-02-02 23:51:35 +00002039 android_log_write_int32(ctx, std::min(swap_kb, (int)INT32_MAX));
Suren Baghdasaryanaf1b0e02021-11-16 11:50:29 -08002040 android_log_write_int32(ctx, mi ? (int32_t)mi->field.total_gpu_kb : 0);
Suren Baghdasaryan39b54802021-08-09 15:10:25 -07002041 if (ki) {
2042 android_log_write_int32(ctx, ki->thrashing);
2043 android_log_write_int32(ctx, ki->max_thrashing);
2044 } else {
2045 android_log_write_int32(ctx, 0);
2046 android_log_write_int32(ctx, 0);
2047 }
Suren Baghdasaryand7b4fcb2020-07-23 18:00:43 -07002048
Suren Baghdasaryan014dd712022-02-18 12:51:15 -08002049 if (pd) {
2050 android_log_write_float32(ctx, pd->mem_stats[PSI_SOME].avg10);
2051 android_log_write_float32(ctx, pd->mem_stats[PSI_FULL].avg10);
2052 android_log_write_float32(ctx, pd->io_stats[PSI_SOME].avg10);
2053 android_log_write_float32(ctx, pd->io_stats[PSI_FULL].avg10);
2054 android_log_write_float32(ctx, pd->cpu_stats[PSI_SOME].avg10);
2055 } else {
2056 for (int i = 0; i < 5; i++) {
2057 android_log_write_float32(ctx, 0);
2058 }
2059 }
2060
Suren Baghdasaryan08bfa982018-07-26 16:34:27 -07002061 android_log_write_list(ctx, LOG_ID_EVENTS);
2062 android_log_reset(ctx);
2063}
2064
Suren Baghdasaryanaf1b0e02021-11-16 11:50:29 -08002065// Note: returned entry is only an anchor and does not hold a valid process info.
2066// When called from a non-main thread, adjslot_list_lock read lock should be taken.
2067static struct proc *proc_adj_head(int oomadj) {
2068 return (struct proc *)&procadjslot_list[ADJTOSLOT(oomadj)];
2069}
2070
2071// When called from a non-main thread, adjslot_list_lock read lock should be taken.
2072static struct proc *proc_adj_tail(int oomadj) {
Todd Poynorc58c5142013-07-09 19:35:14 -07002073 return (struct proc *)adjslot_tail(&procadjslot_list[ADJTOSLOT(oomadj)]);
2074}
2075
Suren Baghdasaryanaf1b0e02021-11-16 11:50:29 -08002076// When called from a non-main thread, adjslot_list_lock read lock should be taken.
2077static struct proc *proc_adj_prev(int oomadj, int pid) {
2078 struct adjslot_list *head = &procadjslot_list[ADJTOSLOT(oomadj)];
2079 struct adjslot_list *curr = adjslot_tail(&procadjslot_list[ADJTOSLOT(oomadj)]);
2080
2081 while (curr != head) {
2082 if (((struct proc *)curr)->pid == pid) {
2083 return (struct proc *)curr->prev;
2084 }
2085 curr = curr->prev;
2086 }
2087
2088 return NULL;
2089}
2090
2091// When called from a non-main thread, adjslot_list_lock read lock should be taken.
Suren Baghdasaryaneb7c5492017-12-08 13:17:06 -08002092static struct proc *proc_get_heaviest(int oomadj) {
2093 struct adjslot_list *head = &procadjslot_list[ADJTOSLOT(oomadj)];
2094 struct adjslot_list *curr = head->next;
2095 struct proc *maxprocp = NULL;
2096 int maxsize = 0;
2097 while (curr != head) {
2098 int pid = ((struct proc *)curr)->pid;
2099 int tasksize = proc_get_size(pid);
Suren Baghdasaryan5263aa72021-04-29 15:28:57 -07002100 if (tasksize < 0) {
Suren Baghdasaryaneb7c5492017-12-08 13:17:06 -08002101 struct adjslot_list *next = curr->next;
2102 pid_remove(pid);
2103 curr = next;
2104 } else {
2105 if (tasksize > maxsize) {
2106 maxsize = tasksize;
2107 maxprocp = (struct proc *)curr;
2108 }
2109 curr = curr->next;
2110 }
2111 }
2112 return maxprocp;
2113}
2114
Suren Baghdasaryanaf1b0e02021-11-16 11:50:29 -08002115static bool find_victim(int oom_score, int prev_pid, struct proc &target_proc) {
2116 struct proc *procp;
2117 std::shared_lock lock(adjslot_list_lock);
2118
2119 if (!prev_pid) {
2120 procp = proc_adj_tail(oom_score);
2121 } else {
2122 procp = proc_adj_prev(oom_score, prev_pid);
2123 if (!procp) {
2124 // pid was removed, restart at the tail
2125 procp = proc_adj_tail(oom_score);
2126 }
2127 }
2128
2129 // the list is empty at this oom_score or we looped through it
2130 if (!procp || procp == proc_adj_head(oom_score)) {
2131 return false;
2132 }
2133
2134 // make a copy because original might be destroyed after adjslot_list_lock is released
2135 target_proc = *procp;
2136
2137 return true;
2138}
2139
2140static void watchdog_callback() {
2141 int prev_pid = 0;
2142
2143 ALOGW("lmkd watchdog timed out!");
2144 for (int oom_score = OOM_SCORE_ADJ_MAX; oom_score >= 0;) {
2145 struct proc target;
2146
2147 if (!find_victim(oom_score, prev_pid, target)) {
2148 oom_score--;
2149 prev_pid = 0;
2150 continue;
2151 }
2152
Suren Baghdasaryan2bdf7f02022-01-20 18:48:52 -08002153 if (reaper.kill({ target.pidfd, target.pid, target.uid }, true) == 0) {
Suren Baghdasaryanaf1b0e02021-11-16 11:50:29 -08002154 ALOGW("lmkd watchdog killed process %d, oom_score_adj %d", target.pid, oom_score);
Suren Baghdasaryan014dd712022-02-18 12:51:15 -08002155 killinfo_log(&target, 0, 0, 0, NULL, NULL, NULL, NULL, NULL);
Suren Baghdasaryanaf1b0e02021-11-16 11:50:29 -08002156 break;
2157 }
2158 prev_pid = target.pid;
2159 }
2160}
2161
2162static Watchdog watchdog(WATCHDOG_TIMEOUT_SEC, watchdog_callback);
2163
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002164static bool is_kill_pending(void) {
2165 char buf[24];
2166
2167 if (last_kill_pid_or_fd < 0) {
2168 return false;
2169 }
2170
2171 if (pidfd_supported) {
2172 return true;
2173 }
2174
2175 /* when pidfd is not supported base the decision on /proc/<pid> existence */
2176 snprintf(buf, sizeof(buf), "/proc/%d/", last_kill_pid_or_fd);
2177 if (access(buf, F_OK) == 0) {
2178 return true;
2179 }
2180
2181 return false;
2182}
2183
2184static bool is_waiting_for_kill(void) {
2185 return pidfd_supported && last_kill_pid_or_fd >= 0;
2186}
2187
2188static void stop_wait_for_proc_kill(bool finished) {
2189 struct epoll_event epev;
2190
2191 if (last_kill_pid_or_fd < 0) {
2192 return;
2193 }
2194
2195 if (debug_process_killing) {
2196 struct timespec curr_tm;
2197
2198 if (clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm) != 0) {
2199 /*
2200 * curr_tm is used here merely to report kill duration, so this failure is not fatal.
2201 * Log an error and continue.
2202 */
2203 ALOGE("Failed to get current time");
2204 }
2205
2206 if (finished) {
2207 ALOGI("Process got killed in %ldms",
2208 get_time_diff_ms(&last_kill_tm, &curr_tm));
2209 } else {
2210 ALOGI("Stop waiting for process kill after %ldms",
2211 get_time_diff_ms(&last_kill_tm, &curr_tm));
2212 }
2213 }
2214
2215 if (pidfd_supported) {
2216 /* unregister fd */
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07002217 if (epoll_ctl(epollfd, EPOLL_CTL_DEL, last_kill_pid_or_fd, &epev)) {
2218 // Log an error and keep going
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002219 ALOGE("epoll_ctl for last killed process failed; errno=%d", errno);
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002220 }
2221 maxevents--;
2222 close(last_kill_pid_or_fd);
2223 }
2224
2225 last_kill_pid_or_fd = -1;
2226}
2227
2228static void kill_done_handler(int data __unused, uint32_t events __unused,
2229 struct polling_params *poll_params) {
2230 stop_wait_for_proc_kill(true);
2231 poll_params->update = POLLING_RESUME;
2232}
2233
Suren Baghdasaryan7c3addb2021-06-11 12:12:56 -07002234static void kill_fail_handler(int data __unused, uint32_t events __unused,
2235 struct polling_params *poll_params) {
2236 int pid;
2237
2238 // Extract pid from the communication pipe. Clearing the pipe this way allows further
2239 // epoll_wait calls to sleep until the next event.
2240 if (TEMP_FAILURE_RETRY(read(reaper_comm_fd[0], &pid, sizeof(pid))) != sizeof(pid)) {
2241 ALOGE("thread communication read failed: %s", strerror(errno));
2242 }
2243 stop_wait_for_proc_kill(false);
2244 poll_params->update = POLLING_RESUME;
2245}
2246
Suren Baghdasaryana10157c2019-07-19 10:55:39 -07002247static void start_wait_for_proc_kill(int pid_or_fd) {
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002248 static struct event_handler_info kill_done_hinfo = { 0, kill_done_handler };
2249 struct epoll_event epev;
2250
2251 if (last_kill_pid_or_fd >= 0) {
2252 /* Should not happen but if it does we should stop previous wait */
2253 ALOGE("Attempt to wait for a kill while another wait is in progress");
2254 stop_wait_for_proc_kill(false);
2255 }
2256
Suren Baghdasaryana10157c2019-07-19 10:55:39 -07002257 last_kill_pid_or_fd = pid_or_fd;
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002258
Suren Baghdasaryana10157c2019-07-19 10:55:39 -07002259 if (!pidfd_supported) {
2260 /* If pidfd is not supported just store PID and exit */
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002261 return;
2262 }
2263
2264 epev.events = EPOLLIN;
2265 epev.data.ptr = (void *)&kill_done_hinfo;
2266 if (epoll_ctl(epollfd, EPOLL_CTL_ADD, last_kill_pid_or_fd, &epev) != 0) {
2267 ALOGE("epoll_ctl for last kill failed; errno=%d", errno);
2268 close(last_kill_pid_or_fd);
2269 last_kill_pid_or_fd = -1;
2270 return;
2271 }
2272 maxevents++;
2273}
Tim Murraya79ec0f2018-10-25 17:05:41 -07002274
Ioannis Ilkos279268a2020-08-01 10:50:40 +01002275/* Kill one process specified by procp. Returns the size (in pages) of the process killed */
Suren Baghdasaryane1604752021-07-22 16:21:21 -07002276static int kill_one_process(struct proc* procp, int min_oom_score, struct kill_info *ki,
Suren Baghdasaryan014dd712022-02-18 12:51:15 -08002277 union meminfo *mi, struct wakeup_info *wi, struct timespec *tm,
2278 struct psi_data *pd) {
Colin Cross3d57a512014-07-14 12:39:56 -07002279 int pid = procp->pid;
Suren Baghdasaryana10157c2019-07-19 10:55:39 -07002280 int pidfd = procp->pidfd;
Colin Cross3d57a512014-07-14 12:39:56 -07002281 uid_t uid = procp->uid;
2282 char *taskname;
Suren Baghdasaryan7c3addb2021-06-11 12:12:56 -07002283 int kill_result;
Suren Baghdasaryan8b00c6d2018-10-12 11:28:33 -07002284 int result = -1;
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07002285 struct memory_stat *mem_st;
Suren Baghdasaryan3cc1f132020-09-09 20:19:02 -07002286 struct kill_stat kill_st;
Ioannis Ilkos279268a2020-08-01 10:50:40 +01002287 int64_t tgid;
2288 int64_t rss_kb;
2289 int64_t swap_kb;
2290 char buf[PAGE_SIZE];
Suren Baghdasaryan34928bb2021-07-29 17:02:51 -07002291 char desc[LINE_MAX];
Rajeev Kumar4aba9152018-01-31 17:54:56 -08002292
Ioannis Ilkos279268a2020-08-01 10:50:40 +01002293 if (!read_proc_status(pid, buf, sizeof(buf))) {
2294 goto out;
2295 }
2296 if (!parse_status_tag(buf, PROC_STATUS_TGID_FIELD, &tgid)) {
2297 ALOGE("Unable to parse tgid from /proc/%d/status", pid);
2298 goto out;
2299 }
2300 if (tgid != pid) {
2301 ALOGE("Possible pid reuse detected (pid %d, tgid %" PRId64 ")!", pid, tgid);
2302 goto out;
2303 }
2304 // Zombie processes will not have RSS / Swap fields.
2305 if (!parse_status_tag(buf, PROC_STATUS_RSS_FIELD, &rss_kb)) {
2306 goto out;
2307 }
2308 if (!parse_status_tag(buf, PROC_STATUS_SWAP_FIELD, &swap_kb)) {
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -07002309 goto out;
2310 }
2311
Suren Baghdasaryan632f1c52019-10-04 16:06:55 -07002312 taskname = proc_get_name(pid, buf, sizeof(buf));
Ioannis Ilkos279268a2020-08-01 10:50:40 +01002313 // taskname will point inside buf, do not reuse buf onwards.
Colin Cross3d57a512014-07-14 12:39:56 -07002314 if (!taskname) {
Suren Baghdasaryan8b00c6d2018-10-12 11:28:33 -07002315 goto out;
Colin Cross3d57a512014-07-14 12:39:56 -07002316 }
2317
Ioannis Ilkos279268a2020-08-01 10:50:40 +01002318 mem_st = stats_read_memory_stat(per_app_memcg, pid, uid, rss_kb * 1024, swap_kb * 1024);
Rajeev Kumar4aba9152018-01-31 17:54:56 -08002319
George Burgess IVe849f142021-08-05 06:59:42 +00002320 snprintf(desc, sizeof(desc), "lmk,%d,%d,%d,%d,%d", pid, ki ? (int)ki->kill_reason : -1,
2321 procp->oomadj, min_oom_score, ki ? ki->max_thrashing : -1);
Suren Baghdasaryan7c3addb2021-06-11 12:12:56 -07002322
Suren Baghdasaryan34928bb2021-07-29 17:02:51 -07002323 trace_kill_start(pid, desc);
Suren Baghdasaryan03e19872018-01-04 10:43:58 -08002324
Suren Baghdasaryan7c3addb2021-06-11 12:12:56 -07002325 start_wait_for_proc_kill(pidfd < 0 ? pid : pidfd);
Suren Baghdasaryan2bdf7f02022-01-20 18:48:52 -08002326 kill_result = reaper.kill({ pidfd, pid, uid }, false);
Wei Wangf1ee2e12018-11-21 00:11:44 -08002327
Suren Baghdasaryan34928bb2021-07-29 17:02:51 -07002328 trace_kill_end();
Suren Baghdasaryanc2e05b62019-09-04 16:44:47 -07002329
Suren Baghdasaryan7c3addb2021-06-11 12:12:56 -07002330 if (kill_result) {
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002331 stop_wait_for_proc_kill(false);
Suren Baghdasaryanc2e05b62019-09-04 16:44:47 -07002332 ALOGE("kill(%d): errno=%d", pid, errno);
2333 /* Delete process record even when we fail to kill so that we don't get stuck on it */
2334 goto out;
2335 }
2336
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002337 last_kill_tm = *tm;
2338
Suren Baghdasaryana7394ea2018-10-12 11:07:40 -07002339 inc_killcnt(procp->oomadj);
Suren Baghdasaryan12cacae2019-09-16 12:06:30 -07002340
Suren Baghdasaryane1604752021-07-22 16:21:21 -07002341 if (ki) {
2342 kill_st.kill_reason = ki->kill_reason;
2343 kill_st.thrashing = ki->thrashing;
2344 kill_st.max_thrashing = ki->max_thrashing;
Ioannis Ilkos48848902021-02-18 19:53:33 +00002345 ALOGI("Kill '%s' (%d), uid %d, oom_score_adj %d to free %" PRId64 "kB rss, %" PRId64
Suren Baghdasaryane1604752021-07-22 16:21:21 -07002346 "kB swap; reason: %s", taskname, pid, uid, procp->oomadj, rss_kb, swap_kb,
2347 ki->kill_desc);
Suren Baghdasaryan89454e62019-07-15 15:50:17 -07002348 } else {
Suren Baghdasaryane1604752021-07-22 16:21:21 -07002349 kill_st.kill_reason = NONE;
2350 kill_st.thrashing = 0;
2351 kill_st.max_thrashing = 0;
Ioannis Ilkos48848902021-02-18 19:53:33 +00002352 ALOGI("Kill '%s' (%d), uid %d, oom_score_adj %d to free %" PRId64 "kB rss, %" PRId64
2353 "kb swap", taskname, pid, uid, procp->oomadj, rss_kb, swap_kb);
Suren Baghdasaryan89454e62019-07-15 15:50:17 -07002354 }
Suren Baghdasaryan014dd712022-02-18 12:51:15 -08002355 killinfo_log(procp, min_oom_score, rss_kb, swap_kb, ki, mi, wi, tm, pd);
Colin Cross3d57a512014-07-14 12:39:56 -07002356
Suren Baghdasaryan3cc1f132020-09-09 20:19:02 -07002357 kill_st.uid = static_cast<int32_t>(uid);
2358 kill_st.taskname = taskname;
Suren Baghdasaryan3cc1f132020-09-09 20:19:02 -07002359 kill_st.oom_score = procp->oomadj;
2360 kill_st.min_oom_score = min_oom_score;
2361 kill_st.free_mem_kb = mi->field.nr_free_pages * page_k;
2362 kill_st.free_swap_kb = mi->field.free_swap * page_k;
2363 stats_write_lmk_kill_occurred(&kill_st, mem_st);
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07002364
Jing Ji5c480962019-12-04 09:22:05 -08002365 ctrl_data_write_lmk_kill_occurred((pid_t)pid, uid);
2366
Ioannis Ilkos279268a2020-08-01 10:50:40 +01002367 result = rss_kb / page_k;
Mark Salyzyn1d5fdf32018-02-04 15:27:23 -08002368
Suren Baghdasaryan8b00c6d2018-10-12 11:28:33 -07002369out:
2370 /*
2371 * WARNING: After pid_remove() procp is freed and can't be used!
2372 * Therefore placed at the end of the function.
2373 */
2374 pid_remove(pid);
2375 return result;
Colin Cross3d57a512014-07-14 12:39:56 -07002376}
2377
2378/*
Chris Morin74b4df92021-02-26 00:00:35 -08002379 * Find one process to kill at or above the given oom_score_adj level.
Suren Baghdasaryan85c31b52018-10-26 11:32:15 -07002380 * Returns size of the killed process.
Colin Cross3d57a512014-07-14 12:39:56 -07002381 */
Suren Baghdasaryane1604752021-07-22 16:21:21 -07002382static int find_and_kill_process(int min_score_adj, struct kill_info *ki, union meminfo *mi,
Suren Baghdasaryan014dd712022-02-18 12:51:15 -08002383 struct wakeup_info *wi, struct timespec *tm,
2384 struct psi_data *pd) {
Colin Cross3d57a512014-07-14 12:39:56 -07002385 int i;
Suren Baghdasaryan85c31b52018-10-26 11:32:15 -07002386 int killed_size = 0;
Yang Lu5dfffbc2018-05-15 04:59:44 +00002387 bool lmk_state_change_start = false;
Suren Baghdasaryan858e8c62021-03-03 11:05:09 -08002388 bool choose_heaviest_task = kill_heaviest_task;
Rajeev Kumar4aba9152018-01-31 17:54:56 -08002389
Chong Zhang1cd12b52015-10-14 16:19:53 -07002390 for (i = OOM_SCORE_ADJ_MAX; i >= min_score_adj; i--) {
Colin Cross3d57a512014-07-14 12:39:56 -07002391 struct proc *procp;
2392
Suren Baghdasaryan858e8c62021-03-03 11:05:09 -08002393 if (!choose_heaviest_task && i <= PERCEPTIBLE_APP_ADJ) {
2394 /*
2395 * If we have to choose a perceptible process, choose the heaviest one to
2396 * hopefully minimize the number of victims.
2397 */
2398 choose_heaviest_task = true;
2399 }
2400
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002401 while (true) {
Suren Baghdasaryan858e8c62021-03-03 11:05:09 -08002402 procp = choose_heaviest_task ?
Suren Baghdasaryanaf1b0e02021-11-16 11:50:29 -08002403 proc_get_heaviest(i) : proc_adj_tail(i);
Colin Cross3d57a512014-07-14 12:39:56 -07002404
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002405 if (!procp)
2406 break;
2407
Suren Baghdasaryan014dd712022-02-18 12:51:15 -08002408 killed_size = kill_one_process(procp, min_score_adj, ki, mi, wi, tm, pd);
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002409 if (killed_size >= 0) {
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07002410 if (!lmk_state_change_start) {
Yang Lu5dfffbc2018-05-15 04:59:44 +00002411 lmk_state_change_start = true;
Vova Sharaienkoa92b76b2021-04-24 00:30:06 +00002412 stats_write_lmk_state_changed(STATE_START);
Yang Lu5dfffbc2018-05-15 04:59:44 +00002413 }
Suren Baghdasaryan85c31b52018-10-26 11:32:15 -07002414 break;
Colin Cross3d57a512014-07-14 12:39:56 -07002415 }
2416 }
Suren Baghdasaryan85c31b52018-10-26 11:32:15 -07002417 if (killed_size) {
2418 break;
2419 }
Colin Cross3d57a512014-07-14 12:39:56 -07002420 }
2421
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07002422 if (lmk_state_change_start) {
Vova Sharaienkoa92b76b2021-04-24 00:30:06 +00002423 stats_write_lmk_state_changed(STATE_STOP);
Rajeev Kumar4aba9152018-01-31 17:54:56 -08002424 }
Rajeev Kumar4aba9152018-01-31 17:54:56 -08002425
Suren Baghdasaryan85c31b52018-10-26 11:32:15 -07002426 return killed_size;
Colin Cross3d57a512014-07-14 12:39:56 -07002427}
2428
Suren Baghdasaryan87966742018-04-13 12:43:41 -07002429static int64_t get_memory_usage(struct reread_data *file_data) {
Robert Beneac72b2932017-08-21 15:18:31 -07002430 int64_t mem_usage;
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -07002431 char *buf;
Suren Baghdasaryan87966742018-04-13 12:43:41 -07002432
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -07002433 if ((buf = reread_file(file_data)) == NULL) {
Robert Beneac72b2932017-08-21 15:18:31 -07002434 return -1;
2435 }
2436
Suren Baghdasaryan87966742018-04-13 12:43:41 -07002437 if (!parse_int64(buf, &mem_usage)) {
2438 ALOGE("%s parse error", file_data->filename);
Robert Beneac72b2932017-08-21 15:18:31 -07002439 return -1;
2440 }
Robert Beneac72b2932017-08-21 15:18:31 -07002441 if (mem_usage == 0) {
2442 ALOGE("No memory!");
2443 return -1;
2444 }
2445 return mem_usage;
2446}
2447
Suren Baghdasaryane0f3dd12018-04-13 13:41:12 -07002448void record_low_pressure_levels(union meminfo *mi) {
2449 if (low_pressure_mem.min_nr_free_pages == -1 ||
2450 low_pressure_mem.min_nr_free_pages > mi->field.nr_free_pages) {
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002451 if (debug_process_killing) {
Suren Baghdasaryane0f3dd12018-04-13 13:41:12 -07002452 ALOGI("Low pressure min memory update from %" PRId64 " to %" PRId64,
2453 low_pressure_mem.min_nr_free_pages, mi->field.nr_free_pages);
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002454 }
Suren Baghdasaryane0f3dd12018-04-13 13:41:12 -07002455 low_pressure_mem.min_nr_free_pages = mi->field.nr_free_pages;
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002456 }
2457 /*
2458 * Free memory at low vmpressure events occasionally gets spikes,
2459 * possibly a stale low vmpressure event with memory already
2460 * freed up (no memory pressure should have been reported).
Suren Baghdasaryane0f3dd12018-04-13 13:41:12 -07002461 * Ignore large jumps in max_nr_free_pages that would mess up our stats.
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002462 */
Suren Baghdasaryane0f3dd12018-04-13 13:41:12 -07002463 if (low_pressure_mem.max_nr_free_pages == -1 ||
2464 (low_pressure_mem.max_nr_free_pages < mi->field.nr_free_pages &&
2465 mi->field.nr_free_pages - low_pressure_mem.max_nr_free_pages <
2466 low_pressure_mem.max_nr_free_pages * 0.1)) {
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002467 if (debug_process_killing) {
Suren Baghdasaryane0f3dd12018-04-13 13:41:12 -07002468 ALOGI("Low pressure max memory update from %" PRId64 " to %" PRId64,
2469 low_pressure_mem.max_nr_free_pages, mi->field.nr_free_pages);
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002470 }
Suren Baghdasaryane0f3dd12018-04-13 13:41:12 -07002471 low_pressure_mem.max_nr_free_pages = mi->field.nr_free_pages;
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002472 }
2473}
2474
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08002475enum vmpressure_level upgrade_level(enum vmpressure_level level) {
2476 return (enum vmpressure_level)((level < VMPRESS_LEVEL_CRITICAL) ?
2477 level + 1 : level);
2478}
2479
2480enum vmpressure_level downgrade_level(enum vmpressure_level level) {
2481 return (enum vmpressure_level)((level > VMPRESS_LEVEL_LOW) ?
2482 level - 1 : level);
2483}
2484
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002485enum zone_watermark {
2486 WMARK_MIN = 0,
2487 WMARK_LOW,
2488 WMARK_HIGH,
2489 WMARK_NONE
2490};
2491
Suren Baghdasaryan81c75b22019-08-14 09:48:35 -07002492struct zone_watermarks {
2493 long high_wmark;
2494 long low_wmark;
2495 long min_wmark;
2496};
2497
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002498/*
2499 * Returns lowest breached watermark or WMARK_NONE.
2500 */
Suren Baghdasaryan81c75b22019-08-14 09:48:35 -07002501static enum zone_watermark get_lowest_watermark(union meminfo *mi,
2502 struct zone_watermarks *watermarks)
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002503{
Suren Baghdasaryan81c75b22019-08-14 09:48:35 -07002504 int64_t nr_free_pages = mi->field.nr_free_pages - mi->field.cma_free;
2505
2506 if (nr_free_pages < watermarks->min_wmark) {
2507 return WMARK_MIN;
2508 }
2509 if (nr_free_pages < watermarks->low_wmark) {
2510 return WMARK_LOW;
2511 }
2512 if (nr_free_pages < watermarks->high_wmark) {
2513 return WMARK_HIGH;
2514 }
2515 return WMARK_NONE;
2516}
2517
2518void calc_zone_watermarks(struct zoneinfo *zi, struct zone_watermarks *watermarks) {
2519 memset(watermarks, 0, sizeof(struct zone_watermarks));
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002520
2521 for (int node_idx = 0; node_idx < zi->node_count; node_idx++) {
2522 struct zoneinfo_node *node = &zi->nodes[node_idx];
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002523 for (int zone_idx = 0; zone_idx < node->zone_count; zone_idx++) {
2524 struct zoneinfo_zone *zone = &node->zones[zone_idx];
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002525
2526 if (!zone->fields.field.present) {
2527 continue;
2528 }
2529
Suren Baghdasaryan81c75b22019-08-14 09:48:35 -07002530 watermarks->high_wmark += zone->max_protection + zone->fields.field.high;
2531 watermarks->low_wmark += zone->max_protection + zone->fields.field.low;
2532 watermarks->min_wmark += zone->max_protection + zone->fields.field.min;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002533 }
2534 }
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002535}
2536
Suren Baghdasaryan51ee4c52020-04-21 12:27:01 -07002537static int calc_swap_utilization(union meminfo *mi) {
2538 int64_t swap_used = mi->field.total_swap - mi->field.free_swap;
2539 int64_t total_swappable = mi->field.active_anon + mi->field.inactive_anon +
2540 mi->field.shmem + swap_used;
2541 return total_swappable > 0 ? (swap_used * 100) / total_swappable : 0;
2542}
2543
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002544static void mp_event_psi(int data, uint32_t events, struct polling_params *poll_params) {
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002545 enum reclaim_state {
2546 NO_RECLAIM = 0,
2547 KSWAPD_RECLAIM,
2548 DIRECT_RECLAIM,
2549 };
2550 static int64_t init_ws_refault;
Martin Liu1f72f5f2020-08-21 13:18:50 +08002551 static int64_t prev_workingset_refault;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002552 static int64_t base_file_lru;
2553 static int64_t init_pgscan_kswapd;
2554 static int64_t init_pgscan_direct;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002555 static bool killing;
Martin Liu1f72f5f2020-08-21 13:18:50 +08002556 static int thrashing_limit = thrashing_limit_pct;
Suren Baghdasaryan81c75b22019-08-14 09:48:35 -07002557 static struct zone_watermarks watermarks;
2558 static struct timespec wmark_update_tm;
Suren Baghdasaryand7b4fcb2020-07-23 18:00:43 -07002559 static struct wakeup_info wi;
Martin Liu1f72f5f2020-08-21 13:18:50 +08002560 static struct timespec thrashing_reset_tm;
2561 static int64_t prev_thrash_growth = 0;
Suren Baghdasaryan11221d42021-07-14 17:57:52 -07002562 static bool check_filecache = false;
Suren Baghdasaryane1604752021-07-22 16:21:21 -07002563 static int max_thrashing = 0;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002564
2565 union meminfo mi;
2566 union vmstat vs;
Suren Baghdasaryan5ae47a92022-02-10 21:10:23 -08002567 struct psi_data psi_data;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002568 struct timespec curr_tm;
2569 int64_t thrashing = 0;
2570 bool swap_is_low = false;
2571 enum vmpressure_level level = (enum vmpressure_level)data;
2572 enum kill_reasons kill_reason = NONE;
2573 bool cycle_after_kill = false;
2574 enum reclaim_state reclaim = NO_RECLAIM;
2575 enum zone_watermark wmark = WMARK_NONE;
Suren Baghdasaryan89454e62019-07-15 15:50:17 -07002576 char kill_desc[LINE_MAX];
Suren Baghdasaryan970a26a2019-09-19 15:27:21 -07002577 bool cut_thrashing_limit = false;
2578 int min_score_adj = 0;
Suren Baghdasaryan51ee4c52020-04-21 12:27:01 -07002579 int swap_util = 0;
Suren Baghdasaryan6e6d14b2021-10-28 13:30:08 -07002580 int64_t swap_low_threshold;
Martin Liu1f72f5f2020-08-21 13:18:50 +08002581 long since_thrashing_reset_ms;
Suren Baghdasaryandc60f972020-12-14 13:38:48 -08002582 int64_t workingset_refault_file;
Suren Baghdasaryan5ae47a92022-02-10 21:10:23 -08002583 bool critical_stall = false;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002584
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002585 if (clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm) != 0) {
2586 ALOGE("Failed to get current time");
2587 return;
2588 }
2589
Suren Baghdasaryand7b4fcb2020-07-23 18:00:43 -07002590 record_wakeup_time(&curr_tm, events ? Event : Polling, &wi);
2591
Suren Baghdasaryan03dccf32020-04-28 16:02:13 -07002592 bool kill_pending = is_kill_pending();
Suren Baghdasaryaned715a32020-05-11 16:31:57 -07002593 if (kill_pending && (kill_timeout_ms == 0 ||
2594 get_time_diff_ms(&last_kill_tm, &curr_tm) < static_cast<long>(kill_timeout_ms))) {
Suren Baghdasaryan03dccf32020-04-28 16:02:13 -07002595 /* Skip while still killing a process */
Suren Baghdasaryand7b4fcb2020-07-23 18:00:43 -07002596 wi.skipped_wakeups++;
Suren Baghdasaryan03dccf32020-04-28 16:02:13 -07002597 goto no_kill;
2598 }
2599 /*
2600 * Process is dead or kill timeout is over, stop waiting. This has no effect if pidfds are
2601 * supported and death notification already caused waiting to stop.
2602 */
2603 stop_wait_for_proc_kill(!kill_pending);
2604
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002605 if (vmstat_parse(&vs) < 0) {
2606 ALOGE("Failed to parse vmstat!");
2607 return;
2608 }
Suren Baghdasaryandc60f972020-12-14 13:38:48 -08002609 /* Starting 5.9 kernel workingset_refault vmstat field was renamed workingset_refault_file */
2610 workingset_refault_file = vs.field.workingset_refault ? : vs.field.workingset_refault_file;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002611
2612 if (meminfo_parse(&mi) < 0) {
2613 ALOGE("Failed to parse meminfo!");
2614 return;
2615 }
2616
2617 /* Reset states after process got killed */
2618 if (killing) {
2619 killing = false;
2620 cycle_after_kill = true;
2621 /* Reset file-backed pagecache size and refault amounts after a kill */
2622 base_file_lru = vs.field.nr_inactive_file + vs.field.nr_active_file;
Suren Baghdasaryandc60f972020-12-14 13:38:48 -08002623 init_ws_refault = workingset_refault_file;
Martin Liu1f72f5f2020-08-21 13:18:50 +08002624 thrashing_reset_tm = curr_tm;
2625 prev_thrash_growth = 0;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002626 }
2627
2628 /* Check free swap levels */
2629 if (swap_free_low_percentage) {
Suren Baghdasaryan6e6d14b2021-10-28 13:30:08 -07002630 swap_low_threshold = mi.field.total_swap * swap_free_low_percentage / 100;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002631 swap_is_low = mi.field.free_swap < swap_low_threshold;
Suren Baghdasaryan6e6d14b2021-10-28 13:30:08 -07002632 } else {
2633 swap_low_threshold = 0;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002634 }
2635
2636 /* Identify reclaim state */
2637 if (vs.field.pgscan_direct > init_pgscan_direct) {
2638 init_pgscan_direct = vs.field.pgscan_direct;
2639 init_pgscan_kswapd = vs.field.pgscan_kswapd;
2640 reclaim = DIRECT_RECLAIM;
2641 } else if (vs.field.pgscan_kswapd > init_pgscan_kswapd) {
2642 init_pgscan_kswapd = vs.field.pgscan_kswapd;
2643 reclaim = KSWAPD_RECLAIM;
Suren Baghdasaryandc60f972020-12-14 13:38:48 -08002644 } else if (workingset_refault_file == prev_workingset_refault) {
Suren Baghdasaryan11221d42021-07-14 17:57:52 -07002645 /*
2646 * Device is not thrashing and not reclaiming, bail out early until we see these stats
2647 * changing
2648 */
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002649 goto no_kill;
2650 }
2651
Suren Baghdasaryandc60f972020-12-14 13:38:48 -08002652 prev_workingset_refault = workingset_refault_file;
Martin Liu1f72f5f2020-08-21 13:18:50 +08002653
2654 /*
2655 * It's possible we fail to find an eligible process to kill (ex. no process is
2656 * above oom_adj_min). When this happens, we should retry to find a new process
2657 * for a kill whenever a new eligible process is available. This is especially
2658 * important for a slow growing refault case. While retrying, we should keep
2659 * monitoring new thrashing counter as someone could release the memory to mitigate
2660 * the thrashing. Thus, when thrashing reset window comes, we decay the prev thrashing
Suren Baghdasaryan11221d42021-07-14 17:57:52 -07002661 * counter by window counts. If the counter is still greater than thrashing limit,
Martin Liu1f72f5f2020-08-21 13:18:50 +08002662 * we preserve the current prev_thrash counter so we will retry kill again. Otherwise,
2663 * we reset the prev_thrash counter so we will stop retrying.
2664 */
2665 since_thrashing_reset_ms = get_time_diff_ms(&thrashing_reset_tm, &curr_tm);
2666 if (since_thrashing_reset_ms > THRASHING_RESET_INTERVAL_MS) {
2667 long windows_passed;
2668 /* Calculate prev_thrash_growth if we crossed THRASHING_RESET_INTERVAL_MS */
Suren Baghdasaryandc60f972020-12-14 13:38:48 -08002669 prev_thrash_growth = (workingset_refault_file - init_ws_refault) * 100
Martin Liuc3108412020-09-03 22:12:14 +08002670 / (base_file_lru + 1);
Martin Liu1f72f5f2020-08-21 13:18:50 +08002671 windows_passed = (since_thrashing_reset_ms / THRASHING_RESET_INTERVAL_MS);
2672 /*
2673 * Decay prev_thrashing unless over-the-limit thrashing was registered in the window we
2674 * just crossed, which means there were no eligible processes to kill. We preserve the
2675 * counter in that case to ensure a kill if a new eligible process appears.
2676 */
2677 if (windows_passed > 1 || prev_thrash_growth < thrashing_limit) {
2678 prev_thrash_growth >>= windows_passed;
2679 }
2680
2681 /* Record file-backed pagecache size when crossing THRASHING_RESET_INTERVAL_MS */
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002682 base_file_lru = vs.field.nr_inactive_file + vs.field.nr_active_file;
Suren Baghdasaryandc60f972020-12-14 13:38:48 -08002683 init_ws_refault = workingset_refault_file;
Martin Liu1f72f5f2020-08-21 13:18:50 +08002684 thrashing_reset_tm = curr_tm;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002685 thrashing_limit = thrashing_limit_pct;
2686 } else {
2687 /* Calculate what % of the file-backed pagecache refaulted so far */
Suren Baghdasaryandc60f972020-12-14 13:38:48 -08002688 thrashing = (workingset_refault_file - init_ws_refault) * 100 / (base_file_lru + 1);
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002689 }
Martin Liu1f72f5f2020-08-21 13:18:50 +08002690 /* Add previous cycle's decayed thrashing amount */
2691 thrashing += prev_thrash_growth;
Suren Baghdasaryane1604752021-07-22 16:21:21 -07002692 if (max_thrashing < thrashing) {
2693 max_thrashing = thrashing;
2694 }
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002695
Suren Baghdasaryan81c75b22019-08-14 09:48:35 -07002696 /*
2697 * Refresh watermarks once per min in case user updated one of the margins.
2698 * TODO: b/140521024 replace this periodic update with an API for AMS to notify LMKD
2699 * that zone watermarks were changed by the system software.
2700 */
2701 if (watermarks.high_wmark == 0 || get_time_diff_ms(&wmark_update_tm, &curr_tm) > 60000) {
2702 struct zoneinfo zi;
2703
2704 if (zoneinfo_parse(&zi) < 0) {
2705 ALOGE("Failed to parse zoneinfo!");
2706 return;
2707 }
2708
2709 calc_zone_watermarks(&zi, &watermarks);
2710 wmark_update_tm = curr_tm;
Martin Liu1f72f5f2020-08-21 13:18:50 +08002711 }
Suren Baghdasaryan81c75b22019-08-14 09:48:35 -07002712
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002713 /* Find out which watermark is breached if any */
Suren Baghdasaryan81c75b22019-08-14 09:48:35 -07002714 wmark = get_lowest_watermark(&mi, &watermarks);
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002715
Suren Baghdasaryan5ae47a92022-02-10 21:10:23 -08002716 if (!psi_parse_mem(&psi_data)) {
2717 critical_stall = psi_data.mem_stats[PSI_FULL].avg10 > (float)stall_limit_critical;
2718 }
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002719 /*
2720 * TODO: move this logic into a separate function
2721 * Decide if killing a process is necessary and record the reason
2722 */
2723 if (cycle_after_kill && wmark < WMARK_LOW) {
2724 /*
2725 * Prevent kills not freeing enough memory which might lead to OOM kill.
2726 * This might happen when a process is consuming memory faster than reclaim can
2727 * free even after a kill. Mostly happens when running memory stress tests.
2728 */
2729 kill_reason = PRESSURE_AFTER_KILL;
Suren Baghdasaryan89454e62019-07-15 15:50:17 -07002730 strncpy(kill_desc, "min watermark is breached even after kill", sizeof(kill_desc));
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002731 } else if (level == VMPRESS_LEVEL_CRITICAL && events != 0) {
2732 /*
2733 * Device is too busy reclaiming memory which might lead to ANR.
2734 * Critical level is triggered when PSI complete stall (all tasks are blocked because
2735 * of the memory congestion) breaches the configured threshold.
2736 */
2737 kill_reason = NOT_RESPONDING;
Suren Baghdasaryan89454e62019-07-15 15:50:17 -07002738 strncpy(kill_desc, "device is not responding", sizeof(kill_desc));
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002739 } else if (swap_is_low && thrashing > thrashing_limit_pct) {
2740 /* Page cache is thrashing while swap is low */
2741 kill_reason = LOW_SWAP_AND_THRASHING;
Suren Baghdasaryan89454e62019-07-15 15:50:17 -07002742 snprintf(kill_desc, sizeof(kill_desc), "device is low on swap (%" PRId64
2743 "kB < %" PRId64 "kB) and thrashing (%" PRId64 "%%)",
2744 mi.field.free_swap * page_k, swap_low_threshold * page_k, thrashing);
Suren Baghdasaryan0142b3c2021-03-03 11:11:09 -08002745 /* Do not kill perceptible apps unless below min watermark or heavily thrashing */
2746 if (wmark > WMARK_MIN && thrashing < thrashing_critical_pct) {
Suren Baghdasaryan48135c42020-05-19 12:59:18 -07002747 min_score_adj = PERCEPTIBLE_APP_ADJ + 1;
2748 }
Suren Baghdasaryan11221d42021-07-14 17:57:52 -07002749 check_filecache = true;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002750 } else if (swap_is_low && wmark < WMARK_HIGH) {
2751 /* Both free memory and swap are low */
2752 kill_reason = LOW_MEM_AND_SWAP;
Suren Baghdasaryan89454e62019-07-15 15:50:17 -07002753 snprintf(kill_desc, sizeof(kill_desc), "%s watermark is breached and swap is low (%"
Suren Baghdasaryan23678182021-03-02 18:33:09 -08002754 PRId64 "kB < %" PRId64 "kB)", wmark < WMARK_LOW ? "min" : "low",
Suren Baghdasaryan89454e62019-07-15 15:50:17 -07002755 mi.field.free_swap * page_k, swap_low_threshold * page_k);
Suren Baghdasaryan0142b3c2021-03-03 11:11:09 -08002756 /* Do not kill perceptible apps unless below min watermark or heavily thrashing */
2757 if (wmark > WMARK_MIN && thrashing < thrashing_critical_pct) {
Suren Baghdasaryan48135c42020-05-19 12:59:18 -07002758 min_score_adj = PERCEPTIBLE_APP_ADJ + 1;
2759 }
Suren Baghdasaryan51ee4c52020-04-21 12:27:01 -07002760 } else if (wmark < WMARK_HIGH && swap_util_max < 100 &&
2761 (swap_util = calc_swap_utilization(&mi)) > swap_util_max) {
2762 /*
2763 * Too much anon memory is swapped out but swap is not low.
2764 * Non-swappable allocations created memory pressure.
2765 */
2766 kill_reason = LOW_MEM_AND_SWAP_UTIL;
2767 snprintf(kill_desc, sizeof(kill_desc), "%s watermark is breached and swap utilization"
Suren Baghdasaryan23678182021-03-02 18:33:09 -08002768 " is high (%d%% > %d%%)", wmark < WMARK_LOW ? "min" : "low",
Suren Baghdasaryan51ee4c52020-04-21 12:27:01 -07002769 swap_util, swap_util_max);
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002770 } else if (wmark < WMARK_HIGH && thrashing > thrashing_limit) {
2771 /* Page cache is thrashing while memory is low */
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002772 kill_reason = LOW_MEM_AND_THRASHING;
Suren Baghdasaryan89454e62019-07-15 15:50:17 -07002773 snprintf(kill_desc, sizeof(kill_desc), "%s watermark is breached and thrashing (%"
Suren Baghdasaryan23678182021-03-02 18:33:09 -08002774 PRId64 "%%)", wmark < WMARK_LOW ? "min" : "low", thrashing);
Suren Baghdasaryan970a26a2019-09-19 15:27:21 -07002775 cut_thrashing_limit = true;
Suren Baghdasaryan0142b3c2021-03-03 11:11:09 -08002776 /* Do not kill perceptible apps unless thrashing at critical levels */
2777 if (thrashing < thrashing_critical_pct) {
2778 min_score_adj = PERCEPTIBLE_APP_ADJ + 1;
2779 }
Suren Baghdasaryan11221d42021-07-14 17:57:52 -07002780 check_filecache = true;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002781 } else if (reclaim == DIRECT_RECLAIM && thrashing > thrashing_limit) {
2782 /* Page cache is thrashing while in direct reclaim (mostly happens on lowram devices) */
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002783 kill_reason = DIRECT_RECL_AND_THRASHING;
Suren Baghdasaryan89454e62019-07-15 15:50:17 -07002784 snprintf(kill_desc, sizeof(kill_desc), "device is in direct reclaim and thrashing (%"
2785 PRId64 "%%)", thrashing);
Suren Baghdasaryan970a26a2019-09-19 15:27:21 -07002786 cut_thrashing_limit = true;
Suren Baghdasaryan0142b3c2021-03-03 11:11:09 -08002787 /* Do not kill perceptible apps unless thrashing at critical levels */
2788 if (thrashing < thrashing_critical_pct) {
2789 min_score_adj = PERCEPTIBLE_APP_ADJ + 1;
2790 }
Suren Baghdasaryan11221d42021-07-14 17:57:52 -07002791 check_filecache = true;
2792 } else if (check_filecache) {
2793 int64_t file_lru_kb = (vs.field.nr_inactive_file + vs.field.nr_active_file) * page_k;
2794
2795 if (file_lru_kb < filecache_min_kb) {
2796 /* File cache is too low after thrashing, keep killing background processes */
2797 kill_reason = LOW_FILECACHE_AFTER_THRASHING;
2798 snprintf(kill_desc, sizeof(kill_desc),
2799 "filecache is low (%" PRId64 "kB < %" PRId64 "kB) after thrashing",
2800 file_lru_kb, filecache_min_kb);
2801 min_score_adj = PERCEPTIBLE_APP_ADJ + 1;
2802 } else {
2803 /* File cache is big enough, stop checking */
2804 check_filecache = false;
2805 }
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002806 }
2807
2808 /* Kill a process if necessary */
2809 if (kill_reason != NONE) {
Suren Baghdasaryane1604752021-07-22 16:21:21 -07002810 struct kill_info ki = {
2811 .kill_reason = kill_reason,
2812 .kill_desc = kill_desc,
2813 .thrashing = (int)thrashing,
2814 .max_thrashing = max_thrashing,
2815 };
Suren Baghdasaryan5ae47a92022-02-10 21:10:23 -08002816
2817 /* Allow killing perceptible apps if the system is stalled */
2818 if (critical_stall) {
2819 min_score_adj = 0;
2820 }
Suren Baghdasaryan014dd712022-02-18 12:51:15 -08002821 psi_parse_io(&psi_data);
2822 psi_parse_cpu(&psi_data);
2823 int pages_freed = find_and_kill_process(min_score_adj, &ki, &mi, &wi, &curr_tm, &psi_data);
Suren Baghdasaryan970a26a2019-09-19 15:27:21 -07002824 if (pages_freed > 0) {
2825 killing = true;
Suren Baghdasaryane1604752021-07-22 16:21:21 -07002826 max_thrashing = 0;
Suren Baghdasaryan970a26a2019-09-19 15:27:21 -07002827 if (cut_thrashing_limit) {
2828 /*
2829 * Cut thrasing limit by thrashing_limit_decay_pct percentage of the current
2830 * thrashing limit until the system stops thrashing.
2831 */
2832 thrashing_limit = (thrashing_limit * (100 - thrashing_limit_decay_pct)) / 100;
2833 }
2834 }
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002835 }
2836
2837no_kill:
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002838 /* Do not poll if kernel supports pidfd waiting */
2839 if (is_waiting_for_kill()) {
2840 /* Pause polling if we are waiting for process death notification */
2841 poll_params->update = POLLING_PAUSE;
2842 return;
2843 }
2844
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002845 /*
2846 * Start polling after initial PSI event;
2847 * extend polling while device is in direct reclaim or process is being killed;
2848 * do not extend when kswapd reclaims because that might go on for a long time
2849 * without causing memory pressure
2850 */
2851 if (events || killing || reclaim == DIRECT_RECLAIM) {
2852 poll_params->update = POLLING_START;
2853 }
2854
2855 /* Decide the polling interval */
2856 if (swap_is_low || killing) {
2857 /* Fast polling during and after a kill or when swap is low */
2858 poll_params->polling_interval_ms = PSI_POLL_PERIOD_SHORT_MS;
2859 } else {
2860 /* By default use long intervals */
2861 poll_params->polling_interval_ms = PSI_POLL_PERIOD_LONG_MS;
2862 }
2863}
2864
Bart Van Asscheb4d26bb2022-02-17 21:31:51 +00002865static std::string GetCgroupAttributePath(const char* attr) {
2866 std::string path;
2867 if (!CgroupGetAttributePath(attr, &path)) {
2868 ALOGE("Unknown cgroup attribute %s", attr);
2869 }
2870 return path;
2871}
2872
2873// The implementation of this function relies on memcg statistics that are only available in the
2874// v1 cgroup hierarchy.
Suren Baghdasaryane12a0672019-07-15 14:50:49 -07002875static void mp_event_common(int data, uint32_t events, struct polling_params *poll_params) {
Todd Poynorc58c5142013-07-09 19:35:14 -07002876 unsigned long long evcount;
Robert Beneac72b2932017-08-21 15:18:31 -07002877 int64_t mem_usage, memsw_usage;
Robert Benea3be16142017-09-13 15:20:30 -07002878 int64_t mem_pressure;
Suren Baghdasaryane0f3dd12018-04-13 13:41:12 -07002879 union meminfo mi;
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07002880 struct zoneinfo zi;
Suren Baghdasaryan53be36e2018-09-05 15:46:32 -07002881 struct timespec curr_tm;
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -07002882 static unsigned long kill_skip_count = 0;
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08002883 enum vmpressure_level level = (enum vmpressure_level)data;
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07002884 long other_free = 0, other_file = 0;
2885 int min_score_adj;
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07002886 int minfree = 0;
Bart Van Asscheb4d26bb2022-02-17 21:31:51 +00002887 static const std::string mem_usage_path = GetCgroupAttributePath("MemUsage");
Suren Baghdasaryan87966742018-04-13 12:43:41 -07002888 static struct reread_data mem_usage_file_data = {
Bart Van Asscheb4d26bb2022-02-17 21:31:51 +00002889 .filename = mem_usage_path.c_str(),
Suren Baghdasaryan87966742018-04-13 12:43:41 -07002890 .fd = -1,
2891 };
Bart Van Asscheb4d26bb2022-02-17 21:31:51 +00002892 static const std::string memsw_usage_path = GetCgroupAttributePath("MemAndSwapUsage");
Suren Baghdasaryan87966742018-04-13 12:43:41 -07002893 static struct reread_data memsw_usage_file_data = {
Bart Van Asscheb4d26bb2022-02-17 21:31:51 +00002894 .filename = memsw_usage_path.c_str(),
Suren Baghdasaryan87966742018-04-13 12:43:41 -07002895 .fd = -1,
2896 };
Suren Baghdasaryand7b4fcb2020-07-23 18:00:43 -07002897 static struct wakeup_info wi;
Todd Poynorc58c5142013-07-09 19:35:14 -07002898
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08002899 if (debug_process_killing) {
2900 ALOGI("%s memory pressure event is triggered", level_name[level]);
2901 }
2902
2903 if (!use_psi_monitors) {
2904 /*
2905 * Check all event counters from low to critical
2906 * and upgrade to the highest priority one. By reading
2907 * eventfd we also reset the event counters.
2908 */
Tom Cherry43f3d2b2019-12-04 12:46:57 -08002909 for (int lvl = VMPRESS_LEVEL_LOW; lvl < VMPRESS_LEVEL_COUNT; lvl++) {
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08002910 if (mpevfd[lvl] != -1 &&
2911 TEMP_FAILURE_RETRY(read(mpevfd[lvl],
2912 &evcount, sizeof(evcount))) > 0 &&
2913 evcount > 0 && lvl > level) {
Tom Cherry43f3d2b2019-12-04 12:46:57 -08002914 level = static_cast<vmpressure_level>(lvl);
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08002915 }
Suren Baghdasaryan3e1a8492018-01-04 09:16:21 -08002916 }
2917 }
Todd Poynorc58c5142013-07-09 19:35:14 -07002918
Suren Baghdasaryane12a0672019-07-15 14:50:49 -07002919 /* Start polling after initial PSI event */
2920 if (use_psi_monitors && events) {
2921 /* Override polling params only if current event is more critical */
2922 if (!poll_params->poll_handler || data > poll_params->poll_handler->data) {
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002923 poll_params->polling_interval_ms = PSI_POLL_PERIOD_SHORT_MS;
Suren Baghdasaryane12a0672019-07-15 14:50:49 -07002924 poll_params->update = POLLING_START;
2925 }
2926 }
2927
Suren Baghdasaryan53be36e2018-09-05 15:46:32 -07002928 if (clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm) != 0) {
2929 ALOGE("Failed to get current time");
2930 return;
2931 }
2932
Suren Baghdasaryand7b4fcb2020-07-23 18:00:43 -07002933 record_wakeup_time(&curr_tm, events ? Event : Polling, &wi);
2934
Suren Baghdasaryaned715a32020-05-11 16:31:57 -07002935 if (kill_timeout_ms &&
2936 get_time_diff_ms(&last_kill_tm, &curr_tm) < static_cast<long>(kill_timeout_ms)) {
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002937 /*
2938 * If we're within the no-kill timeout, see if there's pending reclaim work
2939 * from the last killed process. If so, skip killing for now.
2940 */
2941 if (is_kill_pending()) {
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -07002942 kill_skip_count++;
Suren Baghdasaryand7b4fcb2020-07-23 18:00:43 -07002943 wi.skipped_wakeups++;
Suren Baghdasaryan30854e72018-01-17 17:28:01 -08002944 return;
2945 }
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002946 /*
2947 * Process is dead, stop waiting. This has no effect if pidfds are supported and
2948 * death notification already caused waiting to stop.
2949 */
2950 stop_wait_for_proc_kill(true);
2951 } else {
2952 /*
2953 * Killing took longer than no-kill timeout. Stop waiting for the last process
2954 * to die because we are ready to kill again.
2955 */
2956 stop_wait_for_proc_kill(false);
Suren Baghdasaryan30854e72018-01-17 17:28:01 -08002957 }
2958
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -07002959 if (kill_skip_count > 0) {
Suren Baghdasaryaneff82332018-05-10 16:10:56 -07002960 ALOGI("%lu memory pressure events were skipped after a kill!",
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -07002961 kill_skip_count);
2962 kill_skip_count = 0;
Suren Baghdasaryan30854e72018-01-17 17:28:01 -08002963 }
2964
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07002965 if (meminfo_parse(&mi) < 0 || zoneinfo_parse(&zi) < 0) {
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002966 ALOGE("Failed to get free memory!");
2967 return;
2968 }
2969
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07002970 if (use_minfree_levels) {
2971 int i;
2972
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07002973 other_free = mi.field.nr_free_pages - zi.totalreserve_pages;
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07002974 if (mi.field.nr_file_pages > (mi.field.shmem + mi.field.unevictable + mi.field.swap_cached)) {
2975 other_file = (mi.field.nr_file_pages - mi.field.shmem -
2976 mi.field.unevictable - mi.field.swap_cached);
2977 } else {
2978 other_file = 0;
2979 }
2980
2981 min_score_adj = OOM_SCORE_ADJ_MAX + 1;
2982 for (i = 0; i < lowmem_targets_size; i++) {
2983 minfree = lowmem_minfree[i];
2984 if (other_free < minfree && other_file < minfree) {
2985 min_score_adj = lowmem_adj[i];
2986 break;
2987 }
2988 }
2989
Suren Baghdasaryanb0bda552018-05-18 14:42:00 -07002990 if (min_score_adj == OOM_SCORE_ADJ_MAX + 1) {
liuhailongcf8af502021-12-04 16:29:52 +08002991 if (debug_process_killing && lowmem_targets_size) {
Suren Baghdasaryanb0bda552018-05-18 14:42:00 -07002992 ALOGI("Ignore %s memory pressure event "
2993 "(free memory=%ldkB, cache=%ldkB, limit=%ldkB)",
2994 level_name[level], other_free * page_k, other_file * page_k,
2995 (long)lowmem_minfree[lowmem_targets_size - 1] * page_k);
2996 }
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07002997 return;
Suren Baghdasaryanb0bda552018-05-18 14:42:00 -07002998 }
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07002999
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07003000 goto do_kill;
3001 }
3002
Suren Baghdasaryane0f3dd12018-04-13 13:41:12 -07003003 if (level == VMPRESS_LEVEL_LOW) {
3004 record_low_pressure_levels(&mi);
3005 }
3006
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08003007 if (level_oomadj[level] > OOM_SCORE_ADJ_MAX) {
3008 /* Do not monitor this pressure level */
3009 return;
3010 }
3011
Suren Baghdasaryan87966742018-04-13 12:43:41 -07003012 if ((mem_usage = get_memory_usage(&mem_usage_file_data)) < 0) {
3013 goto do_kill;
3014 }
3015 if ((memsw_usage = get_memory_usage(&memsw_usage_file_data)) < 0) {
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08003016 goto do_kill;
Robert Benea3be16142017-09-13 15:20:30 -07003017 }
Robert Beneac72b2932017-08-21 15:18:31 -07003018
Robert Benea3be16142017-09-13 15:20:30 -07003019 // Calculate percent for swappinness.
3020 mem_pressure = (mem_usage * 100) / memsw_usage;
3021
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08003022 if (enable_pressure_upgrade && level != VMPRESS_LEVEL_CRITICAL) {
Robert Benea3be16142017-09-13 15:20:30 -07003023 // We are swapping too much.
3024 if (mem_pressure < upgrade_pressure) {
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08003025 level = upgrade_level(level);
3026 if (debug_process_killing) {
3027 ALOGI("Event upgraded to %s", level_name[level]);
3028 }
Robert Beneac72b2932017-08-21 15:18:31 -07003029 }
3030 }
3031
Vic Yang65680692018-08-07 10:18:22 -07003032 // If we still have enough swap space available, check if we want to
3033 // ignore/downgrade pressure events.
3034 if (mi.field.free_swap >=
3035 mi.field.total_swap * swap_free_low_percentage / 100) {
3036 // If the pressure is larger than downgrade_pressure lmk will not
3037 // kill any process, since enough memory is available.
3038 if (mem_pressure > downgrade_pressure) {
3039 if (debug_process_killing) {
3040 ALOGI("Ignore %s memory pressure", level_name[level]);
3041 }
3042 return;
3043 } else if (level == VMPRESS_LEVEL_CRITICAL && mem_pressure > upgrade_pressure) {
3044 if (debug_process_killing) {
3045 ALOGI("Downgrade critical memory pressure");
3046 }
3047 // Downgrade event, since enough memory available.
3048 level = downgrade_level(level);
Robert Benea3be16142017-09-13 15:20:30 -07003049 }
Robert Benea3be16142017-09-13 15:20:30 -07003050 }
3051
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08003052do_kill:
Suren Baghdasaryand1d59f82018-04-13 11:45:38 -07003053 if (low_ram_device) {
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08003054 /* For Go devices kill only one task */
Suren Baghdasaryan014dd712022-02-18 12:51:15 -08003055 if (find_and_kill_process(level_oomadj[level], NULL, &mi, &wi, &curr_tm, NULL) == 0) {
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08003056 if (debug_process_killing) {
3057 ALOGI("Nothing to kill");
3058 }
3059 }
3060 } else {
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07003061 int pages_freed;
Suren Baghdasaryan53be36e2018-09-05 15:46:32 -07003062 static struct timespec last_report_tm;
3063 static unsigned long report_skip_count = 0;
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07003064
3065 if (!use_minfree_levels) {
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07003066 /* Free up enough memory to downgrate the memory pressure to low level */
Suren Baghdasaryan85c31b52018-10-26 11:32:15 -07003067 if (mi.field.nr_free_pages >= low_pressure_mem.max_nr_free_pages) {
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07003068 if (debug_process_killing) {
3069 ALOGI("Ignoring pressure since more memory is "
3070 "available (%" PRId64 ") than watermark (%" PRId64 ")",
3071 mi.field.nr_free_pages, low_pressure_mem.max_nr_free_pages);
3072 }
3073 return;
3074 }
3075 min_score_adj = level_oomadj[level];
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08003076 }
3077
Suren Baghdasaryan014dd712022-02-18 12:51:15 -08003078 pages_freed = find_and_kill_process(min_score_adj, NULL, &mi, &wi, &curr_tm, NULL);
Suren Baghdasaryaneff82332018-05-10 16:10:56 -07003079
Suren Baghdasaryan53be36e2018-09-05 15:46:32 -07003080 if (pages_freed == 0) {
3081 /* Rate limit kill reports when nothing was reclaimed */
3082 if (get_time_diff_ms(&last_report_tm, &curr_tm) < FAIL_REPORT_RLIMIT_MS) {
3083 report_skip_count++;
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -07003084 return;
3085 }
Robert Benea7f68a3f2017-08-11 16:03:20 -07003086 }
Suren Baghdasaryan53be36e2018-09-05 15:46:32 -07003087
Suren Baghdasaryan12cacae2019-09-16 12:06:30 -07003088 /* Log whenever we kill or when report rate limit allows */
Suren Baghdasaryan53be36e2018-09-05 15:46:32 -07003089 if (use_minfree_levels) {
Chris Morin74b4df92021-02-26 00:00:35 -08003090 ALOGI("Reclaimed %ldkB, cache(%ldkB) and free(%" PRId64 "kB)-reserved(%" PRId64 "kB) "
3091 "below min(%ldkB) for oom_score_adj %d",
Suren Baghdasaryan85c31b52018-10-26 11:32:15 -07003092 pages_freed * page_k,
Suren Baghdasaryan53be36e2018-09-05 15:46:32 -07003093 other_file * page_k, mi.field.nr_free_pages * page_k,
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07003094 zi.totalreserve_pages * page_k,
Suren Baghdasaryan53be36e2018-09-05 15:46:32 -07003095 minfree * page_k, min_score_adj);
3096 } else {
Chris Morin74b4df92021-02-26 00:00:35 -08003097 ALOGI("Reclaimed %ldkB at oom_score_adj %d", pages_freed * page_k, min_score_adj);
Suren Baghdasaryan53be36e2018-09-05 15:46:32 -07003098 }
3099
3100 if (report_skip_count > 0) {
3101 ALOGI("Suppressed %lu failed kill reports", report_skip_count);
3102 report_skip_count = 0;
3103 }
3104
3105 last_report_tm = curr_tm;
Colin Cross01db2712014-07-11 17:16:56 -07003106 }
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003107 if (is_waiting_for_kill()) {
3108 /* pause polling if we are waiting for process death notification */
3109 poll_params->update = POLLING_PAUSE;
3110 }
Todd Poynorc58c5142013-07-09 19:35:14 -07003111}
3112
Suren Baghdasaryan2f88e152019-07-15 15:42:09 -07003113static bool init_mp_psi(enum vmpressure_level level, bool use_new_strategy) {
3114 int fd;
3115
3116 /* Do not register a handler if threshold_ms is not set */
3117 if (!psi_thresholds[level].threshold_ms) {
3118 return true;
3119 }
3120
3121 fd = init_psi_monitor(psi_thresholds[level].stall_type,
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08003122 psi_thresholds[level].threshold_ms * US_PER_MS,
3123 PSI_WINDOW_SIZE_MS * US_PER_MS);
3124
3125 if (fd < 0) {
3126 return false;
3127 }
3128
Suren Baghdasaryan2f88e152019-07-15 15:42:09 -07003129 vmpressure_hinfo[level].handler = use_new_strategy ? mp_event_psi : mp_event_common;
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08003130 vmpressure_hinfo[level].data = level;
3131 if (register_psi_monitor(epollfd, fd, &vmpressure_hinfo[level]) < 0) {
3132 destroy_psi_monitor(fd);
3133 return false;
3134 }
3135 maxevents++;
3136 mpevfd[level] = fd;
3137
3138 return true;
3139}
3140
3141static void destroy_mp_psi(enum vmpressure_level level) {
3142 int fd = mpevfd[level];
3143
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07003144 if (fd < 0) {
3145 return;
3146 }
3147
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08003148 if (unregister_psi_monitor(epollfd, fd) < 0) {
3149 ALOGE("Failed to unregister psi monitor for %s memory pressure; errno=%d",
3150 level_name[level], errno);
3151 }
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07003152 maxevents--;
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08003153 destroy_psi_monitor(fd);
3154 mpevfd[level] = -1;
3155}
3156
Bart Van Assche75994362022-02-15 23:45:04 +00003157enum class MemcgVersion {
3158 kNotFound,
3159 kV1,
3160 kV2,
3161};
3162
3163static MemcgVersion __memcg_version() {
3164 std::string cgroupv2_path, memcg_path;
3165
3166 if (!CgroupGetControllerPath("memory", &memcg_path)) {
3167 return MemcgVersion::kNotFound;
3168 }
3169 return CgroupGetControllerPath(CGROUPV2_CONTROLLER_NAME, &cgroupv2_path) &&
3170 cgroupv2_path == memcg_path
3171 ? MemcgVersion::kV2
3172 : MemcgVersion::kV1;
3173}
3174
3175static MemcgVersion memcg_version() {
3176 static MemcgVersion version = __memcg_version();
3177
3178 return version;
3179}
3180
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08003181static bool init_psi_monitors() {
Suren Baghdasaryan2f88e152019-07-15 15:42:09 -07003182 /*
3183 * When PSI is used on low-ram devices or on high-end devices without memfree levels
Bart Van Assche75994362022-02-15 23:45:04 +00003184 * use new kill strategy based on zone watermarks, free swap and thrashing stats.
3185 * Also use the new strategy if memcg has not been mounted in the v1 cgroups hiearchy since
3186 * the old strategy relies on memcg attributes that are available only in the v1 cgroups
3187 * hiearchy.
Suren Baghdasaryan2f88e152019-07-15 15:42:09 -07003188 */
3189 bool use_new_strategy =
Suren Baghdasaryand0a80042021-08-03 15:40:23 -07003190 GET_LMK_PROPERTY(bool, "use_new_strategy", low_ram_device || !use_minfree_levels);
Bart Van Assche75994362022-02-15 23:45:04 +00003191 if (!use_new_strategy && memcg_version() != MemcgVersion::kV1) {
3192 ALOGE("Old kill strategy can only be used with v1 cgroup hierarchy");
3193 return false;
3194 }
Suren Baghdasaryan2f88e152019-07-15 15:42:09 -07003195 /* In default PSI mode override stall amounts using system properties */
3196 if (use_new_strategy) {
3197 /* Do not use low pressure level */
3198 psi_thresholds[VMPRESS_LEVEL_LOW].threshold_ms = 0;
3199 psi_thresholds[VMPRESS_LEVEL_MEDIUM].threshold_ms = psi_partial_stall_ms;
3200 psi_thresholds[VMPRESS_LEVEL_CRITICAL].threshold_ms = psi_complete_stall_ms;
3201 }
3202
3203 if (!init_mp_psi(VMPRESS_LEVEL_LOW, use_new_strategy)) {
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08003204 return false;
3205 }
Suren Baghdasaryan2f88e152019-07-15 15:42:09 -07003206 if (!init_mp_psi(VMPRESS_LEVEL_MEDIUM, use_new_strategy)) {
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08003207 destroy_mp_psi(VMPRESS_LEVEL_LOW);
3208 return false;
3209 }
Suren Baghdasaryan2f88e152019-07-15 15:42:09 -07003210 if (!init_mp_psi(VMPRESS_LEVEL_CRITICAL, use_new_strategy)) {
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08003211 destroy_mp_psi(VMPRESS_LEVEL_MEDIUM);
3212 destroy_mp_psi(VMPRESS_LEVEL_LOW);
3213 return false;
3214 }
3215 return true;
3216}
3217
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003218static bool init_mp_common(enum vmpressure_level level) {
Bart Van Assche75994362022-02-15 23:45:04 +00003219 // The implementation of this function relies on memcg statistics that are only available in the
3220 // v1 cgroup hierarchy.
3221 if (memcg_version() != MemcgVersion::kV1) {
3222 ALOGE("%s: global monitoring is only available for the v1 cgroup hierarchy", __func__);
3223 return false;
3224 }
3225
Todd Poynorc58c5142013-07-09 19:35:14 -07003226 int mpfd;
3227 int evfd;
3228 int evctlfd;
3229 char buf[256];
3230 struct epoll_event epev;
3231 int ret;
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003232 int level_idx = (int)level;
3233 const char *levelstr = level_name[level_idx];
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08003234
Mark Salyzyna00ccd82018-04-09 09:50:32 -07003235 /* gid containing AID_SYSTEM required */
Bart Van Asscheb4d26bb2022-02-17 21:31:51 +00003236 mpfd = open(GetCgroupAttributePath("MemPressureLevel").c_str(), O_RDONLY | O_CLOEXEC);
Todd Poynorc58c5142013-07-09 19:35:14 -07003237 if (mpfd < 0) {
3238 ALOGI("No kernel memory.pressure_level support (errno=%d)", errno);
3239 goto err_open_mpfd;
3240 }
3241
Bart Van Asscheb4d26bb2022-02-17 21:31:51 +00003242 evctlfd = open(GetCgroupAttributePath("CgroupEventControl").c_str(), O_WRONLY | O_CLOEXEC);
Todd Poynorc58c5142013-07-09 19:35:14 -07003243 if (evctlfd < 0) {
3244 ALOGI("No kernel memory cgroup event control (errno=%d)", errno);
3245 goto err_open_evctlfd;
3246 }
3247
Nick Kralevich148d8dd2015-12-18 20:52:37 -08003248 evfd = eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC);
Todd Poynorc58c5142013-07-09 19:35:14 -07003249 if (evfd < 0) {
3250 ALOGE("eventfd failed for level %s; errno=%d", levelstr, errno);
3251 goto err_eventfd;
3252 }
3253
3254 ret = snprintf(buf, sizeof(buf), "%d %d %s", evfd, mpfd, levelstr);
3255 if (ret >= (ssize_t)sizeof(buf)) {
3256 ALOGE("cgroup.event_control line overflow for level %s", levelstr);
3257 goto err;
3258 }
3259
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003260 ret = TEMP_FAILURE_RETRY(write(evctlfd, buf, strlen(buf) + 1));
Todd Poynorc58c5142013-07-09 19:35:14 -07003261 if (ret == -1) {
3262 ALOGE("cgroup.event_control write failed for level %s; errno=%d",
3263 levelstr, errno);
3264 goto err;
3265 }
3266
3267 epev.events = EPOLLIN;
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003268 /* use data to store event level */
3269 vmpressure_hinfo[level_idx].data = level_idx;
3270 vmpressure_hinfo[level_idx].handler = mp_event_common;
3271 epev.data.ptr = (void *)&vmpressure_hinfo[level_idx];
Todd Poynorc58c5142013-07-09 19:35:14 -07003272 ret = epoll_ctl(epollfd, EPOLL_CTL_ADD, evfd, &epev);
3273 if (ret == -1) {
3274 ALOGE("epoll_ctl for level %s failed; errno=%d", levelstr, errno);
3275 goto err;
3276 }
3277 maxevents++;
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08003278 mpevfd[level] = evfd;
Suren Baghdasaryanceffaf22018-01-04 08:54:53 -08003279 close(evctlfd);
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08003280 return true;
Todd Poynorc58c5142013-07-09 19:35:14 -07003281
3282err:
3283 close(evfd);
3284err_eventfd:
3285 close(evctlfd);
3286err_open_evctlfd:
3287 close(mpfd);
3288err_open_mpfd:
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08003289 return false;
Robert Benea58d6a132017-06-01 16:32:31 -07003290}
3291
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07003292static void destroy_mp_common(enum vmpressure_level level) {
3293 struct epoll_event epev;
3294 int fd = mpevfd[level];
3295
3296 if (fd < 0) {
3297 return;
3298 }
3299
3300 if (epoll_ctl(epollfd, EPOLL_CTL_DEL, fd, &epev)) {
3301 // Log an error and keep going
3302 ALOGE("epoll_ctl for level %s failed; errno=%d", level_name[level], errno);
3303 }
3304 maxevents--;
3305 close(fd);
3306 mpevfd[level] = -1;
3307}
3308
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07003309static void kernel_event_handler(int data __unused, uint32_t events __unused,
3310 struct polling_params *poll_params __unused) {
Jing Ji5c480962019-12-04 09:22:05 -08003311 poll_kernel(kpoll_fd);
Jim Blackler700b7192019-04-26 11:18:29 +01003312}
3313
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07003314static bool init_monitors() {
3315 /* Try to use psi monitor first if kernel has it */
Suren Baghdasaryand0a80042021-08-03 15:40:23 -07003316 use_psi_monitors = GET_LMK_PROPERTY(bool, "use_psi", true) &&
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07003317 init_psi_monitors();
3318 /* Fall back to vmpressure */
3319 if (!use_psi_monitors &&
3320 (!init_mp_common(VMPRESS_LEVEL_LOW) ||
3321 !init_mp_common(VMPRESS_LEVEL_MEDIUM) ||
3322 !init_mp_common(VMPRESS_LEVEL_CRITICAL))) {
3323 ALOGE("Kernel does not support memory pressure events or in-kernel low memory killer");
3324 return false;
3325 }
3326 if (use_psi_monitors) {
3327 ALOGI("Using psi monitors for memory pressure detection");
3328 } else {
3329 ALOGI("Using vmpressure for memory pressure detection");
3330 }
3331 return true;
3332}
3333
3334static void destroy_monitors() {
3335 if (use_psi_monitors) {
3336 destroy_mp_psi(VMPRESS_LEVEL_CRITICAL);
3337 destroy_mp_psi(VMPRESS_LEVEL_MEDIUM);
3338 destroy_mp_psi(VMPRESS_LEVEL_LOW);
3339 } else {
3340 destroy_mp_common(VMPRESS_LEVEL_CRITICAL);
3341 destroy_mp_common(VMPRESS_LEVEL_MEDIUM);
3342 destroy_mp_common(VMPRESS_LEVEL_LOW);
3343 }
3344}
3345
Suren Baghdasaryan7c3addb2021-06-11 12:12:56 -07003346static void drop_reaper_comm() {
3347 close(reaper_comm_fd[0]);
3348 close(reaper_comm_fd[1]);
3349}
3350
3351static bool setup_reaper_comm() {
3352 if (pipe(reaper_comm_fd)) {
3353 ALOGE("pipe failed: %s", strerror(errno));
3354 return false;
3355 }
3356
3357 // Ensure main thread never blocks on read
3358 int flags = fcntl(reaper_comm_fd[0], F_GETFL);
3359 if (fcntl(reaper_comm_fd[0], F_SETFL, flags | O_NONBLOCK)) {
3360 ALOGE("fcntl failed: %s", strerror(errno));
3361 drop_reaper_comm();
3362 return false;
3363 }
3364
3365 return true;
3366}
3367
3368static bool init_reaper() {
3369 if (!reaper.is_reaping_supported()) {
3370 ALOGI("Process reaping is not supported");
3371 return false;
3372 }
3373
3374 if (!setup_reaper_comm()) {
3375 ALOGE("Failed to create thread communication channel");
3376 return false;
3377 }
3378
3379 // Setup epoll handler
3380 struct epoll_event epev;
3381 static struct event_handler_info kill_failed_hinfo = { 0, kill_fail_handler };
3382 epev.events = EPOLLIN;
3383 epev.data.ptr = (void *)&kill_failed_hinfo;
3384 if (epoll_ctl(epollfd, EPOLL_CTL_ADD, reaper_comm_fd[0], &epev)) {
3385 ALOGE("epoll_ctl failed: %s", strerror(errno));
3386 drop_reaper_comm();
3387 return false;
3388 }
3389
3390 if (!reaper.init(reaper_comm_fd[1])) {
3391 ALOGE("Failed to initialize reaper object");
3392 if (epoll_ctl(epollfd, EPOLL_CTL_DEL, reaper_comm_fd[0], &epev)) {
3393 ALOGE("epoll_ctl failed: %s", strerror(errno));
3394 }
3395 drop_reaper_comm();
3396 return false;
3397 }
3398 maxevents++;
3399
3400 return true;
3401}
3402
Todd Poynorc58c5142013-07-09 19:35:14 -07003403static int init(void) {
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07003404 static struct event_handler_info kernel_poll_hinfo = { 0, kernel_event_handler };
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -07003405 struct reread_data file_data = {
3406 .filename = ZONEINFO_PATH,
3407 .fd = -1,
3408 };
Todd Poynorc58c5142013-07-09 19:35:14 -07003409 struct epoll_event epev;
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003410 int pidfd;
Todd Poynorc58c5142013-07-09 19:35:14 -07003411 int i;
3412 int ret;
3413
3414 page_k = sysconf(_SC_PAGESIZE);
3415 if (page_k == -1)
3416 page_k = PAGE_SIZE;
3417 page_k /= 1024;
3418
3419 epollfd = epoll_create(MAX_EPOLL_EVENTS);
3420 if (epollfd == -1) {
3421 ALOGE("epoll_create failed (errno=%d)", errno);
3422 return -1;
3423 }
3424
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003425 // mark data connections as not connected
3426 for (int i = 0; i < MAX_DATA_CONN; i++) {
3427 data_sock[i].sock = -1;
3428 }
3429
3430 ctrl_sock.sock = android_get_control_socket("lmkd");
3431 if (ctrl_sock.sock < 0) {
Todd Poynorc58c5142013-07-09 19:35:14 -07003432 ALOGE("get lmkd control socket failed");
3433 return -1;
3434 }
3435
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003436 ret = listen(ctrl_sock.sock, MAX_DATA_CONN);
Todd Poynorc58c5142013-07-09 19:35:14 -07003437 if (ret < 0) {
3438 ALOGE("lmkd control socket listen failed (errno=%d)", errno);
3439 return -1;
3440 }
3441
3442 epev.events = EPOLLIN;
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003443 ctrl_sock.handler_info.handler = ctrl_connect_handler;
3444 epev.data.ptr = (void *)&(ctrl_sock.handler_info);
3445 if (epoll_ctl(epollfd, EPOLL_CTL_ADD, ctrl_sock.sock, &epev) == -1) {
Todd Poynorc58c5142013-07-09 19:35:14 -07003446 ALOGE("epoll_ctl for lmkd control socket failed (errno=%d)", errno);
3447 return -1;
3448 }
3449 maxevents++;
3450
Robert Benea7878c9b2017-09-11 16:53:28 -07003451 has_inkernel_module = !access(INKERNEL_MINFREE_PATH, W_OK);
Suren Baghdasaryane6613ea2018-01-18 17:27:30 -08003452 use_inkernel_interface = has_inkernel_module;
Todd Poynorc58c5142013-07-09 19:35:14 -07003453
3454 if (use_inkernel_interface) {
3455 ALOGI("Using in-kernel low memory killer interface");
Jing Ji5c480962019-12-04 09:22:05 -08003456 if (init_poll_kernel()) {
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07003457 epev.events = EPOLLIN;
3458 epev.data.ptr = (void*)&kernel_poll_hinfo;
Jing Ji5c480962019-12-04 09:22:05 -08003459 if (epoll_ctl(epollfd, EPOLL_CTL_ADD, kpoll_fd, &epev) != 0) {
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07003460 ALOGE("epoll_ctl for lmk events failed (errno=%d)", errno);
Jing Ji5c480962019-12-04 09:22:05 -08003461 close(kpoll_fd);
3462 kpoll_fd = -1;
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07003463 } else {
3464 maxevents++;
Jing Ji5c480962019-12-04 09:22:05 -08003465 /* let the others know it does support reporting kills */
3466 property_set("sys.lmk.reportkills", "1");
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07003467 }
Jim Blackler700b7192019-04-26 11:18:29 +01003468 }
Todd Poynorc58c5142013-07-09 19:35:14 -07003469 } else {
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07003470 if (!init_monitors()) {
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08003471 return -1;
3472 }
Jing Ji5c480962019-12-04 09:22:05 -08003473 /* let the others know it does support reporting kills */
3474 property_set("sys.lmk.reportkills", "1");
Todd Poynorc58c5142013-07-09 19:35:14 -07003475 }
3476
Chong Zhang1cd12b52015-10-14 16:19:53 -07003477 for (i = 0; i <= ADJTOSLOT(OOM_SCORE_ADJ_MAX); i++) {
Todd Poynorc58c5142013-07-09 19:35:14 -07003478 procadjslot_list[i].next = &procadjslot_list[i];
3479 procadjslot_list[i].prev = &procadjslot_list[i];
3480 }
3481
Suren Baghdasaryana7394ea2018-10-12 11:07:40 -07003482 memset(killcnt_idx, KILLCNT_INVALID_IDX, sizeof(killcnt_idx));
3483
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -07003484 /*
3485 * Read zoneinfo as the biggest file we read to create and size the initial
3486 * read buffer and avoid memory re-allocations during memory pressure
3487 */
3488 if (reread_file(&file_data) == NULL) {
3489 ALOGE("Failed to read %s: %s", file_data.filename, strerror(errno));
3490 }
3491
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003492 /* check if kernel supports pidfd_open syscall */
Josh Gao84623be2021-03-18 17:16:08 -07003493 pidfd = TEMP_FAILURE_RETRY(pidfd_open(getpid(), 0));
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003494 if (pidfd < 0) {
3495 pidfd_supported = (errno != ENOSYS);
3496 } else {
3497 pidfd_supported = true;
3498 close(pidfd);
3499 }
3500 ALOGI("Process polling is %s", pidfd_supported ? "supported" : "not supported" );
3501
Todd Poynorc58c5142013-07-09 19:35:14 -07003502 return 0;
3503}
3504
Suren Baghdasaryan03dccf32020-04-28 16:02:13 -07003505static bool polling_paused(struct polling_params *poll_params) {
3506 return poll_params->paused_handler != NULL;
3507}
3508
3509static void resume_polling(struct polling_params *poll_params, struct timespec curr_tm) {
3510 poll_params->poll_start_tm = curr_tm;
3511 poll_params->poll_handler = poll_params->paused_handler;
Martin Liu589b5752020-09-02 23:15:18 +08003512 poll_params->polling_interval_ms = PSI_POLL_PERIOD_SHORT_MS;
3513 poll_params->paused_handler = NULL;
Suren Baghdasaryan03dccf32020-04-28 16:02:13 -07003514}
3515
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003516static void call_handler(struct event_handler_info* handler_info,
3517 struct polling_params *poll_params, uint32_t events) {
3518 struct timespec curr_tm;
3519
Suren Baghdasaryanaf1b0e02021-11-16 11:50:29 -08003520 watchdog.start();
Suren Baghdasaryan9ca53342020-04-24 16:54:55 -07003521 poll_params->update = POLLING_DO_NOT_CHANGE;
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003522 handler_info->handler(handler_info->data, events, poll_params);
3523 clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm);
Suren Baghdasaryan9ca53342020-04-24 16:54:55 -07003524 if (poll_params->poll_handler == handler_info) {
3525 poll_params->last_poll_tm = curr_tm;
3526 }
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003527
3528 switch (poll_params->update) {
3529 case POLLING_START:
3530 /*
3531 * Poll for the duration of PSI_WINDOW_SIZE_MS after the
3532 * initial PSI event because psi events are rate-limited
3533 * at one per sec.
3534 */
3535 poll_params->poll_start_tm = curr_tm;
Greg Kaiser5e80ed52019-10-10 06:52:23 -07003536 poll_params->poll_handler = handler_info;
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003537 break;
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003538 case POLLING_PAUSE:
3539 poll_params->paused_handler = handler_info;
3540 poll_params->poll_handler = NULL;
3541 break;
3542 case POLLING_RESUME:
Suren Baghdasaryan03dccf32020-04-28 16:02:13 -07003543 resume_polling(poll_params, curr_tm);
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003544 break;
3545 case POLLING_DO_NOT_CHANGE:
3546 if (get_time_diff_ms(&poll_params->poll_start_tm, &curr_tm) > PSI_WINDOW_SIZE_MS) {
3547 /* Polled for the duration of PSI window, time to stop */
3548 poll_params->poll_handler = NULL;
3549 }
Suren Baghdasaryan9ca53342020-04-24 16:54:55 -07003550 break;
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003551 }
Suren Baghdasaryanaf1b0e02021-11-16 11:50:29 -08003552 watchdog.stop();
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003553}
3554
Todd Poynorc58c5142013-07-09 19:35:14 -07003555static void mainloop(void) {
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003556 struct event_handler_info* handler_info;
Suren Baghdasaryane12a0672019-07-15 14:50:49 -07003557 struct polling_params poll_params;
3558 struct timespec curr_tm;
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003559 struct epoll_event *evt;
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08003560 long delay = -1;
Suren Baghdasaryane12a0672019-07-15 14:50:49 -07003561
3562 poll_params.poll_handler = NULL;
Suren Baghdasaryan9ca53342020-04-24 16:54:55 -07003563 poll_params.paused_handler = NULL;
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003564
Todd Poynorc58c5142013-07-09 19:35:14 -07003565 while (1) {
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07003566 struct epoll_event events[MAX_EPOLL_EVENTS];
Todd Poynorc58c5142013-07-09 19:35:14 -07003567 int nevents;
3568 int i;
3569
Suren Baghdasaryane12a0672019-07-15 14:50:49 -07003570 if (poll_params.poll_handler) {
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003571 bool poll_now;
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08003572
3573 clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm);
Martin Liu589b5752020-09-02 23:15:18 +08003574 if (poll_params.update == POLLING_RESUME) {
3575 /* Just transitioned into POLLING_RESUME, poll immediately. */
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003576 poll_now = true;
3577 nevents = 0;
3578 } else {
3579 /* Calculate next timeout */
3580 delay = get_time_diff_ms(&poll_params.last_poll_tm, &curr_tm);
3581 delay = (delay < poll_params.polling_interval_ms) ?
3582 poll_params.polling_interval_ms - delay : poll_params.polling_interval_ms;
Suren Baghdasaryane12a0672019-07-15 14:50:49 -07003583
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003584 /* Wait for events until the next polling timeout */
3585 nevents = epoll_wait(epollfd, events, maxevents, delay);
3586
3587 /* Update current time after wait */
3588 clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm);
3589 poll_now = (get_time_diff_ms(&poll_params.last_poll_tm, &curr_tm) >=
3590 poll_params.polling_interval_ms);
3591 }
3592 if (poll_now) {
3593 call_handler(poll_params.poll_handler, &poll_params, 0);
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08003594 }
3595 } else {
Suren Baghdasaryan03dccf32020-04-28 16:02:13 -07003596 if (kill_timeout_ms && is_waiting_for_kill()) {
3597 clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm);
3598 delay = kill_timeout_ms - get_time_diff_ms(&last_kill_tm, &curr_tm);
3599 /* Wait for pidfds notification or kill timeout to expire */
3600 nevents = (delay > 0) ? epoll_wait(epollfd, events, maxevents, delay) : 0;
3601 if (nevents == 0) {
3602 /* Kill notification timed out */
3603 stop_wait_for_proc_kill(false);
3604 if (polling_paused(&poll_params)) {
3605 clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm);
Martin Liu589b5752020-09-02 23:15:18 +08003606 poll_params.update = POLLING_RESUME;
Suren Baghdasaryan03dccf32020-04-28 16:02:13 -07003607 resume_polling(&poll_params, curr_tm);
3608 }
3609 }
3610 } else {
3611 /* Wait for events with no timeout */
3612 nevents = epoll_wait(epollfd, events, maxevents, -1);
3613 }
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08003614 }
Todd Poynorc58c5142013-07-09 19:35:14 -07003615
3616 if (nevents == -1) {
3617 if (errno == EINTR)
3618 continue;
3619 ALOGE("epoll_wait failed (errno=%d)", errno);
3620 continue;
3621 }
3622
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003623 /*
3624 * First pass to see if any data socket connections were dropped.
3625 * Dropped connection should be handled before any other events
3626 * to deallocate data connection and correctly handle cases when
3627 * connection gets dropped and reestablished in the same epoll cycle.
3628 * In such cases it's essential to handle connection closures first.
3629 */
3630 for (i = 0, evt = &events[0]; i < nevents; ++i, evt++) {
3631 if ((evt->events & EPOLLHUP) && evt->data.ptr) {
3632 ALOGI("lmkd data connection dropped");
3633 handler_info = (struct event_handler_info*)evt->data.ptr;
Suren Baghdasaryanaf1b0e02021-11-16 11:50:29 -08003634 watchdog.start();
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003635 ctrl_data_close(handler_info->data);
Suren Baghdasaryanaf1b0e02021-11-16 11:50:29 -08003636 watchdog.stop();
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003637 }
3638 }
3639
3640 /* Second pass to handle all other events */
3641 for (i = 0, evt = &events[0]; i < nevents; ++i, evt++) {
Suren Baghdasaryane12a0672019-07-15 14:50:49 -07003642 if (evt->events & EPOLLERR) {
Todd Poynorc58c5142013-07-09 19:35:14 -07003643 ALOGD("EPOLLERR on event #%d", i);
Suren Baghdasaryane12a0672019-07-15 14:50:49 -07003644 }
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003645 if (evt->events & EPOLLHUP) {
3646 /* This case was handled in the first pass */
3647 continue;
3648 }
3649 if (evt->data.ptr) {
3650 handler_info = (struct event_handler_info*)evt->data.ptr;
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003651 call_handler(handler_info, &poll_params, evt->events);
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003652 }
Todd Poynorc58c5142013-07-09 19:35:14 -07003653 }
3654 }
3655}
3656
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07003657int issue_reinit() {
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07003658 int sock;
Colin Crossd5b510e2014-07-14 14:31:15 -07003659
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07003660 sock = lmkd_connect();
3661 if (sock < 0) {
3662 ALOGE("failed to connect to lmkd: %s", strerror(errno));
3663 return -1;
3664 }
3665
3666 enum update_props_result res = lmkd_update_props(sock);
3667 switch (res) {
3668 case UPDATE_PROPS_SUCCESS:
3669 ALOGI("lmkd updated properties successfully");
3670 break;
3671 case UPDATE_PROPS_SEND_ERR:
3672 ALOGE("failed to send lmkd request: %s", strerror(errno));
3673 break;
3674 case UPDATE_PROPS_RECV_ERR:
3675 ALOGE("failed to receive lmkd reply: %s", strerror(errno));
3676 break;
3677 case UPDATE_PROPS_FORMAT_ERR:
3678 ALOGE("lmkd reply is invalid");
3679 break;
3680 case UPDATE_PROPS_FAIL:
3681 ALOGE("lmkd failed to update its properties");
3682 break;
3683 }
3684
3685 close(sock);
3686 return res == UPDATE_PROPS_SUCCESS ? 0 : -1;
3687}
3688
3689static void update_props() {
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08003690 /* By default disable low level vmpressure events */
3691 level_oomadj[VMPRESS_LEVEL_LOW] =
Suren Baghdasaryand0a80042021-08-03 15:40:23 -07003692 GET_LMK_PROPERTY(int32, "low", OOM_SCORE_ADJ_MAX + 1);
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08003693 level_oomadj[VMPRESS_LEVEL_MEDIUM] =
Suren Baghdasaryand0a80042021-08-03 15:40:23 -07003694 GET_LMK_PROPERTY(int32, "medium", 800);
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08003695 level_oomadj[VMPRESS_LEVEL_CRITICAL] =
Suren Baghdasaryand0a80042021-08-03 15:40:23 -07003696 GET_LMK_PROPERTY(int32, "critical", 0);
3697 debug_process_killing = GET_LMK_PROPERTY(bool, "debug", false);
Suren Baghdasaryan3faa3032017-12-08 13:08:41 -08003698
3699 /* By default disable upgrade/downgrade logic */
3700 enable_pressure_upgrade =
Suren Baghdasaryand0a80042021-08-03 15:40:23 -07003701 GET_LMK_PROPERTY(bool, "critical_upgrade", false);
Suren Baghdasaryan3faa3032017-12-08 13:08:41 -08003702 upgrade_pressure =
Suren Baghdasaryand0a80042021-08-03 15:40:23 -07003703 (int64_t)GET_LMK_PROPERTY(int32, "upgrade_pressure", 100);
Suren Baghdasaryan3faa3032017-12-08 13:08:41 -08003704 downgrade_pressure =
Suren Baghdasaryand0a80042021-08-03 15:40:23 -07003705 (int64_t)GET_LMK_PROPERTY(int32, "downgrade_pressure", 100);
Suren Baghdasaryaneb7c5492017-12-08 13:17:06 -08003706 kill_heaviest_task =
Suren Baghdasaryand0a80042021-08-03 15:40:23 -07003707 GET_LMK_PROPERTY(bool, "kill_heaviest_task", false);
Suren Baghdasaryand1d59f82018-04-13 11:45:38 -07003708 low_ram_device = property_get_bool("ro.config.low_ram", false);
Suren Baghdasaryan30854e72018-01-17 17:28:01 -08003709 kill_timeout_ms =
Suren Baghdasaryand0a80042021-08-03 15:40:23 -07003710 (unsigned long)GET_LMK_PROPERTY(int32, "kill_timeout_ms", 100);
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07003711 use_minfree_levels =
Suren Baghdasaryand0a80042021-08-03 15:40:23 -07003712 GET_LMK_PROPERTY(bool, "use_minfree_levels", false);
Suren Baghdasaryan8389fdb2018-06-19 18:38:12 -07003713 per_app_memcg =
3714 property_get_bool("ro.config.per_app_memcg", low_ram_device);
Suren Baghdasaryand0a80042021-08-03 15:40:23 -07003715 swap_free_low_percentage = clamp(0, 100, GET_LMK_PROPERTY(int32, "swap_free_low_percentage",
Suren Baghdasaryanfb1f5922020-05-19 13:07:23 -07003716 DEF_LOW_SWAP));
Suren Baghdasaryand0a80042021-08-03 15:40:23 -07003717 psi_partial_stall_ms = GET_LMK_PROPERTY(int32, "psi_partial_stall_ms",
Suren Baghdasaryan2f88e152019-07-15 15:42:09 -07003718 low_ram_device ? DEF_PARTIAL_STALL_LOWRAM : DEF_PARTIAL_STALL);
Suren Baghdasaryand0a80042021-08-03 15:40:23 -07003719 psi_complete_stall_ms = GET_LMK_PROPERTY(int32, "psi_complete_stall_ms",
Suren Baghdasaryan2f88e152019-07-15 15:42:09 -07003720 DEF_COMPLETE_STALL);
Bart Van Assche80a3dba2022-02-02 23:51:35 +00003721 thrashing_limit_pct =
3722 std::max(0, GET_LMK_PROPERTY(int32, "thrashing_limit",
3723 low_ram_device ? DEF_THRASHING_LOWRAM : DEF_THRASHING));
Suren Baghdasaryand0a80042021-08-03 15:40:23 -07003724 thrashing_limit_decay_pct = clamp(0, 100, GET_LMK_PROPERTY(int32, "thrashing_limit_decay",
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07003725 low_ram_device ? DEF_THRASHING_DECAY_LOWRAM : DEF_THRASHING_DECAY));
Bart Van Assche80a3dba2022-02-02 23:51:35 +00003726 thrashing_critical_pct = std::max(
3727 0, GET_LMK_PROPERTY(int32, "thrashing_limit_critical", thrashing_limit_pct * 2));
Suren Baghdasaryand0a80042021-08-03 15:40:23 -07003728 swap_util_max = clamp(0, 100, GET_LMK_PROPERTY(int32, "swap_util_max", 100));
3729 filecache_min_kb = GET_LMK_PROPERTY(int64, "filecache_min_kb", 0);
Suren Baghdasaryan5ae47a92022-02-10 21:10:23 -08003730 stall_limit_critical = GET_LMK_PROPERTY(int64, "stall_limit_critical", 100);
Suren Baghdasaryan7c3addb2021-06-11 12:12:56 -07003731
3732 reaper.enable_debug(debug_process_killing);
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07003733}
3734
3735int main(int argc, char **argv) {
3736 if ((argc > 1) && argv[1] && !strcmp(argv[1], "--reinit")) {
Suren Baghdasaryan0e64ead2021-09-01 00:49:51 -07003737 if (property_set(LMKD_REINIT_PROP, "")) {
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07003738 ALOGE("Failed to reset " LMKD_REINIT_PROP " property");
3739 }
3740 return issue_reinit();
3741 }
3742
3743 update_props();
Robert Benea57397dc2017-07-31 17:15:20 -07003744
Suren Baghdasaryan12cacae2019-09-16 12:06:30 -07003745 ctx = create_android_logger(KILLINFO_LOG_TAG);
Suren Baghdasaryan08bfa982018-07-26 16:34:27 -07003746
Mark Salyzyn5cc80b32018-03-21 12:24:58 -07003747 if (!init()) {
3748 if (!use_inkernel_interface) {
3749 /*
3750 * MCL_ONFAULT pins pages as they fault instead of loading
3751 * everything immediately all at once. (Which would be bad,
3752 * because as of this writing, we have a lot of mapped pages we
3753 * never use.) Old kernels will see MCL_ONFAULT and fail with
3754 * EINVAL; we ignore this failure.
3755 *
3756 * N.B. read the man page for mlockall. MCL_CURRENT | MCL_ONFAULT
3757 * pins ⊆ MCL_CURRENT, converging to just MCL_CURRENT as we fault
3758 * in pages.
3759 */
Mark Salyzyna00ccd82018-04-09 09:50:32 -07003760 /* CAP_IPC_LOCK required */
Mark Salyzyn5cc80b32018-03-21 12:24:58 -07003761 if (mlockall(MCL_CURRENT | MCL_FUTURE | MCL_ONFAULT) && (errno != EINVAL)) {
3762 ALOGW("mlockall failed %s", strerror(errno));
3763 }
Daniel Colascione46648332018-01-03 12:01:02 -08003764
Mark Salyzyna00ccd82018-04-09 09:50:32 -07003765 /* CAP_NICE required */
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07003766 struct sched_param param = {
3767 .sched_priority = 1,
3768 };
Mark Salyzyna00ccd82018-04-09 09:50:32 -07003769 if (sched_setscheduler(0, SCHED_FIFO, &param)) {
3770 ALOGW("set SCHED_FIFO failed %s", strerror(errno));
3771 }
Mark Salyzyn5cc80b32018-03-21 12:24:58 -07003772 }
3773
Suren Baghdasaryan7c3addb2021-06-11 12:12:56 -07003774 if (init_reaper()) {
3775 ALOGI("Process reaper initialized with %d threads in the pool",
3776 reaper.thread_cnt());
3777 }
3778
Suren Baghdasaryanaf1b0e02021-11-16 11:50:29 -08003779 if (!watchdog.init()) {
3780 ALOGE("Failed to initialize the watchdog");
3781 }
3782
Todd Poynorc58c5142013-07-09 19:35:14 -07003783 mainloop();
Mark Salyzyn5cc80b32018-03-21 12:24:58 -07003784 }
Todd Poynorc58c5142013-07-09 19:35:14 -07003785
Suren Baghdasaryan08bfa982018-07-26 16:34:27 -07003786 android_log_destroy(&ctx);
3787
Todd Poynorc58c5142013-07-09 19:35:14 -07003788 ALOGI("exiting");
3789 return 0;
3790}