blob: 5821e8f9756791a92fa01e967a829e117573e694 [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 Baghdasaryan26c9de42022-08-23 13:25:56 -07002156 // WARNING: do not use target after pid_remove()
2157 pid_remove(target.pid);
Suren Baghdasaryanaf1b0e02021-11-16 11:50:29 -08002158 break;
2159 }
2160 prev_pid = target.pid;
2161 }
2162}
2163
2164static Watchdog watchdog(WATCHDOG_TIMEOUT_SEC, watchdog_callback);
2165
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002166static bool is_kill_pending(void) {
2167 char buf[24];
2168
2169 if (last_kill_pid_or_fd < 0) {
2170 return false;
2171 }
2172
2173 if (pidfd_supported) {
2174 return true;
2175 }
2176
2177 /* when pidfd is not supported base the decision on /proc/<pid> existence */
2178 snprintf(buf, sizeof(buf), "/proc/%d/", last_kill_pid_or_fd);
2179 if (access(buf, F_OK) == 0) {
2180 return true;
2181 }
2182
2183 return false;
2184}
2185
2186static bool is_waiting_for_kill(void) {
2187 return pidfd_supported && last_kill_pid_or_fd >= 0;
2188}
2189
2190static void stop_wait_for_proc_kill(bool finished) {
2191 struct epoll_event epev;
2192
2193 if (last_kill_pid_or_fd < 0) {
2194 return;
2195 }
2196
2197 if (debug_process_killing) {
2198 struct timespec curr_tm;
2199
2200 if (clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm) != 0) {
2201 /*
2202 * curr_tm is used here merely to report kill duration, so this failure is not fatal.
2203 * Log an error and continue.
2204 */
2205 ALOGE("Failed to get current time");
2206 }
2207
2208 if (finished) {
2209 ALOGI("Process got killed in %ldms",
2210 get_time_diff_ms(&last_kill_tm, &curr_tm));
2211 } else {
2212 ALOGI("Stop waiting for process kill after %ldms",
2213 get_time_diff_ms(&last_kill_tm, &curr_tm));
2214 }
2215 }
2216
2217 if (pidfd_supported) {
2218 /* unregister fd */
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07002219 if (epoll_ctl(epollfd, EPOLL_CTL_DEL, last_kill_pid_or_fd, &epev)) {
2220 // Log an error and keep going
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002221 ALOGE("epoll_ctl for last killed process failed; errno=%d", errno);
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002222 }
2223 maxevents--;
2224 close(last_kill_pid_or_fd);
2225 }
2226
2227 last_kill_pid_or_fd = -1;
2228}
2229
2230static void kill_done_handler(int data __unused, uint32_t events __unused,
2231 struct polling_params *poll_params) {
2232 stop_wait_for_proc_kill(true);
2233 poll_params->update = POLLING_RESUME;
2234}
2235
Suren Baghdasaryan7c3addb2021-06-11 12:12:56 -07002236static void kill_fail_handler(int data __unused, uint32_t events __unused,
2237 struct polling_params *poll_params) {
2238 int pid;
2239
2240 // Extract pid from the communication pipe. Clearing the pipe this way allows further
2241 // epoll_wait calls to sleep until the next event.
2242 if (TEMP_FAILURE_RETRY(read(reaper_comm_fd[0], &pid, sizeof(pid))) != sizeof(pid)) {
2243 ALOGE("thread communication read failed: %s", strerror(errno));
2244 }
2245 stop_wait_for_proc_kill(false);
2246 poll_params->update = POLLING_RESUME;
2247}
2248
Suren Baghdasaryana10157c2019-07-19 10:55:39 -07002249static void start_wait_for_proc_kill(int pid_or_fd) {
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002250 static struct event_handler_info kill_done_hinfo = { 0, kill_done_handler };
2251 struct epoll_event epev;
2252
2253 if (last_kill_pid_or_fd >= 0) {
2254 /* Should not happen but if it does we should stop previous wait */
2255 ALOGE("Attempt to wait for a kill while another wait is in progress");
2256 stop_wait_for_proc_kill(false);
2257 }
2258
Suren Baghdasaryana10157c2019-07-19 10:55:39 -07002259 last_kill_pid_or_fd = pid_or_fd;
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002260
Suren Baghdasaryana10157c2019-07-19 10:55:39 -07002261 if (!pidfd_supported) {
2262 /* If pidfd is not supported just store PID and exit */
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002263 return;
2264 }
2265
2266 epev.events = EPOLLIN;
2267 epev.data.ptr = (void *)&kill_done_hinfo;
2268 if (epoll_ctl(epollfd, EPOLL_CTL_ADD, last_kill_pid_or_fd, &epev) != 0) {
2269 ALOGE("epoll_ctl for last kill failed; errno=%d", errno);
2270 close(last_kill_pid_or_fd);
2271 last_kill_pid_or_fd = -1;
2272 return;
2273 }
2274 maxevents++;
2275}
Tim Murraya79ec0f2018-10-25 17:05:41 -07002276
Ioannis Ilkos279268a2020-08-01 10:50:40 +01002277/* Kill one process specified by procp. Returns the size (in pages) of the process killed */
Suren Baghdasaryane1604752021-07-22 16:21:21 -07002278static int kill_one_process(struct proc* procp, int min_oom_score, struct kill_info *ki,
Suren Baghdasaryan014dd712022-02-18 12:51:15 -08002279 union meminfo *mi, struct wakeup_info *wi, struct timespec *tm,
2280 struct psi_data *pd) {
Colin Cross3d57a512014-07-14 12:39:56 -07002281 int pid = procp->pid;
Suren Baghdasaryana10157c2019-07-19 10:55:39 -07002282 int pidfd = procp->pidfd;
Colin Cross3d57a512014-07-14 12:39:56 -07002283 uid_t uid = procp->uid;
2284 char *taskname;
Suren Baghdasaryan7c3addb2021-06-11 12:12:56 -07002285 int kill_result;
Suren Baghdasaryan8b00c6d2018-10-12 11:28:33 -07002286 int result = -1;
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07002287 struct memory_stat *mem_st;
Suren Baghdasaryan3cc1f132020-09-09 20:19:02 -07002288 struct kill_stat kill_st;
Ioannis Ilkos279268a2020-08-01 10:50:40 +01002289 int64_t tgid;
2290 int64_t rss_kb;
2291 int64_t swap_kb;
2292 char buf[PAGE_SIZE];
Suren Baghdasaryan34928bb2021-07-29 17:02:51 -07002293 char desc[LINE_MAX];
Rajeev Kumar4aba9152018-01-31 17:54:56 -08002294
Ioannis Ilkos279268a2020-08-01 10:50:40 +01002295 if (!read_proc_status(pid, buf, sizeof(buf))) {
2296 goto out;
2297 }
2298 if (!parse_status_tag(buf, PROC_STATUS_TGID_FIELD, &tgid)) {
2299 ALOGE("Unable to parse tgid from /proc/%d/status", pid);
2300 goto out;
2301 }
2302 if (tgid != pid) {
2303 ALOGE("Possible pid reuse detected (pid %d, tgid %" PRId64 ")!", pid, tgid);
2304 goto out;
2305 }
2306 // Zombie processes will not have RSS / Swap fields.
2307 if (!parse_status_tag(buf, PROC_STATUS_RSS_FIELD, &rss_kb)) {
2308 goto out;
2309 }
2310 if (!parse_status_tag(buf, PROC_STATUS_SWAP_FIELD, &swap_kb)) {
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -07002311 goto out;
2312 }
2313
Suren Baghdasaryan632f1c52019-10-04 16:06:55 -07002314 taskname = proc_get_name(pid, buf, sizeof(buf));
Ioannis Ilkos279268a2020-08-01 10:50:40 +01002315 // taskname will point inside buf, do not reuse buf onwards.
Colin Cross3d57a512014-07-14 12:39:56 -07002316 if (!taskname) {
Suren Baghdasaryan8b00c6d2018-10-12 11:28:33 -07002317 goto out;
Colin Cross3d57a512014-07-14 12:39:56 -07002318 }
2319
Ioannis Ilkos279268a2020-08-01 10:50:40 +01002320 mem_st = stats_read_memory_stat(per_app_memcg, pid, uid, rss_kb * 1024, swap_kb * 1024);
Rajeev Kumar4aba9152018-01-31 17:54:56 -08002321
George Burgess IVe849f142021-08-05 06:59:42 +00002322 snprintf(desc, sizeof(desc), "lmk,%d,%d,%d,%d,%d", pid, ki ? (int)ki->kill_reason : -1,
2323 procp->oomadj, min_oom_score, ki ? ki->max_thrashing : -1);
Suren Baghdasaryan7c3addb2021-06-11 12:12:56 -07002324
Suren Baghdasaryan34928bb2021-07-29 17:02:51 -07002325 trace_kill_start(pid, desc);
Suren Baghdasaryan03e19872018-01-04 10:43:58 -08002326
Suren Baghdasaryan7c3addb2021-06-11 12:12:56 -07002327 start_wait_for_proc_kill(pidfd < 0 ? pid : pidfd);
Suren Baghdasaryan2bdf7f02022-01-20 18:48:52 -08002328 kill_result = reaper.kill({ pidfd, pid, uid }, false);
Wei Wangf1ee2e12018-11-21 00:11:44 -08002329
Suren Baghdasaryan34928bb2021-07-29 17:02:51 -07002330 trace_kill_end();
Suren Baghdasaryanc2e05b62019-09-04 16:44:47 -07002331
Suren Baghdasaryan7c3addb2021-06-11 12:12:56 -07002332 if (kill_result) {
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002333 stop_wait_for_proc_kill(false);
Suren Baghdasaryanc2e05b62019-09-04 16:44:47 -07002334 ALOGE("kill(%d): errno=%d", pid, errno);
2335 /* Delete process record even when we fail to kill so that we don't get stuck on it */
2336 goto out;
2337 }
2338
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002339 last_kill_tm = *tm;
2340
Suren Baghdasaryana7394ea2018-10-12 11:07:40 -07002341 inc_killcnt(procp->oomadj);
Suren Baghdasaryan12cacae2019-09-16 12:06:30 -07002342
Suren Baghdasaryane1604752021-07-22 16:21:21 -07002343 if (ki) {
2344 kill_st.kill_reason = ki->kill_reason;
2345 kill_st.thrashing = ki->thrashing;
2346 kill_st.max_thrashing = ki->max_thrashing;
Ioannis Ilkos48848902021-02-18 19:53:33 +00002347 ALOGI("Kill '%s' (%d), uid %d, oom_score_adj %d to free %" PRId64 "kB rss, %" PRId64
Suren Baghdasaryane1604752021-07-22 16:21:21 -07002348 "kB swap; reason: %s", taskname, pid, uid, procp->oomadj, rss_kb, swap_kb,
2349 ki->kill_desc);
Suren Baghdasaryan89454e62019-07-15 15:50:17 -07002350 } else {
Suren Baghdasaryane1604752021-07-22 16:21:21 -07002351 kill_st.kill_reason = NONE;
2352 kill_st.thrashing = 0;
2353 kill_st.max_thrashing = 0;
Ioannis Ilkos48848902021-02-18 19:53:33 +00002354 ALOGI("Kill '%s' (%d), uid %d, oom_score_adj %d to free %" PRId64 "kB rss, %" PRId64
2355 "kb swap", taskname, pid, uid, procp->oomadj, rss_kb, swap_kb);
Suren Baghdasaryan89454e62019-07-15 15:50:17 -07002356 }
Suren Baghdasaryan014dd712022-02-18 12:51:15 -08002357 killinfo_log(procp, min_oom_score, rss_kb, swap_kb, ki, mi, wi, tm, pd);
Colin Cross3d57a512014-07-14 12:39:56 -07002358
Suren Baghdasaryan3cc1f132020-09-09 20:19:02 -07002359 kill_st.uid = static_cast<int32_t>(uid);
2360 kill_st.taskname = taskname;
Suren Baghdasaryan3cc1f132020-09-09 20:19:02 -07002361 kill_st.oom_score = procp->oomadj;
2362 kill_st.min_oom_score = min_oom_score;
2363 kill_st.free_mem_kb = mi->field.nr_free_pages * page_k;
2364 kill_st.free_swap_kb = mi->field.free_swap * page_k;
2365 stats_write_lmk_kill_occurred(&kill_st, mem_st);
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07002366
Jing Ji5c480962019-12-04 09:22:05 -08002367 ctrl_data_write_lmk_kill_occurred((pid_t)pid, uid);
2368
Ioannis Ilkos279268a2020-08-01 10:50:40 +01002369 result = rss_kb / page_k;
Mark Salyzyn1d5fdf32018-02-04 15:27:23 -08002370
Suren Baghdasaryan8b00c6d2018-10-12 11:28:33 -07002371out:
2372 /*
2373 * WARNING: After pid_remove() procp is freed and can't be used!
2374 * Therefore placed at the end of the function.
2375 */
2376 pid_remove(pid);
2377 return result;
Colin Cross3d57a512014-07-14 12:39:56 -07002378}
2379
2380/*
Chris Morin74b4df92021-02-26 00:00:35 -08002381 * Find one process to kill at or above the given oom_score_adj level.
Suren Baghdasaryan85c31b52018-10-26 11:32:15 -07002382 * Returns size of the killed process.
Colin Cross3d57a512014-07-14 12:39:56 -07002383 */
Suren Baghdasaryane1604752021-07-22 16:21:21 -07002384static int find_and_kill_process(int min_score_adj, struct kill_info *ki, union meminfo *mi,
Suren Baghdasaryan014dd712022-02-18 12:51:15 -08002385 struct wakeup_info *wi, struct timespec *tm,
2386 struct psi_data *pd) {
Colin Cross3d57a512014-07-14 12:39:56 -07002387 int i;
Suren Baghdasaryan85c31b52018-10-26 11:32:15 -07002388 int killed_size = 0;
Yang Lu5dfffbc2018-05-15 04:59:44 +00002389 bool lmk_state_change_start = false;
Suren Baghdasaryan858e8c62021-03-03 11:05:09 -08002390 bool choose_heaviest_task = kill_heaviest_task;
Rajeev Kumar4aba9152018-01-31 17:54:56 -08002391
Chong Zhang1cd12b52015-10-14 16:19:53 -07002392 for (i = OOM_SCORE_ADJ_MAX; i >= min_score_adj; i--) {
Colin Cross3d57a512014-07-14 12:39:56 -07002393 struct proc *procp;
2394
Suren Baghdasaryan858e8c62021-03-03 11:05:09 -08002395 if (!choose_heaviest_task && i <= PERCEPTIBLE_APP_ADJ) {
2396 /*
2397 * If we have to choose a perceptible process, choose the heaviest one to
2398 * hopefully minimize the number of victims.
2399 */
2400 choose_heaviest_task = true;
2401 }
2402
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002403 while (true) {
Suren Baghdasaryan858e8c62021-03-03 11:05:09 -08002404 procp = choose_heaviest_task ?
Suren Baghdasaryanaf1b0e02021-11-16 11:50:29 -08002405 proc_get_heaviest(i) : proc_adj_tail(i);
Colin Cross3d57a512014-07-14 12:39:56 -07002406
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002407 if (!procp)
2408 break;
2409
Suren Baghdasaryan014dd712022-02-18 12:51:15 -08002410 killed_size = kill_one_process(procp, min_score_adj, ki, mi, wi, tm, pd);
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002411 if (killed_size >= 0) {
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07002412 if (!lmk_state_change_start) {
Yang Lu5dfffbc2018-05-15 04:59:44 +00002413 lmk_state_change_start = true;
Vova Sharaienkoa92b76b2021-04-24 00:30:06 +00002414 stats_write_lmk_state_changed(STATE_START);
Yang Lu5dfffbc2018-05-15 04:59:44 +00002415 }
Suren Baghdasaryan85c31b52018-10-26 11:32:15 -07002416 break;
Colin Cross3d57a512014-07-14 12:39:56 -07002417 }
2418 }
Suren Baghdasaryan85c31b52018-10-26 11:32:15 -07002419 if (killed_size) {
2420 break;
2421 }
Colin Cross3d57a512014-07-14 12:39:56 -07002422 }
2423
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07002424 if (lmk_state_change_start) {
Vova Sharaienkoa92b76b2021-04-24 00:30:06 +00002425 stats_write_lmk_state_changed(STATE_STOP);
Rajeev Kumar4aba9152018-01-31 17:54:56 -08002426 }
Rajeev Kumar4aba9152018-01-31 17:54:56 -08002427
Suren Baghdasaryan85c31b52018-10-26 11:32:15 -07002428 return killed_size;
Colin Cross3d57a512014-07-14 12:39:56 -07002429}
2430
Suren Baghdasaryan87966742018-04-13 12:43:41 -07002431static int64_t get_memory_usage(struct reread_data *file_data) {
Robert Beneac72b2932017-08-21 15:18:31 -07002432 int64_t mem_usage;
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -07002433 char *buf;
Suren Baghdasaryan87966742018-04-13 12:43:41 -07002434
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -07002435 if ((buf = reread_file(file_data)) == NULL) {
Robert Beneac72b2932017-08-21 15:18:31 -07002436 return -1;
2437 }
2438
Suren Baghdasaryan87966742018-04-13 12:43:41 -07002439 if (!parse_int64(buf, &mem_usage)) {
2440 ALOGE("%s parse error", file_data->filename);
Robert Beneac72b2932017-08-21 15:18:31 -07002441 return -1;
2442 }
Robert Beneac72b2932017-08-21 15:18:31 -07002443 if (mem_usage == 0) {
2444 ALOGE("No memory!");
2445 return -1;
2446 }
2447 return mem_usage;
2448}
2449
Suren Baghdasaryane0f3dd12018-04-13 13:41:12 -07002450void record_low_pressure_levels(union meminfo *mi) {
2451 if (low_pressure_mem.min_nr_free_pages == -1 ||
2452 low_pressure_mem.min_nr_free_pages > mi->field.nr_free_pages) {
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002453 if (debug_process_killing) {
Suren Baghdasaryane0f3dd12018-04-13 13:41:12 -07002454 ALOGI("Low pressure min memory update from %" PRId64 " to %" PRId64,
2455 low_pressure_mem.min_nr_free_pages, mi->field.nr_free_pages);
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002456 }
Suren Baghdasaryane0f3dd12018-04-13 13:41:12 -07002457 low_pressure_mem.min_nr_free_pages = mi->field.nr_free_pages;
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002458 }
2459 /*
2460 * Free memory at low vmpressure events occasionally gets spikes,
2461 * possibly a stale low vmpressure event with memory already
2462 * freed up (no memory pressure should have been reported).
Suren Baghdasaryane0f3dd12018-04-13 13:41:12 -07002463 * Ignore large jumps in max_nr_free_pages that would mess up our stats.
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002464 */
Suren Baghdasaryane0f3dd12018-04-13 13:41:12 -07002465 if (low_pressure_mem.max_nr_free_pages == -1 ||
2466 (low_pressure_mem.max_nr_free_pages < mi->field.nr_free_pages &&
2467 mi->field.nr_free_pages - low_pressure_mem.max_nr_free_pages <
2468 low_pressure_mem.max_nr_free_pages * 0.1)) {
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002469 if (debug_process_killing) {
Suren Baghdasaryane0f3dd12018-04-13 13:41:12 -07002470 ALOGI("Low pressure max memory update from %" PRId64 " to %" PRId64,
2471 low_pressure_mem.max_nr_free_pages, mi->field.nr_free_pages);
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002472 }
Suren Baghdasaryane0f3dd12018-04-13 13:41:12 -07002473 low_pressure_mem.max_nr_free_pages = mi->field.nr_free_pages;
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002474 }
2475}
2476
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08002477enum vmpressure_level upgrade_level(enum vmpressure_level level) {
2478 return (enum vmpressure_level)((level < VMPRESS_LEVEL_CRITICAL) ?
2479 level + 1 : level);
2480}
2481
2482enum vmpressure_level downgrade_level(enum vmpressure_level level) {
2483 return (enum vmpressure_level)((level > VMPRESS_LEVEL_LOW) ?
2484 level - 1 : level);
2485}
2486
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002487enum zone_watermark {
2488 WMARK_MIN = 0,
2489 WMARK_LOW,
2490 WMARK_HIGH,
2491 WMARK_NONE
2492};
2493
Suren Baghdasaryan81c75b22019-08-14 09:48:35 -07002494struct zone_watermarks {
2495 long high_wmark;
2496 long low_wmark;
2497 long min_wmark;
2498};
2499
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002500/*
2501 * Returns lowest breached watermark or WMARK_NONE.
2502 */
Suren Baghdasaryan81c75b22019-08-14 09:48:35 -07002503static enum zone_watermark get_lowest_watermark(union meminfo *mi,
2504 struct zone_watermarks *watermarks)
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002505{
Suren Baghdasaryan81c75b22019-08-14 09:48:35 -07002506 int64_t nr_free_pages = mi->field.nr_free_pages - mi->field.cma_free;
2507
2508 if (nr_free_pages < watermarks->min_wmark) {
2509 return WMARK_MIN;
2510 }
2511 if (nr_free_pages < watermarks->low_wmark) {
2512 return WMARK_LOW;
2513 }
2514 if (nr_free_pages < watermarks->high_wmark) {
2515 return WMARK_HIGH;
2516 }
2517 return WMARK_NONE;
2518}
2519
2520void calc_zone_watermarks(struct zoneinfo *zi, struct zone_watermarks *watermarks) {
2521 memset(watermarks, 0, sizeof(struct zone_watermarks));
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002522
2523 for (int node_idx = 0; node_idx < zi->node_count; node_idx++) {
2524 struct zoneinfo_node *node = &zi->nodes[node_idx];
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002525 for (int zone_idx = 0; zone_idx < node->zone_count; zone_idx++) {
2526 struct zoneinfo_zone *zone = &node->zones[zone_idx];
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002527
2528 if (!zone->fields.field.present) {
2529 continue;
2530 }
2531
Suren Baghdasaryan81c75b22019-08-14 09:48:35 -07002532 watermarks->high_wmark += zone->max_protection + zone->fields.field.high;
2533 watermarks->low_wmark += zone->max_protection + zone->fields.field.low;
2534 watermarks->min_wmark += zone->max_protection + zone->fields.field.min;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002535 }
2536 }
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002537}
2538
Suren Baghdasaryan51ee4c52020-04-21 12:27:01 -07002539static int calc_swap_utilization(union meminfo *mi) {
2540 int64_t swap_used = mi->field.total_swap - mi->field.free_swap;
2541 int64_t total_swappable = mi->field.active_anon + mi->field.inactive_anon +
2542 mi->field.shmem + swap_used;
2543 return total_swappable > 0 ? (swap_used * 100) / total_swappable : 0;
2544}
2545
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002546static void mp_event_psi(int data, uint32_t events, struct polling_params *poll_params) {
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002547 enum reclaim_state {
2548 NO_RECLAIM = 0,
2549 KSWAPD_RECLAIM,
2550 DIRECT_RECLAIM,
2551 };
2552 static int64_t init_ws_refault;
Martin Liu1f72f5f2020-08-21 13:18:50 +08002553 static int64_t prev_workingset_refault;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002554 static int64_t base_file_lru;
2555 static int64_t init_pgscan_kswapd;
2556 static int64_t init_pgscan_direct;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002557 static bool killing;
Martin Liu1f72f5f2020-08-21 13:18:50 +08002558 static int thrashing_limit = thrashing_limit_pct;
Suren Baghdasaryan81c75b22019-08-14 09:48:35 -07002559 static struct zone_watermarks watermarks;
2560 static struct timespec wmark_update_tm;
Suren Baghdasaryand7b4fcb2020-07-23 18:00:43 -07002561 static struct wakeup_info wi;
Martin Liu1f72f5f2020-08-21 13:18:50 +08002562 static struct timespec thrashing_reset_tm;
2563 static int64_t prev_thrash_growth = 0;
Suren Baghdasaryan11221d42021-07-14 17:57:52 -07002564 static bool check_filecache = false;
Suren Baghdasaryane1604752021-07-22 16:21:21 -07002565 static int max_thrashing = 0;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002566
2567 union meminfo mi;
2568 union vmstat vs;
Suren Baghdasaryan5ae47a92022-02-10 21:10:23 -08002569 struct psi_data psi_data;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002570 struct timespec curr_tm;
2571 int64_t thrashing = 0;
2572 bool swap_is_low = false;
2573 enum vmpressure_level level = (enum vmpressure_level)data;
2574 enum kill_reasons kill_reason = NONE;
2575 bool cycle_after_kill = false;
2576 enum reclaim_state reclaim = NO_RECLAIM;
2577 enum zone_watermark wmark = WMARK_NONE;
Suren Baghdasaryan89454e62019-07-15 15:50:17 -07002578 char kill_desc[LINE_MAX];
Suren Baghdasaryan970a26a2019-09-19 15:27:21 -07002579 bool cut_thrashing_limit = false;
2580 int min_score_adj = 0;
Suren Baghdasaryan51ee4c52020-04-21 12:27:01 -07002581 int swap_util = 0;
Suren Baghdasaryan6e6d14b2021-10-28 13:30:08 -07002582 int64_t swap_low_threshold;
Martin Liu1f72f5f2020-08-21 13:18:50 +08002583 long since_thrashing_reset_ms;
Suren Baghdasaryandc60f972020-12-14 13:38:48 -08002584 int64_t workingset_refault_file;
Suren Baghdasaryan5ae47a92022-02-10 21:10:23 -08002585 bool critical_stall = false;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002586
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002587 if (clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm) != 0) {
2588 ALOGE("Failed to get current time");
2589 return;
2590 }
2591
Suren Baghdasaryand7b4fcb2020-07-23 18:00:43 -07002592 record_wakeup_time(&curr_tm, events ? Event : Polling, &wi);
2593
Suren Baghdasaryan03dccf32020-04-28 16:02:13 -07002594 bool kill_pending = is_kill_pending();
Suren Baghdasaryaned715a32020-05-11 16:31:57 -07002595 if (kill_pending && (kill_timeout_ms == 0 ||
2596 get_time_diff_ms(&last_kill_tm, &curr_tm) < static_cast<long>(kill_timeout_ms))) {
Suren Baghdasaryan03dccf32020-04-28 16:02:13 -07002597 /* Skip while still killing a process */
Suren Baghdasaryand7b4fcb2020-07-23 18:00:43 -07002598 wi.skipped_wakeups++;
Suren Baghdasaryan03dccf32020-04-28 16:02:13 -07002599 goto no_kill;
2600 }
2601 /*
2602 * Process is dead or kill timeout is over, stop waiting. This has no effect if pidfds are
2603 * supported and death notification already caused waiting to stop.
2604 */
2605 stop_wait_for_proc_kill(!kill_pending);
2606
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002607 if (vmstat_parse(&vs) < 0) {
2608 ALOGE("Failed to parse vmstat!");
2609 return;
2610 }
Suren Baghdasaryandc60f972020-12-14 13:38:48 -08002611 /* Starting 5.9 kernel workingset_refault vmstat field was renamed workingset_refault_file */
2612 workingset_refault_file = vs.field.workingset_refault ? : vs.field.workingset_refault_file;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002613
2614 if (meminfo_parse(&mi) < 0) {
2615 ALOGE("Failed to parse meminfo!");
2616 return;
2617 }
2618
2619 /* Reset states after process got killed */
2620 if (killing) {
2621 killing = false;
2622 cycle_after_kill = true;
2623 /* Reset file-backed pagecache size and refault amounts after a kill */
2624 base_file_lru = vs.field.nr_inactive_file + vs.field.nr_active_file;
Suren Baghdasaryandc60f972020-12-14 13:38:48 -08002625 init_ws_refault = workingset_refault_file;
Martin Liu1f72f5f2020-08-21 13:18:50 +08002626 thrashing_reset_tm = curr_tm;
2627 prev_thrash_growth = 0;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002628 }
2629
2630 /* Check free swap levels */
2631 if (swap_free_low_percentage) {
Suren Baghdasaryan6e6d14b2021-10-28 13:30:08 -07002632 swap_low_threshold = mi.field.total_swap * swap_free_low_percentage / 100;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002633 swap_is_low = mi.field.free_swap < swap_low_threshold;
Suren Baghdasaryan6e6d14b2021-10-28 13:30:08 -07002634 } else {
2635 swap_low_threshold = 0;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002636 }
2637
2638 /* Identify reclaim state */
2639 if (vs.field.pgscan_direct > init_pgscan_direct) {
2640 init_pgscan_direct = vs.field.pgscan_direct;
2641 init_pgscan_kswapd = vs.field.pgscan_kswapd;
2642 reclaim = DIRECT_RECLAIM;
2643 } else if (vs.field.pgscan_kswapd > init_pgscan_kswapd) {
2644 init_pgscan_kswapd = vs.field.pgscan_kswapd;
2645 reclaim = KSWAPD_RECLAIM;
Suren Baghdasaryandc60f972020-12-14 13:38:48 -08002646 } else if (workingset_refault_file == prev_workingset_refault) {
Suren Baghdasaryan11221d42021-07-14 17:57:52 -07002647 /*
2648 * Device is not thrashing and not reclaiming, bail out early until we see these stats
2649 * changing
2650 */
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002651 goto no_kill;
2652 }
2653
Suren Baghdasaryandc60f972020-12-14 13:38:48 -08002654 prev_workingset_refault = workingset_refault_file;
Martin Liu1f72f5f2020-08-21 13:18:50 +08002655
2656 /*
2657 * It's possible we fail to find an eligible process to kill (ex. no process is
2658 * above oom_adj_min). When this happens, we should retry to find a new process
2659 * for a kill whenever a new eligible process is available. This is especially
2660 * important for a slow growing refault case. While retrying, we should keep
2661 * monitoring new thrashing counter as someone could release the memory to mitigate
2662 * the thrashing. Thus, when thrashing reset window comes, we decay the prev thrashing
Suren Baghdasaryan11221d42021-07-14 17:57:52 -07002663 * counter by window counts. If the counter is still greater than thrashing limit,
Martin Liu1f72f5f2020-08-21 13:18:50 +08002664 * we preserve the current prev_thrash counter so we will retry kill again. Otherwise,
2665 * we reset the prev_thrash counter so we will stop retrying.
2666 */
2667 since_thrashing_reset_ms = get_time_diff_ms(&thrashing_reset_tm, &curr_tm);
2668 if (since_thrashing_reset_ms > THRASHING_RESET_INTERVAL_MS) {
2669 long windows_passed;
2670 /* Calculate prev_thrash_growth if we crossed THRASHING_RESET_INTERVAL_MS */
Suren Baghdasaryandc60f972020-12-14 13:38:48 -08002671 prev_thrash_growth = (workingset_refault_file - init_ws_refault) * 100
Martin Liuc3108412020-09-03 22:12:14 +08002672 / (base_file_lru + 1);
Martin Liu1f72f5f2020-08-21 13:18:50 +08002673 windows_passed = (since_thrashing_reset_ms / THRASHING_RESET_INTERVAL_MS);
2674 /*
2675 * Decay prev_thrashing unless over-the-limit thrashing was registered in the window we
2676 * just crossed, which means there were no eligible processes to kill. We preserve the
2677 * counter in that case to ensure a kill if a new eligible process appears.
2678 */
2679 if (windows_passed > 1 || prev_thrash_growth < thrashing_limit) {
2680 prev_thrash_growth >>= windows_passed;
2681 }
2682
2683 /* Record file-backed pagecache size when crossing THRASHING_RESET_INTERVAL_MS */
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002684 base_file_lru = vs.field.nr_inactive_file + vs.field.nr_active_file;
Suren Baghdasaryandc60f972020-12-14 13:38:48 -08002685 init_ws_refault = workingset_refault_file;
Martin Liu1f72f5f2020-08-21 13:18:50 +08002686 thrashing_reset_tm = curr_tm;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002687 thrashing_limit = thrashing_limit_pct;
2688 } else {
2689 /* Calculate what % of the file-backed pagecache refaulted so far */
Suren Baghdasaryandc60f972020-12-14 13:38:48 -08002690 thrashing = (workingset_refault_file - init_ws_refault) * 100 / (base_file_lru + 1);
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002691 }
Martin Liu1f72f5f2020-08-21 13:18:50 +08002692 /* Add previous cycle's decayed thrashing amount */
2693 thrashing += prev_thrash_growth;
Suren Baghdasaryane1604752021-07-22 16:21:21 -07002694 if (max_thrashing < thrashing) {
2695 max_thrashing = thrashing;
2696 }
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002697
Suren Baghdasaryan81c75b22019-08-14 09:48:35 -07002698 /*
2699 * Refresh watermarks once per min in case user updated one of the margins.
2700 * TODO: b/140521024 replace this periodic update with an API for AMS to notify LMKD
2701 * that zone watermarks were changed by the system software.
2702 */
2703 if (watermarks.high_wmark == 0 || get_time_diff_ms(&wmark_update_tm, &curr_tm) > 60000) {
2704 struct zoneinfo zi;
2705
2706 if (zoneinfo_parse(&zi) < 0) {
2707 ALOGE("Failed to parse zoneinfo!");
2708 return;
2709 }
2710
2711 calc_zone_watermarks(&zi, &watermarks);
2712 wmark_update_tm = curr_tm;
Martin Liu1f72f5f2020-08-21 13:18:50 +08002713 }
Suren Baghdasaryan81c75b22019-08-14 09:48:35 -07002714
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002715 /* Find out which watermark is breached if any */
Suren Baghdasaryan81c75b22019-08-14 09:48:35 -07002716 wmark = get_lowest_watermark(&mi, &watermarks);
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002717
Suren Baghdasaryan5ae47a92022-02-10 21:10:23 -08002718 if (!psi_parse_mem(&psi_data)) {
2719 critical_stall = psi_data.mem_stats[PSI_FULL].avg10 > (float)stall_limit_critical;
2720 }
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002721 /*
2722 * TODO: move this logic into a separate function
2723 * Decide if killing a process is necessary and record the reason
2724 */
2725 if (cycle_after_kill && wmark < WMARK_LOW) {
2726 /*
2727 * Prevent kills not freeing enough memory which might lead to OOM kill.
2728 * This might happen when a process is consuming memory faster than reclaim can
2729 * free even after a kill. Mostly happens when running memory stress tests.
2730 */
2731 kill_reason = PRESSURE_AFTER_KILL;
Suren Baghdasaryan89454e62019-07-15 15:50:17 -07002732 strncpy(kill_desc, "min watermark is breached even after kill", sizeof(kill_desc));
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002733 } else if (level == VMPRESS_LEVEL_CRITICAL && events != 0) {
2734 /*
2735 * Device is too busy reclaiming memory which might lead to ANR.
2736 * Critical level is triggered when PSI complete stall (all tasks are blocked because
2737 * of the memory congestion) breaches the configured threshold.
2738 */
2739 kill_reason = NOT_RESPONDING;
Suren Baghdasaryan89454e62019-07-15 15:50:17 -07002740 strncpy(kill_desc, "device is not responding", sizeof(kill_desc));
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002741 } else if (swap_is_low && thrashing > thrashing_limit_pct) {
2742 /* Page cache is thrashing while swap is low */
2743 kill_reason = LOW_SWAP_AND_THRASHING;
Suren Baghdasaryan89454e62019-07-15 15:50:17 -07002744 snprintf(kill_desc, sizeof(kill_desc), "device is low on swap (%" PRId64
2745 "kB < %" PRId64 "kB) and thrashing (%" PRId64 "%%)",
2746 mi.field.free_swap * page_k, swap_low_threshold * page_k, thrashing);
Suren Baghdasaryan0142b3c2021-03-03 11:11:09 -08002747 /* Do not kill perceptible apps unless below min watermark or heavily thrashing */
2748 if (wmark > WMARK_MIN && thrashing < thrashing_critical_pct) {
Suren Baghdasaryan48135c42020-05-19 12:59:18 -07002749 min_score_adj = PERCEPTIBLE_APP_ADJ + 1;
2750 }
Suren Baghdasaryan11221d42021-07-14 17:57:52 -07002751 check_filecache = true;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002752 } else if (swap_is_low && wmark < WMARK_HIGH) {
2753 /* Both free memory and swap are low */
2754 kill_reason = LOW_MEM_AND_SWAP;
Suren Baghdasaryan89454e62019-07-15 15:50:17 -07002755 snprintf(kill_desc, sizeof(kill_desc), "%s watermark is breached and swap is low (%"
Suren Baghdasaryan23678182021-03-02 18:33:09 -08002756 PRId64 "kB < %" PRId64 "kB)", wmark < WMARK_LOW ? "min" : "low",
Suren Baghdasaryan89454e62019-07-15 15:50:17 -07002757 mi.field.free_swap * page_k, swap_low_threshold * page_k);
Suren Baghdasaryan0142b3c2021-03-03 11:11:09 -08002758 /* Do not kill perceptible apps unless below min watermark or heavily thrashing */
2759 if (wmark > WMARK_MIN && thrashing < thrashing_critical_pct) {
Suren Baghdasaryan48135c42020-05-19 12:59:18 -07002760 min_score_adj = PERCEPTIBLE_APP_ADJ + 1;
2761 }
Suren Baghdasaryan51ee4c52020-04-21 12:27:01 -07002762 } else if (wmark < WMARK_HIGH && swap_util_max < 100 &&
2763 (swap_util = calc_swap_utilization(&mi)) > swap_util_max) {
2764 /*
2765 * Too much anon memory is swapped out but swap is not low.
2766 * Non-swappable allocations created memory pressure.
2767 */
2768 kill_reason = LOW_MEM_AND_SWAP_UTIL;
2769 snprintf(kill_desc, sizeof(kill_desc), "%s watermark is breached and swap utilization"
Suren Baghdasaryan23678182021-03-02 18:33:09 -08002770 " is high (%d%% > %d%%)", wmark < WMARK_LOW ? "min" : "low",
Suren Baghdasaryan51ee4c52020-04-21 12:27:01 -07002771 swap_util, swap_util_max);
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002772 } else if (wmark < WMARK_HIGH && thrashing > thrashing_limit) {
2773 /* Page cache is thrashing while memory is low */
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002774 kill_reason = LOW_MEM_AND_THRASHING;
Suren Baghdasaryan89454e62019-07-15 15:50:17 -07002775 snprintf(kill_desc, sizeof(kill_desc), "%s watermark is breached and thrashing (%"
Suren Baghdasaryan23678182021-03-02 18:33:09 -08002776 PRId64 "%%)", wmark < WMARK_LOW ? "min" : "low", thrashing);
Suren Baghdasaryan970a26a2019-09-19 15:27:21 -07002777 cut_thrashing_limit = true;
Suren Baghdasaryan0142b3c2021-03-03 11:11:09 -08002778 /* Do not kill perceptible apps unless thrashing at critical levels */
2779 if (thrashing < thrashing_critical_pct) {
2780 min_score_adj = PERCEPTIBLE_APP_ADJ + 1;
2781 }
Suren Baghdasaryan11221d42021-07-14 17:57:52 -07002782 check_filecache = true;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002783 } else if (reclaim == DIRECT_RECLAIM && thrashing > thrashing_limit) {
2784 /* Page cache is thrashing while in direct reclaim (mostly happens on lowram devices) */
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002785 kill_reason = DIRECT_RECL_AND_THRASHING;
Suren Baghdasaryan89454e62019-07-15 15:50:17 -07002786 snprintf(kill_desc, sizeof(kill_desc), "device is in direct reclaim and thrashing (%"
2787 PRId64 "%%)", thrashing);
Suren Baghdasaryan970a26a2019-09-19 15:27:21 -07002788 cut_thrashing_limit = true;
Suren Baghdasaryan0142b3c2021-03-03 11:11:09 -08002789 /* Do not kill perceptible apps unless thrashing at critical levels */
2790 if (thrashing < thrashing_critical_pct) {
2791 min_score_adj = PERCEPTIBLE_APP_ADJ + 1;
2792 }
Suren Baghdasaryan11221d42021-07-14 17:57:52 -07002793 check_filecache = true;
2794 } else if (check_filecache) {
2795 int64_t file_lru_kb = (vs.field.nr_inactive_file + vs.field.nr_active_file) * page_k;
2796
2797 if (file_lru_kb < filecache_min_kb) {
2798 /* File cache is too low after thrashing, keep killing background processes */
2799 kill_reason = LOW_FILECACHE_AFTER_THRASHING;
2800 snprintf(kill_desc, sizeof(kill_desc),
2801 "filecache is low (%" PRId64 "kB < %" PRId64 "kB) after thrashing",
2802 file_lru_kb, filecache_min_kb);
2803 min_score_adj = PERCEPTIBLE_APP_ADJ + 1;
2804 } else {
2805 /* File cache is big enough, stop checking */
2806 check_filecache = false;
2807 }
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002808 }
2809
2810 /* Kill a process if necessary */
2811 if (kill_reason != NONE) {
Suren Baghdasaryane1604752021-07-22 16:21:21 -07002812 struct kill_info ki = {
2813 .kill_reason = kill_reason,
2814 .kill_desc = kill_desc,
2815 .thrashing = (int)thrashing,
2816 .max_thrashing = max_thrashing,
2817 };
Suren Baghdasaryan5ae47a92022-02-10 21:10:23 -08002818
2819 /* Allow killing perceptible apps if the system is stalled */
2820 if (critical_stall) {
2821 min_score_adj = 0;
2822 }
Suren Baghdasaryan014dd712022-02-18 12:51:15 -08002823 psi_parse_io(&psi_data);
2824 psi_parse_cpu(&psi_data);
2825 int pages_freed = find_and_kill_process(min_score_adj, &ki, &mi, &wi, &curr_tm, &psi_data);
Suren Baghdasaryan970a26a2019-09-19 15:27:21 -07002826 if (pages_freed > 0) {
2827 killing = true;
Suren Baghdasaryane1604752021-07-22 16:21:21 -07002828 max_thrashing = 0;
Suren Baghdasaryan970a26a2019-09-19 15:27:21 -07002829 if (cut_thrashing_limit) {
2830 /*
2831 * Cut thrasing limit by thrashing_limit_decay_pct percentage of the current
2832 * thrashing limit until the system stops thrashing.
2833 */
2834 thrashing_limit = (thrashing_limit * (100 - thrashing_limit_decay_pct)) / 100;
2835 }
2836 }
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002837 }
2838
2839no_kill:
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002840 /* Do not poll if kernel supports pidfd waiting */
2841 if (is_waiting_for_kill()) {
2842 /* Pause polling if we are waiting for process death notification */
2843 poll_params->update = POLLING_PAUSE;
2844 return;
2845 }
2846
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002847 /*
2848 * Start polling after initial PSI event;
2849 * extend polling while device is in direct reclaim or process is being killed;
2850 * do not extend when kswapd reclaims because that might go on for a long time
2851 * without causing memory pressure
2852 */
2853 if (events || killing || reclaim == DIRECT_RECLAIM) {
2854 poll_params->update = POLLING_START;
2855 }
2856
2857 /* Decide the polling interval */
2858 if (swap_is_low || killing) {
2859 /* Fast polling during and after a kill or when swap is low */
2860 poll_params->polling_interval_ms = PSI_POLL_PERIOD_SHORT_MS;
2861 } else {
2862 /* By default use long intervals */
2863 poll_params->polling_interval_ms = PSI_POLL_PERIOD_LONG_MS;
2864 }
2865}
2866
Bart Van Asscheb4d26bb2022-02-17 21:31:51 +00002867static std::string GetCgroupAttributePath(const char* attr) {
2868 std::string path;
2869 if (!CgroupGetAttributePath(attr, &path)) {
2870 ALOGE("Unknown cgroup attribute %s", attr);
2871 }
2872 return path;
2873}
2874
2875// The implementation of this function relies on memcg statistics that are only available in the
2876// v1 cgroup hierarchy.
Suren Baghdasaryane12a0672019-07-15 14:50:49 -07002877static void mp_event_common(int data, uint32_t events, struct polling_params *poll_params) {
Todd Poynorc58c5142013-07-09 19:35:14 -07002878 unsigned long long evcount;
Robert Beneac72b2932017-08-21 15:18:31 -07002879 int64_t mem_usage, memsw_usage;
Robert Benea3be16142017-09-13 15:20:30 -07002880 int64_t mem_pressure;
Suren Baghdasaryane0f3dd12018-04-13 13:41:12 -07002881 union meminfo mi;
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07002882 struct zoneinfo zi;
Suren Baghdasaryan53be36e2018-09-05 15:46:32 -07002883 struct timespec curr_tm;
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -07002884 static unsigned long kill_skip_count = 0;
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08002885 enum vmpressure_level level = (enum vmpressure_level)data;
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07002886 long other_free = 0, other_file = 0;
2887 int min_score_adj;
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07002888 int minfree = 0;
Bart Van Asscheb4d26bb2022-02-17 21:31:51 +00002889 static const std::string mem_usage_path = GetCgroupAttributePath("MemUsage");
Suren Baghdasaryan87966742018-04-13 12:43:41 -07002890 static struct reread_data mem_usage_file_data = {
Bart Van Asscheb4d26bb2022-02-17 21:31:51 +00002891 .filename = mem_usage_path.c_str(),
Suren Baghdasaryan87966742018-04-13 12:43:41 -07002892 .fd = -1,
2893 };
Bart Van Asscheb4d26bb2022-02-17 21:31:51 +00002894 static const std::string memsw_usage_path = GetCgroupAttributePath("MemAndSwapUsage");
Suren Baghdasaryan87966742018-04-13 12:43:41 -07002895 static struct reread_data memsw_usage_file_data = {
Bart Van Asscheb4d26bb2022-02-17 21:31:51 +00002896 .filename = memsw_usage_path.c_str(),
Suren Baghdasaryan87966742018-04-13 12:43:41 -07002897 .fd = -1,
2898 };
Suren Baghdasaryand7b4fcb2020-07-23 18:00:43 -07002899 static struct wakeup_info wi;
Todd Poynorc58c5142013-07-09 19:35:14 -07002900
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08002901 if (debug_process_killing) {
2902 ALOGI("%s memory pressure event is triggered", level_name[level]);
2903 }
2904
2905 if (!use_psi_monitors) {
2906 /*
2907 * Check all event counters from low to critical
2908 * and upgrade to the highest priority one. By reading
2909 * eventfd we also reset the event counters.
2910 */
Tom Cherry43f3d2b2019-12-04 12:46:57 -08002911 for (int lvl = VMPRESS_LEVEL_LOW; lvl < VMPRESS_LEVEL_COUNT; lvl++) {
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08002912 if (mpevfd[lvl] != -1 &&
2913 TEMP_FAILURE_RETRY(read(mpevfd[lvl],
2914 &evcount, sizeof(evcount))) > 0 &&
2915 evcount > 0 && lvl > level) {
Tom Cherry43f3d2b2019-12-04 12:46:57 -08002916 level = static_cast<vmpressure_level>(lvl);
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08002917 }
Suren Baghdasaryan3e1a8492018-01-04 09:16:21 -08002918 }
2919 }
Todd Poynorc58c5142013-07-09 19:35:14 -07002920
Suren Baghdasaryane12a0672019-07-15 14:50:49 -07002921 /* Start polling after initial PSI event */
2922 if (use_psi_monitors && events) {
2923 /* Override polling params only if current event is more critical */
2924 if (!poll_params->poll_handler || data > poll_params->poll_handler->data) {
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002925 poll_params->polling_interval_ms = PSI_POLL_PERIOD_SHORT_MS;
Suren Baghdasaryane12a0672019-07-15 14:50:49 -07002926 poll_params->update = POLLING_START;
2927 }
2928 }
2929
Suren Baghdasaryan53be36e2018-09-05 15:46:32 -07002930 if (clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm) != 0) {
2931 ALOGE("Failed to get current time");
2932 return;
2933 }
2934
Suren Baghdasaryand7b4fcb2020-07-23 18:00:43 -07002935 record_wakeup_time(&curr_tm, events ? Event : Polling, &wi);
2936
Suren Baghdasaryaned715a32020-05-11 16:31:57 -07002937 if (kill_timeout_ms &&
2938 get_time_diff_ms(&last_kill_tm, &curr_tm) < static_cast<long>(kill_timeout_ms)) {
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002939 /*
2940 * If we're within the no-kill timeout, see if there's pending reclaim work
2941 * from the last killed process. If so, skip killing for now.
2942 */
2943 if (is_kill_pending()) {
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -07002944 kill_skip_count++;
Suren Baghdasaryand7b4fcb2020-07-23 18:00:43 -07002945 wi.skipped_wakeups++;
Suren Baghdasaryan30854e72018-01-17 17:28:01 -08002946 return;
2947 }
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002948 /*
2949 * Process is dead, stop waiting. This has no effect if pidfds are supported and
2950 * death notification already caused waiting to stop.
2951 */
2952 stop_wait_for_proc_kill(true);
2953 } else {
2954 /*
2955 * Killing took longer than no-kill timeout. Stop waiting for the last process
2956 * to die because we are ready to kill again.
2957 */
2958 stop_wait_for_proc_kill(false);
Suren Baghdasaryan30854e72018-01-17 17:28:01 -08002959 }
2960
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -07002961 if (kill_skip_count > 0) {
Suren Baghdasaryaneff82332018-05-10 16:10:56 -07002962 ALOGI("%lu memory pressure events were skipped after a kill!",
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -07002963 kill_skip_count);
2964 kill_skip_count = 0;
Suren Baghdasaryan30854e72018-01-17 17:28:01 -08002965 }
2966
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07002967 if (meminfo_parse(&mi) < 0 || zoneinfo_parse(&zi) < 0) {
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002968 ALOGE("Failed to get free memory!");
2969 return;
2970 }
2971
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07002972 if (use_minfree_levels) {
2973 int i;
2974
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07002975 other_free = mi.field.nr_free_pages - zi.totalreserve_pages;
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07002976 if (mi.field.nr_file_pages > (mi.field.shmem + mi.field.unevictable + mi.field.swap_cached)) {
2977 other_file = (mi.field.nr_file_pages - mi.field.shmem -
2978 mi.field.unevictable - mi.field.swap_cached);
2979 } else {
2980 other_file = 0;
2981 }
2982
2983 min_score_adj = OOM_SCORE_ADJ_MAX + 1;
2984 for (i = 0; i < lowmem_targets_size; i++) {
2985 minfree = lowmem_minfree[i];
2986 if (other_free < minfree && other_file < minfree) {
2987 min_score_adj = lowmem_adj[i];
2988 break;
2989 }
2990 }
2991
Suren Baghdasaryanb0bda552018-05-18 14:42:00 -07002992 if (min_score_adj == OOM_SCORE_ADJ_MAX + 1) {
liuhailongcf8af502021-12-04 16:29:52 +08002993 if (debug_process_killing && lowmem_targets_size) {
Suren Baghdasaryanb0bda552018-05-18 14:42:00 -07002994 ALOGI("Ignore %s memory pressure event "
2995 "(free memory=%ldkB, cache=%ldkB, limit=%ldkB)",
2996 level_name[level], other_free * page_k, other_file * page_k,
2997 (long)lowmem_minfree[lowmem_targets_size - 1] * page_k);
2998 }
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07002999 return;
Suren Baghdasaryanb0bda552018-05-18 14:42:00 -07003000 }
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07003001
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07003002 goto do_kill;
3003 }
3004
Suren Baghdasaryane0f3dd12018-04-13 13:41:12 -07003005 if (level == VMPRESS_LEVEL_LOW) {
3006 record_low_pressure_levels(&mi);
3007 }
3008
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08003009 if (level_oomadj[level] > OOM_SCORE_ADJ_MAX) {
3010 /* Do not monitor this pressure level */
3011 return;
3012 }
3013
Suren Baghdasaryan87966742018-04-13 12:43:41 -07003014 if ((mem_usage = get_memory_usage(&mem_usage_file_data)) < 0) {
3015 goto do_kill;
3016 }
3017 if ((memsw_usage = get_memory_usage(&memsw_usage_file_data)) < 0) {
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08003018 goto do_kill;
Robert Benea3be16142017-09-13 15:20:30 -07003019 }
Robert Beneac72b2932017-08-21 15:18:31 -07003020
Robert Benea3be16142017-09-13 15:20:30 -07003021 // Calculate percent for swappinness.
3022 mem_pressure = (mem_usage * 100) / memsw_usage;
3023
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08003024 if (enable_pressure_upgrade && level != VMPRESS_LEVEL_CRITICAL) {
Robert Benea3be16142017-09-13 15:20:30 -07003025 // We are swapping too much.
3026 if (mem_pressure < upgrade_pressure) {
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08003027 level = upgrade_level(level);
3028 if (debug_process_killing) {
3029 ALOGI("Event upgraded to %s", level_name[level]);
3030 }
Robert Beneac72b2932017-08-21 15:18:31 -07003031 }
3032 }
3033
Vic Yang65680692018-08-07 10:18:22 -07003034 // If we still have enough swap space available, check if we want to
3035 // ignore/downgrade pressure events.
3036 if (mi.field.free_swap >=
3037 mi.field.total_swap * swap_free_low_percentage / 100) {
3038 // If the pressure is larger than downgrade_pressure lmk will not
3039 // kill any process, since enough memory is available.
3040 if (mem_pressure > downgrade_pressure) {
3041 if (debug_process_killing) {
3042 ALOGI("Ignore %s memory pressure", level_name[level]);
3043 }
3044 return;
3045 } else if (level == VMPRESS_LEVEL_CRITICAL && mem_pressure > upgrade_pressure) {
3046 if (debug_process_killing) {
3047 ALOGI("Downgrade critical memory pressure");
3048 }
3049 // Downgrade event, since enough memory available.
3050 level = downgrade_level(level);
Robert Benea3be16142017-09-13 15:20:30 -07003051 }
Robert Benea3be16142017-09-13 15:20:30 -07003052 }
3053
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08003054do_kill:
Suren Baghdasaryand1d59f82018-04-13 11:45:38 -07003055 if (low_ram_device) {
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08003056 /* For Go devices kill only one task */
Suren Baghdasaryan014dd712022-02-18 12:51:15 -08003057 if (find_and_kill_process(level_oomadj[level], NULL, &mi, &wi, &curr_tm, NULL) == 0) {
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08003058 if (debug_process_killing) {
3059 ALOGI("Nothing to kill");
3060 }
3061 }
3062 } else {
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07003063 int pages_freed;
Suren Baghdasaryan53be36e2018-09-05 15:46:32 -07003064 static struct timespec last_report_tm;
3065 static unsigned long report_skip_count = 0;
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07003066
3067 if (!use_minfree_levels) {
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07003068 /* Free up enough memory to downgrate the memory pressure to low level */
Suren Baghdasaryan85c31b52018-10-26 11:32:15 -07003069 if (mi.field.nr_free_pages >= low_pressure_mem.max_nr_free_pages) {
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07003070 if (debug_process_killing) {
3071 ALOGI("Ignoring pressure since more memory is "
3072 "available (%" PRId64 ") than watermark (%" PRId64 ")",
3073 mi.field.nr_free_pages, low_pressure_mem.max_nr_free_pages);
3074 }
3075 return;
3076 }
3077 min_score_adj = level_oomadj[level];
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08003078 }
3079
Suren Baghdasaryan014dd712022-02-18 12:51:15 -08003080 pages_freed = find_and_kill_process(min_score_adj, NULL, &mi, &wi, &curr_tm, NULL);
Suren Baghdasaryaneff82332018-05-10 16:10:56 -07003081
Suren Baghdasaryan53be36e2018-09-05 15:46:32 -07003082 if (pages_freed == 0) {
3083 /* Rate limit kill reports when nothing was reclaimed */
3084 if (get_time_diff_ms(&last_report_tm, &curr_tm) < FAIL_REPORT_RLIMIT_MS) {
3085 report_skip_count++;
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -07003086 return;
3087 }
Robert Benea7f68a3f2017-08-11 16:03:20 -07003088 }
Suren Baghdasaryan53be36e2018-09-05 15:46:32 -07003089
Suren Baghdasaryan12cacae2019-09-16 12:06:30 -07003090 /* Log whenever we kill or when report rate limit allows */
Suren Baghdasaryan53be36e2018-09-05 15:46:32 -07003091 if (use_minfree_levels) {
Chris Morin74b4df92021-02-26 00:00:35 -08003092 ALOGI("Reclaimed %ldkB, cache(%ldkB) and free(%" PRId64 "kB)-reserved(%" PRId64 "kB) "
3093 "below min(%ldkB) for oom_score_adj %d",
Suren Baghdasaryan85c31b52018-10-26 11:32:15 -07003094 pages_freed * page_k,
Suren Baghdasaryan53be36e2018-09-05 15:46:32 -07003095 other_file * page_k, mi.field.nr_free_pages * page_k,
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07003096 zi.totalreserve_pages * page_k,
Suren Baghdasaryan53be36e2018-09-05 15:46:32 -07003097 minfree * page_k, min_score_adj);
3098 } else {
Chris Morin74b4df92021-02-26 00:00:35 -08003099 ALOGI("Reclaimed %ldkB at oom_score_adj %d", pages_freed * page_k, min_score_adj);
Suren Baghdasaryan53be36e2018-09-05 15:46:32 -07003100 }
3101
3102 if (report_skip_count > 0) {
3103 ALOGI("Suppressed %lu failed kill reports", report_skip_count);
3104 report_skip_count = 0;
3105 }
3106
3107 last_report_tm = curr_tm;
Colin Cross01db2712014-07-11 17:16:56 -07003108 }
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003109 if (is_waiting_for_kill()) {
3110 /* pause polling if we are waiting for process death notification */
3111 poll_params->update = POLLING_PAUSE;
3112 }
Todd Poynorc58c5142013-07-09 19:35:14 -07003113}
3114
Suren Baghdasaryan2f88e152019-07-15 15:42:09 -07003115static bool init_mp_psi(enum vmpressure_level level, bool use_new_strategy) {
3116 int fd;
3117
3118 /* Do not register a handler if threshold_ms is not set */
3119 if (!psi_thresholds[level].threshold_ms) {
3120 return true;
3121 }
3122
3123 fd = init_psi_monitor(psi_thresholds[level].stall_type,
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08003124 psi_thresholds[level].threshold_ms * US_PER_MS,
3125 PSI_WINDOW_SIZE_MS * US_PER_MS);
3126
3127 if (fd < 0) {
3128 return false;
3129 }
3130
Suren Baghdasaryan2f88e152019-07-15 15:42:09 -07003131 vmpressure_hinfo[level].handler = use_new_strategy ? mp_event_psi : mp_event_common;
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08003132 vmpressure_hinfo[level].data = level;
3133 if (register_psi_monitor(epollfd, fd, &vmpressure_hinfo[level]) < 0) {
3134 destroy_psi_monitor(fd);
3135 return false;
3136 }
3137 maxevents++;
3138 mpevfd[level] = fd;
3139
3140 return true;
3141}
3142
3143static void destroy_mp_psi(enum vmpressure_level level) {
3144 int fd = mpevfd[level];
3145
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07003146 if (fd < 0) {
3147 return;
3148 }
3149
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08003150 if (unregister_psi_monitor(epollfd, fd) < 0) {
3151 ALOGE("Failed to unregister psi monitor for %s memory pressure; errno=%d",
3152 level_name[level], errno);
3153 }
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07003154 maxevents--;
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08003155 destroy_psi_monitor(fd);
3156 mpevfd[level] = -1;
3157}
3158
Bart Van Assche75994362022-02-15 23:45:04 +00003159enum class MemcgVersion {
3160 kNotFound,
3161 kV1,
3162 kV2,
3163};
3164
3165static MemcgVersion __memcg_version() {
3166 std::string cgroupv2_path, memcg_path;
3167
3168 if (!CgroupGetControllerPath("memory", &memcg_path)) {
3169 return MemcgVersion::kNotFound;
3170 }
3171 return CgroupGetControllerPath(CGROUPV2_CONTROLLER_NAME, &cgroupv2_path) &&
3172 cgroupv2_path == memcg_path
3173 ? MemcgVersion::kV2
3174 : MemcgVersion::kV1;
3175}
3176
3177static MemcgVersion memcg_version() {
3178 static MemcgVersion version = __memcg_version();
3179
3180 return version;
3181}
3182
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08003183static bool init_psi_monitors() {
Suren Baghdasaryan2f88e152019-07-15 15:42:09 -07003184 /*
3185 * When PSI is used on low-ram devices or on high-end devices without memfree levels
Bart Van Assche75994362022-02-15 23:45:04 +00003186 * use new kill strategy based on zone watermarks, free swap and thrashing stats.
3187 * Also use the new strategy if memcg has not been mounted in the v1 cgroups hiearchy since
3188 * the old strategy relies on memcg attributes that are available only in the v1 cgroups
3189 * hiearchy.
Suren Baghdasaryan2f88e152019-07-15 15:42:09 -07003190 */
3191 bool use_new_strategy =
Suren Baghdasaryand0a80042021-08-03 15:40:23 -07003192 GET_LMK_PROPERTY(bool, "use_new_strategy", low_ram_device || !use_minfree_levels);
Bart Van Assche75994362022-02-15 23:45:04 +00003193 if (!use_new_strategy && memcg_version() != MemcgVersion::kV1) {
3194 ALOGE("Old kill strategy can only be used with v1 cgroup hierarchy");
3195 return false;
3196 }
Suren Baghdasaryan2f88e152019-07-15 15:42:09 -07003197 /* In default PSI mode override stall amounts using system properties */
3198 if (use_new_strategy) {
3199 /* Do not use low pressure level */
3200 psi_thresholds[VMPRESS_LEVEL_LOW].threshold_ms = 0;
3201 psi_thresholds[VMPRESS_LEVEL_MEDIUM].threshold_ms = psi_partial_stall_ms;
3202 psi_thresholds[VMPRESS_LEVEL_CRITICAL].threshold_ms = psi_complete_stall_ms;
3203 }
3204
3205 if (!init_mp_psi(VMPRESS_LEVEL_LOW, use_new_strategy)) {
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08003206 return false;
3207 }
Suren Baghdasaryan2f88e152019-07-15 15:42:09 -07003208 if (!init_mp_psi(VMPRESS_LEVEL_MEDIUM, use_new_strategy)) {
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08003209 destroy_mp_psi(VMPRESS_LEVEL_LOW);
3210 return false;
3211 }
Suren Baghdasaryan2f88e152019-07-15 15:42:09 -07003212 if (!init_mp_psi(VMPRESS_LEVEL_CRITICAL, use_new_strategy)) {
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08003213 destroy_mp_psi(VMPRESS_LEVEL_MEDIUM);
3214 destroy_mp_psi(VMPRESS_LEVEL_LOW);
3215 return false;
3216 }
3217 return true;
3218}
3219
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003220static bool init_mp_common(enum vmpressure_level level) {
Bart Van Assche75994362022-02-15 23:45:04 +00003221 // The implementation of this function relies on memcg statistics that are only available in the
3222 // v1 cgroup hierarchy.
3223 if (memcg_version() != MemcgVersion::kV1) {
3224 ALOGE("%s: global monitoring is only available for the v1 cgroup hierarchy", __func__);
3225 return false;
3226 }
3227
Todd Poynorc58c5142013-07-09 19:35:14 -07003228 int mpfd;
3229 int evfd;
3230 int evctlfd;
3231 char buf[256];
3232 struct epoll_event epev;
3233 int ret;
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003234 int level_idx = (int)level;
3235 const char *levelstr = level_name[level_idx];
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08003236
Mark Salyzyna00ccd82018-04-09 09:50:32 -07003237 /* gid containing AID_SYSTEM required */
Bart Van Asscheb4d26bb2022-02-17 21:31:51 +00003238 mpfd = open(GetCgroupAttributePath("MemPressureLevel").c_str(), O_RDONLY | O_CLOEXEC);
Todd Poynorc58c5142013-07-09 19:35:14 -07003239 if (mpfd < 0) {
3240 ALOGI("No kernel memory.pressure_level support (errno=%d)", errno);
3241 goto err_open_mpfd;
3242 }
3243
Bart Van Asscheb4d26bb2022-02-17 21:31:51 +00003244 evctlfd = open(GetCgroupAttributePath("CgroupEventControl").c_str(), O_WRONLY | O_CLOEXEC);
Todd Poynorc58c5142013-07-09 19:35:14 -07003245 if (evctlfd < 0) {
3246 ALOGI("No kernel memory cgroup event control (errno=%d)", errno);
3247 goto err_open_evctlfd;
3248 }
3249
Nick Kralevich148d8dd2015-12-18 20:52:37 -08003250 evfd = eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC);
Todd Poynorc58c5142013-07-09 19:35:14 -07003251 if (evfd < 0) {
3252 ALOGE("eventfd failed for level %s; errno=%d", levelstr, errno);
3253 goto err_eventfd;
3254 }
3255
3256 ret = snprintf(buf, sizeof(buf), "%d %d %s", evfd, mpfd, levelstr);
3257 if (ret >= (ssize_t)sizeof(buf)) {
3258 ALOGE("cgroup.event_control line overflow for level %s", levelstr);
3259 goto err;
3260 }
3261
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003262 ret = TEMP_FAILURE_RETRY(write(evctlfd, buf, strlen(buf) + 1));
Todd Poynorc58c5142013-07-09 19:35:14 -07003263 if (ret == -1) {
3264 ALOGE("cgroup.event_control write failed for level %s; errno=%d",
3265 levelstr, errno);
3266 goto err;
3267 }
3268
3269 epev.events = EPOLLIN;
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003270 /* use data to store event level */
3271 vmpressure_hinfo[level_idx].data = level_idx;
3272 vmpressure_hinfo[level_idx].handler = mp_event_common;
3273 epev.data.ptr = (void *)&vmpressure_hinfo[level_idx];
Todd Poynorc58c5142013-07-09 19:35:14 -07003274 ret = epoll_ctl(epollfd, EPOLL_CTL_ADD, evfd, &epev);
3275 if (ret == -1) {
3276 ALOGE("epoll_ctl for level %s failed; errno=%d", levelstr, errno);
3277 goto err;
3278 }
3279 maxevents++;
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08003280 mpevfd[level] = evfd;
Suren Baghdasaryanceffaf22018-01-04 08:54:53 -08003281 close(evctlfd);
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08003282 return true;
Todd Poynorc58c5142013-07-09 19:35:14 -07003283
3284err:
3285 close(evfd);
3286err_eventfd:
3287 close(evctlfd);
3288err_open_evctlfd:
3289 close(mpfd);
3290err_open_mpfd:
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08003291 return false;
Robert Benea58d6a132017-06-01 16:32:31 -07003292}
3293
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07003294static void destroy_mp_common(enum vmpressure_level level) {
3295 struct epoll_event epev;
3296 int fd = mpevfd[level];
3297
3298 if (fd < 0) {
3299 return;
3300 }
3301
3302 if (epoll_ctl(epollfd, EPOLL_CTL_DEL, fd, &epev)) {
3303 // Log an error and keep going
3304 ALOGE("epoll_ctl for level %s failed; errno=%d", level_name[level], errno);
3305 }
3306 maxevents--;
3307 close(fd);
3308 mpevfd[level] = -1;
3309}
3310
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07003311static void kernel_event_handler(int data __unused, uint32_t events __unused,
3312 struct polling_params *poll_params __unused) {
Jing Ji5c480962019-12-04 09:22:05 -08003313 poll_kernel(kpoll_fd);
Jim Blackler700b7192019-04-26 11:18:29 +01003314}
3315
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07003316static bool init_monitors() {
3317 /* Try to use psi monitor first if kernel has it */
Suren Baghdasaryand0a80042021-08-03 15:40:23 -07003318 use_psi_monitors = GET_LMK_PROPERTY(bool, "use_psi", true) &&
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07003319 init_psi_monitors();
3320 /* Fall back to vmpressure */
3321 if (!use_psi_monitors &&
3322 (!init_mp_common(VMPRESS_LEVEL_LOW) ||
3323 !init_mp_common(VMPRESS_LEVEL_MEDIUM) ||
3324 !init_mp_common(VMPRESS_LEVEL_CRITICAL))) {
3325 ALOGE("Kernel does not support memory pressure events or in-kernel low memory killer");
3326 return false;
3327 }
3328 if (use_psi_monitors) {
3329 ALOGI("Using psi monitors for memory pressure detection");
3330 } else {
3331 ALOGI("Using vmpressure for memory pressure detection");
3332 }
3333 return true;
3334}
3335
3336static void destroy_monitors() {
3337 if (use_psi_monitors) {
3338 destroy_mp_psi(VMPRESS_LEVEL_CRITICAL);
3339 destroy_mp_psi(VMPRESS_LEVEL_MEDIUM);
3340 destroy_mp_psi(VMPRESS_LEVEL_LOW);
3341 } else {
3342 destroy_mp_common(VMPRESS_LEVEL_CRITICAL);
3343 destroy_mp_common(VMPRESS_LEVEL_MEDIUM);
3344 destroy_mp_common(VMPRESS_LEVEL_LOW);
3345 }
3346}
3347
Suren Baghdasaryan7c3addb2021-06-11 12:12:56 -07003348static void drop_reaper_comm() {
3349 close(reaper_comm_fd[0]);
3350 close(reaper_comm_fd[1]);
3351}
3352
3353static bool setup_reaper_comm() {
3354 if (pipe(reaper_comm_fd)) {
3355 ALOGE("pipe failed: %s", strerror(errno));
3356 return false;
3357 }
3358
3359 // Ensure main thread never blocks on read
3360 int flags = fcntl(reaper_comm_fd[0], F_GETFL);
3361 if (fcntl(reaper_comm_fd[0], F_SETFL, flags | O_NONBLOCK)) {
3362 ALOGE("fcntl failed: %s", strerror(errno));
3363 drop_reaper_comm();
3364 return false;
3365 }
3366
3367 return true;
3368}
3369
3370static bool init_reaper() {
3371 if (!reaper.is_reaping_supported()) {
3372 ALOGI("Process reaping is not supported");
3373 return false;
3374 }
3375
3376 if (!setup_reaper_comm()) {
3377 ALOGE("Failed to create thread communication channel");
3378 return false;
3379 }
3380
3381 // Setup epoll handler
3382 struct epoll_event epev;
3383 static struct event_handler_info kill_failed_hinfo = { 0, kill_fail_handler };
3384 epev.events = EPOLLIN;
3385 epev.data.ptr = (void *)&kill_failed_hinfo;
3386 if (epoll_ctl(epollfd, EPOLL_CTL_ADD, reaper_comm_fd[0], &epev)) {
3387 ALOGE("epoll_ctl failed: %s", strerror(errno));
3388 drop_reaper_comm();
3389 return false;
3390 }
3391
3392 if (!reaper.init(reaper_comm_fd[1])) {
3393 ALOGE("Failed to initialize reaper object");
3394 if (epoll_ctl(epollfd, EPOLL_CTL_DEL, reaper_comm_fd[0], &epev)) {
3395 ALOGE("epoll_ctl failed: %s", strerror(errno));
3396 }
3397 drop_reaper_comm();
3398 return false;
3399 }
3400 maxevents++;
3401
3402 return true;
3403}
3404
Todd Poynorc58c5142013-07-09 19:35:14 -07003405static int init(void) {
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07003406 static struct event_handler_info kernel_poll_hinfo = { 0, kernel_event_handler };
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -07003407 struct reread_data file_data = {
3408 .filename = ZONEINFO_PATH,
3409 .fd = -1,
3410 };
Todd Poynorc58c5142013-07-09 19:35:14 -07003411 struct epoll_event epev;
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003412 int pidfd;
Todd Poynorc58c5142013-07-09 19:35:14 -07003413 int i;
3414 int ret;
3415
3416 page_k = sysconf(_SC_PAGESIZE);
3417 if (page_k == -1)
3418 page_k = PAGE_SIZE;
3419 page_k /= 1024;
3420
3421 epollfd = epoll_create(MAX_EPOLL_EVENTS);
3422 if (epollfd == -1) {
3423 ALOGE("epoll_create failed (errno=%d)", errno);
3424 return -1;
3425 }
3426
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003427 // mark data connections as not connected
3428 for (int i = 0; i < MAX_DATA_CONN; i++) {
3429 data_sock[i].sock = -1;
3430 }
3431
3432 ctrl_sock.sock = android_get_control_socket("lmkd");
3433 if (ctrl_sock.sock < 0) {
Todd Poynorc58c5142013-07-09 19:35:14 -07003434 ALOGE("get lmkd control socket failed");
3435 return -1;
3436 }
3437
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003438 ret = listen(ctrl_sock.sock, MAX_DATA_CONN);
Todd Poynorc58c5142013-07-09 19:35:14 -07003439 if (ret < 0) {
3440 ALOGE("lmkd control socket listen failed (errno=%d)", errno);
3441 return -1;
3442 }
3443
3444 epev.events = EPOLLIN;
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003445 ctrl_sock.handler_info.handler = ctrl_connect_handler;
3446 epev.data.ptr = (void *)&(ctrl_sock.handler_info);
3447 if (epoll_ctl(epollfd, EPOLL_CTL_ADD, ctrl_sock.sock, &epev) == -1) {
Todd Poynorc58c5142013-07-09 19:35:14 -07003448 ALOGE("epoll_ctl for lmkd control socket failed (errno=%d)", errno);
3449 return -1;
3450 }
3451 maxevents++;
3452
Robert Benea7878c9b2017-09-11 16:53:28 -07003453 has_inkernel_module = !access(INKERNEL_MINFREE_PATH, W_OK);
Suren Baghdasaryane6613ea2018-01-18 17:27:30 -08003454 use_inkernel_interface = has_inkernel_module;
Todd Poynorc58c5142013-07-09 19:35:14 -07003455
3456 if (use_inkernel_interface) {
3457 ALOGI("Using in-kernel low memory killer interface");
Jing Ji5c480962019-12-04 09:22:05 -08003458 if (init_poll_kernel()) {
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07003459 epev.events = EPOLLIN;
3460 epev.data.ptr = (void*)&kernel_poll_hinfo;
Jing Ji5c480962019-12-04 09:22:05 -08003461 if (epoll_ctl(epollfd, EPOLL_CTL_ADD, kpoll_fd, &epev) != 0) {
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07003462 ALOGE("epoll_ctl for lmk events failed (errno=%d)", errno);
Jing Ji5c480962019-12-04 09:22:05 -08003463 close(kpoll_fd);
3464 kpoll_fd = -1;
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07003465 } else {
3466 maxevents++;
Jing Ji5c480962019-12-04 09:22:05 -08003467 /* let the others know it does support reporting kills */
3468 property_set("sys.lmk.reportkills", "1");
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07003469 }
Jim Blackler700b7192019-04-26 11:18:29 +01003470 }
Todd Poynorc58c5142013-07-09 19:35:14 -07003471 } else {
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07003472 if (!init_monitors()) {
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08003473 return -1;
3474 }
Jing Ji5c480962019-12-04 09:22:05 -08003475 /* let the others know it does support reporting kills */
3476 property_set("sys.lmk.reportkills", "1");
Todd Poynorc58c5142013-07-09 19:35:14 -07003477 }
3478
Chong Zhang1cd12b52015-10-14 16:19:53 -07003479 for (i = 0; i <= ADJTOSLOT(OOM_SCORE_ADJ_MAX); i++) {
Todd Poynorc58c5142013-07-09 19:35:14 -07003480 procadjslot_list[i].next = &procadjslot_list[i];
3481 procadjslot_list[i].prev = &procadjslot_list[i];
3482 }
3483
Suren Baghdasaryana7394ea2018-10-12 11:07:40 -07003484 memset(killcnt_idx, KILLCNT_INVALID_IDX, sizeof(killcnt_idx));
3485
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -07003486 /*
3487 * Read zoneinfo as the biggest file we read to create and size the initial
3488 * read buffer and avoid memory re-allocations during memory pressure
3489 */
3490 if (reread_file(&file_data) == NULL) {
3491 ALOGE("Failed to read %s: %s", file_data.filename, strerror(errno));
3492 }
3493
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003494 /* check if kernel supports pidfd_open syscall */
Josh Gao84623be2021-03-18 17:16:08 -07003495 pidfd = TEMP_FAILURE_RETRY(pidfd_open(getpid(), 0));
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003496 if (pidfd < 0) {
3497 pidfd_supported = (errno != ENOSYS);
3498 } else {
3499 pidfd_supported = true;
3500 close(pidfd);
3501 }
3502 ALOGI("Process polling is %s", pidfd_supported ? "supported" : "not supported" );
3503
Todd Poynorc58c5142013-07-09 19:35:14 -07003504 return 0;
3505}
3506
Suren Baghdasaryan03dccf32020-04-28 16:02:13 -07003507static bool polling_paused(struct polling_params *poll_params) {
3508 return poll_params->paused_handler != NULL;
3509}
3510
3511static void resume_polling(struct polling_params *poll_params, struct timespec curr_tm) {
3512 poll_params->poll_start_tm = curr_tm;
3513 poll_params->poll_handler = poll_params->paused_handler;
Martin Liu589b5752020-09-02 23:15:18 +08003514 poll_params->polling_interval_ms = PSI_POLL_PERIOD_SHORT_MS;
3515 poll_params->paused_handler = NULL;
Suren Baghdasaryan03dccf32020-04-28 16:02:13 -07003516}
3517
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003518static void call_handler(struct event_handler_info* handler_info,
3519 struct polling_params *poll_params, uint32_t events) {
3520 struct timespec curr_tm;
3521
Suren Baghdasaryanaf1b0e02021-11-16 11:50:29 -08003522 watchdog.start();
Suren Baghdasaryan9ca53342020-04-24 16:54:55 -07003523 poll_params->update = POLLING_DO_NOT_CHANGE;
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003524 handler_info->handler(handler_info->data, events, poll_params);
3525 clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm);
Suren Baghdasaryan9ca53342020-04-24 16:54:55 -07003526 if (poll_params->poll_handler == handler_info) {
3527 poll_params->last_poll_tm = curr_tm;
3528 }
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003529
3530 switch (poll_params->update) {
3531 case POLLING_START:
3532 /*
3533 * Poll for the duration of PSI_WINDOW_SIZE_MS after the
3534 * initial PSI event because psi events are rate-limited
3535 * at one per sec.
3536 */
3537 poll_params->poll_start_tm = curr_tm;
Greg Kaiser5e80ed52019-10-10 06:52:23 -07003538 poll_params->poll_handler = handler_info;
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003539 break;
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003540 case POLLING_PAUSE:
3541 poll_params->paused_handler = handler_info;
3542 poll_params->poll_handler = NULL;
3543 break;
3544 case POLLING_RESUME:
Suren Baghdasaryan03dccf32020-04-28 16:02:13 -07003545 resume_polling(poll_params, curr_tm);
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003546 break;
3547 case POLLING_DO_NOT_CHANGE:
3548 if (get_time_diff_ms(&poll_params->poll_start_tm, &curr_tm) > PSI_WINDOW_SIZE_MS) {
3549 /* Polled for the duration of PSI window, time to stop */
3550 poll_params->poll_handler = NULL;
3551 }
Suren Baghdasaryan9ca53342020-04-24 16:54:55 -07003552 break;
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003553 }
Suren Baghdasaryanaf1b0e02021-11-16 11:50:29 -08003554 watchdog.stop();
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003555}
3556
Todd Poynorc58c5142013-07-09 19:35:14 -07003557static void mainloop(void) {
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003558 struct event_handler_info* handler_info;
Suren Baghdasaryane12a0672019-07-15 14:50:49 -07003559 struct polling_params poll_params;
3560 struct timespec curr_tm;
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003561 struct epoll_event *evt;
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08003562 long delay = -1;
Suren Baghdasaryane12a0672019-07-15 14:50:49 -07003563
3564 poll_params.poll_handler = NULL;
Suren Baghdasaryan9ca53342020-04-24 16:54:55 -07003565 poll_params.paused_handler = NULL;
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003566
Todd Poynorc58c5142013-07-09 19:35:14 -07003567 while (1) {
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07003568 struct epoll_event events[MAX_EPOLL_EVENTS];
Todd Poynorc58c5142013-07-09 19:35:14 -07003569 int nevents;
3570 int i;
3571
Suren Baghdasaryane12a0672019-07-15 14:50:49 -07003572 if (poll_params.poll_handler) {
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003573 bool poll_now;
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08003574
3575 clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm);
Martin Liu589b5752020-09-02 23:15:18 +08003576 if (poll_params.update == POLLING_RESUME) {
3577 /* Just transitioned into POLLING_RESUME, poll immediately. */
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003578 poll_now = true;
3579 nevents = 0;
3580 } else {
3581 /* Calculate next timeout */
3582 delay = get_time_diff_ms(&poll_params.last_poll_tm, &curr_tm);
3583 delay = (delay < poll_params.polling_interval_ms) ?
3584 poll_params.polling_interval_ms - delay : poll_params.polling_interval_ms;
Suren Baghdasaryane12a0672019-07-15 14:50:49 -07003585
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003586 /* Wait for events until the next polling timeout */
3587 nevents = epoll_wait(epollfd, events, maxevents, delay);
3588
3589 /* Update current time after wait */
3590 clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm);
3591 poll_now = (get_time_diff_ms(&poll_params.last_poll_tm, &curr_tm) >=
3592 poll_params.polling_interval_ms);
3593 }
3594 if (poll_now) {
3595 call_handler(poll_params.poll_handler, &poll_params, 0);
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08003596 }
3597 } else {
Suren Baghdasaryan03dccf32020-04-28 16:02:13 -07003598 if (kill_timeout_ms && is_waiting_for_kill()) {
3599 clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm);
3600 delay = kill_timeout_ms - get_time_diff_ms(&last_kill_tm, &curr_tm);
3601 /* Wait for pidfds notification or kill timeout to expire */
3602 nevents = (delay > 0) ? epoll_wait(epollfd, events, maxevents, delay) : 0;
3603 if (nevents == 0) {
3604 /* Kill notification timed out */
3605 stop_wait_for_proc_kill(false);
3606 if (polling_paused(&poll_params)) {
3607 clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm);
Martin Liu589b5752020-09-02 23:15:18 +08003608 poll_params.update = POLLING_RESUME;
Suren Baghdasaryan03dccf32020-04-28 16:02:13 -07003609 resume_polling(&poll_params, curr_tm);
3610 }
3611 }
3612 } else {
3613 /* Wait for events with no timeout */
3614 nevents = epoll_wait(epollfd, events, maxevents, -1);
3615 }
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08003616 }
Todd Poynorc58c5142013-07-09 19:35:14 -07003617
3618 if (nevents == -1) {
3619 if (errno == EINTR)
3620 continue;
3621 ALOGE("epoll_wait failed (errno=%d)", errno);
3622 continue;
3623 }
3624
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003625 /*
3626 * First pass to see if any data socket connections were dropped.
3627 * Dropped connection should be handled before any other events
3628 * to deallocate data connection and correctly handle cases when
3629 * connection gets dropped and reestablished in the same epoll cycle.
3630 * In such cases it's essential to handle connection closures first.
3631 */
3632 for (i = 0, evt = &events[0]; i < nevents; ++i, evt++) {
3633 if ((evt->events & EPOLLHUP) && evt->data.ptr) {
3634 ALOGI("lmkd data connection dropped");
3635 handler_info = (struct event_handler_info*)evt->data.ptr;
Suren Baghdasaryanaf1b0e02021-11-16 11:50:29 -08003636 watchdog.start();
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003637 ctrl_data_close(handler_info->data);
Suren Baghdasaryanaf1b0e02021-11-16 11:50:29 -08003638 watchdog.stop();
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003639 }
3640 }
3641
3642 /* Second pass to handle all other events */
3643 for (i = 0, evt = &events[0]; i < nevents; ++i, evt++) {
Suren Baghdasaryane12a0672019-07-15 14:50:49 -07003644 if (evt->events & EPOLLERR) {
Todd Poynorc58c5142013-07-09 19:35:14 -07003645 ALOGD("EPOLLERR on event #%d", i);
Suren Baghdasaryane12a0672019-07-15 14:50:49 -07003646 }
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003647 if (evt->events & EPOLLHUP) {
3648 /* This case was handled in the first pass */
3649 continue;
3650 }
3651 if (evt->data.ptr) {
3652 handler_info = (struct event_handler_info*)evt->data.ptr;
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003653 call_handler(handler_info, &poll_params, evt->events);
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003654 }
Todd Poynorc58c5142013-07-09 19:35:14 -07003655 }
3656 }
3657}
3658
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07003659int issue_reinit() {
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07003660 int sock;
Colin Crossd5b510e2014-07-14 14:31:15 -07003661
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07003662 sock = lmkd_connect();
3663 if (sock < 0) {
3664 ALOGE("failed to connect to lmkd: %s", strerror(errno));
3665 return -1;
3666 }
3667
3668 enum update_props_result res = lmkd_update_props(sock);
3669 switch (res) {
3670 case UPDATE_PROPS_SUCCESS:
3671 ALOGI("lmkd updated properties successfully");
3672 break;
3673 case UPDATE_PROPS_SEND_ERR:
3674 ALOGE("failed to send lmkd request: %s", strerror(errno));
3675 break;
3676 case UPDATE_PROPS_RECV_ERR:
3677 ALOGE("failed to receive lmkd reply: %s", strerror(errno));
3678 break;
3679 case UPDATE_PROPS_FORMAT_ERR:
3680 ALOGE("lmkd reply is invalid");
3681 break;
3682 case UPDATE_PROPS_FAIL:
3683 ALOGE("lmkd failed to update its properties");
3684 break;
3685 }
3686
3687 close(sock);
3688 return res == UPDATE_PROPS_SUCCESS ? 0 : -1;
3689}
3690
3691static void update_props() {
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08003692 /* By default disable low level vmpressure events */
3693 level_oomadj[VMPRESS_LEVEL_LOW] =
Suren Baghdasaryand0a80042021-08-03 15:40:23 -07003694 GET_LMK_PROPERTY(int32, "low", OOM_SCORE_ADJ_MAX + 1);
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08003695 level_oomadj[VMPRESS_LEVEL_MEDIUM] =
Suren Baghdasaryand0a80042021-08-03 15:40:23 -07003696 GET_LMK_PROPERTY(int32, "medium", 800);
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08003697 level_oomadj[VMPRESS_LEVEL_CRITICAL] =
Suren Baghdasaryand0a80042021-08-03 15:40:23 -07003698 GET_LMK_PROPERTY(int32, "critical", 0);
3699 debug_process_killing = GET_LMK_PROPERTY(bool, "debug", false);
Suren Baghdasaryan3faa3032017-12-08 13:08:41 -08003700
3701 /* By default disable upgrade/downgrade logic */
3702 enable_pressure_upgrade =
Suren Baghdasaryand0a80042021-08-03 15:40:23 -07003703 GET_LMK_PROPERTY(bool, "critical_upgrade", false);
Suren Baghdasaryan3faa3032017-12-08 13:08:41 -08003704 upgrade_pressure =
Suren Baghdasaryand0a80042021-08-03 15:40:23 -07003705 (int64_t)GET_LMK_PROPERTY(int32, "upgrade_pressure", 100);
Suren Baghdasaryan3faa3032017-12-08 13:08:41 -08003706 downgrade_pressure =
Suren Baghdasaryand0a80042021-08-03 15:40:23 -07003707 (int64_t)GET_LMK_PROPERTY(int32, "downgrade_pressure", 100);
Suren Baghdasaryaneb7c5492017-12-08 13:17:06 -08003708 kill_heaviest_task =
Suren Baghdasaryand0a80042021-08-03 15:40:23 -07003709 GET_LMK_PROPERTY(bool, "kill_heaviest_task", false);
Suren Baghdasaryand1d59f82018-04-13 11:45:38 -07003710 low_ram_device = property_get_bool("ro.config.low_ram", false);
Suren Baghdasaryan30854e72018-01-17 17:28:01 -08003711 kill_timeout_ms =
Suren Baghdasaryand0a80042021-08-03 15:40:23 -07003712 (unsigned long)GET_LMK_PROPERTY(int32, "kill_timeout_ms", 100);
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07003713 use_minfree_levels =
Suren Baghdasaryand0a80042021-08-03 15:40:23 -07003714 GET_LMK_PROPERTY(bool, "use_minfree_levels", false);
Suren Baghdasaryan8389fdb2018-06-19 18:38:12 -07003715 per_app_memcg =
3716 property_get_bool("ro.config.per_app_memcg", low_ram_device);
Suren Baghdasaryand0a80042021-08-03 15:40:23 -07003717 swap_free_low_percentage = clamp(0, 100, GET_LMK_PROPERTY(int32, "swap_free_low_percentage",
Suren Baghdasaryanfb1f5922020-05-19 13:07:23 -07003718 DEF_LOW_SWAP));
Suren Baghdasaryand0a80042021-08-03 15:40:23 -07003719 psi_partial_stall_ms = GET_LMK_PROPERTY(int32, "psi_partial_stall_ms",
Suren Baghdasaryan2f88e152019-07-15 15:42:09 -07003720 low_ram_device ? DEF_PARTIAL_STALL_LOWRAM : DEF_PARTIAL_STALL);
Suren Baghdasaryand0a80042021-08-03 15:40:23 -07003721 psi_complete_stall_ms = GET_LMK_PROPERTY(int32, "psi_complete_stall_ms",
Suren Baghdasaryan2f88e152019-07-15 15:42:09 -07003722 DEF_COMPLETE_STALL);
Bart Van Assche80a3dba2022-02-02 23:51:35 +00003723 thrashing_limit_pct =
3724 std::max(0, GET_LMK_PROPERTY(int32, "thrashing_limit",
3725 low_ram_device ? DEF_THRASHING_LOWRAM : DEF_THRASHING));
Suren Baghdasaryand0a80042021-08-03 15:40:23 -07003726 thrashing_limit_decay_pct = clamp(0, 100, GET_LMK_PROPERTY(int32, "thrashing_limit_decay",
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07003727 low_ram_device ? DEF_THRASHING_DECAY_LOWRAM : DEF_THRASHING_DECAY));
Bart Van Assche80a3dba2022-02-02 23:51:35 +00003728 thrashing_critical_pct = std::max(
3729 0, GET_LMK_PROPERTY(int32, "thrashing_limit_critical", thrashing_limit_pct * 2));
Suren Baghdasaryand0a80042021-08-03 15:40:23 -07003730 swap_util_max = clamp(0, 100, GET_LMK_PROPERTY(int32, "swap_util_max", 100));
3731 filecache_min_kb = GET_LMK_PROPERTY(int64, "filecache_min_kb", 0);
Suren Baghdasaryan5ae47a92022-02-10 21:10:23 -08003732 stall_limit_critical = GET_LMK_PROPERTY(int64, "stall_limit_critical", 100);
Suren Baghdasaryan7c3addb2021-06-11 12:12:56 -07003733
3734 reaper.enable_debug(debug_process_killing);
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07003735}
3736
3737int main(int argc, char **argv) {
3738 if ((argc > 1) && argv[1] && !strcmp(argv[1], "--reinit")) {
Suren Baghdasaryan0e64ead2021-09-01 00:49:51 -07003739 if (property_set(LMKD_REINIT_PROP, "")) {
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07003740 ALOGE("Failed to reset " LMKD_REINIT_PROP " property");
3741 }
3742 return issue_reinit();
3743 }
3744
3745 update_props();
Robert Benea57397dc2017-07-31 17:15:20 -07003746
Suren Baghdasaryan12cacae2019-09-16 12:06:30 -07003747 ctx = create_android_logger(KILLINFO_LOG_TAG);
Suren Baghdasaryan08bfa982018-07-26 16:34:27 -07003748
Mark Salyzyn5cc80b32018-03-21 12:24:58 -07003749 if (!init()) {
3750 if (!use_inkernel_interface) {
3751 /*
3752 * MCL_ONFAULT pins pages as they fault instead of loading
3753 * everything immediately all at once. (Which would be bad,
3754 * because as of this writing, we have a lot of mapped pages we
3755 * never use.) Old kernels will see MCL_ONFAULT and fail with
3756 * EINVAL; we ignore this failure.
3757 *
3758 * N.B. read the man page for mlockall. MCL_CURRENT | MCL_ONFAULT
3759 * pins ⊆ MCL_CURRENT, converging to just MCL_CURRENT as we fault
3760 * in pages.
3761 */
Mark Salyzyna00ccd82018-04-09 09:50:32 -07003762 /* CAP_IPC_LOCK required */
Mark Salyzyn5cc80b32018-03-21 12:24:58 -07003763 if (mlockall(MCL_CURRENT | MCL_FUTURE | MCL_ONFAULT) && (errno != EINVAL)) {
3764 ALOGW("mlockall failed %s", strerror(errno));
3765 }
Daniel Colascione46648332018-01-03 12:01:02 -08003766
Mark Salyzyna00ccd82018-04-09 09:50:32 -07003767 /* CAP_NICE required */
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07003768 struct sched_param param = {
3769 .sched_priority = 1,
3770 };
Mark Salyzyna00ccd82018-04-09 09:50:32 -07003771 if (sched_setscheduler(0, SCHED_FIFO, &param)) {
3772 ALOGW("set SCHED_FIFO failed %s", strerror(errno));
3773 }
Mark Salyzyn5cc80b32018-03-21 12:24:58 -07003774 }
3775
Suren Baghdasaryan7c3addb2021-06-11 12:12:56 -07003776 if (init_reaper()) {
3777 ALOGI("Process reaper initialized with %d threads in the pool",
3778 reaper.thread_cnt());
3779 }
3780
Suren Baghdasaryanaf1b0e02021-11-16 11:50:29 -08003781 if (!watchdog.init()) {
3782 ALOGE("Failed to initialize the watchdog");
3783 }
3784
Todd Poynorc58c5142013-07-09 19:35:14 -07003785 mainloop();
Mark Salyzyn5cc80b32018-03-21 12:24:58 -07003786 }
Todd Poynorc58c5142013-07-09 19:35:14 -07003787
Suren Baghdasaryan08bfa982018-07-26 16:34:27 -07003788 android_log_destroy(&ctx);
3789
Todd Poynorc58c5142013-07-09 19:35:14 -07003790 ALOGI("exiting");
3791 return 0;
3792}