blob: 6a4e4c86043b01b0c3391a1080d082874bb0b066 [file] [log] [blame]
Todd Poynorc58c5142013-07-09 19:35:14 -07001/*
2 * Copyright (C) 2013 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "lowmemorykiller"
18
Wei Wangf1ee2e12018-11-21 00:11:44 -080019#include <dirent.h>
Todd Poynorc58c5142013-07-09 19:35:14 -070020#include <errno.h>
Robert Beneac72b2932017-08-21 15:18:31 -070021#include <inttypes.h>
Suren Baghdasaryanbb7747b2018-03-20 16:03:29 -070022#include <pwd.h>
Mark Salyzyna1f5b862016-10-17 14:28:00 -070023#include <sched.h>
Todd Poynorc58c5142013-07-09 19:35:14 -070024#include <signal.h>
Suren Baghdasaryanf584fff2018-03-20 13:53:17 -070025#include <stdbool.h>
Todd Poynorc58c5142013-07-09 19:35:14 -070026#include <stdlib.h>
27#include <string.h>
Mark Salyzyneb062742014-04-30 13:36:35 -070028#include <sys/cdefs.h>
Todd Poynorc58c5142013-07-09 19:35:14 -070029#include <sys/epoll.h>
30#include <sys/eventfd.h>
Colin Crossc4059002014-07-11 17:15:44 -070031#include <sys/mman.h>
Josh Gao84623be2021-03-18 17:16:08 -070032#include <sys/pidfd.h>
Wei Wangf1ee2e12018-11-21 00:11:44 -080033#include <sys/resource.h>
Todd Poynorc58c5142013-07-09 19:35:14 -070034#include <sys/socket.h>
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -070035#include <sys/syscall.h>
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -080036#include <sys/sysinfo.h>
Wei Wangf1ee2e12018-11-21 00:11:44 -080037#include <sys/time.h>
Mark Salyzyn5cc80b32018-03-21 12:24:58 -070038#include <sys/types.h>
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -070039#include <time.h>
Mark Salyzyneb062742014-04-30 13:36:35 -070040#include <unistd.h>
41
Robert Benea57397dc2017-07-31 17:15:20 -070042#include <cutils/properties.h>
Wei Wangf1ee2e12018-11-21 00:11:44 -080043#include <cutils/sched_policy.h>
Todd Poynorc58c5142013-07-09 19:35:14 -070044#include <cutils/sockets.h>
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -070045#include <liblmkd_utils.h>
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -080046#include <lmkd.h>
Mark Salyzyn6a63fde2017-01-10 13:19:54 -080047#include <log/log.h>
Suren Baghdasaryan08bfa982018-07-26 16:34:27 -070048#include <log/log_event_list.h>
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -070049#include <log/log_time.h>
Suren Baghdasaryan945658a2019-10-18 11:16:52 -070050#include <private/android_filesystem_config.h>
Suren Baghdasaryan55e31502019-01-08 12:54:48 -080051#include <psi/psi.h>
Wei Wangf1ee2e12018-11-21 00:11:44 -080052#include <system/thread_defs.h>
Mark Salyzyneb062742014-04-30 13:36:35 -070053
Yao Chen337606c2018-05-02 11:19:27 -070054#include "statslog.h"
Rajeev Kumar4aba9152018-01-31 17:54:56 -080055
Suren Baghdasaryan940e7cf2021-05-27 18:15:44 -070056#define BPF_FD_JUST_USE_INT
57#include "BpfSyscallWrappers.h"
58
Suren Baghdasaryan03e19872018-01-04 10:43:58 -080059/*
60 * Define LMKD_TRACE_KILLS to record lmkd kills in kernel traces
61 * to profile and correlate with OOM kills
62 */
63#ifdef LMKD_TRACE_KILLS
64
65#define ATRACE_TAG ATRACE_TAG_ALWAYS
66#include <cutils/trace.h>
67
Suren Baghdasaryan34928bb2021-07-29 17:02:51 -070068static inline void trace_kill_start(int pid, const char *desc) {
69 ATRACE_INT("kill_one_process", pid);
70 ATRACE_BEGIN(desc);
71}
72
73static inline void trace_kill_end() {
74 ATRACE_END();
75 ATRACE_INT("kill_one_process", 0);
76}
Suren Baghdasaryan03e19872018-01-04 10:43:58 -080077
78#else /* LMKD_TRACE_KILLS */
79
Suren Baghdasaryan34928bb2021-07-29 17:02:51 -070080static inline void trace_kill_start(int, const char *) {}
81static inline void trace_kill_end() {}
Suren Baghdasaryan03e19872018-01-04 10:43:58 -080082
83#endif /* LMKD_TRACE_KILLS */
84
Mark Salyzyneb062742014-04-30 13:36:35 -070085#ifndef __unused
86#define __unused __attribute__((__unused__))
87#endif
Todd Poynorc58c5142013-07-09 19:35:14 -070088
89#define MEMCG_SYSFS_PATH "/dev/memcg/"
Robert Beneac72b2932017-08-21 15:18:31 -070090#define MEMCG_MEMORY_USAGE "/dev/memcg/memory.usage_in_bytes"
91#define MEMCG_MEMORYSW_USAGE "/dev/memcg/memory.memsw.usage_in_bytes"
Suren Baghdasaryand28a9732018-04-13 13:11:51 -070092#define ZONEINFO_PATH "/proc/zoneinfo"
93#define MEMINFO_PATH "/proc/meminfo"
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -070094#define VMSTAT_PATH "/proc/vmstat"
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -070095#define PROC_STATUS_TGID_FIELD "Tgid:"
Ioannis Ilkos279268a2020-08-01 10:50:40 +010096#define PROC_STATUS_RSS_FIELD "VmRSS:"
97#define PROC_STATUS_SWAP_FIELD "VmSwap:"
Todd Poynorc58c5142013-07-09 19:35:14 -070098#define LINE_MAX 128
99
Suren Baghdasaryan970a26a2019-09-19 15:27:21 -0700100#define PERCEPTIBLE_APP_ADJ 200
101
Suren Baghdasaryan08bfa982018-07-26 16:34:27 -0700102/* Android Logger event logtags (see event.logtags) */
Suren Baghdasaryan12cacae2019-09-16 12:06:30 -0700103#define KILLINFO_LOG_TAG 10195355
Suren Baghdasaryan08bfa982018-07-26 16:34:27 -0700104
Mark Salyzyna00ccd82018-04-09 09:50:32 -0700105/* gid containing AID_SYSTEM required */
Todd Poynorc58c5142013-07-09 19:35:14 -0700106#define INKERNEL_MINFREE_PATH "/sys/module/lowmemorykiller/parameters/minfree"
107#define INKERNEL_ADJ_PATH "/sys/module/lowmemorykiller/parameters/adj"
108
109#define ARRAY_SIZE(x) (sizeof(x) / sizeof(*(x)))
Robert Benea58d6a132017-06-01 16:32:31 -0700110#define EIGHT_MEGA (1 << 23)
Todd Poynorc58c5142013-07-09 19:35:14 -0700111
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -0700112#define TARGET_UPDATE_MIN_INTERVAL_MS 1000
Martin Liu1f72f5f2020-08-21 13:18:50 +0800113#define THRASHING_RESET_INTERVAL_MS 1000
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -0700114
115#define NS_PER_MS (NS_PER_SEC / MS_PER_SEC)
Suren Baghdasaryan55e31502019-01-08 12:54:48 -0800116#define US_PER_MS (US_PER_SEC / MS_PER_SEC)
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -0700117
Suren Baghdasaryanbb7747b2018-03-20 16:03:29 -0700118/* Defined as ProcessList.SYSTEM_ADJ in ProcessList.java */
119#define SYSTEM_ADJ (-900)
120
Greg Kaiserf5b1d142018-03-23 14:16:12 -0700121#define STRINGIFY(x) STRINGIFY_INTERNAL(x)
122#define STRINGIFY_INTERNAL(x) #x
123
Suren Baghdasaryan55e31502019-01-08 12:54:48 -0800124/*
125 * PSI monitor tracking window size.
126 * PSI monitor generates events at most once per window,
127 * therefore we poll memory state for the duration of
128 * PSI_WINDOW_SIZE_MS after the event happens.
129 */
130#define PSI_WINDOW_SIZE_MS 1000
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -0700131/* Polling period after PSI signal when pressure is high */
132#define PSI_POLL_PERIOD_SHORT_MS 10
133/* Polling period after PSI signal when pressure is low */
134#define PSI_POLL_PERIOD_LONG_MS 100
Suren Baghdasaryan55e31502019-01-08 12:54:48 -0800135
Suren Baghdasaryan08bfa982018-07-26 16:34:27 -0700136#define min(a, b) (((a) < (b)) ? (a) : (b))
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -0700137#define max(a, b) (((a) > (b)) ? (a) : (b))
Suren Baghdasaryan08bfa982018-07-26 16:34:27 -0700138
Suren Baghdasaryan53be36e2018-09-05 15:46:32 -0700139#define FAIL_REPORT_RLIMIT_MS 1000
140
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -0700141/*
142 * System property defaults
143 */
144/* ro.lmk.swap_free_low_percentage property defaults */
Suren Baghdasaryanfb1f5922020-05-19 13:07:23 -0700145#define DEF_LOW_SWAP 10
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -0700146/* ro.lmk.thrashing_limit property defaults */
147#define DEF_THRASHING_LOWRAM 30
148#define DEF_THRASHING 100
149/* ro.lmk.thrashing_limit_decay property defaults */
150#define DEF_THRASHING_DECAY_LOWRAM 50
151#define DEF_THRASHING_DECAY 10
Suren Baghdasaryan2f88e152019-07-15 15:42:09 -0700152/* ro.lmk.psi_partial_stall_ms property defaults */
153#define DEF_PARTIAL_STALL_LOWRAM 200
154#define DEF_PARTIAL_STALL 70
155/* ro.lmk.psi_complete_stall_ms property defaults */
156#define DEF_COMPLETE_STALL 700
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -0700157
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -0700158#define LMKD_REINIT_PROP "lmkd.reinit"
159
Todd Poynorc58c5142013-07-09 19:35:14 -0700160/* default to old in-kernel interface if no memory pressure events */
Mark Salyzyn5cc80b32018-03-21 12:24:58 -0700161static bool use_inkernel_interface = true;
Robert Benea7878c9b2017-09-11 16:53:28 -0700162static bool has_inkernel_module;
Todd Poynorc58c5142013-07-09 19:35:14 -0700163
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -0800164/* memory pressure levels */
165enum vmpressure_level {
166 VMPRESS_LEVEL_LOW = 0,
167 VMPRESS_LEVEL_MEDIUM,
168 VMPRESS_LEVEL_CRITICAL,
169 VMPRESS_LEVEL_COUNT
170};
Todd Poynorc58c5142013-07-09 19:35:14 -0700171
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -0800172static const char *level_name[] = {
173 "low",
174 "medium",
175 "critical"
176};
177
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -0800178struct {
Suren Baghdasaryane0f3dd12018-04-13 13:41:12 -0700179 int64_t min_nr_free_pages; /* recorded but not used yet */
180 int64_t max_nr_free_pages;
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -0800181} low_pressure_mem = { -1, -1 };
182
Suren Baghdasaryan55e31502019-01-08 12:54:48 -0800183struct psi_threshold {
184 enum psi_stall_type stall_type;
185 int threshold_ms;
186};
187
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -0800188static int level_oomadj[VMPRESS_LEVEL_COUNT];
Suren Baghdasaryan3e1a8492018-01-04 09:16:21 -0800189static int mpevfd[VMPRESS_LEVEL_COUNT] = { -1, -1, -1 };
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -0700190static bool pidfd_supported;
191static int last_kill_pid_or_fd = -1;
192static struct timespec last_kill_tm;
193
194/* lmkd configurable parameters */
Robert Beneac72b2932017-08-21 15:18:31 -0700195static bool debug_process_killing;
196static bool enable_pressure_upgrade;
197static int64_t upgrade_pressure;
Robert Benea3be16142017-09-13 15:20:30 -0700198static int64_t downgrade_pressure;
Suren Baghdasaryand1d59f82018-04-13 11:45:38 -0700199static bool low_ram_device;
Suren Baghdasaryaneb7c5492017-12-08 13:17:06 -0800200static bool kill_heaviest_task;
Suren Baghdasaryan30854e72018-01-17 17:28:01 -0800201static unsigned long kill_timeout_ms;
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -0700202static bool use_minfree_levels;
Suren Baghdasaryan8389fdb2018-06-19 18:38:12 -0700203static bool per_app_memcg;
Vic Yang65680692018-08-07 10:18:22 -0700204static int swap_free_low_percentage;
Suren Baghdasaryan2f88e152019-07-15 15:42:09 -0700205static int psi_partial_stall_ms;
206static int psi_complete_stall_ms;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -0700207static int thrashing_limit_pct;
208static int thrashing_limit_decay_pct;
Suren Baghdasaryan0142b3c2021-03-03 11:11:09 -0800209static int thrashing_critical_pct;
Suren Baghdasaryan51ee4c52020-04-21 12:27:01 -0700210static int swap_util_max;
Suren Baghdasaryan11221d42021-07-14 17:57:52 -0700211static int64_t filecache_min_kb;
Suren Baghdasaryan55e31502019-01-08 12:54:48 -0800212static bool use_psi_monitors = false;
Jing Ji5c480962019-12-04 09:22:05 -0800213static int kpoll_fd;
Suren Baghdasaryan55e31502019-01-08 12:54:48 -0800214static struct psi_threshold psi_thresholds[VMPRESS_LEVEL_COUNT] = {
215 { PSI_SOME, 70 }, /* 70ms out of 1sec for partial stall */
216 { PSI_SOME, 100 }, /* 100ms out of 1sec for partial stall */
217 { PSI_FULL, 70 }, /* 70ms out of 1sec for complete stall */
218};
Robert Benea57397dc2017-07-31 17:15:20 -0700219
Suren Baghdasaryan08bfa982018-07-26 16:34:27 -0700220static android_log_context ctx;
221
Suren Baghdasaryane12a0672019-07-15 14:50:49 -0700222enum polling_update {
223 POLLING_DO_NOT_CHANGE,
224 POLLING_START,
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -0700225 POLLING_PAUSE,
226 POLLING_RESUME,
Suren Baghdasaryane12a0672019-07-15 14:50:49 -0700227};
228
229/*
230 * Data used for periodic polling for the memory state of the device.
231 * Note that when system is not polling poll_handler is set to NULL,
232 * when polling starts poll_handler gets set and is reset back to
233 * NULL when polling stops.
234 */
235struct polling_params {
236 struct event_handler_info* poll_handler;
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -0700237 struct event_handler_info* paused_handler;
Suren Baghdasaryane12a0672019-07-15 14:50:49 -0700238 struct timespec poll_start_tm;
239 struct timespec last_poll_tm;
240 int polling_interval_ms;
241 enum polling_update update;
242};
243
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -0800244/* data required to handle events */
245struct event_handler_info {
246 int data;
Suren Baghdasaryane12a0672019-07-15 14:50:49 -0700247 void (*handler)(int data, uint32_t events, struct polling_params *poll_params);
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -0800248};
Todd Poynorc58c5142013-07-09 19:35:14 -0700249
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -0800250/* data required to handle socket events */
251struct sock_event_handler_info {
252 int sock;
Suren Baghdasaryan945658a2019-10-18 11:16:52 -0700253 pid_t pid;
Suren Baghdasaryan36baf442019-12-23 11:37:34 -0800254 uint32_t async_event_mask;
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -0800255 struct event_handler_info handler_info;
256};
257
Suren Baghdasaryanf2cbefd2019-10-21 17:59:22 -0700258/* max supported number of data connections (AMS, init, tests) */
259#define MAX_DATA_CONN 3
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -0800260
261/* socket event handler data */
262static struct sock_event_handler_info ctrl_sock;
263static struct sock_event_handler_info data_sock[MAX_DATA_CONN];
264
265/* vmpressure event handler data */
266static struct event_handler_info vmpressure_hinfo[VMPRESS_LEVEL_COUNT];
267
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -0700268/*
Suren Baghdasaryanf2cbefd2019-10-21 17:59:22 -0700269 * 1 ctrl listen socket, 3 ctrl data socket, 3 memory pressure levels,
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -0700270 * 1 lmk events + 1 fd to wait for process death
271 */
272#define MAX_EPOLL_EVENTS (1 + MAX_DATA_CONN + VMPRESS_LEVEL_COUNT + 1 + 1)
Todd Poynorc58c5142013-07-09 19:35:14 -0700273static int epollfd;
274static int maxevents;
275
Chong Zhang1cd12b52015-10-14 16:19:53 -0700276/* OOM score values used by both kernel and framework */
Todd Poynora08c1722013-09-16 19:26:47 -0700277#define OOM_SCORE_ADJ_MIN (-1000)
278#define OOM_SCORE_ADJ_MAX 1000
279
Todd Poynorc58c5142013-07-09 19:35:14 -0700280static int lowmem_adj[MAX_TARGETS];
281static int lowmem_minfree[MAX_TARGETS];
282static int lowmem_targets_size;
283
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700284/* Fields to parse in /proc/zoneinfo */
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -0700285/* zoneinfo per-zone fields */
286enum zoneinfo_zone_field {
287 ZI_ZONE_NR_FREE_PAGES = 0,
288 ZI_ZONE_MIN,
289 ZI_ZONE_LOW,
290 ZI_ZONE_HIGH,
291 ZI_ZONE_PRESENT,
292 ZI_ZONE_NR_FREE_CMA,
293 ZI_ZONE_FIELD_COUNT
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700294};
295
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -0700296static const char* const zoneinfo_zone_field_names[ZI_ZONE_FIELD_COUNT] = {
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700297 "nr_free_pages",
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -0700298 "min",
299 "low",
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700300 "high",
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -0700301 "present",
302 "nr_free_cma",
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700303};
304
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -0700305/* zoneinfo per-zone special fields */
306enum zoneinfo_zone_spec_field {
307 ZI_ZONE_SPEC_PROTECTION = 0,
308 ZI_ZONE_SPEC_PAGESETS,
309 ZI_ZONE_SPEC_FIELD_COUNT,
310};
311
312static const char* const zoneinfo_zone_spec_field_names[ZI_ZONE_SPEC_FIELD_COUNT] = {
313 "protection:",
314 "pagesets",
315};
316
317/* see __MAX_NR_ZONES definition in kernel mmzone.h */
318#define MAX_NR_ZONES 6
319
320union zoneinfo_zone_fields {
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700321 struct {
322 int64_t nr_free_pages;
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -0700323 int64_t min;
324 int64_t low;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700325 int64_t high;
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -0700326 int64_t present;
327 int64_t nr_free_cma;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700328 } field;
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -0700329 int64_t arr[ZI_ZONE_FIELD_COUNT];
330};
331
332struct zoneinfo_zone {
333 union zoneinfo_zone_fields fields;
334 int64_t protection[MAX_NR_ZONES];
335 int64_t max_protection;
336};
337
338/* zoneinfo per-node fields */
339enum zoneinfo_node_field {
340 ZI_NODE_NR_INACTIVE_FILE = 0,
341 ZI_NODE_NR_ACTIVE_FILE,
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -0700342 ZI_NODE_FIELD_COUNT
343};
344
345static const char* const zoneinfo_node_field_names[ZI_NODE_FIELD_COUNT] = {
346 "nr_inactive_file",
347 "nr_active_file",
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -0700348};
349
350union zoneinfo_node_fields {
351 struct {
352 int64_t nr_inactive_file;
353 int64_t nr_active_file;
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -0700354 } field;
355 int64_t arr[ZI_NODE_FIELD_COUNT];
356};
357
358struct zoneinfo_node {
359 int id;
360 int zone_count;
361 struct zoneinfo_zone zones[MAX_NR_ZONES];
362 union zoneinfo_node_fields fields;
363};
364
365/* for now two memory nodes is more than enough */
366#define MAX_NR_NODES 2
367
368struct zoneinfo {
369 int node_count;
370 struct zoneinfo_node nodes[MAX_NR_NODES];
371 int64_t totalreserve_pages;
372 int64_t total_inactive_file;
373 int64_t total_active_file;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700374};
375
376/* Fields to parse in /proc/meminfo */
377enum meminfo_field {
378 MI_NR_FREE_PAGES = 0,
379 MI_CACHED,
380 MI_SWAP_CACHED,
381 MI_BUFFERS,
382 MI_SHMEM,
383 MI_UNEVICTABLE,
Vic Yang65680692018-08-07 10:18:22 -0700384 MI_TOTAL_SWAP,
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700385 MI_FREE_SWAP,
Suren Baghdasaryan08bfa982018-07-26 16:34:27 -0700386 MI_ACTIVE_ANON,
387 MI_INACTIVE_ANON,
388 MI_ACTIVE_FILE,
389 MI_INACTIVE_FILE,
390 MI_SRECLAIMABLE,
391 MI_SUNRECLAIM,
392 MI_KERNEL_STACK,
393 MI_PAGE_TABLES,
394 MI_ION_HELP,
395 MI_ION_HELP_POOL,
396 MI_CMA_FREE,
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700397 MI_FIELD_COUNT
398};
399
400static const char* const meminfo_field_names[MI_FIELD_COUNT] = {
401 "MemFree:",
402 "Cached:",
403 "SwapCached:",
404 "Buffers:",
405 "Shmem:",
406 "Unevictable:",
Vic Yang65680692018-08-07 10:18:22 -0700407 "SwapTotal:",
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700408 "SwapFree:",
Suren Baghdasaryan08bfa982018-07-26 16:34:27 -0700409 "Active(anon):",
410 "Inactive(anon):",
411 "Active(file):",
412 "Inactive(file):",
413 "SReclaimable:",
414 "SUnreclaim:",
415 "KernelStack:",
416 "PageTables:",
417 "ION_heap:",
418 "ION_heap_pool:",
419 "CmaFree:",
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700420};
421
422union meminfo {
423 struct {
424 int64_t nr_free_pages;
425 int64_t cached;
426 int64_t swap_cached;
427 int64_t buffers;
428 int64_t shmem;
429 int64_t unevictable;
Vic Yang65680692018-08-07 10:18:22 -0700430 int64_t total_swap;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700431 int64_t free_swap;
Suren Baghdasaryan08bfa982018-07-26 16:34:27 -0700432 int64_t active_anon;
433 int64_t inactive_anon;
434 int64_t active_file;
435 int64_t inactive_file;
436 int64_t sreclaimable;
437 int64_t sunreclaimable;
438 int64_t kernel_stack;
439 int64_t page_tables;
440 int64_t ion_heap;
441 int64_t ion_heap_pool;
442 int64_t cma_free;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700443 /* fields below are calculated rather than read from the file */
444 int64_t nr_file_pages;
Suren Baghdasaryan940e7cf2021-05-27 18:15:44 -0700445 int64_t total_gpu_kb;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700446 } field;
447 int64_t arr[MI_FIELD_COUNT];
448};
449
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -0700450/* Fields to parse in /proc/vmstat */
451enum vmstat_field {
452 VS_FREE_PAGES,
453 VS_INACTIVE_FILE,
454 VS_ACTIVE_FILE,
455 VS_WORKINGSET_REFAULT,
Suren Baghdasaryandc60f972020-12-14 13:38:48 -0800456 VS_WORKINGSET_REFAULT_FILE,
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -0700457 VS_PGSCAN_KSWAPD,
458 VS_PGSCAN_DIRECT,
459 VS_PGSCAN_DIRECT_THROTTLE,
460 VS_FIELD_COUNT
461};
462
463static const char* const vmstat_field_names[MI_FIELD_COUNT] = {
464 "nr_free_pages",
465 "nr_inactive_file",
466 "nr_active_file",
467 "workingset_refault",
Suren Baghdasaryandc60f972020-12-14 13:38:48 -0800468 "workingset_refault_file",
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -0700469 "pgscan_kswapd",
470 "pgscan_direct",
471 "pgscan_direct_throttle",
472};
473
474union vmstat {
475 struct {
476 int64_t nr_free_pages;
477 int64_t nr_inactive_file;
478 int64_t nr_active_file;
479 int64_t workingset_refault;
Suren Baghdasaryandc60f972020-12-14 13:38:48 -0800480 int64_t workingset_refault_file;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -0700481 int64_t pgscan_kswapd;
482 int64_t pgscan_direct;
483 int64_t pgscan_direct_throttle;
484 } field;
485 int64_t arr[VS_FIELD_COUNT];
486};
487
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700488enum field_match_result {
489 NO_MATCH,
490 PARSE_FAIL,
491 PARSE_SUCCESS
492};
493
Todd Poynorc58c5142013-07-09 19:35:14 -0700494struct adjslot_list {
495 struct adjslot_list *next;
496 struct adjslot_list *prev;
497};
498
499struct proc {
500 struct adjslot_list asl;
501 int pid;
Suren Baghdasaryana10157c2019-07-19 10:55:39 -0700502 int pidfd;
Colin Cross748d2182014-06-13 14:52:43 -0700503 uid_t uid;
Todd Poynorc58c5142013-07-09 19:35:14 -0700504 int oomadj;
Suren Baghdasaryan945658a2019-10-18 11:16:52 -0700505 pid_t reg_pid; /* PID of the process that registered this record */
Todd Poynorc58c5142013-07-09 19:35:14 -0700506 struct proc *pidhash_next;
507};
508
Suren Baghdasaryan87966742018-04-13 12:43:41 -0700509struct reread_data {
510 const char* const filename;
511 int fd;
512};
513
Todd Poynorc58c5142013-07-09 19:35:14 -0700514#define PIDHASH_SZ 1024
515static struct proc *pidhash[PIDHASH_SZ];
516#define pid_hashfn(x) ((((x) >> 8) ^ (x)) & (PIDHASH_SZ - 1))
517
Chih-Hung Hsieheefa2462016-05-19 16:02:22 -0700518#define ADJTOSLOT(adj) ((adj) + -OOM_SCORE_ADJ_MIN)
Suren Baghdasaryana7394ea2018-10-12 11:07:40 -0700519#define ADJTOSLOT_COUNT (ADJTOSLOT(OOM_SCORE_ADJ_MAX) + 1)
520static struct adjslot_list procadjslot_list[ADJTOSLOT_COUNT];
521
522#define MAX_DISTINCT_OOM_ADJ 32
523#define KILLCNT_INVALID_IDX 0xFF
524/*
525 * Because killcnt array is sparse a two-level indirection is used
526 * to keep the size small. killcnt_idx stores index of the element in
527 * killcnt array. Index KILLCNT_INVALID_IDX indicates an unused slot.
528 */
529static uint8_t killcnt_idx[ADJTOSLOT_COUNT];
530static uint16_t killcnt[MAX_DISTINCT_OOM_ADJ];
531static int killcnt_free_idx = 0;
532static uint32_t killcnt_total = 0;
Todd Poynorc58c5142013-07-09 19:35:14 -0700533
Todd Poynorc58c5142013-07-09 19:35:14 -0700534/* PAGE_SIZE / 1024 */
535static long page_k;
536
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -0700537static void update_props();
538static bool init_monitors();
539static void destroy_monitors();
540
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -0700541static int clamp(int low, int high, int value) {
542 return max(min(value, high), low);
543}
544
Suren Baghdasaryan87966742018-04-13 12:43:41 -0700545static bool parse_int64(const char* str, int64_t* ret) {
546 char* endptr;
547 long long val = strtoll(str, &endptr, 10);
548 if (str == endptr || val > INT64_MAX) {
549 return false;
550 }
551 *ret = (int64_t)val;
552 return true;
553}
554
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -0700555static int find_field(const char* name, const char* const field_names[], int field_count) {
556 for (int i = 0; i < field_count; i++) {
557 if (!strcmp(name, field_names[i])) {
558 return i;
559 }
560 }
561 return -1;
562}
563
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700564static enum field_match_result match_field(const char* cp, const char* ap,
565 const char* const field_names[],
566 int field_count, int64_t* field,
567 int *field_idx) {
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -0700568 int i = find_field(cp, field_names, field_count);
569 if (i < 0) {
570 return NO_MATCH;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700571 }
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -0700572 *field_idx = i;
573 return parse_int64(ap, field) ? PARSE_SUCCESS : PARSE_FAIL;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700574}
575
Suren Baghdasaryan87966742018-04-13 12:43:41 -0700576/*
577 * Read file content from the beginning up to max_len bytes or EOF
578 * whichever happens first.
579 */
Colin Crossdba1cc62014-07-11 17:53:27 -0700580static ssize_t read_all(int fd, char *buf, size_t max_len)
581{
582 ssize_t ret = 0;
Suren Baghdasaryan87966742018-04-13 12:43:41 -0700583 off_t offset = 0;
Colin Crossdba1cc62014-07-11 17:53:27 -0700584
585 while (max_len > 0) {
Suren Baghdasaryan87966742018-04-13 12:43:41 -0700586 ssize_t r = TEMP_FAILURE_RETRY(pread(fd, buf, max_len, offset));
Colin Crossdba1cc62014-07-11 17:53:27 -0700587 if (r == 0) {
588 break;
589 }
590 if (r == -1) {
591 return -1;
592 }
593 ret += r;
594 buf += r;
Suren Baghdasaryan87966742018-04-13 12:43:41 -0700595 offset += r;
Colin Crossdba1cc62014-07-11 17:53:27 -0700596 max_len -= r;
597 }
598
599 return ret;
600}
601
Suren Baghdasaryan87966742018-04-13 12:43:41 -0700602/*
603 * Read a new or already opened file from the beginning.
604 * If the file has not been opened yet data->fd should be set to -1.
605 * To be used with files which are read often and possibly during high
606 * memory pressure to minimize file opening which by itself requires kernel
607 * memory allocation and might result in a stall on memory stressed system.
608 */
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -0700609static char *reread_file(struct reread_data *data) {
610 /* start with page-size buffer and increase if needed */
611 static ssize_t buf_size = PAGE_SIZE;
612 static char *new_buf, *buf = NULL;
Suren Baghdasaryan87966742018-04-13 12:43:41 -0700613 ssize_t size;
614
615 if (data->fd == -1) {
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -0700616 /* First-time buffer initialization */
Tom Cherry43f3d2b2019-12-04 12:46:57 -0800617 if (!buf && (buf = static_cast<char*>(malloc(buf_size))) == nullptr) {
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -0700618 return NULL;
619 }
620
621 data->fd = TEMP_FAILURE_RETRY(open(data->filename, O_RDONLY | O_CLOEXEC));
622 if (data->fd < 0) {
Suren Baghdasaryan87966742018-04-13 12:43:41 -0700623 ALOGE("%s open: %s", data->filename, strerror(errno));
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -0700624 return NULL;
Suren Baghdasaryan87966742018-04-13 12:43:41 -0700625 }
626 }
627
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -0700628 while (true) {
629 size = read_all(data->fd, buf, buf_size - 1);
630 if (size < 0) {
631 ALOGE("%s read: %s", data->filename, strerror(errno));
632 close(data->fd);
633 data->fd = -1;
634 return NULL;
635 }
636 if (size < buf_size - 1) {
637 break;
638 }
639 /*
640 * Since we are reading /proc files we can't use fstat to find out
641 * the real size of the file. Double the buffer size and keep retrying.
642 */
Tom Cherry43f3d2b2019-12-04 12:46:57 -0800643 if ((new_buf = static_cast<char*>(realloc(buf, buf_size * 2))) == nullptr) {
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -0700644 errno = ENOMEM;
645 return NULL;
646 }
647 buf = new_buf;
648 buf_size *= 2;
Suren Baghdasaryan87966742018-04-13 12:43:41 -0700649 }
Suren Baghdasaryan87966742018-04-13 12:43:41 -0700650 buf[size] = 0;
651
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -0700652 return buf;
Suren Baghdasaryan87966742018-04-13 12:43:41 -0700653}
654
Jing Ji5c480962019-12-04 09:22:05 -0800655static bool claim_record(struct proc* procp, pid_t pid) {
656 if (procp->reg_pid == pid) {
657 /* Record already belongs to the registrant */
658 return true;
659 }
660 if (procp->reg_pid == 0) {
661 /* Old registrant is gone, claim the record */
662 procp->reg_pid = pid;
663 return true;
664 }
665 /* The record is owned by another registrant */
666 return false;
667}
668
669static void remove_claims(pid_t pid) {
670 int i;
671
672 for (i = 0; i < PIDHASH_SZ; i++) {
673 struct proc* procp = pidhash[i];
674 while (procp) {
675 if (procp->reg_pid == pid) {
676 procp->reg_pid = 0;
677 }
678 procp = procp->pidhash_next;
679 }
680 }
681}
682
683static void ctrl_data_close(int dsock_idx) {
684 struct epoll_event epev;
685
686 ALOGI("closing lmkd data connection");
687 if (epoll_ctl(epollfd, EPOLL_CTL_DEL, data_sock[dsock_idx].sock, &epev) == -1) {
688 // Log a warning and keep going
689 ALOGW("epoll_ctl for data connection socket failed; errno=%d", errno);
690 }
691 maxevents--;
692
693 close(data_sock[dsock_idx].sock);
694 data_sock[dsock_idx].sock = -1;
695
696 /* Mark all records of the old registrant as unclaimed */
697 remove_claims(data_sock[dsock_idx].pid);
698}
699
700static ssize_t ctrl_data_read(int dsock_idx, char* buf, size_t bufsz, struct ucred* sender_cred) {
701 struct iovec iov = {buf, bufsz};
702 char control[CMSG_SPACE(sizeof(struct ucred))];
703 struct msghdr hdr = {
704 NULL, 0, &iov, 1, control, sizeof(control), 0,
705 };
706 ssize_t ret;
707 ret = TEMP_FAILURE_RETRY(recvmsg(data_sock[dsock_idx].sock, &hdr, 0));
708 if (ret == -1) {
709 ALOGE("control data socket read failed; %s", strerror(errno));
710 return -1;
711 }
712 if (ret == 0) {
713 ALOGE("Got EOF on control data socket");
714 return -1;
715 }
716
717 struct ucred* cred = NULL;
718 struct cmsghdr* cmsg = CMSG_FIRSTHDR(&hdr);
719 while (cmsg != NULL) {
720 if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_CREDENTIALS) {
721 cred = (struct ucred*)CMSG_DATA(cmsg);
722 break;
723 }
724 cmsg = CMSG_NXTHDR(&hdr, cmsg);
725 }
726
727 if (cred == NULL) {
728 ALOGE("Failed to retrieve sender credentials");
729 /* Close the connection */
730 ctrl_data_close(dsock_idx);
731 return -1;
732 }
733
734 memcpy(sender_cred, cred, sizeof(struct ucred));
735
736 /* Store PID of the peer */
737 data_sock[dsock_idx].pid = cred->pid;
738
739 return ret;
740}
741
742static int ctrl_data_write(int dsock_idx, char* buf, size_t bufsz) {
743 int ret = 0;
744
745 ret = TEMP_FAILURE_RETRY(write(data_sock[dsock_idx].sock, buf, bufsz));
746
747 if (ret == -1) {
748 ALOGE("control data socket write failed; errno=%d", errno);
749 } else if (ret == 0) {
750 ALOGE("Got EOF on control data socket");
751 ret = -1;
752 }
753
754 return ret;
755}
756
757/*
758 * Write the pid/uid pair over the data socket, note: all active clients
759 * will receive this unsolicited notification.
760 */
761static void ctrl_data_write_lmk_kill_occurred(pid_t pid, uid_t uid) {
762 LMKD_CTRL_PACKET packet;
763 size_t len = lmkd_pack_set_prockills(packet, pid, uid);
764
765 for (int i = 0; i < MAX_DATA_CONN; i++) {
Suren Baghdasaryan36baf442019-12-23 11:37:34 -0800766 if (data_sock[i].sock >= 0 && data_sock[i].async_event_mask & 1 << LMK_ASYNC_EVENT_KILL) {
Jing Ji5c480962019-12-04 09:22:05 -0800767 ctrl_data_write(i, (char*)packet, len);
768 }
769 }
770}
771
Vova Sharaienkoa92b76b2021-04-24 00:30:06 +0000772/*
773 * Write the kill_stat/memory_stat over the data socket to be propagated via AMS to statsd
774 */
775static void stats_write_lmk_kill_occurred(struct kill_stat *kill_st,
776 struct memory_stat *mem_st) {
777 LMK_KILL_OCCURRED_PACKET packet;
778 const size_t len = lmkd_pack_set_kill_occurred(packet, kill_st, mem_st);
779 if (len == 0) {
780 return;
781 }
782
783 for (int i = 0; i < MAX_DATA_CONN; i++) {
784 if (data_sock[i].sock >= 0 && data_sock[i].async_event_mask & 1 << LMK_ASYNC_EVENT_STAT) {
785 ctrl_data_write(i, packet, len);
786 }
787 }
788
789}
790
791static void stats_write_lmk_kill_occurred_pid(int pid, struct kill_stat *kill_st,
792 struct memory_stat *mem_st) {
793 kill_st->taskname = stats_get_task_name(pid);
794 if (kill_st->taskname != NULL) {
795 stats_write_lmk_kill_occurred(kill_st, mem_st);
796 }
797}
798
799/*
800 * Write the state_changed over the data socket to be propagated via AMS to statsd
801 */
802static void stats_write_lmk_state_changed(enum lmk_state state) {
803 LMKD_CTRL_PACKET packet_state_changed;
804 const size_t len = lmkd_pack_set_state_changed(packet_state_changed, state);
805 if (len == 0) {
806 return;
807 }
808 for (int i = 0; i < MAX_DATA_CONN; i++) {
809 if (data_sock[i].sock >= 0 && data_sock[i].async_event_mask & 1 << LMK_ASYNC_EVENT_STAT) {
810 ctrl_data_write(i, (char*)packet_state_changed, len);
811 }
812 }
813}
814
Jing Ji5c480962019-12-04 09:22:05 -0800815static void poll_kernel(int poll_fd) {
816 if (poll_fd == -1) {
817 // not waiting
818 return;
819 }
820
821 while (1) {
822 char rd_buf[256];
823 int bytes_read = TEMP_FAILURE_RETRY(pread(poll_fd, (void*)rd_buf, sizeof(rd_buf), 0));
824 if (bytes_read <= 0) break;
825 rd_buf[bytes_read] = '\0';
826
827 int64_t pid;
828 int64_t uid;
829 int64_t group_leader_pid;
830 int64_t rss_in_pages;
831 struct memory_stat mem_st = {};
832 int16_t oom_score_adj;
833 int16_t min_score_adj;
834 int64_t starttime;
835 char* taskname = 0;
836
837 int fields_read =
838 sscanf(rd_buf,
839 "%" SCNd64 " %" SCNd64 " %" SCNd64 " %" SCNd64 " %" SCNd64 " %" SCNd64
840 " %" SCNd16 " %" SCNd16 " %" SCNd64 "\n%m[^\n]",
841 &pid, &uid, &group_leader_pid, &mem_st.pgfault, &mem_st.pgmajfault,
842 &rss_in_pages, &oom_score_adj, &min_score_adj, &starttime, &taskname);
843
844 /* only the death of the group leader process is logged */
845 if (fields_read == 10 && group_leader_pid == pid) {
846 ctrl_data_write_lmk_kill_occurred((pid_t)pid, (uid_t)uid);
847 mem_st.process_start_time_ns = starttime * (NS_PER_SEC / sysconf(_SC_CLK_TCK));
848 mem_st.rss_in_bytes = rss_in_pages * PAGE_SIZE;
Suren Baghdasaryan3cc1f132020-09-09 20:19:02 -0700849
850 struct kill_stat kill_st = {
851 .uid = static_cast<int32_t>(uid),
852 .kill_reason = NONE,
853 .oom_score = oom_score_adj,
854 .min_oom_score = min_score_adj,
855 .free_mem_kb = 0,
856 .free_swap_kb = 0,
857 };
858 stats_write_lmk_kill_occurred_pid(pid, &kill_st, &mem_st);
Jing Ji5c480962019-12-04 09:22:05 -0800859 }
860
861 free(taskname);
862 }
863}
864
865static bool init_poll_kernel() {
866 kpoll_fd = TEMP_FAILURE_RETRY(open("/proc/lowmemorykiller", O_RDONLY | O_NONBLOCK | O_CLOEXEC));
867
868 if (kpoll_fd < 0) {
869 ALOGE("kernel lmk event file could not be opened; errno=%d", errno);
870 return false;
871 }
872
873 return true;
874}
875
Todd Poynorc58c5142013-07-09 19:35:14 -0700876static struct proc *pid_lookup(int pid) {
877 struct proc *procp;
878
879 for (procp = pidhash[pid_hashfn(pid)]; procp && procp->pid != pid;
880 procp = procp->pidhash_next)
881 ;
882
883 return procp;
884}
885
Tom Cherry43f3d2b2019-12-04 12:46:57 -0800886static void adjslot_insert(struct adjslot_list *head, struct adjslot_list *new_element)
Todd Poynorc58c5142013-07-09 19:35:14 -0700887{
888 struct adjslot_list *next = head->next;
Tom Cherry43f3d2b2019-12-04 12:46:57 -0800889 new_element->prev = head;
890 new_element->next = next;
891 next->prev = new_element;
892 head->next = new_element;
Todd Poynorc58c5142013-07-09 19:35:14 -0700893}
894
895static void adjslot_remove(struct adjslot_list *old)
896{
897 struct adjslot_list *prev = old->prev;
898 struct adjslot_list *next = old->next;
899 next->prev = prev;
900 prev->next = next;
901}
902
903static struct adjslot_list *adjslot_tail(struct adjslot_list *head) {
904 struct adjslot_list *asl = head->prev;
905
906 return asl == head ? NULL : asl;
907}
908
909static void proc_slot(struct proc *procp) {
910 int adjslot = ADJTOSLOT(procp->oomadj);
911
912 adjslot_insert(&procadjslot_list[adjslot], &procp->asl);
913}
914
915static void proc_unslot(struct proc *procp) {
916 adjslot_remove(&procp->asl);
917}
918
919static void proc_insert(struct proc *procp) {
920 int hval = pid_hashfn(procp->pid);
921
922 procp->pidhash_next = pidhash[hval];
923 pidhash[hval] = procp;
924 proc_slot(procp);
925}
926
927static int pid_remove(int pid) {
928 int hval = pid_hashfn(pid);
929 struct proc *procp;
930 struct proc *prevp;
931
932 for (procp = pidhash[hval], prevp = NULL; procp && procp->pid != pid;
933 procp = procp->pidhash_next)
934 prevp = procp;
935
936 if (!procp)
937 return -1;
938
939 if (!prevp)
940 pidhash[hval] = procp->pidhash_next;
941 else
942 prevp->pidhash_next = procp->pidhash_next;
943
944 proc_unslot(procp);
Suren Baghdasaryana10157c2019-07-19 10:55:39 -0700945 /*
946 * Close pidfd here if we are not waiting for corresponding process to die,
947 * in which case stop_wait_for_proc_kill() will close the pidfd later
948 */
949 if (procp->pidfd >= 0 && procp->pidfd != last_kill_pid_or_fd) {
950 close(procp->pidfd);
951 }
Todd Poynorc58c5142013-07-09 19:35:14 -0700952 free(procp);
953 return 0;
954}
955
Suren Baghdasaryanf584fff2018-03-20 13:53:17 -0700956/*
957 * Write a string to a file.
958 * Returns false if the file does not exist.
959 */
960static bool writefilestring(const char *path, const char *s,
961 bool err_if_missing) {
Nick Kralevich148d8dd2015-12-18 20:52:37 -0800962 int fd = open(path, O_WRONLY | O_CLOEXEC);
Suren Baghdasaryanf584fff2018-03-20 13:53:17 -0700963 ssize_t len = strlen(s);
964 ssize_t ret;
Todd Poynorc58c5142013-07-09 19:35:14 -0700965
966 if (fd < 0) {
Suren Baghdasaryanf584fff2018-03-20 13:53:17 -0700967 if (err_if_missing) {
968 ALOGE("Error opening %s; errno=%d", path, errno);
969 }
970 return false;
Todd Poynorc58c5142013-07-09 19:35:14 -0700971 }
972
Suren Baghdasaryanf584fff2018-03-20 13:53:17 -0700973 ret = TEMP_FAILURE_RETRY(write(fd, s, len));
Todd Poynorc58c5142013-07-09 19:35:14 -0700974 if (ret < 0) {
975 ALOGE("Error writing %s; errno=%d", path, errno);
976 } else if (ret < len) {
Suren Baghdasaryanf584fff2018-03-20 13:53:17 -0700977 ALOGE("Short write on %s; length=%zd", path, ret);
Todd Poynorc58c5142013-07-09 19:35:14 -0700978 }
979
980 close(fd);
Suren Baghdasaryanf584fff2018-03-20 13:53:17 -0700981 return true;
Todd Poynorc58c5142013-07-09 19:35:14 -0700982}
983
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -0700984static inline long get_time_diff_ms(struct timespec *from,
985 struct timespec *to) {
986 return (to->tv_sec - from->tv_sec) * (long)MS_PER_SEC +
987 (to->tv_nsec - from->tv_nsec) / (long)NS_PER_MS;
988}
989
Ioannis Ilkos279268a2020-08-01 10:50:40 +0100990/* Reads /proc/pid/status into buf. */
991static bool read_proc_status(int pid, char *buf, size_t buf_sz) {
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -0700992 char path[PATH_MAX];
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -0700993 int fd;
994 ssize_t size;
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -0700995
996 snprintf(path, PATH_MAX, "/proc/%d/status", pid);
997 fd = open(path, O_RDONLY | O_CLOEXEC);
998 if (fd < 0) {
Ioannis Ilkos279268a2020-08-01 10:50:40 +0100999 return false;
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -07001000 }
1001
Ioannis Ilkos279268a2020-08-01 10:50:40 +01001002 size = read_all(fd, buf, buf_sz - 1);
1003 close(fd);
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -07001004 if (size < 0) {
Ioannis Ilkos279268a2020-08-01 10:50:40 +01001005 return false;
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -07001006 }
1007 buf[size] = 0;
Ioannis Ilkos279268a2020-08-01 10:50:40 +01001008 return true;
1009}
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -07001010
Ioannis Ilkos279268a2020-08-01 10:50:40 +01001011/* Looks for tag in buf and parses the first integer */
1012static bool parse_status_tag(char *buf, const char *tag, int64_t *out) {
1013 char *pos = buf;
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -07001014 while (true) {
Ioannis Ilkos279268a2020-08-01 10:50:40 +01001015 pos = strstr(pos, tag);
1016 /* Stop if tag not found or found at the line beginning */
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -07001017 if (pos == NULL || pos == buf || pos[-1] == '\n') {
1018 break;
1019 }
1020 pos++;
1021 }
1022
1023 if (pos == NULL) {
Ioannis Ilkos279268a2020-08-01 10:50:40 +01001024 return false;
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -07001025 }
1026
Ioannis Ilkos279268a2020-08-01 10:50:40 +01001027 pos += strlen(tag);
1028 while (*pos == ' ') ++pos;
1029 return parse_int64(pos, out);
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -07001030}
1031
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07001032static int proc_get_size(int pid) {
1033 char path[PATH_MAX];
1034 char line[LINE_MAX];
1035 int fd;
1036 int rss = 0;
1037 int total;
1038 ssize_t ret;
1039
1040 /* gid containing AID_READPROC required */
1041 snprintf(path, PATH_MAX, "/proc/%d/statm", pid);
1042 fd = open(path, O_RDONLY | O_CLOEXEC);
1043 if (fd == -1)
1044 return -1;
1045
1046 ret = read_all(fd, line, sizeof(line) - 1);
1047 if (ret < 0) {
1048 close(fd);
1049 return -1;
1050 }
Suren Baghdasaryan632f1c52019-10-04 16:06:55 -07001051 line[ret] = '\0';
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07001052
1053 sscanf(line, "%d %d ", &total, &rss);
1054 close(fd);
1055 return rss;
1056}
1057
Suren Baghdasaryan632f1c52019-10-04 16:06:55 -07001058static char *proc_get_name(int pid, char *buf, size_t buf_size) {
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07001059 char path[PATH_MAX];
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07001060 int fd;
1061 char *cp;
1062 ssize_t ret;
1063
1064 /* gid containing AID_READPROC required */
1065 snprintf(path, PATH_MAX, "/proc/%d/cmdline", pid);
1066 fd = open(path, O_RDONLY | O_CLOEXEC);
1067 if (fd == -1) {
1068 return NULL;
1069 }
Suren Baghdasaryan632f1c52019-10-04 16:06:55 -07001070 ret = read_all(fd, buf, buf_size - 1);
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07001071 close(fd);
1072 if (ret < 0) {
1073 return NULL;
1074 }
Suren Baghdasaryan632f1c52019-10-04 16:06:55 -07001075 buf[ret] = '\0';
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07001076
Suren Baghdasaryan632f1c52019-10-04 16:06:55 -07001077 cp = strchr(buf, ' ');
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07001078 if (cp) {
1079 *cp = '\0';
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07001080 }
1081
Suren Baghdasaryan632f1c52019-10-04 16:06:55 -07001082 return buf;
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07001083}
1084
Suren Baghdasaryana93503e2019-10-22 17:12:01 -07001085static void cmd_procprio(LMKD_CTRL_PACKET packet, int field_count, struct ucred *cred) {
Todd Poynorc58c5142013-07-09 19:35:14 -07001086 struct proc *procp;
Suren Baghdasaryan632f1c52019-10-04 16:06:55 -07001087 char path[LINE_MAX];
Todd Poynorc58c5142013-07-09 19:35:14 -07001088 char val[20];
Robert Benea58d6a132017-06-01 16:32:31 -07001089 int soft_limit_mult;
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -08001090 struct lmk_procprio params;
Suren Baghdasaryanbb7747b2018-03-20 16:03:29 -07001091 bool is_system_server;
1092 struct passwd *pwdrec;
Ioannis Ilkos279268a2020-08-01 10:50:40 +01001093 int64_t tgid;
1094 char buf[PAGE_SIZE];
Todd Poynorc58c5142013-07-09 19:35:14 -07001095
Suren Baghdasaryana93503e2019-10-22 17:12:01 -07001096 lmkd_pack_get_procprio(packet, field_count, &params);
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -08001097
1098 if (params.oomadj < OOM_SCORE_ADJ_MIN ||
1099 params.oomadj > OOM_SCORE_ADJ_MAX) {
1100 ALOGE("Invalid PROCPRIO oomadj argument %d", params.oomadj);
Todd Poynorc58c5142013-07-09 19:35:14 -07001101 return;
1102 }
1103
Suren Baghdasaryana93503e2019-10-22 17:12:01 -07001104 if (params.ptype < PROC_TYPE_FIRST || params.ptype >= PROC_TYPE_COUNT) {
1105 ALOGE("Invalid PROCPRIO process type argument %d", params.ptype);
1106 return;
1107 }
1108
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -07001109 /* Check if registered process is a thread group leader */
Ioannis Ilkos279268a2020-08-01 10:50:40 +01001110 if (read_proc_status(params.pid, buf, sizeof(buf))) {
1111 if (parse_status_tag(buf, PROC_STATUS_TGID_FIELD, &tgid) && tgid != params.pid) {
1112 ALOGE("Attempt to register a task that is not a thread group leader "
1113 "(tid %d, tgid %" PRId64 ")", params.pid, tgid);
1114 return;
1115 }
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -07001116 }
1117
Mark Salyzyna00ccd82018-04-09 09:50:32 -07001118 /* gid containing AID_READPROC required */
1119 /* CAP_SYS_RESOURCE required */
1120 /* CAP_DAC_OVERRIDE required */
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -08001121 snprintf(path, sizeof(path), "/proc/%d/oom_score_adj", params.pid);
1122 snprintf(val, sizeof(val), "%d", params.oomadj);
Suren Baghdasaryanf584fff2018-03-20 13:53:17 -07001123 if (!writefilestring(path, val, false)) {
1124 ALOGW("Failed to open %s; errno=%d: process %d might have been killed",
1125 path, errno, params.pid);
1126 /* If this file does not exist the process is dead. */
1127 return;
1128 }
Todd Poynorc58c5142013-07-09 19:35:14 -07001129
Mark Salyzyn5cc80b32018-03-21 12:24:58 -07001130 if (use_inkernel_interface) {
Jing Ji5c480962019-12-04 09:22:05 -08001131 stats_store_taskname(params.pid, proc_get_name(params.pid, path, sizeof(path)));
Todd Poynorc58c5142013-07-09 19:35:14 -07001132 return;
Mark Salyzyn5cc80b32018-03-21 12:24:58 -07001133 }
Todd Poynorc58c5142013-07-09 19:35:14 -07001134
Suren Baghdasaryana93503e2019-10-22 17:12:01 -07001135 /* lmkd should not change soft limits for services */
1136 if (params.ptype == PROC_TYPE_APP && per_app_memcg) {
Suren Baghdasaryanb0bda552018-05-18 14:42:00 -07001137 if (params.oomadj >= 900) {
1138 soft_limit_mult = 0;
1139 } else if (params.oomadj >= 800) {
1140 soft_limit_mult = 0;
1141 } else if (params.oomadj >= 700) {
1142 soft_limit_mult = 0;
1143 } else if (params.oomadj >= 600) {
1144 // Launcher should be perceptible, don't kill it.
1145 params.oomadj = 200;
1146 soft_limit_mult = 1;
1147 } else if (params.oomadj >= 500) {
1148 soft_limit_mult = 0;
1149 } else if (params.oomadj >= 400) {
1150 soft_limit_mult = 0;
1151 } else if (params.oomadj >= 300) {
1152 soft_limit_mult = 1;
1153 } else if (params.oomadj >= 200) {
Srinivas Paladugua453f0b2018-10-09 14:21:10 -07001154 soft_limit_mult = 8;
Suren Baghdasaryanb0bda552018-05-18 14:42:00 -07001155 } else if (params.oomadj >= 100) {
1156 soft_limit_mult = 10;
1157 } else if (params.oomadj >= 0) {
1158 soft_limit_mult = 20;
1159 } else {
1160 // Persistent processes will have a large
1161 // soft limit 512MB.
1162 soft_limit_mult = 64;
1163 }
Robert Benea58d6a132017-06-01 16:32:31 -07001164
Suren Baghdasaryanbf919ff2018-05-21 19:48:47 -07001165 snprintf(path, sizeof(path), MEMCG_SYSFS_PATH
1166 "apps/uid_%d/pid_%d/memory.soft_limit_in_bytes",
1167 params.uid, params.pid);
Suren Baghdasaryanb0bda552018-05-18 14:42:00 -07001168 snprintf(val, sizeof(val), "%d", soft_limit_mult * EIGHT_MEGA);
Suren Baghdasaryanbf919ff2018-05-21 19:48:47 -07001169
1170 /*
1171 * system_server process has no memcg under /dev/memcg/apps but should be
1172 * registered with lmkd. This is the best way so far to identify it.
1173 */
1174 is_system_server = (params.oomadj == SYSTEM_ADJ &&
1175 (pwdrec = getpwnam("system")) != NULL &&
1176 params.uid == pwdrec->pw_uid);
1177 writefilestring(path, val, !is_system_server);
Robert Benea58d6a132017-06-01 16:32:31 -07001178 }
1179
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -08001180 procp = pid_lookup(params.pid);
Todd Poynorc58c5142013-07-09 19:35:14 -07001181 if (!procp) {
Suren Baghdasaryana10157c2019-07-19 10:55:39 -07001182 int pidfd = -1;
1183
1184 if (pidfd_supported) {
Josh Gao84623be2021-03-18 17:16:08 -07001185 pidfd = TEMP_FAILURE_RETRY(pidfd_open(params.pid, 0));
Suren Baghdasaryana10157c2019-07-19 10:55:39 -07001186 if (pidfd < 0) {
1187 ALOGE("pidfd_open for pid %d failed; errno=%d", params.pid, errno);
Todd Poynorc58c5142013-07-09 19:35:14 -07001188 return;
1189 }
Suren Baghdasaryana10157c2019-07-19 10:55:39 -07001190 }
Todd Poynorc58c5142013-07-09 19:35:14 -07001191
Tom Cherry43f3d2b2019-12-04 12:46:57 -08001192 procp = static_cast<struct proc*>(calloc(1, sizeof(struct proc)));
Suren Baghdasaryana10157c2019-07-19 10:55:39 -07001193 if (!procp) {
1194 // Oh, the irony. May need to rebuild our state.
1195 return;
1196 }
1197
1198 procp->pid = params.pid;
1199 procp->pidfd = pidfd;
1200 procp->uid = params.uid;
Suren Baghdasaryan945658a2019-10-18 11:16:52 -07001201 procp->reg_pid = cred->pid;
Suren Baghdasaryana10157c2019-07-19 10:55:39 -07001202 procp->oomadj = params.oomadj;
1203 proc_insert(procp);
Todd Poynorc58c5142013-07-09 19:35:14 -07001204 } else {
Suren Baghdasaryan945658a2019-10-18 11:16:52 -07001205 if (!claim_record(procp, cred->pid)) {
1206 char buf[LINE_MAX];
Suren Baghdasaryan9f1be122021-04-23 13:39:37 -07001207 char *taskname = proc_get_name(cred->pid, buf, sizeof(buf));
Suren Baghdasaryan945658a2019-10-18 11:16:52 -07001208 /* Only registrant of the record can remove it */
1209 ALOGE("%s (%d, %d) attempts to modify a process registered by another client",
Suren Baghdasaryan9f1be122021-04-23 13:39:37 -07001210 taskname ? taskname : "A process ", cred->uid, cred->pid);
Suren Baghdasaryan945658a2019-10-18 11:16:52 -07001211 return;
1212 }
Todd Poynorc58c5142013-07-09 19:35:14 -07001213 proc_unslot(procp);
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -08001214 procp->oomadj = params.oomadj;
Todd Poynorc58c5142013-07-09 19:35:14 -07001215 proc_slot(procp);
1216 }
1217}
1218
Suren Baghdasaryan945658a2019-10-18 11:16:52 -07001219static void cmd_procremove(LMKD_CTRL_PACKET packet, struct ucred *cred) {
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -08001220 struct lmk_procremove params;
Suren Baghdasaryan945658a2019-10-18 11:16:52 -07001221 struct proc *procp;
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -08001222
George Burgess IV3b36b902019-10-02 11:22:55 -07001223 lmkd_pack_get_procremove(packet, &params);
Suren Baghdasaryan945658a2019-10-18 11:16:52 -07001224
Mark Salyzyn5cc80b32018-03-21 12:24:58 -07001225 if (use_inkernel_interface) {
Jing Ji5c480962019-12-04 09:22:05 -08001226 /*
1227 * Perform an extra check before the pid is removed, after which it
1228 * will be impossible for poll_kernel to get the taskname. poll_kernel()
1229 * is potentially a long-running blocking function; however this method
1230 * handles AMS requests but does not block AMS.
1231 */
1232 poll_kernel(kpoll_fd);
1233
1234 stats_remove_taskname(params.pid);
Todd Poynorc58c5142013-07-09 19:35:14 -07001235 return;
Mark Salyzyn5cc80b32018-03-21 12:24:58 -07001236 }
Todd Poynorc58c5142013-07-09 19:35:14 -07001237
Suren Baghdasaryan945658a2019-10-18 11:16:52 -07001238 procp = pid_lookup(params.pid);
1239 if (!procp) {
1240 return;
1241 }
1242
1243 if (!claim_record(procp, cred->pid)) {
1244 char buf[LINE_MAX];
Suren Baghdasaryan9f1be122021-04-23 13:39:37 -07001245 char *taskname = proc_get_name(cred->pid, buf, sizeof(buf));
Suren Baghdasaryan945658a2019-10-18 11:16:52 -07001246 /* Only registrant of the record can remove it */
1247 ALOGE("%s (%d, %d) attempts to unregister a process registered by another client",
Suren Baghdasaryan9f1be122021-04-23 13:39:37 -07001248 taskname ? taskname : "A process ", cred->uid, cred->pid);
Suren Baghdasaryan945658a2019-10-18 11:16:52 -07001249 return;
1250 }
1251
Suren Baghdasaryan8b00c6d2018-10-12 11:28:33 -07001252 /*
1253 * WARNING: After pid_remove() procp is freed and can't be used!
1254 * Therefore placed at the end of the function.
1255 */
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -08001256 pid_remove(params.pid);
Todd Poynorc58c5142013-07-09 19:35:14 -07001257}
1258
Suren Baghdasaryan945658a2019-10-18 11:16:52 -07001259static void cmd_procpurge(struct ucred *cred) {
Suren Baghdasaryan83df0082018-10-10 14:17:17 -07001260 int i;
1261 struct proc *procp;
1262 struct proc *next;
1263
1264 if (use_inkernel_interface) {
Jim Blackler90853b62019-09-10 15:30:05 +01001265 stats_purge_tasknames();
Suren Baghdasaryan83df0082018-10-10 14:17:17 -07001266 return;
1267 }
1268
Suren Baghdasaryan83df0082018-10-10 14:17:17 -07001269 for (i = 0; i < PIDHASH_SZ; i++) {
1270 procp = pidhash[i];
1271 while (procp) {
1272 next = procp->pidhash_next;
Suren Baghdasaryan945658a2019-10-18 11:16:52 -07001273 /* Purge only records created by the requestor */
1274 if (claim_record(procp, cred->pid)) {
1275 pid_remove(procp->pid);
1276 }
Suren Baghdasaryan83df0082018-10-10 14:17:17 -07001277 procp = next;
1278 }
1279 }
Suren Baghdasaryan83df0082018-10-10 14:17:17 -07001280}
1281
Suren Baghdasaryan36baf442019-12-23 11:37:34 -08001282static void cmd_subscribe(int dsock_idx, LMKD_CTRL_PACKET packet) {
1283 struct lmk_subscribe params;
1284
1285 lmkd_pack_get_subscribe(packet, &params);
1286 data_sock[dsock_idx].async_event_mask |= 1 << params.evt_type;
1287}
1288
Suren Baghdasaryana7394ea2018-10-12 11:07:40 -07001289static void inc_killcnt(int oomadj) {
1290 int slot = ADJTOSLOT(oomadj);
1291 uint8_t idx = killcnt_idx[slot];
1292
1293 if (idx == KILLCNT_INVALID_IDX) {
1294 /* index is not assigned for this oomadj */
1295 if (killcnt_free_idx < MAX_DISTINCT_OOM_ADJ) {
1296 killcnt_idx[slot] = killcnt_free_idx;
1297 killcnt[killcnt_free_idx] = 1;
1298 killcnt_free_idx++;
1299 } else {
1300 ALOGW("Number of distinct oomadj levels exceeds %d",
1301 MAX_DISTINCT_OOM_ADJ);
1302 }
1303 } else {
1304 /*
1305 * wraparound is highly unlikely and is detectable using total
1306 * counter because it has to be equal to the sum of all counters
1307 */
1308 killcnt[idx]++;
1309 }
1310 /* increment total kill counter */
1311 killcnt_total++;
1312}
1313
1314static int get_killcnt(int min_oomadj, int max_oomadj) {
1315 int slot;
1316 int count = 0;
1317
1318 if (min_oomadj > max_oomadj)
1319 return 0;
1320
1321 /* special case to get total kill count */
1322 if (min_oomadj > OOM_SCORE_ADJ_MAX)
1323 return killcnt_total;
1324
1325 while (min_oomadj <= max_oomadj &&
1326 (slot = ADJTOSLOT(min_oomadj)) < ADJTOSLOT_COUNT) {
1327 uint8_t idx = killcnt_idx[slot];
1328 if (idx != KILLCNT_INVALID_IDX) {
1329 count += killcnt[idx];
1330 }
1331 min_oomadj++;
1332 }
1333
1334 return count;
1335}
1336
1337static int cmd_getkillcnt(LMKD_CTRL_PACKET packet) {
1338 struct lmk_getkillcnt params;
1339
1340 if (use_inkernel_interface) {
1341 /* kernel driver does not expose this information */
1342 return 0;
1343 }
1344
1345 lmkd_pack_get_getkillcnt(packet, &params);
1346
1347 return get_killcnt(params.min_oomadj, params.max_oomadj);
1348}
1349
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -08001350static void cmd_target(int ntargets, LMKD_CTRL_PACKET packet) {
Todd Poynorc58c5142013-07-09 19:35:14 -07001351 int i;
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -08001352 struct lmk_target target;
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -07001353 char minfree_str[PROPERTY_VALUE_MAX];
1354 char *pstr = minfree_str;
1355 char *pend = minfree_str + sizeof(minfree_str);
1356 static struct timespec last_req_tm;
1357 struct timespec curr_tm;
Todd Poynorc58c5142013-07-09 19:35:14 -07001358
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -07001359 if (ntargets < 1 || ntargets > (int)ARRAY_SIZE(lowmem_adj))
Todd Poynorc58c5142013-07-09 19:35:14 -07001360 return;
1361
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -07001362 /*
1363 * Ratelimit minfree updates to once per TARGET_UPDATE_MIN_INTERVAL_MS
1364 * to prevent DoS attacks
1365 */
1366 if (clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm) != 0) {
1367 ALOGE("Failed to get current time");
1368 return;
1369 }
1370
1371 if (get_time_diff_ms(&last_req_tm, &curr_tm) <
1372 TARGET_UPDATE_MIN_INTERVAL_MS) {
1373 ALOGE("Ignoring frequent updated to lmkd limits");
1374 return;
1375 }
1376
1377 last_req_tm = curr_tm;
1378
Todd Poynorc58c5142013-07-09 19:35:14 -07001379 for (i = 0; i < ntargets; i++) {
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -08001380 lmkd_pack_get_target(packet, i, &target);
1381 lowmem_minfree[i] = target.minfree;
1382 lowmem_adj[i] = target.oom_adj_score;
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -07001383
1384 pstr += snprintf(pstr, pend - pstr, "%d:%d,", target.minfree,
1385 target.oom_adj_score);
1386 if (pstr >= pend) {
1387 /* if no more space in the buffer then terminate the loop */
1388 pstr = pend;
1389 break;
1390 }
Todd Poynorc58c5142013-07-09 19:35:14 -07001391 }
1392
1393 lowmem_targets_size = ntargets;
1394
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -07001395 /* Override the last extra comma */
1396 pstr[-1] = '\0';
1397 property_set("sys.lmk.minfree_levels", minfree_str);
1398
Robert Benea7878c9b2017-09-11 16:53:28 -07001399 if (has_inkernel_module) {
Todd Poynorc58c5142013-07-09 19:35:14 -07001400 char minfreestr[128];
1401 char killpriostr[128];
1402
1403 minfreestr[0] = '\0';
1404 killpriostr[0] = '\0';
1405
1406 for (i = 0; i < lowmem_targets_size; i++) {
1407 char val[40];
1408
1409 if (i) {
1410 strlcat(minfreestr, ",", sizeof(minfreestr));
1411 strlcat(killpriostr, ",", sizeof(killpriostr));
1412 }
1413
Robert Benea7878c9b2017-09-11 16:53:28 -07001414 snprintf(val, sizeof(val), "%d", use_inkernel_interface ? lowmem_minfree[i] : 0);
Todd Poynorc58c5142013-07-09 19:35:14 -07001415 strlcat(minfreestr, val, sizeof(minfreestr));
Robert Benea7878c9b2017-09-11 16:53:28 -07001416 snprintf(val, sizeof(val), "%d", use_inkernel_interface ? lowmem_adj[i] : 0);
Todd Poynorc58c5142013-07-09 19:35:14 -07001417 strlcat(killpriostr, val, sizeof(killpriostr));
1418 }
1419
Suren Baghdasaryanf584fff2018-03-20 13:53:17 -07001420 writefilestring(INKERNEL_MINFREE_PATH, minfreestr, true);
1421 writefilestring(INKERNEL_ADJ_PATH, killpriostr, true);
Todd Poynorc58c5142013-07-09 19:35:14 -07001422 }
1423}
1424
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08001425static void ctrl_command_handler(int dsock_idx) {
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -08001426 LMKD_CTRL_PACKET packet;
Suren Baghdasaryan945658a2019-10-18 11:16:52 -07001427 struct ucred cred;
Todd Poynorc58c5142013-07-09 19:35:14 -07001428 int len;
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -08001429 enum lmk_cmd cmd;
Todd Poynorc58c5142013-07-09 19:35:14 -07001430 int nargs;
1431 int targets;
Suren Baghdasaryana7394ea2018-10-12 11:07:40 -07001432 int kill_cnt;
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07001433 int result;
Todd Poynorc58c5142013-07-09 19:35:14 -07001434
Suren Baghdasaryan945658a2019-10-18 11:16:52 -07001435 len = ctrl_data_read(dsock_idx, (char *)packet, CTRL_PACKET_MAX_SIZE, &cred);
Todd Poynorc58c5142013-07-09 19:35:14 -07001436 if (len <= 0)
1437 return;
1438
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -08001439 if (len < (int)sizeof(int)) {
1440 ALOGE("Wrong control socket read length len=%d", len);
1441 return;
1442 }
1443
1444 cmd = lmkd_pack_get_cmd(packet);
Todd Poynorc58c5142013-07-09 19:35:14 -07001445 nargs = len / sizeof(int) - 1;
1446 if (nargs < 0)
1447 goto wronglen;
1448
Todd Poynorc58c5142013-07-09 19:35:14 -07001449 switch(cmd) {
1450 case LMK_TARGET:
1451 targets = nargs / 2;
1452 if (nargs & 0x1 || targets > (int)ARRAY_SIZE(lowmem_adj))
1453 goto wronglen;
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -08001454 cmd_target(targets, packet);
Todd Poynorc58c5142013-07-09 19:35:14 -07001455 break;
1456 case LMK_PROCPRIO:
Suren Baghdasaryana93503e2019-10-22 17:12:01 -07001457 /* process type field is optional for backward compatibility */
1458 if (nargs < 3 || nargs > 4)
Todd Poynorc58c5142013-07-09 19:35:14 -07001459 goto wronglen;
Suren Baghdasaryana93503e2019-10-22 17:12:01 -07001460 cmd_procprio(packet, nargs, &cred);
Todd Poynorc58c5142013-07-09 19:35:14 -07001461 break;
1462 case LMK_PROCREMOVE:
1463 if (nargs != 1)
1464 goto wronglen;
Suren Baghdasaryan945658a2019-10-18 11:16:52 -07001465 cmd_procremove(packet, &cred);
Todd Poynorc58c5142013-07-09 19:35:14 -07001466 break;
Suren Baghdasaryan83df0082018-10-10 14:17:17 -07001467 case LMK_PROCPURGE:
1468 if (nargs != 0)
1469 goto wronglen;
Suren Baghdasaryan945658a2019-10-18 11:16:52 -07001470 cmd_procpurge(&cred);
Suren Baghdasaryan83df0082018-10-10 14:17:17 -07001471 break;
Suren Baghdasaryana7394ea2018-10-12 11:07:40 -07001472 case LMK_GETKILLCNT:
1473 if (nargs != 2)
1474 goto wronglen;
1475 kill_cnt = cmd_getkillcnt(packet);
1476 len = lmkd_pack_set_getkillcnt_repl(packet, kill_cnt);
1477 if (ctrl_data_write(dsock_idx, (char *)packet, len) != len)
1478 return;
1479 break;
Suren Baghdasaryan36baf442019-12-23 11:37:34 -08001480 case LMK_SUBSCRIBE:
1481 if (nargs != 1)
1482 goto wronglen;
1483 cmd_subscribe(dsock_idx, packet);
1484 break;
Jing Ji5c480962019-12-04 09:22:05 -08001485 case LMK_PROCKILL:
1486 /* This command code is NOT expected at all */
1487 ALOGE("Received unexpected command code %d", cmd);
1488 break;
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07001489 case LMK_UPDATE_PROPS:
1490 if (nargs != 0)
1491 goto wronglen;
1492 update_props();
1493 if (!use_inkernel_interface) {
1494 /* Reinitialize monitors to apply new settings */
1495 destroy_monitors();
1496 result = init_monitors() ? 0 : -1;
1497 } else {
1498 result = 0;
1499 }
1500 len = lmkd_pack_set_update_props_repl(packet, result);
1501 if (ctrl_data_write(dsock_idx, (char *)packet, len) != len) {
1502 ALOGE("Failed to report operation results");
1503 }
1504 if (!result) {
1505 ALOGI("Properties reinitilized");
1506 } else {
1507 /* New settings can't be supported, crash to be restarted */
1508 ALOGE("New configuration is not supported. Exiting...");
1509 exit(1);
1510 }
1511 break;
Todd Poynorc58c5142013-07-09 19:35:14 -07001512 default:
1513 ALOGE("Received unknown command code %d", cmd);
1514 return;
1515 }
1516
1517 return;
1518
1519wronglen:
1520 ALOGE("Wrong control socket read length cmd=%d len=%d", cmd, len);
1521}
1522
Suren Baghdasaryane12a0672019-07-15 14:50:49 -07001523static void ctrl_data_handler(int data, uint32_t events,
1524 struct polling_params *poll_params __unused) {
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08001525 if (events & EPOLLIN) {
1526 ctrl_command_handler(data);
Todd Poynorc58c5142013-07-09 19:35:14 -07001527 }
1528}
1529
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08001530static int get_free_dsock() {
1531 for (int i = 0; i < MAX_DATA_CONN; i++) {
1532 if (data_sock[i].sock < 0) {
1533 return i;
1534 }
1535 }
1536 return -1;
1537}
Todd Poynorc58c5142013-07-09 19:35:14 -07001538
Suren Baghdasaryane12a0672019-07-15 14:50:49 -07001539static void ctrl_connect_handler(int data __unused, uint32_t events __unused,
1540 struct polling_params *poll_params __unused) {
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08001541 struct epoll_event epev;
1542 int free_dscock_idx = get_free_dsock();
1543
1544 if (free_dscock_idx < 0) {
1545 /*
1546 * Number of data connections exceeded max supported. This should not
1547 * happen but if it does we drop all existing connections and accept
1548 * the new one. This prevents inactive connections from monopolizing
1549 * data socket and if we drop ActivityManager connection it will
1550 * immediately reconnect.
1551 */
1552 for (int i = 0; i < MAX_DATA_CONN; i++) {
1553 ctrl_data_close(i);
1554 }
1555 free_dscock_idx = 0;
Todd Poynorc58c5142013-07-09 19:35:14 -07001556 }
1557
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08001558 data_sock[free_dscock_idx].sock = accept(ctrl_sock.sock, NULL, NULL);
1559 if (data_sock[free_dscock_idx].sock < 0) {
Todd Poynorc58c5142013-07-09 19:35:14 -07001560 ALOGE("lmkd control socket accept failed; errno=%d", errno);
1561 return;
1562 }
1563
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08001564 ALOGI("lmkd data connection established");
1565 /* use data to store data connection idx */
1566 data_sock[free_dscock_idx].handler_info.data = free_dscock_idx;
1567 data_sock[free_dscock_idx].handler_info.handler = ctrl_data_handler;
Suren Baghdasaryan36baf442019-12-23 11:37:34 -08001568 data_sock[free_dscock_idx].async_event_mask = 0;
Todd Poynorc58c5142013-07-09 19:35:14 -07001569 epev.events = EPOLLIN;
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08001570 epev.data.ptr = (void *)&(data_sock[free_dscock_idx].handler_info);
1571 if (epoll_ctl(epollfd, EPOLL_CTL_ADD, data_sock[free_dscock_idx].sock, &epev) == -1) {
Todd Poynorc58c5142013-07-09 19:35:14 -07001572 ALOGE("epoll_ctl for data connection socket failed; errno=%d", errno);
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08001573 ctrl_data_close(free_dscock_idx);
Todd Poynorc58c5142013-07-09 19:35:14 -07001574 return;
1575 }
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08001576 maxevents++;
Todd Poynorc58c5142013-07-09 19:35:14 -07001577}
1578
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001579/*
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07001580 * /proc/zoneinfo parsing routines
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001581 * Expected file format is:
1582 *
1583 * Node <node_id>, zone <zone_name>
1584 * (
1585 * per-node stats
1586 * (<per-node field name> <value>)+
1587 * )?
1588 * (pages free <value>
1589 * (<per-zone field name> <value>)+
1590 * pagesets
1591 * (<unused fields>)*
1592 * )+
1593 * ...
1594 */
1595static void zoneinfo_parse_protection(char *buf, struct zoneinfo_zone *zone) {
1596 int zone_idx;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001597 int64_t max = 0;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001598 char *save_ptr;
1599
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001600 for (buf = strtok_r(buf, "(), ", &save_ptr), zone_idx = 0;
1601 buf && zone_idx < MAX_NR_ZONES;
1602 buf = strtok_r(NULL, "), ", &save_ptr), zone_idx++) {
1603 long long zoneval = strtoll(buf, &buf, 0);
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001604 if (zoneval > max) {
1605 max = (zoneval > INT64_MAX) ? INT64_MAX : zoneval;
1606 }
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001607 zone->protection[zone_idx] = zoneval;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001608 }
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001609 zone->max_protection = max;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001610}
1611
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001612static int zoneinfo_parse_zone(char **buf, struct zoneinfo_zone *zone) {
1613 for (char *line = strtok_r(NULL, "\n", buf); line;
1614 line = strtok_r(NULL, "\n", buf)) {
1615 char *cp;
1616 char *ap;
1617 char *save_ptr;
1618 int64_t val;
1619 int field_idx;
1620 enum field_match_result match_res;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001621
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001622 cp = strtok_r(line, " ", &save_ptr);
1623 if (!cp) {
1624 return false;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001625 }
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001626
1627 field_idx = find_field(cp, zoneinfo_zone_spec_field_names, ZI_ZONE_SPEC_FIELD_COUNT);
1628 if (field_idx >= 0) {
1629 /* special field */
1630 if (field_idx == ZI_ZONE_SPEC_PAGESETS) {
1631 /* no mode fields we are interested in */
1632 return true;
1633 }
1634
1635 /* protection field */
1636 ap = strtok_r(NULL, ")", &save_ptr);
1637 if (ap) {
1638 zoneinfo_parse_protection(ap, zone);
1639 }
1640 continue;
1641 }
1642
1643 ap = strtok_r(NULL, " ", &save_ptr);
1644 if (!ap) {
1645 continue;
1646 }
1647
1648 match_res = match_field(cp, ap, zoneinfo_zone_field_names, ZI_ZONE_FIELD_COUNT,
1649 &val, &field_idx);
1650 if (match_res == PARSE_FAIL) {
1651 return false;
1652 }
1653 if (match_res == PARSE_SUCCESS) {
1654 zone->fields.arr[field_idx] = val;
1655 }
1656 if (field_idx == ZI_ZONE_PRESENT && val == 0) {
1657 /* zone is not populated, stop parsing it */
1658 return true;
1659 }
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001660 }
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001661 return false;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001662}
1663
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001664static int zoneinfo_parse_node(char **buf, struct zoneinfo_node *node) {
1665 int fields_to_match = ZI_NODE_FIELD_COUNT;
1666
1667 for (char *line = strtok_r(NULL, "\n", buf); line;
1668 line = strtok_r(NULL, "\n", buf)) {
1669 char *cp;
1670 char *ap;
1671 char *save_ptr;
1672 int64_t val;
1673 int field_idx;
1674 enum field_match_result match_res;
1675
1676 cp = strtok_r(line, " ", &save_ptr);
1677 if (!cp) {
1678 return false;
1679 }
1680
1681 ap = strtok_r(NULL, " ", &save_ptr);
1682 if (!ap) {
1683 return false;
1684 }
1685
1686 match_res = match_field(cp, ap, zoneinfo_node_field_names, ZI_NODE_FIELD_COUNT,
1687 &val, &field_idx);
1688 if (match_res == PARSE_FAIL) {
1689 return false;
1690 }
1691 if (match_res == PARSE_SUCCESS) {
1692 node->fields.arr[field_idx] = val;
1693 fields_to_match--;
1694 if (!fields_to_match) {
1695 return true;
1696 }
1697 }
1698 }
1699 return false;
1700}
1701
1702static int zoneinfo_parse(struct zoneinfo *zi) {
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001703 static struct reread_data file_data = {
1704 .filename = ZONEINFO_PATH,
1705 .fd = -1,
1706 };
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -07001707 char *buf;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001708 char *save_ptr;
1709 char *line;
Greg Kaiser259984f2019-10-02 07:07:32 -07001710 char zone_name[LINE_MAX + 1];
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001711 struct zoneinfo_node *node = NULL;
1712 int node_idx = 0;
1713 int zone_idx = 0;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001714
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001715 memset(zi, 0, sizeof(struct zoneinfo));
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001716
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -07001717 if ((buf = reread_file(&file_data)) == NULL) {
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001718 return -1;
1719 }
1720
1721 for (line = strtok_r(buf, "\n", &save_ptr); line;
1722 line = strtok_r(NULL, "\n", &save_ptr)) {
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001723 int node_id;
1724 if (sscanf(line, "Node %d, zone %" STRINGIFY(LINE_MAX) "s", &node_id, zone_name) == 2) {
1725 if (!node || node->id != node_id) {
1726 /* new node is found */
1727 if (node) {
1728 node->zone_count = zone_idx + 1;
1729 node_idx++;
1730 if (node_idx == MAX_NR_NODES) {
1731 /* max node count exceeded */
1732 ALOGE("%s parse error", file_data.filename);
1733 return -1;
1734 }
1735 }
1736 node = &zi->nodes[node_idx];
1737 node->id = node_id;
1738 zone_idx = 0;
1739 if (!zoneinfo_parse_node(&save_ptr, node)) {
1740 ALOGE("%s parse error", file_data.filename);
1741 return -1;
1742 }
1743 } else {
1744 /* new zone is found */
1745 zone_idx++;
1746 }
1747 if (!zoneinfo_parse_zone(&save_ptr, &node->zones[zone_idx])) {
1748 ALOGE("%s parse error", file_data.filename);
1749 return -1;
1750 }
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001751 }
1752 }
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001753 if (!node) {
1754 ALOGE("%s parse error", file_data.filename);
1755 return -1;
1756 }
1757 node->zone_count = zone_idx + 1;
1758 zi->node_count = node_idx + 1;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001759
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001760 /* calculate totals fields */
1761 for (node_idx = 0; node_idx < zi->node_count; node_idx++) {
1762 node = &zi->nodes[node_idx];
1763 for (zone_idx = 0; zone_idx < node->zone_count; zone_idx++) {
1764 struct zoneinfo_zone *zone = &zi->nodes[node_idx].zones[zone_idx];
1765 zi->totalreserve_pages += zone->max_protection + zone->fields.field.high;
1766 }
1767 zi->total_inactive_file += node->fields.field.nr_inactive_file;
1768 zi->total_active_file += node->fields.field.nr_active_file;
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001769 }
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001770 return 0;
1771}
1772
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07001773/* /proc/meminfo parsing routines */
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001774static bool meminfo_parse_line(char *line, union meminfo *mi) {
1775 char *cp = line;
1776 char *ap;
1777 char *save_ptr;
1778 int64_t val;
1779 int field_idx;
1780 enum field_match_result match_res;
1781
1782 cp = strtok_r(line, " ", &save_ptr);
1783 if (!cp) {
1784 return false;
1785 }
1786
1787 ap = strtok_r(NULL, " ", &save_ptr);
1788 if (!ap) {
1789 return false;
1790 }
1791
1792 match_res = match_field(cp, ap, meminfo_field_names, MI_FIELD_COUNT,
1793 &val, &field_idx);
1794 if (match_res == PARSE_SUCCESS) {
1795 mi->arr[field_idx] = val / page_k;
1796 }
1797 return (match_res != PARSE_FAIL);
1798}
1799
Suren Baghdasaryan940e7cf2021-05-27 18:15:44 -07001800static int64_t read_gpu_total_kb() {
1801 static int fd = android::bpf::bpfFdGet(
1802 "/sys/fs/bpf/map_gpu_mem_gpu_mem_total_map", BPF_F_RDONLY);
1803 static constexpr uint64_t kBpfKeyGpuTotalUsage = 0;
1804 uint64_t value;
1805
1806 if (fd < 0) {
1807 return 0;
1808 }
1809
1810 return android::bpf::findMapEntry(fd, &kBpfKeyGpuTotalUsage, &value)
1811 ? 0
1812 : (int32_t)(value / 1024);
1813}
1814
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001815static int meminfo_parse(union meminfo *mi) {
1816 static struct reread_data file_data = {
1817 .filename = MEMINFO_PATH,
1818 .fd = -1,
1819 };
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -07001820 char *buf;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001821 char *save_ptr;
1822 char *line;
1823
1824 memset(mi, 0, sizeof(union meminfo));
1825
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -07001826 if ((buf = reread_file(&file_data)) == NULL) {
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001827 return -1;
1828 }
1829
1830 for (line = strtok_r(buf, "\n", &save_ptr); line;
1831 line = strtok_r(NULL, "\n", &save_ptr)) {
1832 if (!meminfo_parse_line(line, mi)) {
1833 ALOGE("%s parse error", file_data.filename);
1834 return -1;
1835 }
1836 }
1837 mi->field.nr_file_pages = mi->field.cached + mi->field.swap_cached +
1838 mi->field.buffers;
Suren Baghdasaryan940e7cf2021-05-27 18:15:44 -07001839 mi->field.total_gpu_kb = read_gpu_total_kb();
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001840
1841 return 0;
1842}
1843
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07001844/* /proc/vmstat parsing routines */
1845static bool vmstat_parse_line(char *line, union vmstat *vs) {
1846 char *cp;
1847 char *ap;
1848 char *save_ptr;
1849 int64_t val;
1850 int field_idx;
1851 enum field_match_result match_res;
1852
1853 cp = strtok_r(line, " ", &save_ptr);
1854 if (!cp) {
1855 return false;
1856 }
1857
1858 ap = strtok_r(NULL, " ", &save_ptr);
1859 if (!ap) {
1860 return false;
1861 }
1862
1863 match_res = match_field(cp, ap, vmstat_field_names, VS_FIELD_COUNT,
1864 &val, &field_idx);
1865 if (match_res == PARSE_SUCCESS) {
1866 vs->arr[field_idx] = val;
1867 }
1868 return (match_res != PARSE_FAIL);
1869}
1870
1871static int vmstat_parse(union vmstat *vs) {
1872 static struct reread_data file_data = {
1873 .filename = VMSTAT_PATH,
1874 .fd = -1,
1875 };
1876 char *buf;
1877 char *save_ptr;
1878 char *line;
1879
1880 memset(vs, 0, sizeof(union vmstat));
1881
1882 if ((buf = reread_file(&file_data)) == NULL) {
1883 return -1;
1884 }
1885
1886 for (line = strtok_r(buf, "\n", &save_ptr); line;
1887 line = strtok_r(NULL, "\n", &save_ptr)) {
1888 if (!vmstat_parse_line(line, vs)) {
1889 ALOGE("%s parse error", file_data.filename);
1890 return -1;
1891 }
1892 }
1893
1894 return 0;
1895}
1896
Suren Baghdasaryand7b4fcb2020-07-23 18:00:43 -07001897enum wakeup_reason {
1898 Event,
1899 Polling
1900};
1901
1902struct wakeup_info {
1903 struct timespec wakeup_tm;
1904 struct timespec prev_wakeup_tm;
1905 struct timespec last_event_tm;
1906 int wakeups_since_event;
1907 int skipped_wakeups;
1908};
1909
1910/*
1911 * After the initial memory pressure event is received lmkd schedules periodic wakeups to check
1912 * the memory conditions and kill if needed (polling). This is done because pressure events are
1913 * rate-limited and memory conditions can change in between events. Therefore after the initial
1914 * event there might be multiple wakeups. This function records the wakeup information such as the
1915 * timestamps of the last event and the last wakeup, the number of wakeups since the last event
1916 * and how many of those wakeups were skipped (some wakeups are skipped if previously killed
1917 * process is still freeing its memory).
1918 */
1919static void record_wakeup_time(struct timespec *tm, enum wakeup_reason reason,
1920 struct wakeup_info *wi) {
1921 wi->prev_wakeup_tm = wi->wakeup_tm;
1922 wi->wakeup_tm = *tm;
1923 if (reason == Event) {
1924 wi->last_event_tm = *tm;
1925 wi->wakeups_since_event = 0;
1926 wi->skipped_wakeups = 0;
1927 } else {
1928 wi->wakeups_since_event++;
1929 }
1930}
1931
Suren Baghdasaryan39b54802021-08-09 15:10:25 -07001932struct kill_info {
1933 enum kill_reasons kill_reason;
1934 const char *kill_desc;
1935 int thrashing;
1936 int max_thrashing;
1937};
1938
Ioannis Ilkos279268a2020-08-01 10:50:40 +01001939static void killinfo_log(struct proc* procp, int min_oom_score, int rss_kb,
Suren Baghdasaryan39b54802021-08-09 15:10:25 -07001940 int swap_kb, struct kill_info *ki, union meminfo *mi,
Suren Baghdasaryand7b4fcb2020-07-23 18:00:43 -07001941 struct wakeup_info *wi, struct timespec *tm) {
Suren Baghdasaryan12cacae2019-09-16 12:06:30 -07001942 /* log process information */
1943 android_log_write_int32(ctx, procp->pid);
1944 android_log_write_int32(ctx, procp->uid);
1945 android_log_write_int32(ctx, procp->oomadj);
1946 android_log_write_int32(ctx, min_oom_score);
Ioannis Ilkos279268a2020-08-01 10:50:40 +01001947 android_log_write_int32(ctx, (int32_t)min(rss_kb, INT32_MAX));
Suren Baghdasaryan39b54802021-08-09 15:10:25 -07001948 android_log_write_int32(ctx, ki ? ki->kill_reason : NONE);
Suren Baghdasaryan12cacae2019-09-16 12:06:30 -07001949
1950 /* log meminfo fields */
Suren Baghdasaryan08bfa982018-07-26 16:34:27 -07001951 for (int field_idx = 0; field_idx < MI_FIELD_COUNT; field_idx++) {
1952 android_log_write_int32(ctx, (int32_t)min(mi->arr[field_idx] * page_k, INT32_MAX));
1953 }
1954
Suren Baghdasaryand7b4fcb2020-07-23 18:00:43 -07001955 /* log lmkd wakeup information */
1956 android_log_write_int32(ctx, (int32_t)get_time_diff_ms(&wi->last_event_tm, tm));
1957 android_log_write_int32(ctx, (int32_t)get_time_diff_ms(&wi->prev_wakeup_tm, tm));
1958 android_log_write_int32(ctx, wi->wakeups_since_event);
1959 android_log_write_int32(ctx, wi->skipped_wakeups);
Ioannis Ilkos282437f2021-03-04 17:50:05 +00001960 android_log_write_int32(ctx, (int32_t)min(swap_kb, INT32_MAX));
Suren Baghdasaryan940e7cf2021-05-27 18:15:44 -07001961 android_log_write_int32(ctx, (int32_t)mi->field.total_gpu_kb);
Suren Baghdasaryan39b54802021-08-09 15:10:25 -07001962 if (ki) {
1963 android_log_write_int32(ctx, ki->thrashing);
1964 android_log_write_int32(ctx, ki->max_thrashing);
1965 } else {
1966 android_log_write_int32(ctx, 0);
1967 android_log_write_int32(ctx, 0);
1968 }
Suren Baghdasaryand7b4fcb2020-07-23 18:00:43 -07001969
Suren Baghdasaryan08bfa982018-07-26 16:34:27 -07001970 android_log_write_list(ctx, LOG_ID_EVENTS);
1971 android_log_reset(ctx);
1972}
1973
Todd Poynorc58c5142013-07-09 19:35:14 -07001974static struct proc *proc_adj_lru(int oomadj) {
1975 return (struct proc *)adjslot_tail(&procadjslot_list[ADJTOSLOT(oomadj)]);
1976}
1977
Suren Baghdasaryaneb7c5492017-12-08 13:17:06 -08001978static struct proc *proc_get_heaviest(int oomadj) {
1979 struct adjslot_list *head = &procadjslot_list[ADJTOSLOT(oomadj)];
1980 struct adjslot_list *curr = head->next;
1981 struct proc *maxprocp = NULL;
1982 int maxsize = 0;
1983 while (curr != head) {
1984 int pid = ((struct proc *)curr)->pid;
1985 int tasksize = proc_get_size(pid);
Suren Baghdasaryan5263aa72021-04-29 15:28:57 -07001986 if (tasksize < 0) {
Suren Baghdasaryaneb7c5492017-12-08 13:17:06 -08001987 struct adjslot_list *next = curr->next;
1988 pid_remove(pid);
1989 curr = next;
1990 } else {
1991 if (tasksize > maxsize) {
1992 maxsize = tasksize;
1993 maxprocp = (struct proc *)curr;
1994 }
1995 curr = curr->next;
1996 }
1997 }
1998 return maxprocp;
1999}
2000
Wei Wangf1ee2e12018-11-21 00:11:44 -08002001static void set_process_group_and_prio(int pid, SchedPolicy sp, int prio) {
2002 DIR* d;
2003 char proc_path[PATH_MAX];
2004 struct dirent* de;
2005
2006 snprintf(proc_path, sizeof(proc_path), "/proc/%d/task", pid);
2007 if (!(d = opendir(proc_path))) {
2008 ALOGW("Failed to open %s; errno=%d: process pid(%d) might have died", proc_path, errno,
2009 pid);
2010 return;
2011 }
2012
2013 while ((de = readdir(d))) {
2014 int t_pid;
2015
2016 if (de->d_name[0] == '.') continue;
2017 t_pid = atoi(de->d_name);
2018
2019 if (!t_pid) {
2020 ALOGW("Failed to get t_pid for '%s' of pid(%d)", de->d_name, pid);
2021 continue;
2022 }
2023
2024 if (setpriority(PRIO_PROCESS, t_pid, prio) && errno != ESRCH) {
2025 ALOGW("Unable to raise priority of killing t_pid (%d): errno=%d", t_pid, errno);
2026 }
2027
2028 if (set_cpuset_policy(t_pid, sp)) {
2029 ALOGW("Failed to set_cpuset_policy on pid(%d) t_pid(%d) to %d", pid, t_pid, (int)sp);
2030 continue;
2031 }
2032 }
2033 closedir(d);
2034}
2035
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002036static bool is_kill_pending(void) {
2037 char buf[24];
2038
2039 if (last_kill_pid_or_fd < 0) {
2040 return false;
2041 }
2042
2043 if (pidfd_supported) {
2044 return true;
2045 }
2046
2047 /* when pidfd is not supported base the decision on /proc/<pid> existence */
2048 snprintf(buf, sizeof(buf), "/proc/%d/", last_kill_pid_or_fd);
2049 if (access(buf, F_OK) == 0) {
2050 return true;
2051 }
2052
2053 return false;
2054}
2055
2056static bool is_waiting_for_kill(void) {
2057 return pidfd_supported && last_kill_pid_or_fd >= 0;
2058}
2059
2060static void stop_wait_for_proc_kill(bool finished) {
2061 struct epoll_event epev;
2062
2063 if (last_kill_pid_or_fd < 0) {
2064 return;
2065 }
2066
2067 if (debug_process_killing) {
2068 struct timespec curr_tm;
2069
2070 if (clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm) != 0) {
2071 /*
2072 * curr_tm is used here merely to report kill duration, so this failure is not fatal.
2073 * Log an error and continue.
2074 */
2075 ALOGE("Failed to get current time");
2076 }
2077
2078 if (finished) {
2079 ALOGI("Process got killed in %ldms",
2080 get_time_diff_ms(&last_kill_tm, &curr_tm));
2081 } else {
2082 ALOGI("Stop waiting for process kill after %ldms",
2083 get_time_diff_ms(&last_kill_tm, &curr_tm));
2084 }
2085 }
2086
2087 if (pidfd_supported) {
2088 /* unregister fd */
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07002089 if (epoll_ctl(epollfd, EPOLL_CTL_DEL, last_kill_pid_or_fd, &epev)) {
2090 // Log an error and keep going
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002091 ALOGE("epoll_ctl for last killed process failed; errno=%d", errno);
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002092 }
2093 maxevents--;
2094 close(last_kill_pid_or_fd);
2095 }
2096
2097 last_kill_pid_or_fd = -1;
2098}
2099
2100static void kill_done_handler(int data __unused, uint32_t events __unused,
2101 struct polling_params *poll_params) {
2102 stop_wait_for_proc_kill(true);
2103 poll_params->update = POLLING_RESUME;
2104}
2105
Suren Baghdasaryana10157c2019-07-19 10:55:39 -07002106static void start_wait_for_proc_kill(int pid_or_fd) {
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002107 static struct event_handler_info kill_done_hinfo = { 0, kill_done_handler };
2108 struct epoll_event epev;
2109
2110 if (last_kill_pid_or_fd >= 0) {
2111 /* Should not happen but if it does we should stop previous wait */
2112 ALOGE("Attempt to wait for a kill while another wait is in progress");
2113 stop_wait_for_proc_kill(false);
2114 }
2115
Suren Baghdasaryana10157c2019-07-19 10:55:39 -07002116 last_kill_pid_or_fd = pid_or_fd;
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002117
Suren Baghdasaryana10157c2019-07-19 10:55:39 -07002118 if (!pidfd_supported) {
2119 /* If pidfd is not supported just store PID and exit */
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002120 return;
2121 }
2122
2123 epev.events = EPOLLIN;
2124 epev.data.ptr = (void *)&kill_done_hinfo;
2125 if (epoll_ctl(epollfd, EPOLL_CTL_ADD, last_kill_pid_or_fd, &epev) != 0) {
2126 ALOGE("epoll_ctl for last kill failed; errno=%d", errno);
2127 close(last_kill_pid_or_fd);
2128 last_kill_pid_or_fd = -1;
2129 return;
2130 }
2131 maxevents++;
2132}
Tim Murraya79ec0f2018-10-25 17:05:41 -07002133
Ioannis Ilkos279268a2020-08-01 10:50:40 +01002134/* Kill one process specified by procp. Returns the size (in pages) of the process killed */
Suren Baghdasaryane1604752021-07-22 16:21:21 -07002135static int kill_one_process(struct proc* procp, int min_oom_score, struct kill_info *ki,
2136 union meminfo *mi, struct wakeup_info *wi, struct timespec *tm) {
Colin Cross3d57a512014-07-14 12:39:56 -07002137 int pid = procp->pid;
Suren Baghdasaryana10157c2019-07-19 10:55:39 -07002138 int pidfd = procp->pidfd;
Colin Cross3d57a512014-07-14 12:39:56 -07002139 uid_t uid = procp->uid;
2140 char *taskname;
Colin Cross3d57a512014-07-14 12:39:56 -07002141 int r;
Suren Baghdasaryan8b00c6d2018-10-12 11:28:33 -07002142 int result = -1;
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07002143 struct memory_stat *mem_st;
Suren Baghdasaryan3cc1f132020-09-09 20:19:02 -07002144 struct kill_stat kill_st;
Ioannis Ilkos279268a2020-08-01 10:50:40 +01002145 int64_t tgid;
2146 int64_t rss_kb;
2147 int64_t swap_kb;
2148 char buf[PAGE_SIZE];
Suren Baghdasaryan34928bb2021-07-29 17:02:51 -07002149 char desc[LINE_MAX];
Rajeev Kumar4aba9152018-01-31 17:54:56 -08002150
Ioannis Ilkos279268a2020-08-01 10:50:40 +01002151 if (!read_proc_status(pid, buf, sizeof(buf))) {
2152 goto out;
2153 }
2154 if (!parse_status_tag(buf, PROC_STATUS_TGID_FIELD, &tgid)) {
2155 ALOGE("Unable to parse tgid from /proc/%d/status", pid);
2156 goto out;
2157 }
2158 if (tgid != pid) {
2159 ALOGE("Possible pid reuse detected (pid %d, tgid %" PRId64 ")!", pid, tgid);
2160 goto out;
2161 }
2162 // Zombie processes will not have RSS / Swap fields.
2163 if (!parse_status_tag(buf, PROC_STATUS_RSS_FIELD, &rss_kb)) {
2164 goto out;
2165 }
2166 if (!parse_status_tag(buf, PROC_STATUS_SWAP_FIELD, &swap_kb)) {
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -07002167 goto out;
2168 }
2169
Suren Baghdasaryan632f1c52019-10-04 16:06:55 -07002170 taskname = proc_get_name(pid, buf, sizeof(buf));
Ioannis Ilkos279268a2020-08-01 10:50:40 +01002171 // taskname will point inside buf, do not reuse buf onwards.
Colin Cross3d57a512014-07-14 12:39:56 -07002172 if (!taskname) {
Suren Baghdasaryan8b00c6d2018-10-12 11:28:33 -07002173 goto out;
Colin Cross3d57a512014-07-14 12:39:56 -07002174 }
2175
Ioannis Ilkos279268a2020-08-01 10:50:40 +01002176 mem_st = stats_read_memory_stat(per_app_memcg, pid, uid, rss_kb * 1024, swap_kb * 1024);
Rajeev Kumar4aba9152018-01-31 17:54:56 -08002177
George Burgess IVe849f142021-08-05 06:59:42 +00002178 snprintf(desc, sizeof(desc), "lmk,%d,%d,%d,%d,%d", pid, ki ? (int)ki->kill_reason : -1,
2179 procp->oomadj, min_oom_score, ki ? ki->max_thrashing : -1);
Suren Baghdasaryan34928bb2021-07-29 17:02:51 -07002180 trace_kill_start(pid, desc);
Suren Baghdasaryan03e19872018-01-04 10:43:58 -08002181
Mark Salyzyna00ccd82018-04-09 09:50:32 -07002182 /* CAP_KILL required */
Suren Baghdasaryana10157c2019-07-19 10:55:39 -07002183 if (pidfd < 0) {
2184 start_wait_for_proc_kill(pid);
2185 r = kill(pid, SIGKILL);
2186 } else {
2187 start_wait_for_proc_kill(pidfd);
Josh Gao84623be2021-03-18 17:16:08 -07002188 r = pidfd_send_signal(pidfd, SIGKILL, NULL, 0);
Suren Baghdasaryana10157c2019-07-19 10:55:39 -07002189 }
Wei Wangf1ee2e12018-11-21 00:11:44 -08002190
Suren Baghdasaryan34928bb2021-07-29 17:02:51 -07002191 trace_kill_end();
Suren Baghdasaryanc2e05b62019-09-04 16:44:47 -07002192
2193 if (r) {
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002194 stop_wait_for_proc_kill(false);
Suren Baghdasaryanc2e05b62019-09-04 16:44:47 -07002195 ALOGE("kill(%d): errno=%d", pid, errno);
2196 /* Delete process record even when we fail to kill so that we don't get stuck on it */
2197 goto out;
2198 }
2199
Wei Wangf1ee2e12018-11-21 00:11:44 -08002200 set_process_group_and_prio(pid, SP_FOREGROUND, ANDROID_PRIORITY_HIGHEST);
2201
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002202 last_kill_tm = *tm;
2203
Suren Baghdasaryana7394ea2018-10-12 11:07:40 -07002204 inc_killcnt(procp->oomadj);
Suren Baghdasaryan12cacae2019-09-16 12:06:30 -07002205
Suren Baghdasaryane1604752021-07-22 16:21:21 -07002206 if (ki) {
2207 kill_st.kill_reason = ki->kill_reason;
2208 kill_st.thrashing = ki->thrashing;
2209 kill_st.max_thrashing = ki->max_thrashing;
Ioannis Ilkos48848902021-02-18 19:53:33 +00002210 ALOGI("Kill '%s' (%d), uid %d, oom_score_adj %d to free %" PRId64 "kB rss, %" PRId64
Suren Baghdasaryane1604752021-07-22 16:21:21 -07002211 "kB swap; reason: %s", taskname, pid, uid, procp->oomadj, rss_kb, swap_kb,
2212 ki->kill_desc);
Suren Baghdasaryan89454e62019-07-15 15:50:17 -07002213 } else {
Suren Baghdasaryane1604752021-07-22 16:21:21 -07002214 kill_st.kill_reason = NONE;
2215 kill_st.thrashing = 0;
2216 kill_st.max_thrashing = 0;
Ioannis Ilkos48848902021-02-18 19:53:33 +00002217 ALOGI("Kill '%s' (%d), uid %d, oom_score_adj %d to free %" PRId64 "kB rss, %" PRId64
2218 "kb swap", taskname, pid, uid, procp->oomadj, rss_kb, swap_kb);
Suren Baghdasaryan89454e62019-07-15 15:50:17 -07002219 }
Suren Baghdasaryan39b54802021-08-09 15:10:25 -07002220 killinfo_log(procp, min_oom_score, rss_kb, swap_kb, ki, mi, wi, tm);
Colin Cross3d57a512014-07-14 12:39:56 -07002221
Suren Baghdasaryan3cc1f132020-09-09 20:19:02 -07002222 kill_st.uid = static_cast<int32_t>(uid);
2223 kill_st.taskname = taskname;
Suren Baghdasaryan3cc1f132020-09-09 20:19:02 -07002224 kill_st.oom_score = procp->oomadj;
2225 kill_st.min_oom_score = min_oom_score;
2226 kill_st.free_mem_kb = mi->field.nr_free_pages * page_k;
2227 kill_st.free_swap_kb = mi->field.free_swap * page_k;
2228 stats_write_lmk_kill_occurred(&kill_st, mem_st);
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07002229
Jing Ji5c480962019-12-04 09:22:05 -08002230 ctrl_data_write_lmk_kill_occurred((pid_t)pid, uid);
2231
Ioannis Ilkos279268a2020-08-01 10:50:40 +01002232 result = rss_kb / page_k;
Mark Salyzyn1d5fdf32018-02-04 15:27:23 -08002233
Suren Baghdasaryan8b00c6d2018-10-12 11:28:33 -07002234out:
2235 /*
2236 * WARNING: After pid_remove() procp is freed and can't be used!
2237 * Therefore placed at the end of the function.
2238 */
2239 pid_remove(pid);
2240 return result;
Colin Cross3d57a512014-07-14 12:39:56 -07002241}
2242
2243/*
Chris Morin74b4df92021-02-26 00:00:35 -08002244 * Find one process to kill at or above the given oom_score_adj level.
Suren Baghdasaryan85c31b52018-10-26 11:32:15 -07002245 * Returns size of the killed process.
Colin Cross3d57a512014-07-14 12:39:56 -07002246 */
Suren Baghdasaryane1604752021-07-22 16:21:21 -07002247static int find_and_kill_process(int min_score_adj, struct kill_info *ki, union meminfo *mi,
Suren Baghdasaryan3cc1f132020-09-09 20:19:02 -07002248 struct wakeup_info *wi, struct timespec *tm) {
Colin Cross3d57a512014-07-14 12:39:56 -07002249 int i;
Suren Baghdasaryan85c31b52018-10-26 11:32:15 -07002250 int killed_size = 0;
Yang Lu5dfffbc2018-05-15 04:59:44 +00002251 bool lmk_state_change_start = false;
Suren Baghdasaryan858e8c62021-03-03 11:05:09 -08002252 bool choose_heaviest_task = kill_heaviest_task;
Rajeev Kumar4aba9152018-01-31 17:54:56 -08002253
Chong Zhang1cd12b52015-10-14 16:19:53 -07002254 for (i = OOM_SCORE_ADJ_MAX; i >= min_score_adj; i--) {
Colin Cross3d57a512014-07-14 12:39:56 -07002255 struct proc *procp;
2256
Suren Baghdasaryan858e8c62021-03-03 11:05:09 -08002257 if (!choose_heaviest_task && i <= PERCEPTIBLE_APP_ADJ) {
2258 /*
2259 * If we have to choose a perceptible process, choose the heaviest one to
2260 * hopefully minimize the number of victims.
2261 */
2262 choose_heaviest_task = true;
2263 }
2264
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002265 while (true) {
Suren Baghdasaryan858e8c62021-03-03 11:05:09 -08002266 procp = choose_heaviest_task ?
Suren Baghdasaryan36b2c492018-04-13 11:49:54 -07002267 proc_get_heaviest(i) : proc_adj_lru(i);
Colin Cross3d57a512014-07-14 12:39:56 -07002268
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002269 if (!procp)
2270 break;
2271
Suren Baghdasaryane1604752021-07-22 16:21:21 -07002272 killed_size = kill_one_process(procp, min_score_adj, ki, mi, wi, tm);
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002273 if (killed_size >= 0) {
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07002274 if (!lmk_state_change_start) {
Yang Lu5dfffbc2018-05-15 04:59:44 +00002275 lmk_state_change_start = true;
Vova Sharaienkoa92b76b2021-04-24 00:30:06 +00002276 stats_write_lmk_state_changed(STATE_START);
Yang Lu5dfffbc2018-05-15 04:59:44 +00002277 }
Suren Baghdasaryan85c31b52018-10-26 11:32:15 -07002278 break;
Colin Cross3d57a512014-07-14 12:39:56 -07002279 }
2280 }
Suren Baghdasaryan85c31b52018-10-26 11:32:15 -07002281 if (killed_size) {
2282 break;
2283 }
Colin Cross3d57a512014-07-14 12:39:56 -07002284 }
2285
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07002286 if (lmk_state_change_start) {
Vova Sharaienkoa92b76b2021-04-24 00:30:06 +00002287 stats_write_lmk_state_changed(STATE_STOP);
Rajeev Kumar4aba9152018-01-31 17:54:56 -08002288 }
Rajeev Kumar4aba9152018-01-31 17:54:56 -08002289
Suren Baghdasaryan85c31b52018-10-26 11:32:15 -07002290 return killed_size;
Colin Cross3d57a512014-07-14 12:39:56 -07002291}
2292
Suren Baghdasaryan87966742018-04-13 12:43:41 -07002293static int64_t get_memory_usage(struct reread_data *file_data) {
Robert Beneac72b2932017-08-21 15:18:31 -07002294 int64_t mem_usage;
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -07002295 char *buf;
Suren Baghdasaryan87966742018-04-13 12:43:41 -07002296
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -07002297 if ((buf = reread_file(file_data)) == NULL) {
Robert Beneac72b2932017-08-21 15:18:31 -07002298 return -1;
2299 }
2300
Suren Baghdasaryan87966742018-04-13 12:43:41 -07002301 if (!parse_int64(buf, &mem_usage)) {
2302 ALOGE("%s parse error", file_data->filename);
Robert Beneac72b2932017-08-21 15:18:31 -07002303 return -1;
2304 }
Robert Beneac72b2932017-08-21 15:18:31 -07002305 if (mem_usage == 0) {
2306 ALOGE("No memory!");
2307 return -1;
2308 }
2309 return mem_usage;
2310}
2311
Suren Baghdasaryane0f3dd12018-04-13 13:41:12 -07002312void record_low_pressure_levels(union meminfo *mi) {
2313 if (low_pressure_mem.min_nr_free_pages == -1 ||
2314 low_pressure_mem.min_nr_free_pages > mi->field.nr_free_pages) {
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002315 if (debug_process_killing) {
Suren Baghdasaryane0f3dd12018-04-13 13:41:12 -07002316 ALOGI("Low pressure min memory update from %" PRId64 " to %" PRId64,
2317 low_pressure_mem.min_nr_free_pages, mi->field.nr_free_pages);
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002318 }
Suren Baghdasaryane0f3dd12018-04-13 13:41:12 -07002319 low_pressure_mem.min_nr_free_pages = mi->field.nr_free_pages;
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002320 }
2321 /*
2322 * Free memory at low vmpressure events occasionally gets spikes,
2323 * possibly a stale low vmpressure event with memory already
2324 * freed up (no memory pressure should have been reported).
Suren Baghdasaryane0f3dd12018-04-13 13:41:12 -07002325 * Ignore large jumps in max_nr_free_pages that would mess up our stats.
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002326 */
Suren Baghdasaryane0f3dd12018-04-13 13:41:12 -07002327 if (low_pressure_mem.max_nr_free_pages == -1 ||
2328 (low_pressure_mem.max_nr_free_pages < mi->field.nr_free_pages &&
2329 mi->field.nr_free_pages - low_pressure_mem.max_nr_free_pages <
2330 low_pressure_mem.max_nr_free_pages * 0.1)) {
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002331 if (debug_process_killing) {
Suren Baghdasaryane0f3dd12018-04-13 13:41:12 -07002332 ALOGI("Low pressure max memory update from %" PRId64 " to %" PRId64,
2333 low_pressure_mem.max_nr_free_pages, mi->field.nr_free_pages);
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002334 }
Suren Baghdasaryane0f3dd12018-04-13 13:41:12 -07002335 low_pressure_mem.max_nr_free_pages = mi->field.nr_free_pages;
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002336 }
2337}
2338
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08002339enum vmpressure_level upgrade_level(enum vmpressure_level level) {
2340 return (enum vmpressure_level)((level < VMPRESS_LEVEL_CRITICAL) ?
2341 level + 1 : level);
2342}
2343
2344enum vmpressure_level downgrade_level(enum vmpressure_level level) {
2345 return (enum vmpressure_level)((level > VMPRESS_LEVEL_LOW) ?
2346 level - 1 : level);
2347}
2348
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002349enum zone_watermark {
2350 WMARK_MIN = 0,
2351 WMARK_LOW,
2352 WMARK_HIGH,
2353 WMARK_NONE
2354};
2355
Suren Baghdasaryan81c75b22019-08-14 09:48:35 -07002356struct zone_watermarks {
2357 long high_wmark;
2358 long low_wmark;
2359 long min_wmark;
2360};
2361
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002362/*
2363 * Returns lowest breached watermark or WMARK_NONE.
2364 */
Suren Baghdasaryan81c75b22019-08-14 09:48:35 -07002365static enum zone_watermark get_lowest_watermark(union meminfo *mi,
2366 struct zone_watermarks *watermarks)
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002367{
Suren Baghdasaryan81c75b22019-08-14 09:48:35 -07002368 int64_t nr_free_pages = mi->field.nr_free_pages - mi->field.cma_free;
2369
2370 if (nr_free_pages < watermarks->min_wmark) {
2371 return WMARK_MIN;
2372 }
2373 if (nr_free_pages < watermarks->low_wmark) {
2374 return WMARK_LOW;
2375 }
2376 if (nr_free_pages < watermarks->high_wmark) {
2377 return WMARK_HIGH;
2378 }
2379 return WMARK_NONE;
2380}
2381
2382void calc_zone_watermarks(struct zoneinfo *zi, struct zone_watermarks *watermarks) {
2383 memset(watermarks, 0, sizeof(struct zone_watermarks));
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002384
2385 for (int node_idx = 0; node_idx < zi->node_count; node_idx++) {
2386 struct zoneinfo_node *node = &zi->nodes[node_idx];
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002387 for (int zone_idx = 0; zone_idx < node->zone_count; zone_idx++) {
2388 struct zoneinfo_zone *zone = &node->zones[zone_idx];
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002389
2390 if (!zone->fields.field.present) {
2391 continue;
2392 }
2393
Suren Baghdasaryan81c75b22019-08-14 09:48:35 -07002394 watermarks->high_wmark += zone->max_protection + zone->fields.field.high;
2395 watermarks->low_wmark += zone->max_protection + zone->fields.field.low;
2396 watermarks->min_wmark += zone->max_protection + zone->fields.field.min;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002397 }
2398 }
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002399}
2400
Suren Baghdasaryan51ee4c52020-04-21 12:27:01 -07002401static int calc_swap_utilization(union meminfo *mi) {
2402 int64_t swap_used = mi->field.total_swap - mi->field.free_swap;
2403 int64_t total_swappable = mi->field.active_anon + mi->field.inactive_anon +
2404 mi->field.shmem + swap_used;
2405 return total_swappable > 0 ? (swap_used * 100) / total_swappable : 0;
2406}
2407
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002408static void mp_event_psi(int data, uint32_t events, struct polling_params *poll_params) {
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002409 enum reclaim_state {
2410 NO_RECLAIM = 0,
2411 KSWAPD_RECLAIM,
2412 DIRECT_RECLAIM,
2413 };
2414 static int64_t init_ws_refault;
Martin Liu1f72f5f2020-08-21 13:18:50 +08002415 static int64_t prev_workingset_refault;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002416 static int64_t base_file_lru;
2417 static int64_t init_pgscan_kswapd;
2418 static int64_t init_pgscan_direct;
2419 static int64_t swap_low_threshold;
2420 static bool killing;
Martin Liu1f72f5f2020-08-21 13:18:50 +08002421 static int thrashing_limit = thrashing_limit_pct;
Suren Baghdasaryan81c75b22019-08-14 09:48:35 -07002422 static struct zone_watermarks watermarks;
2423 static struct timespec wmark_update_tm;
Suren Baghdasaryand7b4fcb2020-07-23 18:00:43 -07002424 static struct wakeup_info wi;
Martin Liu1f72f5f2020-08-21 13:18:50 +08002425 static struct timespec thrashing_reset_tm;
2426 static int64_t prev_thrash_growth = 0;
Suren Baghdasaryan11221d42021-07-14 17:57:52 -07002427 static bool check_filecache = false;
Suren Baghdasaryane1604752021-07-22 16:21:21 -07002428 static int max_thrashing = 0;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002429
2430 union meminfo mi;
2431 union vmstat vs;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002432 struct timespec curr_tm;
2433 int64_t thrashing = 0;
2434 bool swap_is_low = false;
2435 enum vmpressure_level level = (enum vmpressure_level)data;
2436 enum kill_reasons kill_reason = NONE;
2437 bool cycle_after_kill = false;
2438 enum reclaim_state reclaim = NO_RECLAIM;
2439 enum zone_watermark wmark = WMARK_NONE;
Suren Baghdasaryan89454e62019-07-15 15:50:17 -07002440 char kill_desc[LINE_MAX];
Suren Baghdasaryan970a26a2019-09-19 15:27:21 -07002441 bool cut_thrashing_limit = false;
2442 int min_score_adj = 0;
Suren Baghdasaryan51ee4c52020-04-21 12:27:01 -07002443 int swap_util = 0;
Martin Liu1f72f5f2020-08-21 13:18:50 +08002444 long since_thrashing_reset_ms;
Suren Baghdasaryandc60f972020-12-14 13:38:48 -08002445 int64_t workingset_refault_file;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002446
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002447 if (clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm) != 0) {
2448 ALOGE("Failed to get current time");
2449 return;
2450 }
2451
Suren Baghdasaryand7b4fcb2020-07-23 18:00:43 -07002452 record_wakeup_time(&curr_tm, events ? Event : Polling, &wi);
2453
Suren Baghdasaryan03dccf32020-04-28 16:02:13 -07002454 bool kill_pending = is_kill_pending();
Suren Baghdasaryaned715a32020-05-11 16:31:57 -07002455 if (kill_pending && (kill_timeout_ms == 0 ||
2456 get_time_diff_ms(&last_kill_tm, &curr_tm) < static_cast<long>(kill_timeout_ms))) {
Suren Baghdasaryan03dccf32020-04-28 16:02:13 -07002457 /* Skip while still killing a process */
Suren Baghdasaryand7b4fcb2020-07-23 18:00:43 -07002458 wi.skipped_wakeups++;
Suren Baghdasaryan03dccf32020-04-28 16:02:13 -07002459 goto no_kill;
2460 }
2461 /*
2462 * Process is dead or kill timeout is over, stop waiting. This has no effect if pidfds are
2463 * supported and death notification already caused waiting to stop.
2464 */
2465 stop_wait_for_proc_kill(!kill_pending);
2466
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002467 if (vmstat_parse(&vs) < 0) {
2468 ALOGE("Failed to parse vmstat!");
2469 return;
2470 }
Suren Baghdasaryandc60f972020-12-14 13:38:48 -08002471 /* Starting 5.9 kernel workingset_refault vmstat field was renamed workingset_refault_file */
2472 workingset_refault_file = vs.field.workingset_refault ? : vs.field.workingset_refault_file;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002473
2474 if (meminfo_parse(&mi) < 0) {
2475 ALOGE("Failed to parse meminfo!");
2476 return;
2477 }
2478
2479 /* Reset states after process got killed */
2480 if (killing) {
2481 killing = false;
2482 cycle_after_kill = true;
2483 /* Reset file-backed pagecache size and refault amounts after a kill */
2484 base_file_lru = vs.field.nr_inactive_file + vs.field.nr_active_file;
Suren Baghdasaryandc60f972020-12-14 13:38:48 -08002485 init_ws_refault = workingset_refault_file;
Martin Liu1f72f5f2020-08-21 13:18:50 +08002486 thrashing_reset_tm = curr_tm;
2487 prev_thrash_growth = 0;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002488 }
2489
2490 /* Check free swap levels */
2491 if (swap_free_low_percentage) {
2492 if (!swap_low_threshold) {
2493 swap_low_threshold = mi.field.total_swap * swap_free_low_percentage / 100;
2494 }
2495 swap_is_low = mi.field.free_swap < swap_low_threshold;
2496 }
2497
2498 /* Identify reclaim state */
2499 if (vs.field.pgscan_direct > init_pgscan_direct) {
2500 init_pgscan_direct = vs.field.pgscan_direct;
2501 init_pgscan_kswapd = vs.field.pgscan_kswapd;
2502 reclaim = DIRECT_RECLAIM;
2503 } else if (vs.field.pgscan_kswapd > init_pgscan_kswapd) {
2504 init_pgscan_kswapd = vs.field.pgscan_kswapd;
2505 reclaim = KSWAPD_RECLAIM;
Suren Baghdasaryandc60f972020-12-14 13:38:48 -08002506 } else if (workingset_refault_file == prev_workingset_refault) {
Suren Baghdasaryan11221d42021-07-14 17:57:52 -07002507 /*
2508 * Device is not thrashing and not reclaiming, bail out early until we see these stats
2509 * changing
2510 */
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002511 goto no_kill;
2512 }
2513
Suren Baghdasaryandc60f972020-12-14 13:38:48 -08002514 prev_workingset_refault = workingset_refault_file;
Martin Liu1f72f5f2020-08-21 13:18:50 +08002515
2516 /*
2517 * It's possible we fail to find an eligible process to kill (ex. no process is
2518 * above oom_adj_min). When this happens, we should retry to find a new process
2519 * for a kill whenever a new eligible process is available. This is especially
2520 * important for a slow growing refault case. While retrying, we should keep
2521 * monitoring new thrashing counter as someone could release the memory to mitigate
2522 * the thrashing. Thus, when thrashing reset window comes, we decay the prev thrashing
Suren Baghdasaryan11221d42021-07-14 17:57:52 -07002523 * counter by window counts. If the counter is still greater than thrashing limit,
Martin Liu1f72f5f2020-08-21 13:18:50 +08002524 * we preserve the current prev_thrash counter so we will retry kill again. Otherwise,
2525 * we reset the prev_thrash counter so we will stop retrying.
2526 */
2527 since_thrashing_reset_ms = get_time_diff_ms(&thrashing_reset_tm, &curr_tm);
2528 if (since_thrashing_reset_ms > THRASHING_RESET_INTERVAL_MS) {
2529 long windows_passed;
2530 /* Calculate prev_thrash_growth if we crossed THRASHING_RESET_INTERVAL_MS */
Suren Baghdasaryandc60f972020-12-14 13:38:48 -08002531 prev_thrash_growth = (workingset_refault_file - init_ws_refault) * 100
Martin Liuc3108412020-09-03 22:12:14 +08002532 / (base_file_lru + 1);
Martin Liu1f72f5f2020-08-21 13:18:50 +08002533 windows_passed = (since_thrashing_reset_ms / THRASHING_RESET_INTERVAL_MS);
2534 /*
2535 * Decay prev_thrashing unless over-the-limit thrashing was registered in the window we
2536 * just crossed, which means there were no eligible processes to kill. We preserve the
2537 * counter in that case to ensure a kill if a new eligible process appears.
2538 */
2539 if (windows_passed > 1 || prev_thrash_growth < thrashing_limit) {
2540 prev_thrash_growth >>= windows_passed;
2541 }
2542
2543 /* Record file-backed pagecache size when crossing THRASHING_RESET_INTERVAL_MS */
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002544 base_file_lru = vs.field.nr_inactive_file + vs.field.nr_active_file;
Suren Baghdasaryandc60f972020-12-14 13:38:48 -08002545 init_ws_refault = workingset_refault_file;
Martin Liu1f72f5f2020-08-21 13:18:50 +08002546 thrashing_reset_tm = curr_tm;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002547 thrashing_limit = thrashing_limit_pct;
2548 } else {
2549 /* Calculate what % of the file-backed pagecache refaulted so far */
Suren Baghdasaryandc60f972020-12-14 13:38:48 -08002550 thrashing = (workingset_refault_file - init_ws_refault) * 100 / (base_file_lru + 1);
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002551 }
Martin Liu1f72f5f2020-08-21 13:18:50 +08002552 /* Add previous cycle's decayed thrashing amount */
2553 thrashing += prev_thrash_growth;
Suren Baghdasaryane1604752021-07-22 16:21:21 -07002554 if (max_thrashing < thrashing) {
2555 max_thrashing = thrashing;
2556 }
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002557
Suren Baghdasaryan81c75b22019-08-14 09:48:35 -07002558 /*
2559 * Refresh watermarks once per min in case user updated one of the margins.
2560 * TODO: b/140521024 replace this periodic update with an API for AMS to notify LMKD
2561 * that zone watermarks were changed by the system software.
2562 */
2563 if (watermarks.high_wmark == 0 || get_time_diff_ms(&wmark_update_tm, &curr_tm) > 60000) {
2564 struct zoneinfo zi;
2565
2566 if (zoneinfo_parse(&zi) < 0) {
2567 ALOGE("Failed to parse zoneinfo!");
2568 return;
2569 }
2570
2571 calc_zone_watermarks(&zi, &watermarks);
2572 wmark_update_tm = curr_tm;
Martin Liu1f72f5f2020-08-21 13:18:50 +08002573 }
Suren Baghdasaryan81c75b22019-08-14 09:48:35 -07002574
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002575 /* Find out which watermark is breached if any */
Suren Baghdasaryan81c75b22019-08-14 09:48:35 -07002576 wmark = get_lowest_watermark(&mi, &watermarks);
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002577
2578 /*
2579 * TODO: move this logic into a separate function
2580 * Decide if killing a process is necessary and record the reason
2581 */
2582 if (cycle_after_kill && wmark < WMARK_LOW) {
2583 /*
2584 * Prevent kills not freeing enough memory which might lead to OOM kill.
2585 * This might happen when a process is consuming memory faster than reclaim can
2586 * free even after a kill. Mostly happens when running memory stress tests.
2587 */
2588 kill_reason = PRESSURE_AFTER_KILL;
Suren Baghdasaryan89454e62019-07-15 15:50:17 -07002589 strncpy(kill_desc, "min watermark is breached even after kill", sizeof(kill_desc));
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002590 } else if (level == VMPRESS_LEVEL_CRITICAL && events != 0) {
2591 /*
2592 * Device is too busy reclaiming memory which might lead to ANR.
2593 * Critical level is triggered when PSI complete stall (all tasks are blocked because
2594 * of the memory congestion) breaches the configured threshold.
2595 */
2596 kill_reason = NOT_RESPONDING;
Suren Baghdasaryan89454e62019-07-15 15:50:17 -07002597 strncpy(kill_desc, "device is not responding", sizeof(kill_desc));
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002598 } else if (swap_is_low && thrashing > thrashing_limit_pct) {
2599 /* Page cache is thrashing while swap is low */
2600 kill_reason = LOW_SWAP_AND_THRASHING;
Suren Baghdasaryan89454e62019-07-15 15:50:17 -07002601 snprintf(kill_desc, sizeof(kill_desc), "device is low on swap (%" PRId64
2602 "kB < %" PRId64 "kB) and thrashing (%" PRId64 "%%)",
2603 mi.field.free_swap * page_k, swap_low_threshold * page_k, thrashing);
Suren Baghdasaryan0142b3c2021-03-03 11:11:09 -08002604 /* Do not kill perceptible apps unless below min watermark or heavily thrashing */
2605 if (wmark > WMARK_MIN && thrashing < thrashing_critical_pct) {
Suren Baghdasaryan48135c42020-05-19 12:59:18 -07002606 min_score_adj = PERCEPTIBLE_APP_ADJ + 1;
2607 }
Suren Baghdasaryan11221d42021-07-14 17:57:52 -07002608 check_filecache = true;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002609 } else if (swap_is_low && wmark < WMARK_HIGH) {
2610 /* Both free memory and swap are low */
2611 kill_reason = LOW_MEM_AND_SWAP;
Suren Baghdasaryan89454e62019-07-15 15:50:17 -07002612 snprintf(kill_desc, sizeof(kill_desc), "%s watermark is breached and swap is low (%"
Suren Baghdasaryan23678182021-03-02 18:33:09 -08002613 PRId64 "kB < %" PRId64 "kB)", wmark < WMARK_LOW ? "min" : "low",
Suren Baghdasaryan89454e62019-07-15 15:50:17 -07002614 mi.field.free_swap * page_k, swap_low_threshold * page_k);
Suren Baghdasaryan0142b3c2021-03-03 11:11:09 -08002615 /* Do not kill perceptible apps unless below min watermark or heavily thrashing */
2616 if (wmark > WMARK_MIN && thrashing < thrashing_critical_pct) {
Suren Baghdasaryan48135c42020-05-19 12:59:18 -07002617 min_score_adj = PERCEPTIBLE_APP_ADJ + 1;
2618 }
Suren Baghdasaryan51ee4c52020-04-21 12:27:01 -07002619 } else if (wmark < WMARK_HIGH && swap_util_max < 100 &&
2620 (swap_util = calc_swap_utilization(&mi)) > swap_util_max) {
2621 /*
2622 * Too much anon memory is swapped out but swap is not low.
2623 * Non-swappable allocations created memory pressure.
2624 */
2625 kill_reason = LOW_MEM_AND_SWAP_UTIL;
2626 snprintf(kill_desc, sizeof(kill_desc), "%s watermark is breached and swap utilization"
Suren Baghdasaryan23678182021-03-02 18:33:09 -08002627 " is high (%d%% > %d%%)", wmark < WMARK_LOW ? "min" : "low",
Suren Baghdasaryan51ee4c52020-04-21 12:27:01 -07002628 swap_util, swap_util_max);
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002629 } else if (wmark < WMARK_HIGH && thrashing > thrashing_limit) {
2630 /* Page cache is thrashing while memory is low */
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002631 kill_reason = LOW_MEM_AND_THRASHING;
Suren Baghdasaryan89454e62019-07-15 15:50:17 -07002632 snprintf(kill_desc, sizeof(kill_desc), "%s watermark is breached and thrashing (%"
Suren Baghdasaryan23678182021-03-02 18:33:09 -08002633 PRId64 "%%)", wmark < WMARK_LOW ? "min" : "low", thrashing);
Suren Baghdasaryan970a26a2019-09-19 15:27:21 -07002634 cut_thrashing_limit = true;
Suren Baghdasaryan0142b3c2021-03-03 11:11:09 -08002635 /* Do not kill perceptible apps unless thrashing at critical levels */
2636 if (thrashing < thrashing_critical_pct) {
2637 min_score_adj = PERCEPTIBLE_APP_ADJ + 1;
2638 }
Suren Baghdasaryan11221d42021-07-14 17:57:52 -07002639 check_filecache = true;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002640 } else if (reclaim == DIRECT_RECLAIM && thrashing > thrashing_limit) {
2641 /* Page cache is thrashing while in direct reclaim (mostly happens on lowram devices) */
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002642 kill_reason = DIRECT_RECL_AND_THRASHING;
Suren Baghdasaryan89454e62019-07-15 15:50:17 -07002643 snprintf(kill_desc, sizeof(kill_desc), "device is in direct reclaim and thrashing (%"
2644 PRId64 "%%)", thrashing);
Suren Baghdasaryan970a26a2019-09-19 15:27:21 -07002645 cut_thrashing_limit = true;
Suren Baghdasaryan0142b3c2021-03-03 11:11:09 -08002646 /* Do not kill perceptible apps unless thrashing at critical levels */
2647 if (thrashing < thrashing_critical_pct) {
2648 min_score_adj = PERCEPTIBLE_APP_ADJ + 1;
2649 }
Suren Baghdasaryan11221d42021-07-14 17:57:52 -07002650 check_filecache = true;
2651 } else if (check_filecache) {
2652 int64_t file_lru_kb = (vs.field.nr_inactive_file + vs.field.nr_active_file) * page_k;
2653
2654 if (file_lru_kb < filecache_min_kb) {
2655 /* File cache is too low after thrashing, keep killing background processes */
2656 kill_reason = LOW_FILECACHE_AFTER_THRASHING;
2657 snprintf(kill_desc, sizeof(kill_desc),
2658 "filecache is low (%" PRId64 "kB < %" PRId64 "kB) after thrashing",
2659 file_lru_kb, filecache_min_kb);
2660 min_score_adj = PERCEPTIBLE_APP_ADJ + 1;
2661 } else {
2662 /* File cache is big enough, stop checking */
2663 check_filecache = false;
2664 }
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002665 }
2666
2667 /* Kill a process if necessary */
2668 if (kill_reason != NONE) {
Suren Baghdasaryane1604752021-07-22 16:21:21 -07002669 struct kill_info ki = {
2670 .kill_reason = kill_reason,
2671 .kill_desc = kill_desc,
2672 .thrashing = (int)thrashing,
2673 .max_thrashing = max_thrashing,
2674 };
2675 int pages_freed = find_and_kill_process(min_score_adj, &ki, &mi, &wi, &curr_tm);
Suren Baghdasaryan970a26a2019-09-19 15:27:21 -07002676 if (pages_freed > 0) {
2677 killing = true;
Suren Baghdasaryane1604752021-07-22 16:21:21 -07002678 max_thrashing = 0;
Suren Baghdasaryan970a26a2019-09-19 15:27:21 -07002679 if (cut_thrashing_limit) {
2680 /*
2681 * Cut thrasing limit by thrashing_limit_decay_pct percentage of the current
2682 * thrashing limit until the system stops thrashing.
2683 */
2684 thrashing_limit = (thrashing_limit * (100 - thrashing_limit_decay_pct)) / 100;
2685 }
2686 }
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002687 }
2688
2689no_kill:
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002690 /* Do not poll if kernel supports pidfd waiting */
2691 if (is_waiting_for_kill()) {
2692 /* Pause polling if we are waiting for process death notification */
2693 poll_params->update = POLLING_PAUSE;
2694 return;
2695 }
2696
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002697 /*
2698 * Start polling after initial PSI event;
2699 * extend polling while device is in direct reclaim or process is being killed;
2700 * do not extend when kswapd reclaims because that might go on for a long time
2701 * without causing memory pressure
2702 */
2703 if (events || killing || reclaim == DIRECT_RECLAIM) {
2704 poll_params->update = POLLING_START;
2705 }
2706
2707 /* Decide the polling interval */
2708 if (swap_is_low || killing) {
2709 /* Fast polling during and after a kill or when swap is low */
2710 poll_params->polling_interval_ms = PSI_POLL_PERIOD_SHORT_MS;
2711 } else {
2712 /* By default use long intervals */
2713 poll_params->polling_interval_ms = PSI_POLL_PERIOD_LONG_MS;
2714 }
2715}
2716
Suren Baghdasaryane12a0672019-07-15 14:50:49 -07002717static void mp_event_common(int data, uint32_t events, struct polling_params *poll_params) {
Todd Poynorc58c5142013-07-09 19:35:14 -07002718 unsigned long long evcount;
Robert Beneac72b2932017-08-21 15:18:31 -07002719 int64_t mem_usage, memsw_usage;
Robert Benea3be16142017-09-13 15:20:30 -07002720 int64_t mem_pressure;
Suren Baghdasaryane0f3dd12018-04-13 13:41:12 -07002721 union meminfo mi;
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07002722 struct zoneinfo zi;
Suren Baghdasaryan53be36e2018-09-05 15:46:32 -07002723 struct timespec curr_tm;
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -07002724 static unsigned long kill_skip_count = 0;
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08002725 enum vmpressure_level level = (enum vmpressure_level)data;
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07002726 long other_free = 0, other_file = 0;
2727 int min_score_adj;
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07002728 int minfree = 0;
Suren Baghdasaryan87966742018-04-13 12:43:41 -07002729 static struct reread_data mem_usage_file_data = {
2730 .filename = MEMCG_MEMORY_USAGE,
2731 .fd = -1,
2732 };
2733 static struct reread_data memsw_usage_file_data = {
2734 .filename = MEMCG_MEMORYSW_USAGE,
2735 .fd = -1,
2736 };
Suren Baghdasaryand7b4fcb2020-07-23 18:00:43 -07002737 static struct wakeup_info wi;
Todd Poynorc58c5142013-07-09 19:35:14 -07002738
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08002739 if (debug_process_killing) {
2740 ALOGI("%s memory pressure event is triggered", level_name[level]);
2741 }
2742
2743 if (!use_psi_monitors) {
2744 /*
2745 * Check all event counters from low to critical
2746 * and upgrade to the highest priority one. By reading
2747 * eventfd we also reset the event counters.
2748 */
Tom Cherry43f3d2b2019-12-04 12:46:57 -08002749 for (int lvl = VMPRESS_LEVEL_LOW; lvl < VMPRESS_LEVEL_COUNT; lvl++) {
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08002750 if (mpevfd[lvl] != -1 &&
2751 TEMP_FAILURE_RETRY(read(mpevfd[lvl],
2752 &evcount, sizeof(evcount))) > 0 &&
2753 evcount > 0 && lvl > level) {
Tom Cherry43f3d2b2019-12-04 12:46:57 -08002754 level = static_cast<vmpressure_level>(lvl);
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08002755 }
Suren Baghdasaryan3e1a8492018-01-04 09:16:21 -08002756 }
2757 }
Todd Poynorc58c5142013-07-09 19:35:14 -07002758
Suren Baghdasaryane12a0672019-07-15 14:50:49 -07002759 /* Start polling after initial PSI event */
2760 if (use_psi_monitors && events) {
2761 /* Override polling params only if current event is more critical */
2762 if (!poll_params->poll_handler || data > poll_params->poll_handler->data) {
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002763 poll_params->polling_interval_ms = PSI_POLL_PERIOD_SHORT_MS;
Suren Baghdasaryane12a0672019-07-15 14:50:49 -07002764 poll_params->update = POLLING_START;
2765 }
2766 }
2767
Suren Baghdasaryan53be36e2018-09-05 15:46:32 -07002768 if (clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm) != 0) {
2769 ALOGE("Failed to get current time");
2770 return;
2771 }
2772
Suren Baghdasaryand7b4fcb2020-07-23 18:00:43 -07002773 record_wakeup_time(&curr_tm, events ? Event : Polling, &wi);
2774
Suren Baghdasaryaned715a32020-05-11 16:31:57 -07002775 if (kill_timeout_ms &&
2776 get_time_diff_ms(&last_kill_tm, &curr_tm) < static_cast<long>(kill_timeout_ms)) {
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002777 /*
2778 * If we're within the no-kill timeout, see if there's pending reclaim work
2779 * from the last killed process. If so, skip killing for now.
2780 */
2781 if (is_kill_pending()) {
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -07002782 kill_skip_count++;
Suren Baghdasaryand7b4fcb2020-07-23 18:00:43 -07002783 wi.skipped_wakeups++;
Suren Baghdasaryan30854e72018-01-17 17:28:01 -08002784 return;
2785 }
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002786 /*
2787 * Process is dead, stop waiting. This has no effect if pidfds are supported and
2788 * death notification already caused waiting to stop.
2789 */
2790 stop_wait_for_proc_kill(true);
2791 } else {
2792 /*
2793 * Killing took longer than no-kill timeout. Stop waiting for the last process
2794 * to die because we are ready to kill again.
2795 */
2796 stop_wait_for_proc_kill(false);
Suren Baghdasaryan30854e72018-01-17 17:28:01 -08002797 }
2798
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -07002799 if (kill_skip_count > 0) {
Suren Baghdasaryaneff82332018-05-10 16:10:56 -07002800 ALOGI("%lu memory pressure events were skipped after a kill!",
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -07002801 kill_skip_count);
2802 kill_skip_count = 0;
Suren Baghdasaryan30854e72018-01-17 17:28:01 -08002803 }
2804
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07002805 if (meminfo_parse(&mi) < 0 || zoneinfo_parse(&zi) < 0) {
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002806 ALOGE("Failed to get free memory!");
2807 return;
2808 }
2809
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07002810 if (use_minfree_levels) {
2811 int i;
2812
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07002813 other_free = mi.field.nr_free_pages - zi.totalreserve_pages;
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07002814 if (mi.field.nr_file_pages > (mi.field.shmem + mi.field.unevictable + mi.field.swap_cached)) {
2815 other_file = (mi.field.nr_file_pages - mi.field.shmem -
2816 mi.field.unevictable - mi.field.swap_cached);
2817 } else {
2818 other_file = 0;
2819 }
2820
2821 min_score_adj = OOM_SCORE_ADJ_MAX + 1;
2822 for (i = 0; i < lowmem_targets_size; i++) {
2823 minfree = lowmem_minfree[i];
2824 if (other_free < minfree && other_file < minfree) {
2825 min_score_adj = lowmem_adj[i];
2826 break;
2827 }
2828 }
2829
Suren Baghdasaryanb0bda552018-05-18 14:42:00 -07002830 if (min_score_adj == OOM_SCORE_ADJ_MAX + 1) {
2831 if (debug_process_killing) {
2832 ALOGI("Ignore %s memory pressure event "
2833 "(free memory=%ldkB, cache=%ldkB, limit=%ldkB)",
2834 level_name[level], other_free * page_k, other_file * page_k,
2835 (long)lowmem_minfree[lowmem_targets_size - 1] * page_k);
2836 }
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07002837 return;
Suren Baghdasaryanb0bda552018-05-18 14:42:00 -07002838 }
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07002839
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07002840 goto do_kill;
2841 }
2842
Suren Baghdasaryane0f3dd12018-04-13 13:41:12 -07002843 if (level == VMPRESS_LEVEL_LOW) {
2844 record_low_pressure_levels(&mi);
2845 }
2846
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002847 if (level_oomadj[level] > OOM_SCORE_ADJ_MAX) {
2848 /* Do not monitor this pressure level */
2849 return;
2850 }
2851
Suren Baghdasaryan87966742018-04-13 12:43:41 -07002852 if ((mem_usage = get_memory_usage(&mem_usage_file_data)) < 0) {
2853 goto do_kill;
2854 }
2855 if ((memsw_usage = get_memory_usage(&memsw_usage_file_data)) < 0) {
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08002856 goto do_kill;
Robert Benea3be16142017-09-13 15:20:30 -07002857 }
Robert Beneac72b2932017-08-21 15:18:31 -07002858
Robert Benea3be16142017-09-13 15:20:30 -07002859 // Calculate percent for swappinness.
2860 mem_pressure = (mem_usage * 100) / memsw_usage;
2861
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08002862 if (enable_pressure_upgrade && level != VMPRESS_LEVEL_CRITICAL) {
Robert Benea3be16142017-09-13 15:20:30 -07002863 // We are swapping too much.
2864 if (mem_pressure < upgrade_pressure) {
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08002865 level = upgrade_level(level);
2866 if (debug_process_killing) {
2867 ALOGI("Event upgraded to %s", level_name[level]);
2868 }
Robert Beneac72b2932017-08-21 15:18:31 -07002869 }
2870 }
2871
Vic Yang65680692018-08-07 10:18:22 -07002872 // If we still have enough swap space available, check if we want to
2873 // ignore/downgrade pressure events.
2874 if (mi.field.free_swap >=
2875 mi.field.total_swap * swap_free_low_percentage / 100) {
2876 // If the pressure is larger than downgrade_pressure lmk will not
2877 // kill any process, since enough memory is available.
2878 if (mem_pressure > downgrade_pressure) {
2879 if (debug_process_killing) {
2880 ALOGI("Ignore %s memory pressure", level_name[level]);
2881 }
2882 return;
2883 } else if (level == VMPRESS_LEVEL_CRITICAL && mem_pressure > upgrade_pressure) {
2884 if (debug_process_killing) {
2885 ALOGI("Downgrade critical memory pressure");
2886 }
2887 // Downgrade event, since enough memory available.
2888 level = downgrade_level(level);
Robert Benea3be16142017-09-13 15:20:30 -07002889 }
Robert Benea3be16142017-09-13 15:20:30 -07002890 }
2891
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08002892do_kill:
Suren Baghdasaryand1d59f82018-04-13 11:45:38 -07002893 if (low_ram_device) {
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002894 /* For Go devices kill only one task */
Suren Baghdasaryane1604752021-07-22 16:21:21 -07002895 if (find_and_kill_process(level_oomadj[level], NULL, &mi, &wi, &curr_tm) == 0) {
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002896 if (debug_process_killing) {
2897 ALOGI("Nothing to kill");
2898 }
2899 }
2900 } else {
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07002901 int pages_freed;
Suren Baghdasaryan53be36e2018-09-05 15:46:32 -07002902 static struct timespec last_report_tm;
2903 static unsigned long report_skip_count = 0;
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07002904
2905 if (!use_minfree_levels) {
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07002906 /* Free up enough memory to downgrate the memory pressure to low level */
Suren Baghdasaryan85c31b52018-10-26 11:32:15 -07002907 if (mi.field.nr_free_pages >= low_pressure_mem.max_nr_free_pages) {
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07002908 if (debug_process_killing) {
2909 ALOGI("Ignoring pressure since more memory is "
2910 "available (%" PRId64 ") than watermark (%" PRId64 ")",
2911 mi.field.nr_free_pages, low_pressure_mem.max_nr_free_pages);
2912 }
2913 return;
2914 }
2915 min_score_adj = level_oomadj[level];
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002916 }
2917
Suren Baghdasaryane1604752021-07-22 16:21:21 -07002918 pages_freed = find_and_kill_process(min_score_adj, NULL, &mi, &wi, &curr_tm);
Suren Baghdasaryaneff82332018-05-10 16:10:56 -07002919
Suren Baghdasaryan53be36e2018-09-05 15:46:32 -07002920 if (pages_freed == 0) {
2921 /* Rate limit kill reports when nothing was reclaimed */
2922 if (get_time_diff_ms(&last_report_tm, &curr_tm) < FAIL_REPORT_RLIMIT_MS) {
2923 report_skip_count++;
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -07002924 return;
2925 }
Robert Benea7f68a3f2017-08-11 16:03:20 -07002926 }
Suren Baghdasaryan53be36e2018-09-05 15:46:32 -07002927
Suren Baghdasaryan12cacae2019-09-16 12:06:30 -07002928 /* Log whenever we kill or when report rate limit allows */
Suren Baghdasaryan53be36e2018-09-05 15:46:32 -07002929 if (use_minfree_levels) {
Chris Morin74b4df92021-02-26 00:00:35 -08002930 ALOGI("Reclaimed %ldkB, cache(%ldkB) and free(%" PRId64 "kB)-reserved(%" PRId64 "kB) "
2931 "below min(%ldkB) for oom_score_adj %d",
Suren Baghdasaryan85c31b52018-10-26 11:32:15 -07002932 pages_freed * page_k,
Suren Baghdasaryan53be36e2018-09-05 15:46:32 -07002933 other_file * page_k, mi.field.nr_free_pages * page_k,
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07002934 zi.totalreserve_pages * page_k,
Suren Baghdasaryan53be36e2018-09-05 15:46:32 -07002935 minfree * page_k, min_score_adj);
2936 } else {
Chris Morin74b4df92021-02-26 00:00:35 -08002937 ALOGI("Reclaimed %ldkB at oom_score_adj %d", pages_freed * page_k, min_score_adj);
Suren Baghdasaryan53be36e2018-09-05 15:46:32 -07002938 }
2939
2940 if (report_skip_count > 0) {
2941 ALOGI("Suppressed %lu failed kill reports", report_skip_count);
2942 report_skip_count = 0;
2943 }
2944
2945 last_report_tm = curr_tm;
Colin Cross01db2712014-07-11 17:16:56 -07002946 }
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002947 if (is_waiting_for_kill()) {
2948 /* pause polling if we are waiting for process death notification */
2949 poll_params->update = POLLING_PAUSE;
2950 }
Todd Poynorc58c5142013-07-09 19:35:14 -07002951}
2952
Suren Baghdasaryan2f88e152019-07-15 15:42:09 -07002953static bool init_mp_psi(enum vmpressure_level level, bool use_new_strategy) {
2954 int fd;
2955
2956 /* Do not register a handler if threshold_ms is not set */
2957 if (!psi_thresholds[level].threshold_ms) {
2958 return true;
2959 }
2960
2961 fd = init_psi_monitor(psi_thresholds[level].stall_type,
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08002962 psi_thresholds[level].threshold_ms * US_PER_MS,
2963 PSI_WINDOW_SIZE_MS * US_PER_MS);
2964
2965 if (fd < 0) {
2966 return false;
2967 }
2968
Suren Baghdasaryan2f88e152019-07-15 15:42:09 -07002969 vmpressure_hinfo[level].handler = use_new_strategy ? mp_event_psi : mp_event_common;
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08002970 vmpressure_hinfo[level].data = level;
2971 if (register_psi_monitor(epollfd, fd, &vmpressure_hinfo[level]) < 0) {
2972 destroy_psi_monitor(fd);
2973 return false;
2974 }
2975 maxevents++;
2976 mpevfd[level] = fd;
2977
2978 return true;
2979}
2980
2981static void destroy_mp_psi(enum vmpressure_level level) {
2982 int fd = mpevfd[level];
2983
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07002984 if (fd < 0) {
2985 return;
2986 }
2987
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08002988 if (unregister_psi_monitor(epollfd, fd) < 0) {
2989 ALOGE("Failed to unregister psi monitor for %s memory pressure; errno=%d",
2990 level_name[level], errno);
2991 }
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07002992 maxevents--;
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08002993 destroy_psi_monitor(fd);
2994 mpevfd[level] = -1;
2995}
2996
2997static bool init_psi_monitors() {
Suren Baghdasaryan2f88e152019-07-15 15:42:09 -07002998 /*
2999 * When PSI is used on low-ram devices or on high-end devices without memfree levels
3000 * use new kill strategy based on zone watermarks, free swap and thrashing stats
3001 */
3002 bool use_new_strategy =
3003 property_get_bool("ro.lmk.use_new_strategy", low_ram_device || !use_minfree_levels);
3004
3005 /* In default PSI mode override stall amounts using system properties */
3006 if (use_new_strategy) {
3007 /* Do not use low pressure level */
3008 psi_thresholds[VMPRESS_LEVEL_LOW].threshold_ms = 0;
3009 psi_thresholds[VMPRESS_LEVEL_MEDIUM].threshold_ms = psi_partial_stall_ms;
3010 psi_thresholds[VMPRESS_LEVEL_CRITICAL].threshold_ms = psi_complete_stall_ms;
3011 }
3012
3013 if (!init_mp_psi(VMPRESS_LEVEL_LOW, use_new_strategy)) {
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08003014 return false;
3015 }
Suren Baghdasaryan2f88e152019-07-15 15:42:09 -07003016 if (!init_mp_psi(VMPRESS_LEVEL_MEDIUM, use_new_strategy)) {
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08003017 destroy_mp_psi(VMPRESS_LEVEL_LOW);
3018 return false;
3019 }
Suren Baghdasaryan2f88e152019-07-15 15:42:09 -07003020 if (!init_mp_psi(VMPRESS_LEVEL_CRITICAL, use_new_strategy)) {
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08003021 destroy_mp_psi(VMPRESS_LEVEL_MEDIUM);
3022 destroy_mp_psi(VMPRESS_LEVEL_LOW);
3023 return false;
3024 }
3025 return true;
3026}
3027
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003028static bool init_mp_common(enum vmpressure_level level) {
Todd Poynorc58c5142013-07-09 19:35:14 -07003029 int mpfd;
3030 int evfd;
3031 int evctlfd;
3032 char buf[256];
3033 struct epoll_event epev;
3034 int ret;
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003035 int level_idx = (int)level;
3036 const char *levelstr = level_name[level_idx];
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08003037
Mark Salyzyna00ccd82018-04-09 09:50:32 -07003038 /* gid containing AID_SYSTEM required */
Nick Kralevich148d8dd2015-12-18 20:52:37 -08003039 mpfd = open(MEMCG_SYSFS_PATH "memory.pressure_level", O_RDONLY | O_CLOEXEC);
Todd Poynorc58c5142013-07-09 19:35:14 -07003040 if (mpfd < 0) {
3041 ALOGI("No kernel memory.pressure_level support (errno=%d)", errno);
3042 goto err_open_mpfd;
3043 }
3044
Nick Kralevich148d8dd2015-12-18 20:52:37 -08003045 evctlfd = open(MEMCG_SYSFS_PATH "cgroup.event_control", O_WRONLY | O_CLOEXEC);
Todd Poynorc58c5142013-07-09 19:35:14 -07003046 if (evctlfd < 0) {
3047 ALOGI("No kernel memory cgroup event control (errno=%d)", errno);
3048 goto err_open_evctlfd;
3049 }
3050
Nick Kralevich148d8dd2015-12-18 20:52:37 -08003051 evfd = eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC);
Todd Poynorc58c5142013-07-09 19:35:14 -07003052 if (evfd < 0) {
3053 ALOGE("eventfd failed for level %s; errno=%d", levelstr, errno);
3054 goto err_eventfd;
3055 }
3056
3057 ret = snprintf(buf, sizeof(buf), "%d %d %s", evfd, mpfd, levelstr);
3058 if (ret >= (ssize_t)sizeof(buf)) {
3059 ALOGE("cgroup.event_control line overflow for level %s", levelstr);
3060 goto err;
3061 }
3062
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003063 ret = TEMP_FAILURE_RETRY(write(evctlfd, buf, strlen(buf) + 1));
Todd Poynorc58c5142013-07-09 19:35:14 -07003064 if (ret == -1) {
3065 ALOGE("cgroup.event_control write failed for level %s; errno=%d",
3066 levelstr, errno);
3067 goto err;
3068 }
3069
3070 epev.events = EPOLLIN;
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003071 /* use data to store event level */
3072 vmpressure_hinfo[level_idx].data = level_idx;
3073 vmpressure_hinfo[level_idx].handler = mp_event_common;
3074 epev.data.ptr = (void *)&vmpressure_hinfo[level_idx];
Todd Poynorc58c5142013-07-09 19:35:14 -07003075 ret = epoll_ctl(epollfd, EPOLL_CTL_ADD, evfd, &epev);
3076 if (ret == -1) {
3077 ALOGE("epoll_ctl for level %s failed; errno=%d", levelstr, errno);
3078 goto err;
3079 }
3080 maxevents++;
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08003081 mpevfd[level] = evfd;
Suren Baghdasaryanceffaf22018-01-04 08:54:53 -08003082 close(evctlfd);
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08003083 return true;
Todd Poynorc58c5142013-07-09 19:35:14 -07003084
3085err:
3086 close(evfd);
3087err_eventfd:
3088 close(evctlfd);
3089err_open_evctlfd:
3090 close(mpfd);
3091err_open_mpfd:
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08003092 return false;
Robert Benea58d6a132017-06-01 16:32:31 -07003093}
3094
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07003095static void destroy_mp_common(enum vmpressure_level level) {
3096 struct epoll_event epev;
3097 int fd = mpevfd[level];
3098
3099 if (fd < 0) {
3100 return;
3101 }
3102
3103 if (epoll_ctl(epollfd, EPOLL_CTL_DEL, fd, &epev)) {
3104 // Log an error and keep going
3105 ALOGE("epoll_ctl for level %s failed; errno=%d", level_name[level], errno);
3106 }
3107 maxevents--;
3108 close(fd);
3109 mpevfd[level] = -1;
3110}
3111
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07003112static void kernel_event_handler(int data __unused, uint32_t events __unused,
3113 struct polling_params *poll_params __unused) {
Jing Ji5c480962019-12-04 09:22:05 -08003114 poll_kernel(kpoll_fd);
Jim Blackler700b7192019-04-26 11:18:29 +01003115}
3116
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07003117static bool init_monitors() {
3118 /* Try to use psi monitor first if kernel has it */
3119 use_psi_monitors = property_get_bool("ro.lmk.use_psi", true) &&
3120 init_psi_monitors();
3121 /* Fall back to vmpressure */
3122 if (!use_psi_monitors &&
3123 (!init_mp_common(VMPRESS_LEVEL_LOW) ||
3124 !init_mp_common(VMPRESS_LEVEL_MEDIUM) ||
3125 !init_mp_common(VMPRESS_LEVEL_CRITICAL))) {
3126 ALOGE("Kernel does not support memory pressure events or in-kernel low memory killer");
3127 return false;
3128 }
3129 if (use_psi_monitors) {
3130 ALOGI("Using psi monitors for memory pressure detection");
3131 } else {
3132 ALOGI("Using vmpressure for memory pressure detection");
3133 }
3134 return true;
3135}
3136
3137static void destroy_monitors() {
3138 if (use_psi_monitors) {
3139 destroy_mp_psi(VMPRESS_LEVEL_CRITICAL);
3140 destroy_mp_psi(VMPRESS_LEVEL_MEDIUM);
3141 destroy_mp_psi(VMPRESS_LEVEL_LOW);
3142 } else {
3143 destroy_mp_common(VMPRESS_LEVEL_CRITICAL);
3144 destroy_mp_common(VMPRESS_LEVEL_MEDIUM);
3145 destroy_mp_common(VMPRESS_LEVEL_LOW);
3146 }
3147}
3148
Todd Poynorc58c5142013-07-09 19:35:14 -07003149static int init(void) {
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07003150 static struct event_handler_info kernel_poll_hinfo = { 0, kernel_event_handler };
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -07003151 struct reread_data file_data = {
3152 .filename = ZONEINFO_PATH,
3153 .fd = -1,
3154 };
Todd Poynorc58c5142013-07-09 19:35:14 -07003155 struct epoll_event epev;
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003156 int pidfd;
Todd Poynorc58c5142013-07-09 19:35:14 -07003157 int i;
3158 int ret;
3159
3160 page_k = sysconf(_SC_PAGESIZE);
3161 if (page_k == -1)
3162 page_k = PAGE_SIZE;
3163 page_k /= 1024;
3164
3165 epollfd = epoll_create(MAX_EPOLL_EVENTS);
3166 if (epollfd == -1) {
3167 ALOGE("epoll_create failed (errno=%d)", errno);
3168 return -1;
3169 }
3170
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003171 // mark data connections as not connected
3172 for (int i = 0; i < MAX_DATA_CONN; i++) {
3173 data_sock[i].sock = -1;
3174 }
3175
3176 ctrl_sock.sock = android_get_control_socket("lmkd");
3177 if (ctrl_sock.sock < 0) {
Todd Poynorc58c5142013-07-09 19:35:14 -07003178 ALOGE("get lmkd control socket failed");
3179 return -1;
3180 }
3181
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003182 ret = listen(ctrl_sock.sock, MAX_DATA_CONN);
Todd Poynorc58c5142013-07-09 19:35:14 -07003183 if (ret < 0) {
3184 ALOGE("lmkd control socket listen failed (errno=%d)", errno);
3185 return -1;
3186 }
3187
3188 epev.events = EPOLLIN;
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003189 ctrl_sock.handler_info.handler = ctrl_connect_handler;
3190 epev.data.ptr = (void *)&(ctrl_sock.handler_info);
3191 if (epoll_ctl(epollfd, EPOLL_CTL_ADD, ctrl_sock.sock, &epev) == -1) {
Todd Poynorc58c5142013-07-09 19:35:14 -07003192 ALOGE("epoll_ctl for lmkd control socket failed (errno=%d)", errno);
3193 return -1;
3194 }
3195 maxevents++;
3196
Robert Benea7878c9b2017-09-11 16:53:28 -07003197 has_inkernel_module = !access(INKERNEL_MINFREE_PATH, W_OK);
Suren Baghdasaryane6613ea2018-01-18 17:27:30 -08003198 use_inkernel_interface = has_inkernel_module;
Todd Poynorc58c5142013-07-09 19:35:14 -07003199
3200 if (use_inkernel_interface) {
3201 ALOGI("Using in-kernel low memory killer interface");
Jing Ji5c480962019-12-04 09:22:05 -08003202 if (init_poll_kernel()) {
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07003203 epev.events = EPOLLIN;
3204 epev.data.ptr = (void*)&kernel_poll_hinfo;
Jing Ji5c480962019-12-04 09:22:05 -08003205 if (epoll_ctl(epollfd, EPOLL_CTL_ADD, kpoll_fd, &epev) != 0) {
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07003206 ALOGE("epoll_ctl for lmk events failed (errno=%d)", errno);
Jing Ji5c480962019-12-04 09:22:05 -08003207 close(kpoll_fd);
3208 kpoll_fd = -1;
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07003209 } else {
3210 maxevents++;
Jing Ji5c480962019-12-04 09:22:05 -08003211 /* let the others know it does support reporting kills */
3212 property_set("sys.lmk.reportkills", "1");
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07003213 }
Jim Blackler700b7192019-04-26 11:18:29 +01003214 }
Todd Poynorc58c5142013-07-09 19:35:14 -07003215 } else {
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07003216 if (!init_monitors()) {
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08003217 return -1;
3218 }
Jing Ji5c480962019-12-04 09:22:05 -08003219 /* let the others know it does support reporting kills */
3220 property_set("sys.lmk.reportkills", "1");
Todd Poynorc58c5142013-07-09 19:35:14 -07003221 }
3222
Chong Zhang1cd12b52015-10-14 16:19:53 -07003223 for (i = 0; i <= ADJTOSLOT(OOM_SCORE_ADJ_MAX); i++) {
Todd Poynorc58c5142013-07-09 19:35:14 -07003224 procadjslot_list[i].next = &procadjslot_list[i];
3225 procadjslot_list[i].prev = &procadjslot_list[i];
3226 }
3227
Suren Baghdasaryana7394ea2018-10-12 11:07:40 -07003228 memset(killcnt_idx, KILLCNT_INVALID_IDX, sizeof(killcnt_idx));
3229
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -07003230 /*
3231 * Read zoneinfo as the biggest file we read to create and size the initial
3232 * read buffer and avoid memory re-allocations during memory pressure
3233 */
3234 if (reread_file(&file_data) == NULL) {
3235 ALOGE("Failed to read %s: %s", file_data.filename, strerror(errno));
3236 }
3237
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003238 /* check if kernel supports pidfd_open syscall */
Josh Gao84623be2021-03-18 17:16:08 -07003239 pidfd = TEMP_FAILURE_RETRY(pidfd_open(getpid(), 0));
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003240 if (pidfd < 0) {
3241 pidfd_supported = (errno != ENOSYS);
3242 } else {
3243 pidfd_supported = true;
3244 close(pidfd);
3245 }
3246 ALOGI("Process polling is %s", pidfd_supported ? "supported" : "not supported" );
3247
Todd Poynorc58c5142013-07-09 19:35:14 -07003248 return 0;
3249}
3250
Suren Baghdasaryan03dccf32020-04-28 16:02:13 -07003251static bool polling_paused(struct polling_params *poll_params) {
3252 return poll_params->paused_handler != NULL;
3253}
3254
3255static void resume_polling(struct polling_params *poll_params, struct timespec curr_tm) {
3256 poll_params->poll_start_tm = curr_tm;
3257 poll_params->poll_handler = poll_params->paused_handler;
Martin Liu589b5752020-09-02 23:15:18 +08003258 poll_params->polling_interval_ms = PSI_POLL_PERIOD_SHORT_MS;
3259 poll_params->paused_handler = NULL;
Suren Baghdasaryan03dccf32020-04-28 16:02:13 -07003260}
3261
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003262static void call_handler(struct event_handler_info* handler_info,
3263 struct polling_params *poll_params, uint32_t events) {
3264 struct timespec curr_tm;
3265
Suren Baghdasaryan9ca53342020-04-24 16:54:55 -07003266 poll_params->update = POLLING_DO_NOT_CHANGE;
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003267 handler_info->handler(handler_info->data, events, poll_params);
3268 clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm);
Suren Baghdasaryan9ca53342020-04-24 16:54:55 -07003269 if (poll_params->poll_handler == handler_info) {
3270 poll_params->last_poll_tm = curr_tm;
3271 }
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003272
3273 switch (poll_params->update) {
3274 case POLLING_START:
3275 /*
3276 * Poll for the duration of PSI_WINDOW_SIZE_MS after the
3277 * initial PSI event because psi events are rate-limited
3278 * at one per sec.
3279 */
3280 poll_params->poll_start_tm = curr_tm;
Greg Kaiser5e80ed52019-10-10 06:52:23 -07003281 poll_params->poll_handler = handler_info;
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003282 break;
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003283 case POLLING_PAUSE:
3284 poll_params->paused_handler = handler_info;
3285 poll_params->poll_handler = NULL;
3286 break;
3287 case POLLING_RESUME:
Suren Baghdasaryan03dccf32020-04-28 16:02:13 -07003288 resume_polling(poll_params, curr_tm);
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003289 break;
3290 case POLLING_DO_NOT_CHANGE:
3291 if (get_time_diff_ms(&poll_params->poll_start_tm, &curr_tm) > PSI_WINDOW_SIZE_MS) {
3292 /* Polled for the duration of PSI window, time to stop */
3293 poll_params->poll_handler = NULL;
3294 }
Suren Baghdasaryan9ca53342020-04-24 16:54:55 -07003295 break;
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003296 }
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003297}
3298
Todd Poynorc58c5142013-07-09 19:35:14 -07003299static void mainloop(void) {
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003300 struct event_handler_info* handler_info;
Suren Baghdasaryane12a0672019-07-15 14:50:49 -07003301 struct polling_params poll_params;
3302 struct timespec curr_tm;
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003303 struct epoll_event *evt;
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08003304 long delay = -1;
Suren Baghdasaryane12a0672019-07-15 14:50:49 -07003305
3306 poll_params.poll_handler = NULL;
Suren Baghdasaryan9ca53342020-04-24 16:54:55 -07003307 poll_params.paused_handler = NULL;
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003308
Todd Poynorc58c5142013-07-09 19:35:14 -07003309 while (1) {
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07003310 struct epoll_event events[MAX_EPOLL_EVENTS];
Todd Poynorc58c5142013-07-09 19:35:14 -07003311 int nevents;
3312 int i;
3313
Suren Baghdasaryane12a0672019-07-15 14:50:49 -07003314 if (poll_params.poll_handler) {
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003315 bool poll_now;
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08003316
3317 clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm);
Martin Liu589b5752020-09-02 23:15:18 +08003318 if (poll_params.update == POLLING_RESUME) {
3319 /* Just transitioned into POLLING_RESUME, poll immediately. */
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003320 poll_now = true;
3321 nevents = 0;
3322 } else {
3323 /* Calculate next timeout */
3324 delay = get_time_diff_ms(&poll_params.last_poll_tm, &curr_tm);
3325 delay = (delay < poll_params.polling_interval_ms) ?
3326 poll_params.polling_interval_ms - delay : poll_params.polling_interval_ms;
Suren Baghdasaryane12a0672019-07-15 14:50:49 -07003327
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003328 /* Wait for events until the next polling timeout */
3329 nevents = epoll_wait(epollfd, events, maxevents, delay);
3330
3331 /* Update current time after wait */
3332 clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm);
3333 poll_now = (get_time_diff_ms(&poll_params.last_poll_tm, &curr_tm) >=
3334 poll_params.polling_interval_ms);
3335 }
3336 if (poll_now) {
3337 call_handler(poll_params.poll_handler, &poll_params, 0);
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08003338 }
3339 } else {
Suren Baghdasaryan03dccf32020-04-28 16:02:13 -07003340 if (kill_timeout_ms && is_waiting_for_kill()) {
3341 clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm);
3342 delay = kill_timeout_ms - get_time_diff_ms(&last_kill_tm, &curr_tm);
3343 /* Wait for pidfds notification or kill timeout to expire */
3344 nevents = (delay > 0) ? epoll_wait(epollfd, events, maxevents, delay) : 0;
3345 if (nevents == 0) {
3346 /* Kill notification timed out */
3347 stop_wait_for_proc_kill(false);
3348 if (polling_paused(&poll_params)) {
3349 clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm);
Martin Liu589b5752020-09-02 23:15:18 +08003350 poll_params.update = POLLING_RESUME;
Suren Baghdasaryan03dccf32020-04-28 16:02:13 -07003351 resume_polling(&poll_params, curr_tm);
3352 }
3353 }
3354 } else {
3355 /* Wait for events with no timeout */
3356 nevents = epoll_wait(epollfd, events, maxevents, -1);
3357 }
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08003358 }
Todd Poynorc58c5142013-07-09 19:35:14 -07003359
3360 if (nevents == -1) {
3361 if (errno == EINTR)
3362 continue;
3363 ALOGE("epoll_wait failed (errno=%d)", errno);
3364 continue;
3365 }
3366
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003367 /*
3368 * First pass to see if any data socket connections were dropped.
3369 * Dropped connection should be handled before any other events
3370 * to deallocate data connection and correctly handle cases when
3371 * connection gets dropped and reestablished in the same epoll cycle.
3372 * In such cases it's essential to handle connection closures first.
3373 */
3374 for (i = 0, evt = &events[0]; i < nevents; ++i, evt++) {
3375 if ((evt->events & EPOLLHUP) && evt->data.ptr) {
3376 ALOGI("lmkd data connection dropped");
3377 handler_info = (struct event_handler_info*)evt->data.ptr;
3378 ctrl_data_close(handler_info->data);
3379 }
3380 }
3381
3382 /* Second pass to handle all other events */
3383 for (i = 0, evt = &events[0]; i < nevents; ++i, evt++) {
Suren Baghdasaryane12a0672019-07-15 14:50:49 -07003384 if (evt->events & EPOLLERR) {
Todd Poynorc58c5142013-07-09 19:35:14 -07003385 ALOGD("EPOLLERR on event #%d", i);
Suren Baghdasaryane12a0672019-07-15 14:50:49 -07003386 }
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003387 if (evt->events & EPOLLHUP) {
3388 /* This case was handled in the first pass */
3389 continue;
3390 }
3391 if (evt->data.ptr) {
3392 handler_info = (struct event_handler_info*)evt->data.ptr;
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003393 call_handler(handler_info, &poll_params, evt->events);
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003394 }
Todd Poynorc58c5142013-07-09 19:35:14 -07003395 }
3396 }
3397}
3398
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07003399int issue_reinit() {
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07003400 int sock;
Colin Crossd5b510e2014-07-14 14:31:15 -07003401
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07003402 sock = lmkd_connect();
3403 if (sock < 0) {
3404 ALOGE("failed to connect to lmkd: %s", strerror(errno));
3405 return -1;
3406 }
3407
3408 enum update_props_result res = lmkd_update_props(sock);
3409 switch (res) {
3410 case UPDATE_PROPS_SUCCESS:
3411 ALOGI("lmkd updated properties successfully");
3412 break;
3413 case UPDATE_PROPS_SEND_ERR:
3414 ALOGE("failed to send lmkd request: %s", strerror(errno));
3415 break;
3416 case UPDATE_PROPS_RECV_ERR:
3417 ALOGE("failed to receive lmkd reply: %s", strerror(errno));
3418 break;
3419 case UPDATE_PROPS_FORMAT_ERR:
3420 ALOGE("lmkd reply is invalid");
3421 break;
3422 case UPDATE_PROPS_FAIL:
3423 ALOGE("lmkd failed to update its properties");
3424 break;
3425 }
3426
3427 close(sock);
3428 return res == UPDATE_PROPS_SUCCESS ? 0 : -1;
3429}
3430
3431static void update_props() {
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08003432 /* By default disable low level vmpressure events */
3433 level_oomadj[VMPRESS_LEVEL_LOW] =
3434 property_get_int32("ro.lmk.low", OOM_SCORE_ADJ_MAX + 1);
3435 level_oomadj[VMPRESS_LEVEL_MEDIUM] =
3436 property_get_int32("ro.lmk.medium", 800);
3437 level_oomadj[VMPRESS_LEVEL_CRITICAL] =
3438 property_get_int32("ro.lmk.critical", 0);
Robert Benea7f68a3f2017-08-11 16:03:20 -07003439 debug_process_killing = property_get_bool("ro.lmk.debug", false);
Suren Baghdasaryan3faa3032017-12-08 13:08:41 -08003440
3441 /* By default disable upgrade/downgrade logic */
3442 enable_pressure_upgrade =
3443 property_get_bool("ro.lmk.critical_upgrade", false);
3444 upgrade_pressure =
3445 (int64_t)property_get_int32("ro.lmk.upgrade_pressure", 100);
3446 downgrade_pressure =
3447 (int64_t)property_get_int32("ro.lmk.downgrade_pressure", 100);
Suren Baghdasaryaneb7c5492017-12-08 13:17:06 -08003448 kill_heaviest_task =
Suren Baghdasaryan36b2c492018-04-13 11:49:54 -07003449 property_get_bool("ro.lmk.kill_heaviest_task", false);
Suren Baghdasaryand1d59f82018-04-13 11:45:38 -07003450 low_ram_device = property_get_bool("ro.config.low_ram", false);
Suren Baghdasaryan30854e72018-01-17 17:28:01 -08003451 kill_timeout_ms =
Suren Baghdasaryan7d1f4f02020-07-08 11:40:10 -07003452 (unsigned long)property_get_int32("ro.lmk.kill_timeout_ms", 100);
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07003453 use_minfree_levels =
3454 property_get_bool("ro.lmk.use_minfree_levels", false);
Suren Baghdasaryan8389fdb2018-06-19 18:38:12 -07003455 per_app_memcg =
3456 property_get_bool("ro.config.per_app_memcg", low_ram_device);
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07003457 swap_free_low_percentage = clamp(0, 100, property_get_int32("ro.lmk.swap_free_low_percentage",
Suren Baghdasaryanfb1f5922020-05-19 13:07:23 -07003458 DEF_LOW_SWAP));
Suren Baghdasaryan2f88e152019-07-15 15:42:09 -07003459 psi_partial_stall_ms = property_get_int32("ro.lmk.psi_partial_stall_ms",
3460 low_ram_device ? DEF_PARTIAL_STALL_LOWRAM : DEF_PARTIAL_STALL);
3461 psi_complete_stall_ms = property_get_int32("ro.lmk.psi_complete_stall_ms",
3462 DEF_COMPLETE_STALL);
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07003463 thrashing_limit_pct = max(0, property_get_int32("ro.lmk.thrashing_limit",
3464 low_ram_device ? DEF_THRASHING_LOWRAM : DEF_THRASHING));
3465 thrashing_limit_decay_pct = clamp(0, 100, property_get_int32("ro.lmk.thrashing_limit_decay",
3466 low_ram_device ? DEF_THRASHING_DECAY_LOWRAM : DEF_THRASHING_DECAY));
Suren Baghdasaryan0142b3c2021-03-03 11:11:09 -08003467 thrashing_critical_pct = max(0, property_get_int32("ro.lmk.thrashing_limit_critical",
Suren Baghdasaryan1ef47182021-07-22 20:59:31 +00003468 thrashing_limit_pct * 2));
Suren Baghdasaryan51ee4c52020-04-21 12:27:01 -07003469 swap_util_max = clamp(0, 100, property_get_int32("ro.lmk.swap_util_max", 100));
Suren Baghdasaryan11221d42021-07-14 17:57:52 -07003470 filecache_min_kb = property_get_int64("ro.lmk.filecache_min_kb", 0);
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07003471}
3472
3473int main(int argc, char **argv) {
3474 if ((argc > 1) && argv[1] && !strcmp(argv[1], "--reinit")) {
3475 if (property_set(LMKD_REINIT_PROP, "0")) {
3476 ALOGE("Failed to reset " LMKD_REINIT_PROP " property");
3477 }
3478 return issue_reinit();
3479 }
3480
3481 update_props();
Robert Benea57397dc2017-07-31 17:15:20 -07003482
Suren Baghdasaryan12cacae2019-09-16 12:06:30 -07003483 ctx = create_android_logger(KILLINFO_LOG_TAG);
Suren Baghdasaryan08bfa982018-07-26 16:34:27 -07003484
Mark Salyzyn5cc80b32018-03-21 12:24:58 -07003485 if (!init()) {
3486 if (!use_inkernel_interface) {
3487 /*
3488 * MCL_ONFAULT pins pages as they fault instead of loading
3489 * everything immediately all at once. (Which would be bad,
3490 * because as of this writing, we have a lot of mapped pages we
3491 * never use.) Old kernels will see MCL_ONFAULT and fail with
3492 * EINVAL; we ignore this failure.
3493 *
3494 * N.B. read the man page for mlockall. MCL_CURRENT | MCL_ONFAULT
3495 * pins ⊆ MCL_CURRENT, converging to just MCL_CURRENT as we fault
3496 * in pages.
3497 */
Mark Salyzyna00ccd82018-04-09 09:50:32 -07003498 /* CAP_IPC_LOCK required */
Mark Salyzyn5cc80b32018-03-21 12:24:58 -07003499 if (mlockall(MCL_CURRENT | MCL_FUTURE | MCL_ONFAULT) && (errno != EINVAL)) {
3500 ALOGW("mlockall failed %s", strerror(errno));
3501 }
Daniel Colascione46648332018-01-03 12:01:02 -08003502
Mark Salyzyna00ccd82018-04-09 09:50:32 -07003503 /* CAP_NICE required */
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07003504 struct sched_param param = {
3505 .sched_priority = 1,
3506 };
Mark Salyzyna00ccd82018-04-09 09:50:32 -07003507 if (sched_setscheduler(0, SCHED_FIFO, &param)) {
3508 ALOGW("set SCHED_FIFO failed %s", strerror(errno));
3509 }
Mark Salyzyn5cc80b32018-03-21 12:24:58 -07003510 }
3511
Todd Poynorc58c5142013-07-09 19:35:14 -07003512 mainloop();
Mark Salyzyn5cc80b32018-03-21 12:24:58 -07003513 }
Todd Poynorc58c5142013-07-09 19:35:14 -07003514
Suren Baghdasaryan08bfa982018-07-26 16:34:27 -07003515 android_log_destroy(&ctx);
3516
Todd Poynorc58c5142013-07-09 19:35:14 -07003517 ALOGI("exiting");
3518 return 0;
3519}