blob: 0afcf2fbc0d7d9d5d2809ff1e1f326db469d97da [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
68#define TRACE_KILL_START(pid) ATRACE_INT(__FUNCTION__, pid);
69#define TRACE_KILL_END() ATRACE_INT(__FUNCTION__, 0);
70
71#else /* LMKD_TRACE_KILLS */
72
Daniel Colascione56b95d72018-02-12 11:24:47 -080073#define TRACE_KILL_START(pid) ((void)(pid))
74#define TRACE_KILL_END() ((void)0)
Suren Baghdasaryan03e19872018-01-04 10:43:58 -080075
76#endif /* LMKD_TRACE_KILLS */
77
Mark Salyzyneb062742014-04-30 13:36:35 -070078#ifndef __unused
79#define __unused __attribute__((__unused__))
80#endif
Todd Poynorc58c5142013-07-09 19:35:14 -070081
82#define MEMCG_SYSFS_PATH "/dev/memcg/"
Robert Beneac72b2932017-08-21 15:18:31 -070083#define MEMCG_MEMORY_USAGE "/dev/memcg/memory.usage_in_bytes"
84#define MEMCG_MEMORYSW_USAGE "/dev/memcg/memory.memsw.usage_in_bytes"
Suren Baghdasaryand28a9732018-04-13 13:11:51 -070085#define ZONEINFO_PATH "/proc/zoneinfo"
86#define MEMINFO_PATH "/proc/meminfo"
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -070087#define VMSTAT_PATH "/proc/vmstat"
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -070088#define PROC_STATUS_TGID_FIELD "Tgid:"
Ioannis Ilkos279268a2020-08-01 10:50:40 +010089#define PROC_STATUS_RSS_FIELD "VmRSS:"
90#define PROC_STATUS_SWAP_FIELD "VmSwap:"
Todd Poynorc58c5142013-07-09 19:35:14 -070091#define LINE_MAX 128
92
Suren Baghdasaryan970a26a2019-09-19 15:27:21 -070093#define PERCEPTIBLE_APP_ADJ 200
94
Suren Baghdasaryan08bfa982018-07-26 16:34:27 -070095/* Android Logger event logtags (see event.logtags) */
Suren Baghdasaryan12cacae2019-09-16 12:06:30 -070096#define KILLINFO_LOG_TAG 10195355
Suren Baghdasaryan08bfa982018-07-26 16:34:27 -070097
Mark Salyzyna00ccd82018-04-09 09:50:32 -070098/* gid containing AID_SYSTEM required */
Todd Poynorc58c5142013-07-09 19:35:14 -070099#define INKERNEL_MINFREE_PATH "/sys/module/lowmemorykiller/parameters/minfree"
100#define INKERNEL_ADJ_PATH "/sys/module/lowmemorykiller/parameters/adj"
101
102#define ARRAY_SIZE(x) (sizeof(x) / sizeof(*(x)))
Robert Benea58d6a132017-06-01 16:32:31 -0700103#define EIGHT_MEGA (1 << 23)
Todd Poynorc58c5142013-07-09 19:35:14 -0700104
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -0700105#define TARGET_UPDATE_MIN_INTERVAL_MS 1000
Martin Liu1f72f5f2020-08-21 13:18:50 +0800106#define THRASHING_RESET_INTERVAL_MS 1000
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -0700107
108#define NS_PER_MS (NS_PER_SEC / MS_PER_SEC)
Suren Baghdasaryan55e31502019-01-08 12:54:48 -0800109#define US_PER_MS (US_PER_SEC / MS_PER_SEC)
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -0700110
Suren Baghdasaryanbb7747b2018-03-20 16:03:29 -0700111/* Defined as ProcessList.SYSTEM_ADJ in ProcessList.java */
112#define SYSTEM_ADJ (-900)
113
Greg Kaiserf5b1d142018-03-23 14:16:12 -0700114#define STRINGIFY(x) STRINGIFY_INTERNAL(x)
115#define STRINGIFY_INTERNAL(x) #x
116
Suren Baghdasaryan55e31502019-01-08 12:54:48 -0800117/*
118 * PSI monitor tracking window size.
119 * PSI monitor generates events at most once per window,
120 * therefore we poll memory state for the duration of
121 * PSI_WINDOW_SIZE_MS after the event happens.
122 */
123#define PSI_WINDOW_SIZE_MS 1000
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -0700124/* Polling period after PSI signal when pressure is high */
125#define PSI_POLL_PERIOD_SHORT_MS 10
126/* Polling period after PSI signal when pressure is low */
127#define PSI_POLL_PERIOD_LONG_MS 100
Suren Baghdasaryan55e31502019-01-08 12:54:48 -0800128
Suren Baghdasaryan08bfa982018-07-26 16:34:27 -0700129#define min(a, b) (((a) < (b)) ? (a) : (b))
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -0700130#define max(a, b) (((a) > (b)) ? (a) : (b))
Suren Baghdasaryan08bfa982018-07-26 16:34:27 -0700131
Suren Baghdasaryan53be36e2018-09-05 15:46:32 -0700132#define FAIL_REPORT_RLIMIT_MS 1000
133
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -0700134/*
135 * System property defaults
136 */
137/* ro.lmk.swap_free_low_percentage property defaults */
Suren Baghdasaryanfb1f5922020-05-19 13:07:23 -0700138#define DEF_LOW_SWAP 10
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -0700139/* ro.lmk.thrashing_limit property defaults */
140#define DEF_THRASHING_LOWRAM 30
141#define DEF_THRASHING 100
142/* ro.lmk.thrashing_limit_decay property defaults */
143#define DEF_THRASHING_DECAY_LOWRAM 50
144#define DEF_THRASHING_DECAY 10
Suren Baghdasaryan2f88e152019-07-15 15:42:09 -0700145/* ro.lmk.psi_partial_stall_ms property defaults */
146#define DEF_PARTIAL_STALL_LOWRAM 200
147#define DEF_PARTIAL_STALL 70
148/* ro.lmk.psi_complete_stall_ms property defaults */
149#define DEF_COMPLETE_STALL 700
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -0700150
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -0700151#define LMKD_REINIT_PROP "lmkd.reinit"
152
Todd Poynorc58c5142013-07-09 19:35:14 -0700153/* default to old in-kernel interface if no memory pressure events */
Mark Salyzyn5cc80b32018-03-21 12:24:58 -0700154static bool use_inkernel_interface = true;
Robert Benea7878c9b2017-09-11 16:53:28 -0700155static bool has_inkernel_module;
Todd Poynorc58c5142013-07-09 19:35:14 -0700156
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -0800157/* memory pressure levels */
158enum vmpressure_level {
159 VMPRESS_LEVEL_LOW = 0,
160 VMPRESS_LEVEL_MEDIUM,
161 VMPRESS_LEVEL_CRITICAL,
162 VMPRESS_LEVEL_COUNT
163};
Todd Poynorc58c5142013-07-09 19:35:14 -0700164
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -0800165static const char *level_name[] = {
166 "low",
167 "medium",
168 "critical"
169};
170
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -0800171struct {
Suren Baghdasaryane0f3dd12018-04-13 13:41:12 -0700172 int64_t min_nr_free_pages; /* recorded but not used yet */
173 int64_t max_nr_free_pages;
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -0800174} low_pressure_mem = { -1, -1 };
175
Suren Baghdasaryan55e31502019-01-08 12:54:48 -0800176struct psi_threshold {
177 enum psi_stall_type stall_type;
178 int threshold_ms;
179};
180
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -0800181static int level_oomadj[VMPRESS_LEVEL_COUNT];
Suren Baghdasaryan3e1a8492018-01-04 09:16:21 -0800182static int mpevfd[VMPRESS_LEVEL_COUNT] = { -1, -1, -1 };
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -0700183static bool pidfd_supported;
184static int last_kill_pid_or_fd = -1;
185static struct timespec last_kill_tm;
186
187/* lmkd configurable parameters */
Robert Beneac72b2932017-08-21 15:18:31 -0700188static bool debug_process_killing;
189static bool enable_pressure_upgrade;
190static int64_t upgrade_pressure;
Robert Benea3be16142017-09-13 15:20:30 -0700191static int64_t downgrade_pressure;
Suren Baghdasaryand1d59f82018-04-13 11:45:38 -0700192static bool low_ram_device;
Suren Baghdasaryaneb7c5492017-12-08 13:17:06 -0800193static bool kill_heaviest_task;
Suren Baghdasaryan30854e72018-01-17 17:28:01 -0800194static unsigned long kill_timeout_ms;
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -0700195static bool use_minfree_levels;
Suren Baghdasaryan8389fdb2018-06-19 18:38:12 -0700196static bool per_app_memcg;
Vic Yang65680692018-08-07 10:18:22 -0700197static int swap_free_low_percentage;
Suren Baghdasaryan2f88e152019-07-15 15:42:09 -0700198static int psi_partial_stall_ms;
199static int psi_complete_stall_ms;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -0700200static int thrashing_limit_pct;
201static int thrashing_limit_decay_pct;
Suren Baghdasaryan0142b3c2021-03-03 11:11:09 -0800202static int thrashing_critical_pct;
Suren Baghdasaryan51ee4c52020-04-21 12:27:01 -0700203static int swap_util_max;
Suren Baghdasaryan55e31502019-01-08 12:54:48 -0800204static bool use_psi_monitors = false;
Jing Ji5c480962019-12-04 09:22:05 -0800205static int kpoll_fd;
Suren Baghdasaryan55e31502019-01-08 12:54:48 -0800206static struct psi_threshold psi_thresholds[VMPRESS_LEVEL_COUNT] = {
207 { PSI_SOME, 70 }, /* 70ms out of 1sec for partial stall */
208 { PSI_SOME, 100 }, /* 100ms out of 1sec for partial stall */
209 { PSI_FULL, 70 }, /* 70ms out of 1sec for complete stall */
210};
Robert Benea57397dc2017-07-31 17:15:20 -0700211
Suren Baghdasaryan08bfa982018-07-26 16:34:27 -0700212static android_log_context ctx;
213
Suren Baghdasaryane12a0672019-07-15 14:50:49 -0700214enum polling_update {
215 POLLING_DO_NOT_CHANGE,
216 POLLING_START,
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -0700217 POLLING_PAUSE,
218 POLLING_RESUME,
Suren Baghdasaryane12a0672019-07-15 14:50:49 -0700219};
220
221/*
222 * Data used for periodic polling for the memory state of the device.
223 * Note that when system is not polling poll_handler is set to NULL,
224 * when polling starts poll_handler gets set and is reset back to
225 * NULL when polling stops.
226 */
227struct polling_params {
228 struct event_handler_info* poll_handler;
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -0700229 struct event_handler_info* paused_handler;
Suren Baghdasaryane12a0672019-07-15 14:50:49 -0700230 struct timespec poll_start_tm;
231 struct timespec last_poll_tm;
232 int polling_interval_ms;
233 enum polling_update update;
234};
235
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -0800236/* data required to handle events */
237struct event_handler_info {
238 int data;
Suren Baghdasaryane12a0672019-07-15 14:50:49 -0700239 void (*handler)(int data, uint32_t events, struct polling_params *poll_params);
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -0800240};
Todd Poynorc58c5142013-07-09 19:35:14 -0700241
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -0800242/* data required to handle socket events */
243struct sock_event_handler_info {
244 int sock;
Suren Baghdasaryan945658a2019-10-18 11:16:52 -0700245 pid_t pid;
Suren Baghdasaryan36baf442019-12-23 11:37:34 -0800246 uint32_t async_event_mask;
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -0800247 struct event_handler_info handler_info;
248};
249
Suren Baghdasaryanf2cbefd2019-10-21 17:59:22 -0700250/* max supported number of data connections (AMS, init, tests) */
251#define MAX_DATA_CONN 3
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -0800252
253/* socket event handler data */
254static struct sock_event_handler_info ctrl_sock;
255static struct sock_event_handler_info data_sock[MAX_DATA_CONN];
256
257/* vmpressure event handler data */
258static struct event_handler_info vmpressure_hinfo[VMPRESS_LEVEL_COUNT];
259
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -0700260/*
Suren Baghdasaryanf2cbefd2019-10-21 17:59:22 -0700261 * 1 ctrl listen socket, 3 ctrl data socket, 3 memory pressure levels,
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -0700262 * 1 lmk events + 1 fd to wait for process death
263 */
264#define MAX_EPOLL_EVENTS (1 + MAX_DATA_CONN + VMPRESS_LEVEL_COUNT + 1 + 1)
Todd Poynorc58c5142013-07-09 19:35:14 -0700265static int epollfd;
266static int maxevents;
267
Chong Zhang1cd12b52015-10-14 16:19:53 -0700268/* OOM score values used by both kernel and framework */
Todd Poynora08c1722013-09-16 19:26:47 -0700269#define OOM_SCORE_ADJ_MIN (-1000)
270#define OOM_SCORE_ADJ_MAX 1000
271
Todd Poynorc58c5142013-07-09 19:35:14 -0700272static int lowmem_adj[MAX_TARGETS];
273static int lowmem_minfree[MAX_TARGETS];
274static int lowmem_targets_size;
275
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700276/* Fields to parse in /proc/zoneinfo */
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -0700277/* zoneinfo per-zone fields */
278enum zoneinfo_zone_field {
279 ZI_ZONE_NR_FREE_PAGES = 0,
280 ZI_ZONE_MIN,
281 ZI_ZONE_LOW,
282 ZI_ZONE_HIGH,
283 ZI_ZONE_PRESENT,
284 ZI_ZONE_NR_FREE_CMA,
285 ZI_ZONE_FIELD_COUNT
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700286};
287
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -0700288static const char* const zoneinfo_zone_field_names[ZI_ZONE_FIELD_COUNT] = {
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700289 "nr_free_pages",
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -0700290 "min",
291 "low",
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700292 "high",
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -0700293 "present",
294 "nr_free_cma",
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700295};
296
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -0700297/* zoneinfo per-zone special fields */
298enum zoneinfo_zone_spec_field {
299 ZI_ZONE_SPEC_PROTECTION = 0,
300 ZI_ZONE_SPEC_PAGESETS,
301 ZI_ZONE_SPEC_FIELD_COUNT,
302};
303
304static const char* const zoneinfo_zone_spec_field_names[ZI_ZONE_SPEC_FIELD_COUNT] = {
305 "protection:",
306 "pagesets",
307};
308
309/* see __MAX_NR_ZONES definition in kernel mmzone.h */
310#define MAX_NR_ZONES 6
311
312union zoneinfo_zone_fields {
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700313 struct {
314 int64_t nr_free_pages;
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -0700315 int64_t min;
316 int64_t low;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700317 int64_t high;
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -0700318 int64_t present;
319 int64_t nr_free_cma;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700320 } field;
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -0700321 int64_t arr[ZI_ZONE_FIELD_COUNT];
322};
323
324struct zoneinfo_zone {
325 union zoneinfo_zone_fields fields;
326 int64_t protection[MAX_NR_ZONES];
327 int64_t max_protection;
328};
329
330/* zoneinfo per-node fields */
331enum zoneinfo_node_field {
332 ZI_NODE_NR_INACTIVE_FILE = 0,
333 ZI_NODE_NR_ACTIVE_FILE,
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -0700334 ZI_NODE_FIELD_COUNT
335};
336
337static const char* const zoneinfo_node_field_names[ZI_NODE_FIELD_COUNT] = {
338 "nr_inactive_file",
339 "nr_active_file",
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -0700340};
341
342union zoneinfo_node_fields {
343 struct {
344 int64_t nr_inactive_file;
345 int64_t nr_active_file;
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -0700346 } field;
347 int64_t arr[ZI_NODE_FIELD_COUNT];
348};
349
350struct zoneinfo_node {
351 int id;
352 int zone_count;
353 struct zoneinfo_zone zones[MAX_NR_ZONES];
354 union zoneinfo_node_fields fields;
355};
356
357/* for now two memory nodes is more than enough */
358#define MAX_NR_NODES 2
359
360struct zoneinfo {
361 int node_count;
362 struct zoneinfo_node nodes[MAX_NR_NODES];
363 int64_t totalreserve_pages;
364 int64_t total_inactive_file;
365 int64_t total_active_file;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700366};
367
368/* Fields to parse in /proc/meminfo */
369enum meminfo_field {
370 MI_NR_FREE_PAGES = 0,
371 MI_CACHED,
372 MI_SWAP_CACHED,
373 MI_BUFFERS,
374 MI_SHMEM,
375 MI_UNEVICTABLE,
Vic Yang65680692018-08-07 10:18:22 -0700376 MI_TOTAL_SWAP,
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700377 MI_FREE_SWAP,
Suren Baghdasaryan08bfa982018-07-26 16:34:27 -0700378 MI_ACTIVE_ANON,
379 MI_INACTIVE_ANON,
380 MI_ACTIVE_FILE,
381 MI_INACTIVE_FILE,
382 MI_SRECLAIMABLE,
383 MI_SUNRECLAIM,
384 MI_KERNEL_STACK,
385 MI_PAGE_TABLES,
386 MI_ION_HELP,
387 MI_ION_HELP_POOL,
388 MI_CMA_FREE,
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700389 MI_FIELD_COUNT
390};
391
392static const char* const meminfo_field_names[MI_FIELD_COUNT] = {
393 "MemFree:",
394 "Cached:",
395 "SwapCached:",
396 "Buffers:",
397 "Shmem:",
398 "Unevictable:",
Vic Yang65680692018-08-07 10:18:22 -0700399 "SwapTotal:",
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700400 "SwapFree:",
Suren Baghdasaryan08bfa982018-07-26 16:34:27 -0700401 "Active(anon):",
402 "Inactive(anon):",
403 "Active(file):",
404 "Inactive(file):",
405 "SReclaimable:",
406 "SUnreclaim:",
407 "KernelStack:",
408 "PageTables:",
409 "ION_heap:",
410 "ION_heap_pool:",
411 "CmaFree:",
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700412};
413
414union meminfo {
415 struct {
416 int64_t nr_free_pages;
417 int64_t cached;
418 int64_t swap_cached;
419 int64_t buffers;
420 int64_t shmem;
421 int64_t unevictable;
Vic Yang65680692018-08-07 10:18:22 -0700422 int64_t total_swap;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700423 int64_t free_swap;
Suren Baghdasaryan08bfa982018-07-26 16:34:27 -0700424 int64_t active_anon;
425 int64_t inactive_anon;
426 int64_t active_file;
427 int64_t inactive_file;
428 int64_t sreclaimable;
429 int64_t sunreclaimable;
430 int64_t kernel_stack;
431 int64_t page_tables;
432 int64_t ion_heap;
433 int64_t ion_heap_pool;
434 int64_t cma_free;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700435 /* fields below are calculated rather than read from the file */
436 int64_t nr_file_pages;
Suren Baghdasaryan940e7cf2021-05-27 18:15:44 -0700437 int64_t total_gpu_kb;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700438 } field;
439 int64_t arr[MI_FIELD_COUNT];
440};
441
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -0700442/* Fields to parse in /proc/vmstat */
443enum vmstat_field {
444 VS_FREE_PAGES,
445 VS_INACTIVE_FILE,
446 VS_ACTIVE_FILE,
447 VS_WORKINGSET_REFAULT,
Suren Baghdasaryandc60f972020-12-14 13:38:48 -0800448 VS_WORKINGSET_REFAULT_FILE,
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -0700449 VS_PGSCAN_KSWAPD,
450 VS_PGSCAN_DIRECT,
451 VS_PGSCAN_DIRECT_THROTTLE,
452 VS_FIELD_COUNT
453};
454
455static const char* const vmstat_field_names[MI_FIELD_COUNT] = {
456 "nr_free_pages",
457 "nr_inactive_file",
458 "nr_active_file",
459 "workingset_refault",
Suren Baghdasaryandc60f972020-12-14 13:38:48 -0800460 "workingset_refault_file",
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -0700461 "pgscan_kswapd",
462 "pgscan_direct",
463 "pgscan_direct_throttle",
464};
465
466union vmstat {
467 struct {
468 int64_t nr_free_pages;
469 int64_t nr_inactive_file;
470 int64_t nr_active_file;
471 int64_t workingset_refault;
Suren Baghdasaryandc60f972020-12-14 13:38:48 -0800472 int64_t workingset_refault_file;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -0700473 int64_t pgscan_kswapd;
474 int64_t pgscan_direct;
475 int64_t pgscan_direct_throttle;
476 } field;
477 int64_t arr[VS_FIELD_COUNT];
478};
479
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700480enum field_match_result {
481 NO_MATCH,
482 PARSE_FAIL,
483 PARSE_SUCCESS
484};
485
Todd Poynorc58c5142013-07-09 19:35:14 -0700486struct adjslot_list {
487 struct adjslot_list *next;
488 struct adjslot_list *prev;
489};
490
491struct proc {
492 struct adjslot_list asl;
493 int pid;
Suren Baghdasaryana10157c2019-07-19 10:55:39 -0700494 int pidfd;
Colin Cross748d2182014-06-13 14:52:43 -0700495 uid_t uid;
Todd Poynorc58c5142013-07-09 19:35:14 -0700496 int oomadj;
Suren Baghdasaryan945658a2019-10-18 11:16:52 -0700497 pid_t reg_pid; /* PID of the process that registered this record */
Todd Poynorc58c5142013-07-09 19:35:14 -0700498 struct proc *pidhash_next;
499};
500
Suren Baghdasaryan87966742018-04-13 12:43:41 -0700501struct reread_data {
502 const char* const filename;
503 int fd;
504};
505
Todd Poynorc58c5142013-07-09 19:35:14 -0700506#define PIDHASH_SZ 1024
507static struct proc *pidhash[PIDHASH_SZ];
508#define pid_hashfn(x) ((((x) >> 8) ^ (x)) & (PIDHASH_SZ - 1))
509
Chih-Hung Hsieheefa2462016-05-19 16:02:22 -0700510#define ADJTOSLOT(adj) ((adj) + -OOM_SCORE_ADJ_MIN)
Suren Baghdasaryana7394ea2018-10-12 11:07:40 -0700511#define ADJTOSLOT_COUNT (ADJTOSLOT(OOM_SCORE_ADJ_MAX) + 1)
512static struct adjslot_list procadjslot_list[ADJTOSLOT_COUNT];
513
514#define MAX_DISTINCT_OOM_ADJ 32
515#define KILLCNT_INVALID_IDX 0xFF
516/*
517 * Because killcnt array is sparse a two-level indirection is used
518 * to keep the size small. killcnt_idx stores index of the element in
519 * killcnt array. Index KILLCNT_INVALID_IDX indicates an unused slot.
520 */
521static uint8_t killcnt_idx[ADJTOSLOT_COUNT];
522static uint16_t killcnt[MAX_DISTINCT_OOM_ADJ];
523static int killcnt_free_idx = 0;
524static uint32_t killcnt_total = 0;
Todd Poynorc58c5142013-07-09 19:35:14 -0700525
Todd Poynorc58c5142013-07-09 19:35:14 -0700526/* PAGE_SIZE / 1024 */
527static long page_k;
528
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -0700529static void update_props();
530static bool init_monitors();
531static void destroy_monitors();
532
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -0700533static int clamp(int low, int high, int value) {
534 return max(min(value, high), low);
535}
536
Suren Baghdasaryan87966742018-04-13 12:43:41 -0700537static bool parse_int64(const char* str, int64_t* ret) {
538 char* endptr;
539 long long val = strtoll(str, &endptr, 10);
540 if (str == endptr || val > INT64_MAX) {
541 return false;
542 }
543 *ret = (int64_t)val;
544 return true;
545}
546
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -0700547static int find_field(const char* name, const char* const field_names[], int field_count) {
548 for (int i = 0; i < field_count; i++) {
549 if (!strcmp(name, field_names[i])) {
550 return i;
551 }
552 }
553 return -1;
554}
555
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700556static enum field_match_result match_field(const char* cp, const char* ap,
557 const char* const field_names[],
558 int field_count, int64_t* field,
559 int *field_idx) {
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -0700560 int i = find_field(cp, field_names, field_count);
561 if (i < 0) {
562 return NO_MATCH;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700563 }
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -0700564 *field_idx = i;
565 return parse_int64(ap, field) ? PARSE_SUCCESS : PARSE_FAIL;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700566}
567
Suren Baghdasaryan87966742018-04-13 12:43:41 -0700568/*
569 * Read file content from the beginning up to max_len bytes or EOF
570 * whichever happens first.
571 */
Colin Crossdba1cc62014-07-11 17:53:27 -0700572static ssize_t read_all(int fd, char *buf, size_t max_len)
573{
574 ssize_t ret = 0;
Suren Baghdasaryan87966742018-04-13 12:43:41 -0700575 off_t offset = 0;
Colin Crossdba1cc62014-07-11 17:53:27 -0700576
577 while (max_len > 0) {
Suren Baghdasaryan87966742018-04-13 12:43:41 -0700578 ssize_t r = TEMP_FAILURE_RETRY(pread(fd, buf, max_len, offset));
Colin Crossdba1cc62014-07-11 17:53:27 -0700579 if (r == 0) {
580 break;
581 }
582 if (r == -1) {
583 return -1;
584 }
585 ret += r;
586 buf += r;
Suren Baghdasaryan87966742018-04-13 12:43:41 -0700587 offset += r;
Colin Crossdba1cc62014-07-11 17:53:27 -0700588 max_len -= r;
589 }
590
591 return ret;
592}
593
Suren Baghdasaryan87966742018-04-13 12:43:41 -0700594/*
595 * Read a new or already opened file from the beginning.
596 * If the file has not been opened yet data->fd should be set to -1.
597 * To be used with files which are read often and possibly during high
598 * memory pressure to minimize file opening which by itself requires kernel
599 * memory allocation and might result in a stall on memory stressed system.
600 */
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -0700601static char *reread_file(struct reread_data *data) {
602 /* start with page-size buffer and increase if needed */
603 static ssize_t buf_size = PAGE_SIZE;
604 static char *new_buf, *buf = NULL;
Suren Baghdasaryan87966742018-04-13 12:43:41 -0700605 ssize_t size;
606
607 if (data->fd == -1) {
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -0700608 /* First-time buffer initialization */
Tom Cherry43f3d2b2019-12-04 12:46:57 -0800609 if (!buf && (buf = static_cast<char*>(malloc(buf_size))) == nullptr) {
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -0700610 return NULL;
611 }
612
613 data->fd = TEMP_FAILURE_RETRY(open(data->filename, O_RDONLY | O_CLOEXEC));
614 if (data->fd < 0) {
Suren Baghdasaryan87966742018-04-13 12:43:41 -0700615 ALOGE("%s open: %s", data->filename, strerror(errno));
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -0700616 return NULL;
Suren Baghdasaryan87966742018-04-13 12:43:41 -0700617 }
618 }
619
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -0700620 while (true) {
621 size = read_all(data->fd, buf, buf_size - 1);
622 if (size < 0) {
623 ALOGE("%s read: %s", data->filename, strerror(errno));
624 close(data->fd);
625 data->fd = -1;
626 return NULL;
627 }
628 if (size < buf_size - 1) {
629 break;
630 }
631 /*
632 * Since we are reading /proc files we can't use fstat to find out
633 * the real size of the file. Double the buffer size and keep retrying.
634 */
Tom Cherry43f3d2b2019-12-04 12:46:57 -0800635 if ((new_buf = static_cast<char*>(realloc(buf, buf_size * 2))) == nullptr) {
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -0700636 errno = ENOMEM;
637 return NULL;
638 }
639 buf = new_buf;
640 buf_size *= 2;
Suren Baghdasaryan87966742018-04-13 12:43:41 -0700641 }
Suren Baghdasaryan87966742018-04-13 12:43:41 -0700642 buf[size] = 0;
643
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -0700644 return buf;
Suren Baghdasaryan87966742018-04-13 12:43:41 -0700645}
646
Jing Ji5c480962019-12-04 09:22:05 -0800647static bool claim_record(struct proc* procp, pid_t pid) {
648 if (procp->reg_pid == pid) {
649 /* Record already belongs to the registrant */
650 return true;
651 }
652 if (procp->reg_pid == 0) {
653 /* Old registrant is gone, claim the record */
654 procp->reg_pid = pid;
655 return true;
656 }
657 /* The record is owned by another registrant */
658 return false;
659}
660
661static void remove_claims(pid_t pid) {
662 int i;
663
664 for (i = 0; i < PIDHASH_SZ; i++) {
665 struct proc* procp = pidhash[i];
666 while (procp) {
667 if (procp->reg_pid == pid) {
668 procp->reg_pid = 0;
669 }
670 procp = procp->pidhash_next;
671 }
672 }
673}
674
675static void ctrl_data_close(int dsock_idx) {
676 struct epoll_event epev;
677
678 ALOGI("closing lmkd data connection");
679 if (epoll_ctl(epollfd, EPOLL_CTL_DEL, data_sock[dsock_idx].sock, &epev) == -1) {
680 // Log a warning and keep going
681 ALOGW("epoll_ctl for data connection socket failed; errno=%d", errno);
682 }
683 maxevents--;
684
685 close(data_sock[dsock_idx].sock);
686 data_sock[dsock_idx].sock = -1;
687
688 /* Mark all records of the old registrant as unclaimed */
689 remove_claims(data_sock[dsock_idx].pid);
690}
691
692static ssize_t ctrl_data_read(int dsock_idx, char* buf, size_t bufsz, struct ucred* sender_cred) {
693 struct iovec iov = {buf, bufsz};
694 char control[CMSG_SPACE(sizeof(struct ucred))];
695 struct msghdr hdr = {
696 NULL, 0, &iov, 1, control, sizeof(control), 0,
697 };
698 ssize_t ret;
699 ret = TEMP_FAILURE_RETRY(recvmsg(data_sock[dsock_idx].sock, &hdr, 0));
700 if (ret == -1) {
701 ALOGE("control data socket read failed; %s", strerror(errno));
702 return -1;
703 }
704 if (ret == 0) {
705 ALOGE("Got EOF on control data socket");
706 return -1;
707 }
708
709 struct ucred* cred = NULL;
710 struct cmsghdr* cmsg = CMSG_FIRSTHDR(&hdr);
711 while (cmsg != NULL) {
712 if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_CREDENTIALS) {
713 cred = (struct ucred*)CMSG_DATA(cmsg);
714 break;
715 }
716 cmsg = CMSG_NXTHDR(&hdr, cmsg);
717 }
718
719 if (cred == NULL) {
720 ALOGE("Failed to retrieve sender credentials");
721 /* Close the connection */
722 ctrl_data_close(dsock_idx);
723 return -1;
724 }
725
726 memcpy(sender_cred, cred, sizeof(struct ucred));
727
728 /* Store PID of the peer */
729 data_sock[dsock_idx].pid = cred->pid;
730
731 return ret;
732}
733
734static int ctrl_data_write(int dsock_idx, char* buf, size_t bufsz) {
735 int ret = 0;
736
737 ret = TEMP_FAILURE_RETRY(write(data_sock[dsock_idx].sock, buf, bufsz));
738
739 if (ret == -1) {
740 ALOGE("control data socket write failed; errno=%d", errno);
741 } else if (ret == 0) {
742 ALOGE("Got EOF on control data socket");
743 ret = -1;
744 }
745
746 return ret;
747}
748
749/*
750 * Write the pid/uid pair over the data socket, note: all active clients
751 * will receive this unsolicited notification.
752 */
753static void ctrl_data_write_lmk_kill_occurred(pid_t pid, uid_t uid) {
754 LMKD_CTRL_PACKET packet;
755 size_t len = lmkd_pack_set_prockills(packet, pid, uid);
756
757 for (int i = 0; i < MAX_DATA_CONN; i++) {
Suren Baghdasaryan36baf442019-12-23 11:37:34 -0800758 if (data_sock[i].sock >= 0 && data_sock[i].async_event_mask & 1 << LMK_ASYNC_EVENT_KILL) {
Jing Ji5c480962019-12-04 09:22:05 -0800759 ctrl_data_write(i, (char*)packet, len);
760 }
761 }
762}
763
Vova Sharaienkoa92b76b2021-04-24 00:30:06 +0000764/*
765 * Write the kill_stat/memory_stat over the data socket to be propagated via AMS to statsd
766 */
767static void stats_write_lmk_kill_occurred(struct kill_stat *kill_st,
768 struct memory_stat *mem_st) {
769 LMK_KILL_OCCURRED_PACKET packet;
770 const size_t len = lmkd_pack_set_kill_occurred(packet, kill_st, mem_st);
771 if (len == 0) {
772 return;
773 }
774
775 for (int i = 0; i < MAX_DATA_CONN; i++) {
776 if (data_sock[i].sock >= 0 && data_sock[i].async_event_mask & 1 << LMK_ASYNC_EVENT_STAT) {
777 ctrl_data_write(i, packet, len);
778 }
779 }
780
781}
782
783static void stats_write_lmk_kill_occurred_pid(int pid, struct kill_stat *kill_st,
784 struct memory_stat *mem_st) {
785 kill_st->taskname = stats_get_task_name(pid);
786 if (kill_st->taskname != NULL) {
787 stats_write_lmk_kill_occurred(kill_st, mem_st);
788 }
789}
790
791/*
792 * Write the state_changed over the data socket to be propagated via AMS to statsd
793 */
794static void stats_write_lmk_state_changed(enum lmk_state state) {
795 LMKD_CTRL_PACKET packet_state_changed;
796 const size_t len = lmkd_pack_set_state_changed(packet_state_changed, state);
797 if (len == 0) {
798 return;
799 }
800 for (int i = 0; i < MAX_DATA_CONN; i++) {
801 if (data_sock[i].sock >= 0 && data_sock[i].async_event_mask & 1 << LMK_ASYNC_EVENT_STAT) {
802 ctrl_data_write(i, (char*)packet_state_changed, len);
803 }
804 }
805}
806
Jing Ji5c480962019-12-04 09:22:05 -0800807static void poll_kernel(int poll_fd) {
808 if (poll_fd == -1) {
809 // not waiting
810 return;
811 }
812
813 while (1) {
814 char rd_buf[256];
815 int bytes_read = TEMP_FAILURE_RETRY(pread(poll_fd, (void*)rd_buf, sizeof(rd_buf), 0));
816 if (bytes_read <= 0) break;
817 rd_buf[bytes_read] = '\0';
818
819 int64_t pid;
820 int64_t uid;
821 int64_t group_leader_pid;
822 int64_t rss_in_pages;
823 struct memory_stat mem_st = {};
824 int16_t oom_score_adj;
825 int16_t min_score_adj;
826 int64_t starttime;
827 char* taskname = 0;
828
829 int fields_read =
830 sscanf(rd_buf,
831 "%" SCNd64 " %" SCNd64 " %" SCNd64 " %" SCNd64 " %" SCNd64 " %" SCNd64
832 " %" SCNd16 " %" SCNd16 " %" SCNd64 "\n%m[^\n]",
833 &pid, &uid, &group_leader_pid, &mem_st.pgfault, &mem_st.pgmajfault,
834 &rss_in_pages, &oom_score_adj, &min_score_adj, &starttime, &taskname);
835
836 /* only the death of the group leader process is logged */
837 if (fields_read == 10 && group_leader_pid == pid) {
838 ctrl_data_write_lmk_kill_occurred((pid_t)pid, (uid_t)uid);
839 mem_st.process_start_time_ns = starttime * (NS_PER_SEC / sysconf(_SC_CLK_TCK));
840 mem_st.rss_in_bytes = rss_in_pages * PAGE_SIZE;
Suren Baghdasaryan3cc1f132020-09-09 20:19:02 -0700841
842 struct kill_stat kill_st = {
843 .uid = static_cast<int32_t>(uid),
844 .kill_reason = NONE,
845 .oom_score = oom_score_adj,
846 .min_oom_score = min_score_adj,
847 .free_mem_kb = 0,
848 .free_swap_kb = 0,
849 };
850 stats_write_lmk_kill_occurred_pid(pid, &kill_st, &mem_st);
Jing Ji5c480962019-12-04 09:22:05 -0800851 }
852
853 free(taskname);
854 }
855}
856
857static bool init_poll_kernel() {
858 kpoll_fd = TEMP_FAILURE_RETRY(open("/proc/lowmemorykiller", O_RDONLY | O_NONBLOCK | O_CLOEXEC));
859
860 if (kpoll_fd < 0) {
861 ALOGE("kernel lmk event file could not be opened; errno=%d", errno);
862 return false;
863 }
864
865 return true;
866}
867
Todd Poynorc58c5142013-07-09 19:35:14 -0700868static struct proc *pid_lookup(int pid) {
869 struct proc *procp;
870
871 for (procp = pidhash[pid_hashfn(pid)]; procp && procp->pid != pid;
872 procp = procp->pidhash_next)
873 ;
874
875 return procp;
876}
877
Tom Cherry43f3d2b2019-12-04 12:46:57 -0800878static void adjslot_insert(struct adjslot_list *head, struct adjslot_list *new_element)
Todd Poynorc58c5142013-07-09 19:35:14 -0700879{
880 struct adjslot_list *next = head->next;
Tom Cherry43f3d2b2019-12-04 12:46:57 -0800881 new_element->prev = head;
882 new_element->next = next;
883 next->prev = new_element;
884 head->next = new_element;
Todd Poynorc58c5142013-07-09 19:35:14 -0700885}
886
887static void adjslot_remove(struct adjslot_list *old)
888{
889 struct adjslot_list *prev = old->prev;
890 struct adjslot_list *next = old->next;
891 next->prev = prev;
892 prev->next = next;
893}
894
895static struct adjslot_list *adjslot_tail(struct adjslot_list *head) {
896 struct adjslot_list *asl = head->prev;
897
898 return asl == head ? NULL : asl;
899}
900
901static void proc_slot(struct proc *procp) {
902 int adjslot = ADJTOSLOT(procp->oomadj);
903
904 adjslot_insert(&procadjslot_list[adjslot], &procp->asl);
905}
906
907static void proc_unslot(struct proc *procp) {
908 adjslot_remove(&procp->asl);
909}
910
911static void proc_insert(struct proc *procp) {
912 int hval = pid_hashfn(procp->pid);
913
914 procp->pidhash_next = pidhash[hval];
915 pidhash[hval] = procp;
916 proc_slot(procp);
917}
918
919static int pid_remove(int pid) {
920 int hval = pid_hashfn(pid);
921 struct proc *procp;
922 struct proc *prevp;
923
924 for (procp = pidhash[hval], prevp = NULL; procp && procp->pid != pid;
925 procp = procp->pidhash_next)
926 prevp = procp;
927
928 if (!procp)
929 return -1;
930
931 if (!prevp)
932 pidhash[hval] = procp->pidhash_next;
933 else
934 prevp->pidhash_next = procp->pidhash_next;
935
936 proc_unslot(procp);
Suren Baghdasaryana10157c2019-07-19 10:55:39 -0700937 /*
938 * Close pidfd here if we are not waiting for corresponding process to die,
939 * in which case stop_wait_for_proc_kill() will close the pidfd later
940 */
941 if (procp->pidfd >= 0 && procp->pidfd != last_kill_pid_or_fd) {
942 close(procp->pidfd);
943 }
Todd Poynorc58c5142013-07-09 19:35:14 -0700944 free(procp);
945 return 0;
946}
947
Suren Baghdasaryanf584fff2018-03-20 13:53:17 -0700948/*
949 * Write a string to a file.
950 * Returns false if the file does not exist.
951 */
952static bool writefilestring(const char *path, const char *s,
953 bool err_if_missing) {
Nick Kralevich148d8dd2015-12-18 20:52:37 -0800954 int fd = open(path, O_WRONLY | O_CLOEXEC);
Suren Baghdasaryanf584fff2018-03-20 13:53:17 -0700955 ssize_t len = strlen(s);
956 ssize_t ret;
Todd Poynorc58c5142013-07-09 19:35:14 -0700957
958 if (fd < 0) {
Suren Baghdasaryanf584fff2018-03-20 13:53:17 -0700959 if (err_if_missing) {
960 ALOGE("Error opening %s; errno=%d", path, errno);
961 }
962 return false;
Todd Poynorc58c5142013-07-09 19:35:14 -0700963 }
964
Suren Baghdasaryanf584fff2018-03-20 13:53:17 -0700965 ret = TEMP_FAILURE_RETRY(write(fd, s, len));
Todd Poynorc58c5142013-07-09 19:35:14 -0700966 if (ret < 0) {
967 ALOGE("Error writing %s; errno=%d", path, errno);
968 } else if (ret < len) {
Suren Baghdasaryanf584fff2018-03-20 13:53:17 -0700969 ALOGE("Short write on %s; length=%zd", path, ret);
Todd Poynorc58c5142013-07-09 19:35:14 -0700970 }
971
972 close(fd);
Suren Baghdasaryanf584fff2018-03-20 13:53:17 -0700973 return true;
Todd Poynorc58c5142013-07-09 19:35:14 -0700974}
975
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -0700976static inline long get_time_diff_ms(struct timespec *from,
977 struct timespec *to) {
978 return (to->tv_sec - from->tv_sec) * (long)MS_PER_SEC +
979 (to->tv_nsec - from->tv_nsec) / (long)NS_PER_MS;
980}
981
Ioannis Ilkos279268a2020-08-01 10:50:40 +0100982/* Reads /proc/pid/status into buf. */
983static bool read_proc_status(int pid, char *buf, size_t buf_sz) {
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -0700984 char path[PATH_MAX];
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -0700985 int fd;
986 ssize_t size;
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -0700987
988 snprintf(path, PATH_MAX, "/proc/%d/status", pid);
989 fd = open(path, O_RDONLY | O_CLOEXEC);
990 if (fd < 0) {
Ioannis Ilkos279268a2020-08-01 10:50:40 +0100991 return false;
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -0700992 }
993
Ioannis Ilkos279268a2020-08-01 10:50:40 +0100994 size = read_all(fd, buf, buf_sz - 1);
995 close(fd);
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -0700996 if (size < 0) {
Ioannis Ilkos279268a2020-08-01 10:50:40 +0100997 return false;
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -0700998 }
999 buf[size] = 0;
Ioannis Ilkos279268a2020-08-01 10:50:40 +01001000 return true;
1001}
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -07001002
Ioannis Ilkos279268a2020-08-01 10:50:40 +01001003/* Looks for tag in buf and parses the first integer */
1004static bool parse_status_tag(char *buf, const char *tag, int64_t *out) {
1005 char *pos = buf;
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -07001006 while (true) {
Ioannis Ilkos279268a2020-08-01 10:50:40 +01001007 pos = strstr(pos, tag);
1008 /* Stop if tag not found or found at the line beginning */
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -07001009 if (pos == NULL || pos == buf || pos[-1] == '\n') {
1010 break;
1011 }
1012 pos++;
1013 }
1014
1015 if (pos == NULL) {
Ioannis Ilkos279268a2020-08-01 10:50:40 +01001016 return false;
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -07001017 }
1018
Ioannis Ilkos279268a2020-08-01 10:50:40 +01001019 pos += strlen(tag);
1020 while (*pos == ' ') ++pos;
1021 return parse_int64(pos, out);
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -07001022}
1023
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07001024static int proc_get_size(int pid) {
1025 char path[PATH_MAX];
1026 char line[LINE_MAX];
1027 int fd;
1028 int rss = 0;
1029 int total;
1030 ssize_t ret;
1031
1032 /* gid containing AID_READPROC required */
1033 snprintf(path, PATH_MAX, "/proc/%d/statm", pid);
1034 fd = open(path, O_RDONLY | O_CLOEXEC);
1035 if (fd == -1)
1036 return -1;
1037
1038 ret = read_all(fd, line, sizeof(line) - 1);
1039 if (ret < 0) {
1040 close(fd);
1041 return -1;
1042 }
Suren Baghdasaryan632f1c52019-10-04 16:06:55 -07001043 line[ret] = '\0';
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07001044
1045 sscanf(line, "%d %d ", &total, &rss);
1046 close(fd);
1047 return rss;
1048}
1049
Suren Baghdasaryan632f1c52019-10-04 16:06:55 -07001050static char *proc_get_name(int pid, char *buf, size_t buf_size) {
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07001051 char path[PATH_MAX];
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07001052 int fd;
1053 char *cp;
1054 ssize_t ret;
1055
1056 /* gid containing AID_READPROC required */
1057 snprintf(path, PATH_MAX, "/proc/%d/cmdline", pid);
1058 fd = open(path, O_RDONLY | O_CLOEXEC);
1059 if (fd == -1) {
1060 return NULL;
1061 }
Suren Baghdasaryan632f1c52019-10-04 16:06:55 -07001062 ret = read_all(fd, buf, buf_size - 1);
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07001063 close(fd);
1064 if (ret < 0) {
1065 return NULL;
1066 }
Suren Baghdasaryan632f1c52019-10-04 16:06:55 -07001067 buf[ret] = '\0';
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07001068
Suren Baghdasaryan632f1c52019-10-04 16:06:55 -07001069 cp = strchr(buf, ' ');
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07001070 if (cp) {
1071 *cp = '\0';
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07001072 }
1073
Suren Baghdasaryan632f1c52019-10-04 16:06:55 -07001074 return buf;
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07001075}
1076
Suren Baghdasaryana93503e2019-10-22 17:12:01 -07001077static void cmd_procprio(LMKD_CTRL_PACKET packet, int field_count, struct ucred *cred) {
Todd Poynorc58c5142013-07-09 19:35:14 -07001078 struct proc *procp;
Suren Baghdasaryan632f1c52019-10-04 16:06:55 -07001079 char path[LINE_MAX];
Todd Poynorc58c5142013-07-09 19:35:14 -07001080 char val[20];
Robert Benea58d6a132017-06-01 16:32:31 -07001081 int soft_limit_mult;
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -08001082 struct lmk_procprio params;
Suren Baghdasaryanbb7747b2018-03-20 16:03:29 -07001083 bool is_system_server;
1084 struct passwd *pwdrec;
Ioannis Ilkos279268a2020-08-01 10:50:40 +01001085 int64_t tgid;
1086 char buf[PAGE_SIZE];
Todd Poynorc58c5142013-07-09 19:35:14 -07001087
Suren Baghdasaryana93503e2019-10-22 17:12:01 -07001088 lmkd_pack_get_procprio(packet, field_count, &params);
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -08001089
1090 if (params.oomadj < OOM_SCORE_ADJ_MIN ||
1091 params.oomadj > OOM_SCORE_ADJ_MAX) {
1092 ALOGE("Invalid PROCPRIO oomadj argument %d", params.oomadj);
Todd Poynorc58c5142013-07-09 19:35:14 -07001093 return;
1094 }
1095
Suren Baghdasaryana93503e2019-10-22 17:12:01 -07001096 if (params.ptype < PROC_TYPE_FIRST || params.ptype >= PROC_TYPE_COUNT) {
1097 ALOGE("Invalid PROCPRIO process type argument %d", params.ptype);
1098 return;
1099 }
1100
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -07001101 /* Check if registered process is a thread group leader */
Ioannis Ilkos279268a2020-08-01 10:50:40 +01001102 if (read_proc_status(params.pid, buf, sizeof(buf))) {
1103 if (parse_status_tag(buf, PROC_STATUS_TGID_FIELD, &tgid) && tgid != params.pid) {
1104 ALOGE("Attempt to register a task that is not a thread group leader "
1105 "(tid %d, tgid %" PRId64 ")", params.pid, tgid);
1106 return;
1107 }
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -07001108 }
1109
Mark Salyzyna00ccd82018-04-09 09:50:32 -07001110 /* gid containing AID_READPROC required */
1111 /* CAP_SYS_RESOURCE required */
1112 /* CAP_DAC_OVERRIDE required */
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -08001113 snprintf(path, sizeof(path), "/proc/%d/oom_score_adj", params.pid);
1114 snprintf(val, sizeof(val), "%d", params.oomadj);
Suren Baghdasaryanf584fff2018-03-20 13:53:17 -07001115 if (!writefilestring(path, val, false)) {
1116 ALOGW("Failed to open %s; errno=%d: process %d might have been killed",
1117 path, errno, params.pid);
1118 /* If this file does not exist the process is dead. */
1119 return;
1120 }
Todd Poynorc58c5142013-07-09 19:35:14 -07001121
Mark Salyzyn5cc80b32018-03-21 12:24:58 -07001122 if (use_inkernel_interface) {
Jing Ji5c480962019-12-04 09:22:05 -08001123 stats_store_taskname(params.pid, proc_get_name(params.pid, path, sizeof(path)));
Todd Poynorc58c5142013-07-09 19:35:14 -07001124 return;
Mark Salyzyn5cc80b32018-03-21 12:24:58 -07001125 }
Todd Poynorc58c5142013-07-09 19:35:14 -07001126
Suren Baghdasaryana93503e2019-10-22 17:12:01 -07001127 /* lmkd should not change soft limits for services */
1128 if (params.ptype == PROC_TYPE_APP && per_app_memcg) {
Suren Baghdasaryanb0bda552018-05-18 14:42:00 -07001129 if (params.oomadj >= 900) {
1130 soft_limit_mult = 0;
1131 } else if (params.oomadj >= 800) {
1132 soft_limit_mult = 0;
1133 } else if (params.oomadj >= 700) {
1134 soft_limit_mult = 0;
1135 } else if (params.oomadj >= 600) {
1136 // Launcher should be perceptible, don't kill it.
1137 params.oomadj = 200;
1138 soft_limit_mult = 1;
1139 } else if (params.oomadj >= 500) {
1140 soft_limit_mult = 0;
1141 } else if (params.oomadj >= 400) {
1142 soft_limit_mult = 0;
1143 } else if (params.oomadj >= 300) {
1144 soft_limit_mult = 1;
1145 } else if (params.oomadj >= 200) {
Srinivas Paladugua453f0b2018-10-09 14:21:10 -07001146 soft_limit_mult = 8;
Suren Baghdasaryanb0bda552018-05-18 14:42:00 -07001147 } else if (params.oomadj >= 100) {
1148 soft_limit_mult = 10;
1149 } else if (params.oomadj >= 0) {
1150 soft_limit_mult = 20;
1151 } else {
1152 // Persistent processes will have a large
1153 // soft limit 512MB.
1154 soft_limit_mult = 64;
1155 }
Robert Benea58d6a132017-06-01 16:32:31 -07001156
Suren Baghdasaryanbf919ff2018-05-21 19:48:47 -07001157 snprintf(path, sizeof(path), MEMCG_SYSFS_PATH
1158 "apps/uid_%d/pid_%d/memory.soft_limit_in_bytes",
1159 params.uid, params.pid);
Suren Baghdasaryanb0bda552018-05-18 14:42:00 -07001160 snprintf(val, sizeof(val), "%d", soft_limit_mult * EIGHT_MEGA);
Suren Baghdasaryanbf919ff2018-05-21 19:48:47 -07001161
1162 /*
1163 * system_server process has no memcg under /dev/memcg/apps but should be
1164 * registered with lmkd. This is the best way so far to identify it.
1165 */
1166 is_system_server = (params.oomadj == SYSTEM_ADJ &&
1167 (pwdrec = getpwnam("system")) != NULL &&
1168 params.uid == pwdrec->pw_uid);
1169 writefilestring(path, val, !is_system_server);
Robert Benea58d6a132017-06-01 16:32:31 -07001170 }
1171
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -08001172 procp = pid_lookup(params.pid);
Todd Poynorc58c5142013-07-09 19:35:14 -07001173 if (!procp) {
Suren Baghdasaryana10157c2019-07-19 10:55:39 -07001174 int pidfd = -1;
1175
1176 if (pidfd_supported) {
Josh Gao84623be2021-03-18 17:16:08 -07001177 pidfd = TEMP_FAILURE_RETRY(pidfd_open(params.pid, 0));
Suren Baghdasaryana10157c2019-07-19 10:55:39 -07001178 if (pidfd < 0) {
1179 ALOGE("pidfd_open for pid %d failed; errno=%d", params.pid, errno);
Todd Poynorc58c5142013-07-09 19:35:14 -07001180 return;
1181 }
Suren Baghdasaryana10157c2019-07-19 10:55:39 -07001182 }
Todd Poynorc58c5142013-07-09 19:35:14 -07001183
Tom Cherry43f3d2b2019-12-04 12:46:57 -08001184 procp = static_cast<struct proc*>(calloc(1, sizeof(struct proc)));
Suren Baghdasaryana10157c2019-07-19 10:55:39 -07001185 if (!procp) {
1186 // Oh, the irony. May need to rebuild our state.
1187 return;
1188 }
1189
1190 procp->pid = params.pid;
1191 procp->pidfd = pidfd;
1192 procp->uid = params.uid;
Suren Baghdasaryan945658a2019-10-18 11:16:52 -07001193 procp->reg_pid = cred->pid;
Suren Baghdasaryana10157c2019-07-19 10:55:39 -07001194 procp->oomadj = params.oomadj;
1195 proc_insert(procp);
Todd Poynorc58c5142013-07-09 19:35:14 -07001196 } else {
Suren Baghdasaryan945658a2019-10-18 11:16:52 -07001197 if (!claim_record(procp, cred->pid)) {
1198 char buf[LINE_MAX];
Suren Baghdasaryan9f1be122021-04-23 13:39:37 -07001199 char *taskname = proc_get_name(cred->pid, buf, sizeof(buf));
Suren Baghdasaryan945658a2019-10-18 11:16:52 -07001200 /* Only registrant of the record can remove it */
1201 ALOGE("%s (%d, %d) attempts to modify a process registered by another client",
Suren Baghdasaryan9f1be122021-04-23 13:39:37 -07001202 taskname ? taskname : "A process ", cred->uid, cred->pid);
Suren Baghdasaryan945658a2019-10-18 11:16:52 -07001203 return;
1204 }
Todd Poynorc58c5142013-07-09 19:35:14 -07001205 proc_unslot(procp);
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -08001206 procp->oomadj = params.oomadj;
Todd Poynorc58c5142013-07-09 19:35:14 -07001207 proc_slot(procp);
1208 }
1209}
1210
Suren Baghdasaryan945658a2019-10-18 11:16:52 -07001211static void cmd_procremove(LMKD_CTRL_PACKET packet, struct ucred *cred) {
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -08001212 struct lmk_procremove params;
Suren Baghdasaryan945658a2019-10-18 11:16:52 -07001213 struct proc *procp;
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -08001214
George Burgess IV3b36b902019-10-02 11:22:55 -07001215 lmkd_pack_get_procremove(packet, &params);
Suren Baghdasaryan945658a2019-10-18 11:16:52 -07001216
Mark Salyzyn5cc80b32018-03-21 12:24:58 -07001217 if (use_inkernel_interface) {
Jing Ji5c480962019-12-04 09:22:05 -08001218 /*
1219 * Perform an extra check before the pid is removed, after which it
1220 * will be impossible for poll_kernel to get the taskname. poll_kernel()
1221 * is potentially a long-running blocking function; however this method
1222 * handles AMS requests but does not block AMS.
1223 */
1224 poll_kernel(kpoll_fd);
1225
1226 stats_remove_taskname(params.pid);
Todd Poynorc58c5142013-07-09 19:35:14 -07001227 return;
Mark Salyzyn5cc80b32018-03-21 12:24:58 -07001228 }
Todd Poynorc58c5142013-07-09 19:35:14 -07001229
Suren Baghdasaryan945658a2019-10-18 11:16:52 -07001230 procp = pid_lookup(params.pid);
1231 if (!procp) {
1232 return;
1233 }
1234
1235 if (!claim_record(procp, cred->pid)) {
1236 char buf[LINE_MAX];
Suren Baghdasaryan9f1be122021-04-23 13:39:37 -07001237 char *taskname = proc_get_name(cred->pid, buf, sizeof(buf));
Suren Baghdasaryan945658a2019-10-18 11:16:52 -07001238 /* Only registrant of the record can remove it */
1239 ALOGE("%s (%d, %d) attempts to unregister a process registered by another client",
Suren Baghdasaryan9f1be122021-04-23 13:39:37 -07001240 taskname ? taskname : "A process ", cred->uid, cred->pid);
Suren Baghdasaryan945658a2019-10-18 11:16:52 -07001241 return;
1242 }
1243
Suren Baghdasaryan8b00c6d2018-10-12 11:28:33 -07001244 /*
1245 * WARNING: After pid_remove() procp is freed and can't be used!
1246 * Therefore placed at the end of the function.
1247 */
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -08001248 pid_remove(params.pid);
Todd Poynorc58c5142013-07-09 19:35:14 -07001249}
1250
Suren Baghdasaryan945658a2019-10-18 11:16:52 -07001251static void cmd_procpurge(struct ucred *cred) {
Suren Baghdasaryan83df0082018-10-10 14:17:17 -07001252 int i;
1253 struct proc *procp;
1254 struct proc *next;
1255
1256 if (use_inkernel_interface) {
Jim Blackler90853b62019-09-10 15:30:05 +01001257 stats_purge_tasknames();
Suren Baghdasaryan83df0082018-10-10 14:17:17 -07001258 return;
1259 }
1260
Suren Baghdasaryan83df0082018-10-10 14:17:17 -07001261 for (i = 0; i < PIDHASH_SZ; i++) {
1262 procp = pidhash[i];
1263 while (procp) {
1264 next = procp->pidhash_next;
Suren Baghdasaryan945658a2019-10-18 11:16:52 -07001265 /* Purge only records created by the requestor */
1266 if (claim_record(procp, cred->pid)) {
1267 pid_remove(procp->pid);
1268 }
Suren Baghdasaryan83df0082018-10-10 14:17:17 -07001269 procp = next;
1270 }
1271 }
Suren Baghdasaryan83df0082018-10-10 14:17:17 -07001272}
1273
Suren Baghdasaryan36baf442019-12-23 11:37:34 -08001274static void cmd_subscribe(int dsock_idx, LMKD_CTRL_PACKET packet) {
1275 struct lmk_subscribe params;
1276
1277 lmkd_pack_get_subscribe(packet, &params);
1278 data_sock[dsock_idx].async_event_mask |= 1 << params.evt_type;
1279}
1280
Suren Baghdasaryana7394ea2018-10-12 11:07:40 -07001281static void inc_killcnt(int oomadj) {
1282 int slot = ADJTOSLOT(oomadj);
1283 uint8_t idx = killcnt_idx[slot];
1284
1285 if (idx == KILLCNT_INVALID_IDX) {
1286 /* index is not assigned for this oomadj */
1287 if (killcnt_free_idx < MAX_DISTINCT_OOM_ADJ) {
1288 killcnt_idx[slot] = killcnt_free_idx;
1289 killcnt[killcnt_free_idx] = 1;
1290 killcnt_free_idx++;
1291 } else {
1292 ALOGW("Number of distinct oomadj levels exceeds %d",
1293 MAX_DISTINCT_OOM_ADJ);
1294 }
1295 } else {
1296 /*
1297 * wraparound is highly unlikely and is detectable using total
1298 * counter because it has to be equal to the sum of all counters
1299 */
1300 killcnt[idx]++;
1301 }
1302 /* increment total kill counter */
1303 killcnt_total++;
1304}
1305
1306static int get_killcnt(int min_oomadj, int max_oomadj) {
1307 int slot;
1308 int count = 0;
1309
1310 if (min_oomadj > max_oomadj)
1311 return 0;
1312
1313 /* special case to get total kill count */
1314 if (min_oomadj > OOM_SCORE_ADJ_MAX)
1315 return killcnt_total;
1316
1317 while (min_oomadj <= max_oomadj &&
1318 (slot = ADJTOSLOT(min_oomadj)) < ADJTOSLOT_COUNT) {
1319 uint8_t idx = killcnt_idx[slot];
1320 if (idx != KILLCNT_INVALID_IDX) {
1321 count += killcnt[idx];
1322 }
1323 min_oomadj++;
1324 }
1325
1326 return count;
1327}
1328
1329static int cmd_getkillcnt(LMKD_CTRL_PACKET packet) {
1330 struct lmk_getkillcnt params;
1331
1332 if (use_inkernel_interface) {
1333 /* kernel driver does not expose this information */
1334 return 0;
1335 }
1336
1337 lmkd_pack_get_getkillcnt(packet, &params);
1338
1339 return get_killcnt(params.min_oomadj, params.max_oomadj);
1340}
1341
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -08001342static void cmd_target(int ntargets, LMKD_CTRL_PACKET packet) {
Todd Poynorc58c5142013-07-09 19:35:14 -07001343 int i;
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -08001344 struct lmk_target target;
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -07001345 char minfree_str[PROPERTY_VALUE_MAX];
1346 char *pstr = minfree_str;
1347 char *pend = minfree_str + sizeof(minfree_str);
1348 static struct timespec last_req_tm;
1349 struct timespec curr_tm;
Todd Poynorc58c5142013-07-09 19:35:14 -07001350
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -07001351 if (ntargets < 1 || ntargets > (int)ARRAY_SIZE(lowmem_adj))
Todd Poynorc58c5142013-07-09 19:35:14 -07001352 return;
1353
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -07001354 /*
1355 * Ratelimit minfree updates to once per TARGET_UPDATE_MIN_INTERVAL_MS
1356 * to prevent DoS attacks
1357 */
1358 if (clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm) != 0) {
1359 ALOGE("Failed to get current time");
1360 return;
1361 }
1362
1363 if (get_time_diff_ms(&last_req_tm, &curr_tm) <
1364 TARGET_UPDATE_MIN_INTERVAL_MS) {
1365 ALOGE("Ignoring frequent updated to lmkd limits");
1366 return;
1367 }
1368
1369 last_req_tm = curr_tm;
1370
Todd Poynorc58c5142013-07-09 19:35:14 -07001371 for (i = 0; i < ntargets; i++) {
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -08001372 lmkd_pack_get_target(packet, i, &target);
1373 lowmem_minfree[i] = target.minfree;
1374 lowmem_adj[i] = target.oom_adj_score;
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -07001375
1376 pstr += snprintf(pstr, pend - pstr, "%d:%d,", target.minfree,
1377 target.oom_adj_score);
1378 if (pstr >= pend) {
1379 /* if no more space in the buffer then terminate the loop */
1380 pstr = pend;
1381 break;
1382 }
Todd Poynorc58c5142013-07-09 19:35:14 -07001383 }
1384
1385 lowmem_targets_size = ntargets;
1386
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -07001387 /* Override the last extra comma */
1388 pstr[-1] = '\0';
1389 property_set("sys.lmk.minfree_levels", minfree_str);
1390
Robert Benea7878c9b2017-09-11 16:53:28 -07001391 if (has_inkernel_module) {
Todd Poynorc58c5142013-07-09 19:35:14 -07001392 char minfreestr[128];
1393 char killpriostr[128];
1394
1395 minfreestr[0] = '\0';
1396 killpriostr[0] = '\0';
1397
1398 for (i = 0; i < lowmem_targets_size; i++) {
1399 char val[40];
1400
1401 if (i) {
1402 strlcat(minfreestr, ",", sizeof(minfreestr));
1403 strlcat(killpriostr, ",", sizeof(killpriostr));
1404 }
1405
Robert Benea7878c9b2017-09-11 16:53:28 -07001406 snprintf(val, sizeof(val), "%d", use_inkernel_interface ? lowmem_minfree[i] : 0);
Todd Poynorc58c5142013-07-09 19:35:14 -07001407 strlcat(minfreestr, val, sizeof(minfreestr));
Robert Benea7878c9b2017-09-11 16:53:28 -07001408 snprintf(val, sizeof(val), "%d", use_inkernel_interface ? lowmem_adj[i] : 0);
Todd Poynorc58c5142013-07-09 19:35:14 -07001409 strlcat(killpriostr, val, sizeof(killpriostr));
1410 }
1411
Suren Baghdasaryanf584fff2018-03-20 13:53:17 -07001412 writefilestring(INKERNEL_MINFREE_PATH, minfreestr, true);
1413 writefilestring(INKERNEL_ADJ_PATH, killpriostr, true);
Todd Poynorc58c5142013-07-09 19:35:14 -07001414 }
1415}
1416
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08001417static void ctrl_command_handler(int dsock_idx) {
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -08001418 LMKD_CTRL_PACKET packet;
Suren Baghdasaryan945658a2019-10-18 11:16:52 -07001419 struct ucred cred;
Todd Poynorc58c5142013-07-09 19:35:14 -07001420 int len;
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -08001421 enum lmk_cmd cmd;
Todd Poynorc58c5142013-07-09 19:35:14 -07001422 int nargs;
1423 int targets;
Suren Baghdasaryana7394ea2018-10-12 11:07:40 -07001424 int kill_cnt;
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07001425 int result;
Todd Poynorc58c5142013-07-09 19:35:14 -07001426
Suren Baghdasaryan945658a2019-10-18 11:16:52 -07001427 len = ctrl_data_read(dsock_idx, (char *)packet, CTRL_PACKET_MAX_SIZE, &cred);
Todd Poynorc58c5142013-07-09 19:35:14 -07001428 if (len <= 0)
1429 return;
1430
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -08001431 if (len < (int)sizeof(int)) {
1432 ALOGE("Wrong control socket read length len=%d", len);
1433 return;
1434 }
1435
1436 cmd = lmkd_pack_get_cmd(packet);
Todd Poynorc58c5142013-07-09 19:35:14 -07001437 nargs = len / sizeof(int) - 1;
1438 if (nargs < 0)
1439 goto wronglen;
1440
Todd Poynorc58c5142013-07-09 19:35:14 -07001441 switch(cmd) {
1442 case LMK_TARGET:
1443 targets = nargs / 2;
1444 if (nargs & 0x1 || targets > (int)ARRAY_SIZE(lowmem_adj))
1445 goto wronglen;
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -08001446 cmd_target(targets, packet);
Todd Poynorc58c5142013-07-09 19:35:14 -07001447 break;
1448 case LMK_PROCPRIO:
Suren Baghdasaryana93503e2019-10-22 17:12:01 -07001449 /* process type field is optional for backward compatibility */
1450 if (nargs < 3 || nargs > 4)
Todd Poynorc58c5142013-07-09 19:35:14 -07001451 goto wronglen;
Suren Baghdasaryana93503e2019-10-22 17:12:01 -07001452 cmd_procprio(packet, nargs, &cred);
Todd Poynorc58c5142013-07-09 19:35:14 -07001453 break;
1454 case LMK_PROCREMOVE:
1455 if (nargs != 1)
1456 goto wronglen;
Suren Baghdasaryan945658a2019-10-18 11:16:52 -07001457 cmd_procremove(packet, &cred);
Todd Poynorc58c5142013-07-09 19:35:14 -07001458 break;
Suren Baghdasaryan83df0082018-10-10 14:17:17 -07001459 case LMK_PROCPURGE:
1460 if (nargs != 0)
1461 goto wronglen;
Suren Baghdasaryan945658a2019-10-18 11:16:52 -07001462 cmd_procpurge(&cred);
Suren Baghdasaryan83df0082018-10-10 14:17:17 -07001463 break;
Suren Baghdasaryana7394ea2018-10-12 11:07:40 -07001464 case LMK_GETKILLCNT:
1465 if (nargs != 2)
1466 goto wronglen;
1467 kill_cnt = cmd_getkillcnt(packet);
1468 len = lmkd_pack_set_getkillcnt_repl(packet, kill_cnt);
1469 if (ctrl_data_write(dsock_idx, (char *)packet, len) != len)
1470 return;
1471 break;
Suren Baghdasaryan36baf442019-12-23 11:37:34 -08001472 case LMK_SUBSCRIBE:
1473 if (nargs != 1)
1474 goto wronglen;
1475 cmd_subscribe(dsock_idx, packet);
1476 break;
Jing Ji5c480962019-12-04 09:22:05 -08001477 case LMK_PROCKILL:
1478 /* This command code is NOT expected at all */
1479 ALOGE("Received unexpected command code %d", cmd);
1480 break;
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07001481 case LMK_UPDATE_PROPS:
1482 if (nargs != 0)
1483 goto wronglen;
1484 update_props();
1485 if (!use_inkernel_interface) {
1486 /* Reinitialize monitors to apply new settings */
1487 destroy_monitors();
1488 result = init_monitors() ? 0 : -1;
1489 } else {
1490 result = 0;
1491 }
1492 len = lmkd_pack_set_update_props_repl(packet, result);
1493 if (ctrl_data_write(dsock_idx, (char *)packet, len) != len) {
1494 ALOGE("Failed to report operation results");
1495 }
1496 if (!result) {
1497 ALOGI("Properties reinitilized");
1498 } else {
1499 /* New settings can't be supported, crash to be restarted */
1500 ALOGE("New configuration is not supported. Exiting...");
1501 exit(1);
1502 }
1503 break;
Todd Poynorc58c5142013-07-09 19:35:14 -07001504 default:
1505 ALOGE("Received unknown command code %d", cmd);
1506 return;
1507 }
1508
1509 return;
1510
1511wronglen:
1512 ALOGE("Wrong control socket read length cmd=%d len=%d", cmd, len);
1513}
1514
Suren Baghdasaryane12a0672019-07-15 14:50:49 -07001515static void ctrl_data_handler(int data, uint32_t events,
1516 struct polling_params *poll_params __unused) {
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08001517 if (events & EPOLLIN) {
1518 ctrl_command_handler(data);
Todd Poynorc58c5142013-07-09 19:35:14 -07001519 }
1520}
1521
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08001522static int get_free_dsock() {
1523 for (int i = 0; i < MAX_DATA_CONN; i++) {
1524 if (data_sock[i].sock < 0) {
1525 return i;
1526 }
1527 }
1528 return -1;
1529}
Todd Poynorc58c5142013-07-09 19:35:14 -07001530
Suren Baghdasaryane12a0672019-07-15 14:50:49 -07001531static void ctrl_connect_handler(int data __unused, uint32_t events __unused,
1532 struct polling_params *poll_params __unused) {
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08001533 struct epoll_event epev;
1534 int free_dscock_idx = get_free_dsock();
1535
1536 if (free_dscock_idx < 0) {
1537 /*
1538 * Number of data connections exceeded max supported. This should not
1539 * happen but if it does we drop all existing connections and accept
1540 * the new one. This prevents inactive connections from monopolizing
1541 * data socket and if we drop ActivityManager connection it will
1542 * immediately reconnect.
1543 */
1544 for (int i = 0; i < MAX_DATA_CONN; i++) {
1545 ctrl_data_close(i);
1546 }
1547 free_dscock_idx = 0;
Todd Poynorc58c5142013-07-09 19:35:14 -07001548 }
1549
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08001550 data_sock[free_dscock_idx].sock = accept(ctrl_sock.sock, NULL, NULL);
1551 if (data_sock[free_dscock_idx].sock < 0) {
Todd Poynorc58c5142013-07-09 19:35:14 -07001552 ALOGE("lmkd control socket accept failed; errno=%d", errno);
1553 return;
1554 }
1555
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08001556 ALOGI("lmkd data connection established");
1557 /* use data to store data connection idx */
1558 data_sock[free_dscock_idx].handler_info.data = free_dscock_idx;
1559 data_sock[free_dscock_idx].handler_info.handler = ctrl_data_handler;
Suren Baghdasaryan36baf442019-12-23 11:37:34 -08001560 data_sock[free_dscock_idx].async_event_mask = 0;
Todd Poynorc58c5142013-07-09 19:35:14 -07001561 epev.events = EPOLLIN;
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08001562 epev.data.ptr = (void *)&(data_sock[free_dscock_idx].handler_info);
1563 if (epoll_ctl(epollfd, EPOLL_CTL_ADD, data_sock[free_dscock_idx].sock, &epev) == -1) {
Todd Poynorc58c5142013-07-09 19:35:14 -07001564 ALOGE("epoll_ctl for data connection socket failed; errno=%d", errno);
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08001565 ctrl_data_close(free_dscock_idx);
Todd Poynorc58c5142013-07-09 19:35:14 -07001566 return;
1567 }
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08001568 maxevents++;
Todd Poynorc58c5142013-07-09 19:35:14 -07001569}
1570
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001571/*
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07001572 * /proc/zoneinfo parsing routines
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001573 * Expected file format is:
1574 *
1575 * Node <node_id>, zone <zone_name>
1576 * (
1577 * per-node stats
1578 * (<per-node field name> <value>)+
1579 * )?
1580 * (pages free <value>
1581 * (<per-zone field name> <value>)+
1582 * pagesets
1583 * (<unused fields>)*
1584 * )+
1585 * ...
1586 */
1587static void zoneinfo_parse_protection(char *buf, struct zoneinfo_zone *zone) {
1588 int zone_idx;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001589 int64_t max = 0;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001590 char *save_ptr;
1591
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001592 for (buf = strtok_r(buf, "(), ", &save_ptr), zone_idx = 0;
1593 buf && zone_idx < MAX_NR_ZONES;
1594 buf = strtok_r(NULL, "), ", &save_ptr), zone_idx++) {
1595 long long zoneval = strtoll(buf, &buf, 0);
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001596 if (zoneval > max) {
1597 max = (zoneval > INT64_MAX) ? INT64_MAX : zoneval;
1598 }
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001599 zone->protection[zone_idx] = zoneval;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001600 }
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001601 zone->max_protection = max;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001602}
1603
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001604static int zoneinfo_parse_zone(char **buf, struct zoneinfo_zone *zone) {
1605 for (char *line = strtok_r(NULL, "\n", buf); line;
1606 line = strtok_r(NULL, "\n", buf)) {
1607 char *cp;
1608 char *ap;
1609 char *save_ptr;
1610 int64_t val;
1611 int field_idx;
1612 enum field_match_result match_res;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001613
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001614 cp = strtok_r(line, " ", &save_ptr);
1615 if (!cp) {
1616 return false;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001617 }
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001618
1619 field_idx = find_field(cp, zoneinfo_zone_spec_field_names, ZI_ZONE_SPEC_FIELD_COUNT);
1620 if (field_idx >= 0) {
1621 /* special field */
1622 if (field_idx == ZI_ZONE_SPEC_PAGESETS) {
1623 /* no mode fields we are interested in */
1624 return true;
1625 }
1626
1627 /* protection field */
1628 ap = strtok_r(NULL, ")", &save_ptr);
1629 if (ap) {
1630 zoneinfo_parse_protection(ap, zone);
1631 }
1632 continue;
1633 }
1634
1635 ap = strtok_r(NULL, " ", &save_ptr);
1636 if (!ap) {
1637 continue;
1638 }
1639
1640 match_res = match_field(cp, ap, zoneinfo_zone_field_names, ZI_ZONE_FIELD_COUNT,
1641 &val, &field_idx);
1642 if (match_res == PARSE_FAIL) {
1643 return false;
1644 }
1645 if (match_res == PARSE_SUCCESS) {
1646 zone->fields.arr[field_idx] = val;
1647 }
1648 if (field_idx == ZI_ZONE_PRESENT && val == 0) {
1649 /* zone is not populated, stop parsing it */
1650 return true;
1651 }
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001652 }
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001653 return false;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001654}
1655
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001656static int zoneinfo_parse_node(char **buf, struct zoneinfo_node *node) {
1657 int fields_to_match = ZI_NODE_FIELD_COUNT;
1658
1659 for (char *line = strtok_r(NULL, "\n", buf); line;
1660 line = strtok_r(NULL, "\n", buf)) {
1661 char *cp;
1662 char *ap;
1663 char *save_ptr;
1664 int64_t val;
1665 int field_idx;
1666 enum field_match_result match_res;
1667
1668 cp = strtok_r(line, " ", &save_ptr);
1669 if (!cp) {
1670 return false;
1671 }
1672
1673 ap = strtok_r(NULL, " ", &save_ptr);
1674 if (!ap) {
1675 return false;
1676 }
1677
1678 match_res = match_field(cp, ap, zoneinfo_node_field_names, ZI_NODE_FIELD_COUNT,
1679 &val, &field_idx);
1680 if (match_res == PARSE_FAIL) {
1681 return false;
1682 }
1683 if (match_res == PARSE_SUCCESS) {
1684 node->fields.arr[field_idx] = val;
1685 fields_to_match--;
1686 if (!fields_to_match) {
1687 return true;
1688 }
1689 }
1690 }
1691 return false;
1692}
1693
1694static int zoneinfo_parse(struct zoneinfo *zi) {
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001695 static struct reread_data file_data = {
1696 .filename = ZONEINFO_PATH,
1697 .fd = -1,
1698 };
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -07001699 char *buf;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001700 char *save_ptr;
1701 char *line;
Greg Kaiser259984f2019-10-02 07:07:32 -07001702 char zone_name[LINE_MAX + 1];
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001703 struct zoneinfo_node *node = NULL;
1704 int node_idx = 0;
1705 int zone_idx = 0;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001706
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001707 memset(zi, 0, sizeof(struct zoneinfo));
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001708
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -07001709 if ((buf = reread_file(&file_data)) == NULL) {
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001710 return -1;
1711 }
1712
1713 for (line = strtok_r(buf, "\n", &save_ptr); line;
1714 line = strtok_r(NULL, "\n", &save_ptr)) {
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001715 int node_id;
1716 if (sscanf(line, "Node %d, zone %" STRINGIFY(LINE_MAX) "s", &node_id, zone_name) == 2) {
1717 if (!node || node->id != node_id) {
1718 /* new node is found */
1719 if (node) {
1720 node->zone_count = zone_idx + 1;
1721 node_idx++;
1722 if (node_idx == MAX_NR_NODES) {
1723 /* max node count exceeded */
1724 ALOGE("%s parse error", file_data.filename);
1725 return -1;
1726 }
1727 }
1728 node = &zi->nodes[node_idx];
1729 node->id = node_id;
1730 zone_idx = 0;
1731 if (!zoneinfo_parse_node(&save_ptr, node)) {
1732 ALOGE("%s parse error", file_data.filename);
1733 return -1;
1734 }
1735 } else {
1736 /* new zone is found */
1737 zone_idx++;
1738 }
1739 if (!zoneinfo_parse_zone(&save_ptr, &node->zones[zone_idx])) {
1740 ALOGE("%s parse error", file_data.filename);
1741 return -1;
1742 }
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001743 }
1744 }
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001745 if (!node) {
1746 ALOGE("%s parse error", file_data.filename);
1747 return -1;
1748 }
1749 node->zone_count = zone_idx + 1;
1750 zi->node_count = node_idx + 1;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001751
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001752 /* calculate totals fields */
1753 for (node_idx = 0; node_idx < zi->node_count; node_idx++) {
1754 node = &zi->nodes[node_idx];
1755 for (zone_idx = 0; zone_idx < node->zone_count; zone_idx++) {
1756 struct zoneinfo_zone *zone = &zi->nodes[node_idx].zones[zone_idx];
1757 zi->totalreserve_pages += zone->max_protection + zone->fields.field.high;
1758 }
1759 zi->total_inactive_file += node->fields.field.nr_inactive_file;
1760 zi->total_active_file += node->fields.field.nr_active_file;
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001761 }
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001762 return 0;
1763}
1764
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07001765/* /proc/meminfo parsing routines */
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001766static bool meminfo_parse_line(char *line, union meminfo *mi) {
1767 char *cp = line;
1768 char *ap;
1769 char *save_ptr;
1770 int64_t val;
1771 int field_idx;
1772 enum field_match_result match_res;
1773
1774 cp = strtok_r(line, " ", &save_ptr);
1775 if (!cp) {
1776 return false;
1777 }
1778
1779 ap = strtok_r(NULL, " ", &save_ptr);
1780 if (!ap) {
1781 return false;
1782 }
1783
1784 match_res = match_field(cp, ap, meminfo_field_names, MI_FIELD_COUNT,
1785 &val, &field_idx);
1786 if (match_res == PARSE_SUCCESS) {
1787 mi->arr[field_idx] = val / page_k;
1788 }
1789 return (match_res != PARSE_FAIL);
1790}
1791
Suren Baghdasaryan940e7cf2021-05-27 18:15:44 -07001792static int64_t read_gpu_total_kb() {
1793 static int fd = android::bpf::bpfFdGet(
1794 "/sys/fs/bpf/map_gpu_mem_gpu_mem_total_map", BPF_F_RDONLY);
1795 static constexpr uint64_t kBpfKeyGpuTotalUsage = 0;
1796 uint64_t value;
1797
1798 if (fd < 0) {
1799 return 0;
1800 }
1801
1802 return android::bpf::findMapEntry(fd, &kBpfKeyGpuTotalUsage, &value)
1803 ? 0
1804 : (int32_t)(value / 1024);
1805}
1806
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001807static int meminfo_parse(union meminfo *mi) {
1808 static struct reread_data file_data = {
1809 .filename = MEMINFO_PATH,
1810 .fd = -1,
1811 };
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -07001812 char *buf;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001813 char *save_ptr;
1814 char *line;
1815
1816 memset(mi, 0, sizeof(union meminfo));
1817
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -07001818 if ((buf = reread_file(&file_data)) == NULL) {
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001819 return -1;
1820 }
1821
1822 for (line = strtok_r(buf, "\n", &save_ptr); line;
1823 line = strtok_r(NULL, "\n", &save_ptr)) {
1824 if (!meminfo_parse_line(line, mi)) {
1825 ALOGE("%s parse error", file_data.filename);
1826 return -1;
1827 }
1828 }
1829 mi->field.nr_file_pages = mi->field.cached + mi->field.swap_cached +
1830 mi->field.buffers;
Suren Baghdasaryan940e7cf2021-05-27 18:15:44 -07001831 mi->field.total_gpu_kb = read_gpu_total_kb();
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001832
1833 return 0;
1834}
1835
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07001836/* /proc/vmstat parsing routines */
1837static bool vmstat_parse_line(char *line, union vmstat *vs) {
1838 char *cp;
1839 char *ap;
1840 char *save_ptr;
1841 int64_t val;
1842 int field_idx;
1843 enum field_match_result match_res;
1844
1845 cp = strtok_r(line, " ", &save_ptr);
1846 if (!cp) {
1847 return false;
1848 }
1849
1850 ap = strtok_r(NULL, " ", &save_ptr);
1851 if (!ap) {
1852 return false;
1853 }
1854
1855 match_res = match_field(cp, ap, vmstat_field_names, VS_FIELD_COUNT,
1856 &val, &field_idx);
1857 if (match_res == PARSE_SUCCESS) {
1858 vs->arr[field_idx] = val;
1859 }
1860 return (match_res != PARSE_FAIL);
1861}
1862
1863static int vmstat_parse(union vmstat *vs) {
1864 static struct reread_data file_data = {
1865 .filename = VMSTAT_PATH,
1866 .fd = -1,
1867 };
1868 char *buf;
1869 char *save_ptr;
1870 char *line;
1871
1872 memset(vs, 0, sizeof(union vmstat));
1873
1874 if ((buf = reread_file(&file_data)) == NULL) {
1875 return -1;
1876 }
1877
1878 for (line = strtok_r(buf, "\n", &save_ptr); line;
1879 line = strtok_r(NULL, "\n", &save_ptr)) {
1880 if (!vmstat_parse_line(line, vs)) {
1881 ALOGE("%s parse error", file_data.filename);
1882 return -1;
1883 }
1884 }
1885
1886 return 0;
1887}
1888
Suren Baghdasaryand7b4fcb2020-07-23 18:00:43 -07001889enum wakeup_reason {
1890 Event,
1891 Polling
1892};
1893
1894struct wakeup_info {
1895 struct timespec wakeup_tm;
1896 struct timespec prev_wakeup_tm;
1897 struct timespec last_event_tm;
1898 int wakeups_since_event;
1899 int skipped_wakeups;
1900};
1901
1902/*
1903 * After the initial memory pressure event is received lmkd schedules periodic wakeups to check
1904 * the memory conditions and kill if needed (polling). This is done because pressure events are
1905 * rate-limited and memory conditions can change in between events. Therefore after the initial
1906 * event there might be multiple wakeups. This function records the wakeup information such as the
1907 * timestamps of the last event and the last wakeup, the number of wakeups since the last event
1908 * and how many of those wakeups were skipped (some wakeups are skipped if previously killed
1909 * process is still freeing its memory).
1910 */
1911static void record_wakeup_time(struct timespec *tm, enum wakeup_reason reason,
1912 struct wakeup_info *wi) {
1913 wi->prev_wakeup_tm = wi->wakeup_tm;
1914 wi->wakeup_tm = *tm;
1915 if (reason == Event) {
1916 wi->last_event_tm = *tm;
1917 wi->wakeups_since_event = 0;
1918 wi->skipped_wakeups = 0;
1919 } else {
1920 wi->wakeups_since_event++;
1921 }
1922}
1923
Ioannis Ilkos279268a2020-08-01 10:50:40 +01001924static void killinfo_log(struct proc* procp, int min_oom_score, int rss_kb,
Ioannis Ilkos48848902021-02-18 19:53:33 +00001925 int swap_kb, int kill_reason, union meminfo *mi,
Suren Baghdasaryand7b4fcb2020-07-23 18:00:43 -07001926 struct wakeup_info *wi, struct timespec *tm) {
Suren Baghdasaryan12cacae2019-09-16 12:06:30 -07001927 /* log process information */
1928 android_log_write_int32(ctx, procp->pid);
1929 android_log_write_int32(ctx, procp->uid);
1930 android_log_write_int32(ctx, procp->oomadj);
1931 android_log_write_int32(ctx, min_oom_score);
Ioannis Ilkos279268a2020-08-01 10:50:40 +01001932 android_log_write_int32(ctx, (int32_t)min(rss_kb, INT32_MAX));
Suren Baghdasaryan12cacae2019-09-16 12:06:30 -07001933 android_log_write_int32(ctx, kill_reason);
1934
1935 /* log meminfo fields */
Suren Baghdasaryan08bfa982018-07-26 16:34:27 -07001936 for (int field_idx = 0; field_idx < MI_FIELD_COUNT; field_idx++) {
1937 android_log_write_int32(ctx, (int32_t)min(mi->arr[field_idx] * page_k, INT32_MAX));
1938 }
1939
Suren Baghdasaryand7b4fcb2020-07-23 18:00:43 -07001940 /* log lmkd wakeup information */
1941 android_log_write_int32(ctx, (int32_t)get_time_diff_ms(&wi->last_event_tm, tm));
1942 android_log_write_int32(ctx, (int32_t)get_time_diff_ms(&wi->prev_wakeup_tm, tm));
1943 android_log_write_int32(ctx, wi->wakeups_since_event);
1944 android_log_write_int32(ctx, wi->skipped_wakeups);
Ioannis Ilkos282437f2021-03-04 17:50:05 +00001945 android_log_write_int32(ctx, (int32_t)min(swap_kb, INT32_MAX));
Suren Baghdasaryan940e7cf2021-05-27 18:15:44 -07001946 android_log_write_int32(ctx, (int32_t)mi->field.total_gpu_kb);
Suren Baghdasaryand7b4fcb2020-07-23 18:00:43 -07001947
Suren Baghdasaryan08bfa982018-07-26 16:34:27 -07001948 android_log_write_list(ctx, LOG_ID_EVENTS);
1949 android_log_reset(ctx);
1950}
1951
Todd Poynorc58c5142013-07-09 19:35:14 -07001952static struct proc *proc_adj_lru(int oomadj) {
1953 return (struct proc *)adjslot_tail(&procadjslot_list[ADJTOSLOT(oomadj)]);
1954}
1955
Suren Baghdasaryaneb7c5492017-12-08 13:17:06 -08001956static struct proc *proc_get_heaviest(int oomadj) {
1957 struct adjslot_list *head = &procadjslot_list[ADJTOSLOT(oomadj)];
1958 struct adjslot_list *curr = head->next;
1959 struct proc *maxprocp = NULL;
1960 int maxsize = 0;
1961 while (curr != head) {
1962 int pid = ((struct proc *)curr)->pid;
1963 int tasksize = proc_get_size(pid);
Suren Baghdasaryan5263aa72021-04-29 15:28:57 -07001964 if (tasksize < 0) {
Suren Baghdasaryaneb7c5492017-12-08 13:17:06 -08001965 struct adjslot_list *next = curr->next;
1966 pid_remove(pid);
1967 curr = next;
1968 } else {
1969 if (tasksize > maxsize) {
1970 maxsize = tasksize;
1971 maxprocp = (struct proc *)curr;
1972 }
1973 curr = curr->next;
1974 }
1975 }
1976 return maxprocp;
1977}
1978
Wei Wangf1ee2e12018-11-21 00:11:44 -08001979static void set_process_group_and_prio(int pid, SchedPolicy sp, int prio) {
1980 DIR* d;
1981 char proc_path[PATH_MAX];
1982 struct dirent* de;
1983
1984 snprintf(proc_path, sizeof(proc_path), "/proc/%d/task", pid);
1985 if (!(d = opendir(proc_path))) {
1986 ALOGW("Failed to open %s; errno=%d: process pid(%d) might have died", proc_path, errno,
1987 pid);
1988 return;
1989 }
1990
1991 while ((de = readdir(d))) {
1992 int t_pid;
1993
1994 if (de->d_name[0] == '.') continue;
1995 t_pid = atoi(de->d_name);
1996
1997 if (!t_pid) {
1998 ALOGW("Failed to get t_pid for '%s' of pid(%d)", de->d_name, pid);
1999 continue;
2000 }
2001
2002 if (setpriority(PRIO_PROCESS, t_pid, prio) && errno != ESRCH) {
2003 ALOGW("Unable to raise priority of killing t_pid (%d): errno=%d", t_pid, errno);
2004 }
2005
2006 if (set_cpuset_policy(t_pid, sp)) {
2007 ALOGW("Failed to set_cpuset_policy on pid(%d) t_pid(%d) to %d", pid, t_pid, (int)sp);
2008 continue;
2009 }
2010 }
2011 closedir(d);
2012}
2013
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002014static bool is_kill_pending(void) {
2015 char buf[24];
2016
2017 if (last_kill_pid_or_fd < 0) {
2018 return false;
2019 }
2020
2021 if (pidfd_supported) {
2022 return true;
2023 }
2024
2025 /* when pidfd is not supported base the decision on /proc/<pid> existence */
2026 snprintf(buf, sizeof(buf), "/proc/%d/", last_kill_pid_or_fd);
2027 if (access(buf, F_OK) == 0) {
2028 return true;
2029 }
2030
2031 return false;
2032}
2033
2034static bool is_waiting_for_kill(void) {
2035 return pidfd_supported && last_kill_pid_or_fd >= 0;
2036}
2037
2038static void stop_wait_for_proc_kill(bool finished) {
2039 struct epoll_event epev;
2040
2041 if (last_kill_pid_or_fd < 0) {
2042 return;
2043 }
2044
2045 if (debug_process_killing) {
2046 struct timespec curr_tm;
2047
2048 if (clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm) != 0) {
2049 /*
2050 * curr_tm is used here merely to report kill duration, so this failure is not fatal.
2051 * Log an error and continue.
2052 */
2053 ALOGE("Failed to get current time");
2054 }
2055
2056 if (finished) {
2057 ALOGI("Process got killed in %ldms",
2058 get_time_diff_ms(&last_kill_tm, &curr_tm));
2059 } else {
2060 ALOGI("Stop waiting for process kill after %ldms",
2061 get_time_diff_ms(&last_kill_tm, &curr_tm));
2062 }
2063 }
2064
2065 if (pidfd_supported) {
2066 /* unregister fd */
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07002067 if (epoll_ctl(epollfd, EPOLL_CTL_DEL, last_kill_pid_or_fd, &epev)) {
2068 // Log an error and keep going
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002069 ALOGE("epoll_ctl for last killed process failed; errno=%d", errno);
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002070 }
2071 maxevents--;
2072 close(last_kill_pid_or_fd);
2073 }
2074
2075 last_kill_pid_or_fd = -1;
2076}
2077
2078static void kill_done_handler(int data __unused, uint32_t events __unused,
2079 struct polling_params *poll_params) {
2080 stop_wait_for_proc_kill(true);
2081 poll_params->update = POLLING_RESUME;
2082}
2083
Suren Baghdasaryana10157c2019-07-19 10:55:39 -07002084static void start_wait_for_proc_kill(int pid_or_fd) {
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002085 static struct event_handler_info kill_done_hinfo = { 0, kill_done_handler };
2086 struct epoll_event epev;
2087
2088 if (last_kill_pid_or_fd >= 0) {
2089 /* Should not happen but if it does we should stop previous wait */
2090 ALOGE("Attempt to wait for a kill while another wait is in progress");
2091 stop_wait_for_proc_kill(false);
2092 }
2093
Suren Baghdasaryana10157c2019-07-19 10:55:39 -07002094 last_kill_pid_or_fd = pid_or_fd;
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002095
Suren Baghdasaryana10157c2019-07-19 10:55:39 -07002096 if (!pidfd_supported) {
2097 /* If pidfd is not supported just store PID and exit */
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002098 return;
2099 }
2100
2101 epev.events = EPOLLIN;
2102 epev.data.ptr = (void *)&kill_done_hinfo;
2103 if (epoll_ctl(epollfd, EPOLL_CTL_ADD, last_kill_pid_or_fd, &epev) != 0) {
2104 ALOGE("epoll_ctl for last kill failed; errno=%d", errno);
2105 close(last_kill_pid_or_fd);
2106 last_kill_pid_or_fd = -1;
2107 return;
2108 }
2109 maxevents++;
2110}
Tim Murraya79ec0f2018-10-25 17:05:41 -07002111
Ioannis Ilkos279268a2020-08-01 10:50:40 +01002112/* Kill one process specified by procp. Returns the size (in pages) of the process killed */
Suren Baghdasaryan3cc1f132020-09-09 20:19:02 -07002113static int kill_one_process(struct proc* procp, int min_oom_score, enum kill_reasons kill_reason,
Suren Baghdasaryand7b4fcb2020-07-23 18:00:43 -07002114 const char *kill_desc, union meminfo *mi, struct wakeup_info *wi,
2115 struct timespec *tm) {
Colin Cross3d57a512014-07-14 12:39:56 -07002116 int pid = procp->pid;
Suren Baghdasaryana10157c2019-07-19 10:55:39 -07002117 int pidfd = procp->pidfd;
Colin Cross3d57a512014-07-14 12:39:56 -07002118 uid_t uid = procp->uid;
2119 char *taskname;
Colin Cross3d57a512014-07-14 12:39:56 -07002120 int r;
Suren Baghdasaryan8b00c6d2018-10-12 11:28:33 -07002121 int result = -1;
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07002122 struct memory_stat *mem_st;
Suren Baghdasaryan3cc1f132020-09-09 20:19:02 -07002123 struct kill_stat kill_st;
Ioannis Ilkos279268a2020-08-01 10:50:40 +01002124 int64_t tgid;
2125 int64_t rss_kb;
2126 int64_t swap_kb;
2127 char buf[PAGE_SIZE];
Rajeev Kumar4aba9152018-01-31 17:54:56 -08002128
Ioannis Ilkos279268a2020-08-01 10:50:40 +01002129 if (!read_proc_status(pid, buf, sizeof(buf))) {
2130 goto out;
2131 }
2132 if (!parse_status_tag(buf, PROC_STATUS_TGID_FIELD, &tgid)) {
2133 ALOGE("Unable to parse tgid from /proc/%d/status", pid);
2134 goto out;
2135 }
2136 if (tgid != pid) {
2137 ALOGE("Possible pid reuse detected (pid %d, tgid %" PRId64 ")!", pid, tgid);
2138 goto out;
2139 }
2140 // Zombie processes will not have RSS / Swap fields.
2141 if (!parse_status_tag(buf, PROC_STATUS_RSS_FIELD, &rss_kb)) {
2142 goto out;
2143 }
2144 if (!parse_status_tag(buf, PROC_STATUS_SWAP_FIELD, &swap_kb)) {
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -07002145 goto out;
2146 }
2147
Suren Baghdasaryan632f1c52019-10-04 16:06:55 -07002148 taskname = proc_get_name(pid, buf, sizeof(buf));
Ioannis Ilkos279268a2020-08-01 10:50:40 +01002149 // taskname will point inside buf, do not reuse buf onwards.
Colin Cross3d57a512014-07-14 12:39:56 -07002150 if (!taskname) {
Suren Baghdasaryan8b00c6d2018-10-12 11:28:33 -07002151 goto out;
Colin Cross3d57a512014-07-14 12:39:56 -07002152 }
2153
Ioannis Ilkos279268a2020-08-01 10:50:40 +01002154 mem_st = stats_read_memory_stat(per_app_memcg, pid, uid, rss_kb * 1024, swap_kb * 1024);
Rajeev Kumar4aba9152018-01-31 17:54:56 -08002155
Suren Baghdasaryan03e19872018-01-04 10:43:58 -08002156 TRACE_KILL_START(pid);
2157
Mark Salyzyna00ccd82018-04-09 09:50:32 -07002158 /* CAP_KILL required */
Suren Baghdasaryana10157c2019-07-19 10:55:39 -07002159 if (pidfd < 0) {
2160 start_wait_for_proc_kill(pid);
2161 r = kill(pid, SIGKILL);
2162 } else {
2163 start_wait_for_proc_kill(pidfd);
Josh Gao84623be2021-03-18 17:16:08 -07002164 r = pidfd_send_signal(pidfd, SIGKILL, NULL, 0);
Suren Baghdasaryana10157c2019-07-19 10:55:39 -07002165 }
Wei Wangf1ee2e12018-11-21 00:11:44 -08002166
Suren Baghdasaryanc2e05b62019-09-04 16:44:47 -07002167 TRACE_KILL_END();
2168
2169 if (r) {
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002170 stop_wait_for_proc_kill(false);
Suren Baghdasaryanc2e05b62019-09-04 16:44:47 -07002171 ALOGE("kill(%d): errno=%d", pid, errno);
2172 /* Delete process record even when we fail to kill so that we don't get stuck on it */
2173 goto out;
2174 }
2175
Wei Wangf1ee2e12018-11-21 00:11:44 -08002176 set_process_group_and_prio(pid, SP_FOREGROUND, ANDROID_PRIORITY_HIGHEST);
2177
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002178 last_kill_tm = *tm;
2179
Suren Baghdasaryana7394ea2018-10-12 11:07:40 -07002180 inc_killcnt(procp->oomadj);
Suren Baghdasaryan12cacae2019-09-16 12:06:30 -07002181
Ioannis Ilkos48848902021-02-18 19:53:33 +00002182 killinfo_log(procp, min_oom_score, rss_kb, swap_kb, kill_reason, mi, wi, tm);
Suren Baghdasaryan12cacae2019-09-16 12:06:30 -07002183
2184 if (kill_desc) {
Ioannis Ilkos48848902021-02-18 19:53:33 +00002185 ALOGI("Kill '%s' (%d), uid %d, oom_score_adj %d to free %" PRId64 "kB rss, %" PRId64
2186 "kB swap; reason: %s", taskname, pid, uid, procp->oomadj, rss_kb, swap_kb, kill_desc);
Suren Baghdasaryan89454e62019-07-15 15:50:17 -07002187 } else {
Ioannis Ilkos48848902021-02-18 19:53:33 +00002188 ALOGI("Kill '%s' (%d), uid %d, oom_score_adj %d to free %" PRId64 "kB rss, %" PRId64
2189 "kb swap", taskname, pid, uid, procp->oomadj, rss_kb, swap_kb);
Suren Baghdasaryan89454e62019-07-15 15:50:17 -07002190 }
Colin Cross3d57a512014-07-14 12:39:56 -07002191
Suren Baghdasaryan3cc1f132020-09-09 20:19:02 -07002192 kill_st.uid = static_cast<int32_t>(uid);
2193 kill_st.taskname = taskname;
2194 kill_st.kill_reason = kill_reason;
2195 kill_st.oom_score = procp->oomadj;
2196 kill_st.min_oom_score = min_oom_score;
2197 kill_st.free_mem_kb = mi->field.nr_free_pages * page_k;
2198 kill_st.free_swap_kb = mi->field.free_swap * page_k;
2199 stats_write_lmk_kill_occurred(&kill_st, mem_st);
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07002200
Jing Ji5c480962019-12-04 09:22:05 -08002201 ctrl_data_write_lmk_kill_occurred((pid_t)pid, uid);
2202
Ioannis Ilkos279268a2020-08-01 10:50:40 +01002203 result = rss_kb / page_k;
Mark Salyzyn1d5fdf32018-02-04 15:27:23 -08002204
Suren Baghdasaryan8b00c6d2018-10-12 11:28:33 -07002205out:
2206 /*
2207 * WARNING: After pid_remove() procp is freed and can't be used!
2208 * Therefore placed at the end of the function.
2209 */
2210 pid_remove(pid);
2211 return result;
Colin Cross3d57a512014-07-14 12:39:56 -07002212}
2213
2214/*
Chris Morin74b4df92021-02-26 00:00:35 -08002215 * Find one process to kill at or above the given oom_score_adj level.
Suren Baghdasaryan85c31b52018-10-26 11:32:15 -07002216 * Returns size of the killed process.
Colin Cross3d57a512014-07-14 12:39:56 -07002217 */
Suren Baghdasaryan3cc1f132020-09-09 20:19:02 -07002218static int find_and_kill_process(int min_score_adj, enum kill_reasons kill_reason,
2219 const char *kill_desc, union meminfo *mi,
2220 struct wakeup_info *wi, struct timespec *tm) {
Colin Cross3d57a512014-07-14 12:39:56 -07002221 int i;
Suren Baghdasaryan85c31b52018-10-26 11:32:15 -07002222 int killed_size = 0;
Yang Lu5dfffbc2018-05-15 04:59:44 +00002223 bool lmk_state_change_start = false;
Suren Baghdasaryan858e8c62021-03-03 11:05:09 -08002224 bool choose_heaviest_task = kill_heaviest_task;
Rajeev Kumar4aba9152018-01-31 17:54:56 -08002225
Chong Zhang1cd12b52015-10-14 16:19:53 -07002226 for (i = OOM_SCORE_ADJ_MAX; i >= min_score_adj; i--) {
Colin Cross3d57a512014-07-14 12:39:56 -07002227 struct proc *procp;
2228
Suren Baghdasaryan858e8c62021-03-03 11:05:09 -08002229 if (!choose_heaviest_task && i <= PERCEPTIBLE_APP_ADJ) {
2230 /*
2231 * If we have to choose a perceptible process, choose the heaviest one to
2232 * hopefully minimize the number of victims.
2233 */
2234 choose_heaviest_task = true;
2235 }
2236
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002237 while (true) {
Suren Baghdasaryan858e8c62021-03-03 11:05:09 -08002238 procp = choose_heaviest_task ?
Suren Baghdasaryan36b2c492018-04-13 11:49:54 -07002239 proc_get_heaviest(i) : proc_adj_lru(i);
Colin Cross3d57a512014-07-14 12:39:56 -07002240
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002241 if (!procp)
2242 break;
2243
Suren Baghdasaryand7b4fcb2020-07-23 18:00:43 -07002244 killed_size = kill_one_process(procp, min_score_adj, kill_reason, kill_desc,
2245 mi, wi, tm);
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002246 if (killed_size >= 0) {
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07002247 if (!lmk_state_change_start) {
Yang Lu5dfffbc2018-05-15 04:59:44 +00002248 lmk_state_change_start = true;
Vova Sharaienkoa92b76b2021-04-24 00:30:06 +00002249 stats_write_lmk_state_changed(STATE_START);
Yang Lu5dfffbc2018-05-15 04:59:44 +00002250 }
Suren Baghdasaryan85c31b52018-10-26 11:32:15 -07002251 break;
Colin Cross3d57a512014-07-14 12:39:56 -07002252 }
2253 }
Suren Baghdasaryan85c31b52018-10-26 11:32:15 -07002254 if (killed_size) {
2255 break;
2256 }
Colin Cross3d57a512014-07-14 12:39:56 -07002257 }
2258
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07002259 if (lmk_state_change_start) {
Vova Sharaienkoa92b76b2021-04-24 00:30:06 +00002260 stats_write_lmk_state_changed(STATE_STOP);
Rajeev Kumar4aba9152018-01-31 17:54:56 -08002261 }
Rajeev Kumar4aba9152018-01-31 17:54:56 -08002262
Suren Baghdasaryan85c31b52018-10-26 11:32:15 -07002263 return killed_size;
Colin Cross3d57a512014-07-14 12:39:56 -07002264}
2265
Suren Baghdasaryan87966742018-04-13 12:43:41 -07002266static int64_t get_memory_usage(struct reread_data *file_data) {
Robert Beneac72b2932017-08-21 15:18:31 -07002267 int64_t mem_usage;
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -07002268 char *buf;
Suren Baghdasaryan87966742018-04-13 12:43:41 -07002269
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -07002270 if ((buf = reread_file(file_data)) == NULL) {
Robert Beneac72b2932017-08-21 15:18:31 -07002271 return -1;
2272 }
2273
Suren Baghdasaryan87966742018-04-13 12:43:41 -07002274 if (!parse_int64(buf, &mem_usage)) {
2275 ALOGE("%s parse error", file_data->filename);
Robert Beneac72b2932017-08-21 15:18:31 -07002276 return -1;
2277 }
Robert Beneac72b2932017-08-21 15:18:31 -07002278 if (mem_usage == 0) {
2279 ALOGE("No memory!");
2280 return -1;
2281 }
2282 return mem_usage;
2283}
2284
Suren Baghdasaryane0f3dd12018-04-13 13:41:12 -07002285void record_low_pressure_levels(union meminfo *mi) {
2286 if (low_pressure_mem.min_nr_free_pages == -1 ||
2287 low_pressure_mem.min_nr_free_pages > mi->field.nr_free_pages) {
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002288 if (debug_process_killing) {
Suren Baghdasaryane0f3dd12018-04-13 13:41:12 -07002289 ALOGI("Low pressure min memory update from %" PRId64 " to %" PRId64,
2290 low_pressure_mem.min_nr_free_pages, mi->field.nr_free_pages);
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002291 }
Suren Baghdasaryane0f3dd12018-04-13 13:41:12 -07002292 low_pressure_mem.min_nr_free_pages = mi->field.nr_free_pages;
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002293 }
2294 /*
2295 * Free memory at low vmpressure events occasionally gets spikes,
2296 * possibly a stale low vmpressure event with memory already
2297 * freed up (no memory pressure should have been reported).
Suren Baghdasaryane0f3dd12018-04-13 13:41:12 -07002298 * Ignore large jumps in max_nr_free_pages that would mess up our stats.
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002299 */
Suren Baghdasaryane0f3dd12018-04-13 13:41:12 -07002300 if (low_pressure_mem.max_nr_free_pages == -1 ||
2301 (low_pressure_mem.max_nr_free_pages < mi->field.nr_free_pages &&
2302 mi->field.nr_free_pages - low_pressure_mem.max_nr_free_pages <
2303 low_pressure_mem.max_nr_free_pages * 0.1)) {
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002304 if (debug_process_killing) {
Suren Baghdasaryane0f3dd12018-04-13 13:41:12 -07002305 ALOGI("Low pressure max memory update from %" PRId64 " to %" PRId64,
2306 low_pressure_mem.max_nr_free_pages, mi->field.nr_free_pages);
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002307 }
Suren Baghdasaryane0f3dd12018-04-13 13:41:12 -07002308 low_pressure_mem.max_nr_free_pages = mi->field.nr_free_pages;
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002309 }
2310}
2311
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08002312enum vmpressure_level upgrade_level(enum vmpressure_level level) {
2313 return (enum vmpressure_level)((level < VMPRESS_LEVEL_CRITICAL) ?
2314 level + 1 : level);
2315}
2316
2317enum vmpressure_level downgrade_level(enum vmpressure_level level) {
2318 return (enum vmpressure_level)((level > VMPRESS_LEVEL_LOW) ?
2319 level - 1 : level);
2320}
2321
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002322enum zone_watermark {
2323 WMARK_MIN = 0,
2324 WMARK_LOW,
2325 WMARK_HIGH,
2326 WMARK_NONE
2327};
2328
Suren Baghdasaryan81c75b22019-08-14 09:48:35 -07002329struct zone_watermarks {
2330 long high_wmark;
2331 long low_wmark;
2332 long min_wmark;
2333};
2334
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002335/*
2336 * Returns lowest breached watermark or WMARK_NONE.
2337 */
Suren Baghdasaryan81c75b22019-08-14 09:48:35 -07002338static enum zone_watermark get_lowest_watermark(union meminfo *mi,
2339 struct zone_watermarks *watermarks)
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002340{
Suren Baghdasaryan81c75b22019-08-14 09:48:35 -07002341 int64_t nr_free_pages = mi->field.nr_free_pages - mi->field.cma_free;
2342
2343 if (nr_free_pages < watermarks->min_wmark) {
2344 return WMARK_MIN;
2345 }
2346 if (nr_free_pages < watermarks->low_wmark) {
2347 return WMARK_LOW;
2348 }
2349 if (nr_free_pages < watermarks->high_wmark) {
2350 return WMARK_HIGH;
2351 }
2352 return WMARK_NONE;
2353}
2354
2355void calc_zone_watermarks(struct zoneinfo *zi, struct zone_watermarks *watermarks) {
2356 memset(watermarks, 0, sizeof(struct zone_watermarks));
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002357
2358 for (int node_idx = 0; node_idx < zi->node_count; node_idx++) {
2359 struct zoneinfo_node *node = &zi->nodes[node_idx];
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002360 for (int zone_idx = 0; zone_idx < node->zone_count; zone_idx++) {
2361 struct zoneinfo_zone *zone = &node->zones[zone_idx];
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002362
2363 if (!zone->fields.field.present) {
2364 continue;
2365 }
2366
Suren Baghdasaryan81c75b22019-08-14 09:48:35 -07002367 watermarks->high_wmark += zone->max_protection + zone->fields.field.high;
2368 watermarks->low_wmark += zone->max_protection + zone->fields.field.low;
2369 watermarks->min_wmark += zone->max_protection + zone->fields.field.min;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002370 }
2371 }
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002372}
2373
Suren Baghdasaryan51ee4c52020-04-21 12:27:01 -07002374static int calc_swap_utilization(union meminfo *mi) {
2375 int64_t swap_used = mi->field.total_swap - mi->field.free_swap;
2376 int64_t total_swappable = mi->field.active_anon + mi->field.inactive_anon +
2377 mi->field.shmem + swap_used;
2378 return total_swappable > 0 ? (swap_used * 100) / total_swappable : 0;
2379}
2380
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002381static void mp_event_psi(int data, uint32_t events, struct polling_params *poll_params) {
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002382 enum reclaim_state {
2383 NO_RECLAIM = 0,
2384 KSWAPD_RECLAIM,
2385 DIRECT_RECLAIM,
2386 };
2387 static int64_t init_ws_refault;
Martin Liu1f72f5f2020-08-21 13:18:50 +08002388 static int64_t prev_workingset_refault;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002389 static int64_t base_file_lru;
2390 static int64_t init_pgscan_kswapd;
2391 static int64_t init_pgscan_direct;
2392 static int64_t swap_low_threshold;
2393 static bool killing;
Martin Liu1f72f5f2020-08-21 13:18:50 +08002394 static int thrashing_limit = thrashing_limit_pct;
Suren Baghdasaryan81c75b22019-08-14 09:48:35 -07002395 static struct zone_watermarks watermarks;
2396 static struct timespec wmark_update_tm;
Suren Baghdasaryand7b4fcb2020-07-23 18:00:43 -07002397 static struct wakeup_info wi;
Martin Liu1f72f5f2020-08-21 13:18:50 +08002398 static struct timespec thrashing_reset_tm;
2399 static int64_t prev_thrash_growth = 0;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002400
2401 union meminfo mi;
2402 union vmstat vs;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002403 struct timespec curr_tm;
2404 int64_t thrashing = 0;
2405 bool swap_is_low = false;
2406 enum vmpressure_level level = (enum vmpressure_level)data;
2407 enum kill_reasons kill_reason = NONE;
2408 bool cycle_after_kill = false;
2409 enum reclaim_state reclaim = NO_RECLAIM;
2410 enum zone_watermark wmark = WMARK_NONE;
Suren Baghdasaryan89454e62019-07-15 15:50:17 -07002411 char kill_desc[LINE_MAX];
Suren Baghdasaryan970a26a2019-09-19 15:27:21 -07002412 bool cut_thrashing_limit = false;
2413 int min_score_adj = 0;
Suren Baghdasaryan51ee4c52020-04-21 12:27:01 -07002414 int swap_util = 0;
Martin Liu1f72f5f2020-08-21 13:18:50 +08002415 long since_thrashing_reset_ms;
Suren Baghdasaryandc60f972020-12-14 13:38:48 -08002416 int64_t workingset_refault_file;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002417
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002418 if (clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm) != 0) {
2419 ALOGE("Failed to get current time");
2420 return;
2421 }
2422
Suren Baghdasaryand7b4fcb2020-07-23 18:00:43 -07002423 record_wakeup_time(&curr_tm, events ? Event : Polling, &wi);
2424
Suren Baghdasaryan03dccf32020-04-28 16:02:13 -07002425 bool kill_pending = is_kill_pending();
Suren Baghdasaryaned715a32020-05-11 16:31:57 -07002426 if (kill_pending && (kill_timeout_ms == 0 ||
2427 get_time_diff_ms(&last_kill_tm, &curr_tm) < static_cast<long>(kill_timeout_ms))) {
Suren Baghdasaryan03dccf32020-04-28 16:02:13 -07002428 /* Skip while still killing a process */
Suren Baghdasaryand7b4fcb2020-07-23 18:00:43 -07002429 wi.skipped_wakeups++;
Suren Baghdasaryan03dccf32020-04-28 16:02:13 -07002430 goto no_kill;
2431 }
2432 /*
2433 * Process is dead or kill timeout is over, stop waiting. This has no effect if pidfds are
2434 * supported and death notification already caused waiting to stop.
2435 */
2436 stop_wait_for_proc_kill(!kill_pending);
2437
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002438 if (vmstat_parse(&vs) < 0) {
2439 ALOGE("Failed to parse vmstat!");
2440 return;
2441 }
Suren Baghdasaryandc60f972020-12-14 13:38:48 -08002442 /* Starting 5.9 kernel workingset_refault vmstat field was renamed workingset_refault_file */
2443 workingset_refault_file = vs.field.workingset_refault ? : vs.field.workingset_refault_file;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002444
2445 if (meminfo_parse(&mi) < 0) {
2446 ALOGE("Failed to parse meminfo!");
2447 return;
2448 }
2449
2450 /* Reset states after process got killed */
2451 if (killing) {
2452 killing = false;
2453 cycle_after_kill = true;
2454 /* Reset file-backed pagecache size and refault amounts after a kill */
2455 base_file_lru = vs.field.nr_inactive_file + vs.field.nr_active_file;
Suren Baghdasaryandc60f972020-12-14 13:38:48 -08002456 init_ws_refault = workingset_refault_file;
Martin Liu1f72f5f2020-08-21 13:18:50 +08002457 thrashing_reset_tm = curr_tm;
2458 prev_thrash_growth = 0;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002459 }
2460
2461 /* Check free swap levels */
2462 if (swap_free_low_percentage) {
2463 if (!swap_low_threshold) {
2464 swap_low_threshold = mi.field.total_swap * swap_free_low_percentage / 100;
2465 }
2466 swap_is_low = mi.field.free_swap < swap_low_threshold;
2467 }
2468
2469 /* Identify reclaim state */
2470 if (vs.field.pgscan_direct > init_pgscan_direct) {
2471 init_pgscan_direct = vs.field.pgscan_direct;
2472 init_pgscan_kswapd = vs.field.pgscan_kswapd;
2473 reclaim = DIRECT_RECLAIM;
2474 } else if (vs.field.pgscan_kswapd > init_pgscan_kswapd) {
2475 init_pgscan_kswapd = vs.field.pgscan_kswapd;
2476 reclaim = KSWAPD_RECLAIM;
Suren Baghdasaryandc60f972020-12-14 13:38:48 -08002477 } else if (workingset_refault_file == prev_workingset_refault) {
Martin Liu1f72f5f2020-08-21 13:18:50 +08002478 /* Device is not thrashing and not reclaiming, bail out early until we see these stats changing*/
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002479 goto no_kill;
2480 }
2481
Suren Baghdasaryandc60f972020-12-14 13:38:48 -08002482 prev_workingset_refault = workingset_refault_file;
Martin Liu1f72f5f2020-08-21 13:18:50 +08002483
2484 /*
2485 * It's possible we fail to find an eligible process to kill (ex. no process is
2486 * above oom_adj_min). When this happens, we should retry to find a new process
2487 * for a kill whenever a new eligible process is available. This is especially
2488 * important for a slow growing refault case. While retrying, we should keep
2489 * monitoring new thrashing counter as someone could release the memory to mitigate
2490 * the thrashing. Thus, when thrashing reset window comes, we decay the prev thrashing
2491 * counter by window counts. if the counter is still greater than thrashing limit,
2492 * we preserve the current prev_thrash counter so we will retry kill again. Otherwise,
2493 * we reset the prev_thrash counter so we will stop retrying.
2494 */
2495 since_thrashing_reset_ms = get_time_diff_ms(&thrashing_reset_tm, &curr_tm);
2496 if (since_thrashing_reset_ms > THRASHING_RESET_INTERVAL_MS) {
2497 long windows_passed;
2498 /* Calculate prev_thrash_growth if we crossed THRASHING_RESET_INTERVAL_MS */
Suren Baghdasaryandc60f972020-12-14 13:38:48 -08002499 prev_thrash_growth = (workingset_refault_file - init_ws_refault) * 100
Martin Liuc3108412020-09-03 22:12:14 +08002500 / (base_file_lru + 1);
Martin Liu1f72f5f2020-08-21 13:18:50 +08002501 windows_passed = (since_thrashing_reset_ms / THRASHING_RESET_INTERVAL_MS);
2502 /*
2503 * Decay prev_thrashing unless over-the-limit thrashing was registered in the window we
2504 * just crossed, which means there were no eligible processes to kill. We preserve the
2505 * counter in that case to ensure a kill if a new eligible process appears.
2506 */
2507 if (windows_passed > 1 || prev_thrash_growth < thrashing_limit) {
2508 prev_thrash_growth >>= windows_passed;
2509 }
2510
2511 /* Record file-backed pagecache size when crossing THRASHING_RESET_INTERVAL_MS */
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002512 base_file_lru = vs.field.nr_inactive_file + vs.field.nr_active_file;
Suren Baghdasaryandc60f972020-12-14 13:38:48 -08002513 init_ws_refault = workingset_refault_file;
Martin Liu1f72f5f2020-08-21 13:18:50 +08002514 thrashing_reset_tm = curr_tm;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002515 thrashing_limit = thrashing_limit_pct;
2516 } else {
2517 /* Calculate what % of the file-backed pagecache refaulted so far */
Suren Baghdasaryandc60f972020-12-14 13:38:48 -08002518 thrashing = (workingset_refault_file - init_ws_refault) * 100 / (base_file_lru + 1);
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002519 }
Martin Liu1f72f5f2020-08-21 13:18:50 +08002520 /* Add previous cycle's decayed thrashing amount */
2521 thrashing += prev_thrash_growth;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002522
Suren Baghdasaryan81c75b22019-08-14 09:48:35 -07002523 /*
2524 * Refresh watermarks once per min in case user updated one of the margins.
2525 * TODO: b/140521024 replace this periodic update with an API for AMS to notify LMKD
2526 * that zone watermarks were changed by the system software.
2527 */
2528 if (watermarks.high_wmark == 0 || get_time_diff_ms(&wmark_update_tm, &curr_tm) > 60000) {
2529 struct zoneinfo zi;
2530
2531 if (zoneinfo_parse(&zi) < 0) {
2532 ALOGE("Failed to parse zoneinfo!");
2533 return;
2534 }
2535
2536 calc_zone_watermarks(&zi, &watermarks);
2537 wmark_update_tm = curr_tm;
Martin Liu1f72f5f2020-08-21 13:18:50 +08002538 }
Suren Baghdasaryan81c75b22019-08-14 09:48:35 -07002539
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002540 /* Find out which watermark is breached if any */
Suren Baghdasaryan81c75b22019-08-14 09:48:35 -07002541 wmark = get_lowest_watermark(&mi, &watermarks);
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002542
2543 /*
2544 * TODO: move this logic into a separate function
2545 * Decide if killing a process is necessary and record the reason
2546 */
2547 if (cycle_after_kill && wmark < WMARK_LOW) {
2548 /*
2549 * Prevent kills not freeing enough memory which might lead to OOM kill.
2550 * This might happen when a process is consuming memory faster than reclaim can
2551 * free even after a kill. Mostly happens when running memory stress tests.
2552 */
2553 kill_reason = PRESSURE_AFTER_KILL;
Suren Baghdasaryan89454e62019-07-15 15:50:17 -07002554 strncpy(kill_desc, "min watermark is breached even after kill", sizeof(kill_desc));
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002555 } else if (level == VMPRESS_LEVEL_CRITICAL && events != 0) {
2556 /*
2557 * Device is too busy reclaiming memory which might lead to ANR.
2558 * Critical level is triggered when PSI complete stall (all tasks are blocked because
2559 * of the memory congestion) breaches the configured threshold.
2560 */
2561 kill_reason = NOT_RESPONDING;
Suren Baghdasaryan89454e62019-07-15 15:50:17 -07002562 strncpy(kill_desc, "device is not responding", sizeof(kill_desc));
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002563 } else if (swap_is_low && thrashing > thrashing_limit_pct) {
2564 /* Page cache is thrashing while swap is low */
2565 kill_reason = LOW_SWAP_AND_THRASHING;
Suren Baghdasaryan89454e62019-07-15 15:50:17 -07002566 snprintf(kill_desc, sizeof(kill_desc), "device is low on swap (%" PRId64
2567 "kB < %" PRId64 "kB) and thrashing (%" PRId64 "%%)",
2568 mi.field.free_swap * page_k, swap_low_threshold * page_k, thrashing);
Suren Baghdasaryan0142b3c2021-03-03 11:11:09 -08002569 /* Do not kill perceptible apps unless below min watermark or heavily thrashing */
2570 if (wmark > WMARK_MIN && thrashing < thrashing_critical_pct) {
Suren Baghdasaryan48135c42020-05-19 12:59:18 -07002571 min_score_adj = PERCEPTIBLE_APP_ADJ + 1;
2572 }
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002573 } else if (swap_is_low && wmark < WMARK_HIGH) {
2574 /* Both free memory and swap are low */
2575 kill_reason = LOW_MEM_AND_SWAP;
Suren Baghdasaryan89454e62019-07-15 15:50:17 -07002576 snprintf(kill_desc, sizeof(kill_desc), "%s watermark is breached and swap is low (%"
Suren Baghdasaryan23678182021-03-02 18:33:09 -08002577 PRId64 "kB < %" PRId64 "kB)", wmark < WMARK_LOW ? "min" : "low",
Suren Baghdasaryan89454e62019-07-15 15:50:17 -07002578 mi.field.free_swap * page_k, swap_low_threshold * page_k);
Suren Baghdasaryan0142b3c2021-03-03 11:11:09 -08002579 /* Do not kill perceptible apps unless below min watermark or heavily thrashing */
2580 if (wmark > WMARK_MIN && thrashing < thrashing_critical_pct) {
Suren Baghdasaryan48135c42020-05-19 12:59:18 -07002581 min_score_adj = PERCEPTIBLE_APP_ADJ + 1;
2582 }
Suren Baghdasaryan51ee4c52020-04-21 12:27:01 -07002583 } else if (wmark < WMARK_HIGH && swap_util_max < 100 &&
2584 (swap_util = calc_swap_utilization(&mi)) > swap_util_max) {
2585 /*
2586 * Too much anon memory is swapped out but swap is not low.
2587 * Non-swappable allocations created memory pressure.
2588 */
2589 kill_reason = LOW_MEM_AND_SWAP_UTIL;
2590 snprintf(kill_desc, sizeof(kill_desc), "%s watermark is breached and swap utilization"
Suren Baghdasaryan23678182021-03-02 18:33:09 -08002591 " is high (%d%% > %d%%)", wmark < WMARK_LOW ? "min" : "low",
Suren Baghdasaryan51ee4c52020-04-21 12:27:01 -07002592 swap_util, swap_util_max);
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002593 } else if (wmark < WMARK_HIGH && thrashing > thrashing_limit) {
2594 /* Page cache is thrashing while memory is low */
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002595 kill_reason = LOW_MEM_AND_THRASHING;
Suren Baghdasaryan89454e62019-07-15 15:50:17 -07002596 snprintf(kill_desc, sizeof(kill_desc), "%s watermark is breached and thrashing (%"
Suren Baghdasaryan23678182021-03-02 18:33:09 -08002597 PRId64 "%%)", wmark < WMARK_LOW ? "min" : "low", thrashing);
Suren Baghdasaryan970a26a2019-09-19 15:27:21 -07002598 cut_thrashing_limit = true;
Suren Baghdasaryan0142b3c2021-03-03 11:11:09 -08002599 /* Do not kill perceptible apps unless thrashing at critical levels */
2600 if (thrashing < thrashing_critical_pct) {
2601 min_score_adj = PERCEPTIBLE_APP_ADJ + 1;
2602 }
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002603 } else if (reclaim == DIRECT_RECLAIM && thrashing > thrashing_limit) {
2604 /* Page cache is thrashing while in direct reclaim (mostly happens on lowram devices) */
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002605 kill_reason = DIRECT_RECL_AND_THRASHING;
Suren Baghdasaryan89454e62019-07-15 15:50:17 -07002606 snprintf(kill_desc, sizeof(kill_desc), "device is in direct reclaim and thrashing (%"
2607 PRId64 "%%)", thrashing);
Suren Baghdasaryan970a26a2019-09-19 15:27:21 -07002608 cut_thrashing_limit = true;
Suren Baghdasaryan0142b3c2021-03-03 11:11:09 -08002609 /* Do not kill perceptible apps unless thrashing at critical levels */
2610 if (thrashing < thrashing_critical_pct) {
2611 min_score_adj = PERCEPTIBLE_APP_ADJ + 1;
2612 }
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002613 }
2614
2615 /* Kill a process if necessary */
2616 if (kill_reason != NONE) {
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002617 int pages_freed = find_and_kill_process(min_score_adj, kill_reason, kill_desc, &mi,
Suren Baghdasaryand7b4fcb2020-07-23 18:00:43 -07002618 &wi, &curr_tm);
Suren Baghdasaryan970a26a2019-09-19 15:27:21 -07002619 if (pages_freed > 0) {
2620 killing = true;
2621 if (cut_thrashing_limit) {
2622 /*
2623 * Cut thrasing limit by thrashing_limit_decay_pct percentage of the current
2624 * thrashing limit until the system stops thrashing.
2625 */
2626 thrashing_limit = (thrashing_limit * (100 - thrashing_limit_decay_pct)) / 100;
2627 }
2628 }
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002629 }
2630
2631no_kill:
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002632 /* Do not poll if kernel supports pidfd waiting */
2633 if (is_waiting_for_kill()) {
2634 /* Pause polling if we are waiting for process death notification */
2635 poll_params->update = POLLING_PAUSE;
2636 return;
2637 }
2638
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002639 /*
2640 * Start polling after initial PSI event;
2641 * extend polling while device is in direct reclaim or process is being killed;
2642 * do not extend when kswapd reclaims because that might go on for a long time
2643 * without causing memory pressure
2644 */
2645 if (events || killing || reclaim == DIRECT_RECLAIM) {
2646 poll_params->update = POLLING_START;
2647 }
2648
2649 /* Decide the polling interval */
2650 if (swap_is_low || killing) {
2651 /* Fast polling during and after a kill or when swap is low */
2652 poll_params->polling_interval_ms = PSI_POLL_PERIOD_SHORT_MS;
2653 } else {
2654 /* By default use long intervals */
2655 poll_params->polling_interval_ms = PSI_POLL_PERIOD_LONG_MS;
2656 }
2657}
2658
Suren Baghdasaryane12a0672019-07-15 14:50:49 -07002659static void mp_event_common(int data, uint32_t events, struct polling_params *poll_params) {
Todd Poynorc58c5142013-07-09 19:35:14 -07002660 unsigned long long evcount;
Robert Beneac72b2932017-08-21 15:18:31 -07002661 int64_t mem_usage, memsw_usage;
Robert Benea3be16142017-09-13 15:20:30 -07002662 int64_t mem_pressure;
Suren Baghdasaryane0f3dd12018-04-13 13:41:12 -07002663 union meminfo mi;
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07002664 struct zoneinfo zi;
Suren Baghdasaryan53be36e2018-09-05 15:46:32 -07002665 struct timespec curr_tm;
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -07002666 static unsigned long kill_skip_count = 0;
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08002667 enum vmpressure_level level = (enum vmpressure_level)data;
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07002668 long other_free = 0, other_file = 0;
2669 int min_score_adj;
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07002670 int minfree = 0;
Suren Baghdasaryan87966742018-04-13 12:43:41 -07002671 static struct reread_data mem_usage_file_data = {
2672 .filename = MEMCG_MEMORY_USAGE,
2673 .fd = -1,
2674 };
2675 static struct reread_data memsw_usage_file_data = {
2676 .filename = MEMCG_MEMORYSW_USAGE,
2677 .fd = -1,
2678 };
Suren Baghdasaryand7b4fcb2020-07-23 18:00:43 -07002679 static struct wakeup_info wi;
Todd Poynorc58c5142013-07-09 19:35:14 -07002680
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08002681 if (debug_process_killing) {
2682 ALOGI("%s memory pressure event is triggered", level_name[level]);
2683 }
2684
2685 if (!use_psi_monitors) {
2686 /*
2687 * Check all event counters from low to critical
2688 * and upgrade to the highest priority one. By reading
2689 * eventfd we also reset the event counters.
2690 */
Tom Cherry43f3d2b2019-12-04 12:46:57 -08002691 for (int lvl = VMPRESS_LEVEL_LOW; lvl < VMPRESS_LEVEL_COUNT; lvl++) {
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08002692 if (mpevfd[lvl] != -1 &&
2693 TEMP_FAILURE_RETRY(read(mpevfd[lvl],
2694 &evcount, sizeof(evcount))) > 0 &&
2695 evcount > 0 && lvl > level) {
Tom Cherry43f3d2b2019-12-04 12:46:57 -08002696 level = static_cast<vmpressure_level>(lvl);
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08002697 }
Suren Baghdasaryan3e1a8492018-01-04 09:16:21 -08002698 }
2699 }
Todd Poynorc58c5142013-07-09 19:35:14 -07002700
Suren Baghdasaryane12a0672019-07-15 14:50:49 -07002701 /* Start polling after initial PSI event */
2702 if (use_psi_monitors && events) {
2703 /* Override polling params only if current event is more critical */
2704 if (!poll_params->poll_handler || data > poll_params->poll_handler->data) {
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002705 poll_params->polling_interval_ms = PSI_POLL_PERIOD_SHORT_MS;
Suren Baghdasaryane12a0672019-07-15 14:50:49 -07002706 poll_params->update = POLLING_START;
2707 }
2708 }
2709
Suren Baghdasaryan53be36e2018-09-05 15:46:32 -07002710 if (clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm) != 0) {
2711 ALOGE("Failed to get current time");
2712 return;
2713 }
2714
Suren Baghdasaryand7b4fcb2020-07-23 18:00:43 -07002715 record_wakeup_time(&curr_tm, events ? Event : Polling, &wi);
2716
Suren Baghdasaryaned715a32020-05-11 16:31:57 -07002717 if (kill_timeout_ms &&
2718 get_time_diff_ms(&last_kill_tm, &curr_tm) < static_cast<long>(kill_timeout_ms)) {
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002719 /*
2720 * If we're within the no-kill timeout, see if there's pending reclaim work
2721 * from the last killed process. If so, skip killing for now.
2722 */
2723 if (is_kill_pending()) {
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -07002724 kill_skip_count++;
Suren Baghdasaryand7b4fcb2020-07-23 18:00:43 -07002725 wi.skipped_wakeups++;
Suren Baghdasaryan30854e72018-01-17 17:28:01 -08002726 return;
2727 }
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002728 /*
2729 * Process is dead, stop waiting. This has no effect if pidfds are supported and
2730 * death notification already caused waiting to stop.
2731 */
2732 stop_wait_for_proc_kill(true);
2733 } else {
2734 /*
2735 * Killing took longer than no-kill timeout. Stop waiting for the last process
2736 * to die because we are ready to kill again.
2737 */
2738 stop_wait_for_proc_kill(false);
Suren Baghdasaryan30854e72018-01-17 17:28:01 -08002739 }
2740
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -07002741 if (kill_skip_count > 0) {
Suren Baghdasaryaneff82332018-05-10 16:10:56 -07002742 ALOGI("%lu memory pressure events were skipped after a kill!",
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -07002743 kill_skip_count);
2744 kill_skip_count = 0;
Suren Baghdasaryan30854e72018-01-17 17:28:01 -08002745 }
2746
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07002747 if (meminfo_parse(&mi) < 0 || zoneinfo_parse(&zi) < 0) {
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002748 ALOGE("Failed to get free memory!");
2749 return;
2750 }
2751
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07002752 if (use_minfree_levels) {
2753 int i;
2754
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07002755 other_free = mi.field.nr_free_pages - zi.totalreserve_pages;
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07002756 if (mi.field.nr_file_pages > (mi.field.shmem + mi.field.unevictable + mi.field.swap_cached)) {
2757 other_file = (mi.field.nr_file_pages - mi.field.shmem -
2758 mi.field.unevictable - mi.field.swap_cached);
2759 } else {
2760 other_file = 0;
2761 }
2762
2763 min_score_adj = OOM_SCORE_ADJ_MAX + 1;
2764 for (i = 0; i < lowmem_targets_size; i++) {
2765 minfree = lowmem_minfree[i];
2766 if (other_free < minfree && other_file < minfree) {
2767 min_score_adj = lowmem_adj[i];
2768 break;
2769 }
2770 }
2771
Suren Baghdasaryanb0bda552018-05-18 14:42:00 -07002772 if (min_score_adj == OOM_SCORE_ADJ_MAX + 1) {
2773 if (debug_process_killing) {
2774 ALOGI("Ignore %s memory pressure event "
2775 "(free memory=%ldkB, cache=%ldkB, limit=%ldkB)",
2776 level_name[level], other_free * page_k, other_file * page_k,
2777 (long)lowmem_minfree[lowmem_targets_size - 1] * page_k);
2778 }
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07002779 return;
Suren Baghdasaryanb0bda552018-05-18 14:42:00 -07002780 }
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07002781
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07002782 goto do_kill;
2783 }
2784
Suren Baghdasaryane0f3dd12018-04-13 13:41:12 -07002785 if (level == VMPRESS_LEVEL_LOW) {
2786 record_low_pressure_levels(&mi);
2787 }
2788
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002789 if (level_oomadj[level] > OOM_SCORE_ADJ_MAX) {
2790 /* Do not monitor this pressure level */
2791 return;
2792 }
2793
Suren Baghdasaryan87966742018-04-13 12:43:41 -07002794 if ((mem_usage = get_memory_usage(&mem_usage_file_data)) < 0) {
2795 goto do_kill;
2796 }
2797 if ((memsw_usage = get_memory_usage(&memsw_usage_file_data)) < 0) {
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08002798 goto do_kill;
Robert Benea3be16142017-09-13 15:20:30 -07002799 }
Robert Beneac72b2932017-08-21 15:18:31 -07002800
Robert Benea3be16142017-09-13 15:20:30 -07002801 // Calculate percent for swappinness.
2802 mem_pressure = (mem_usage * 100) / memsw_usage;
2803
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08002804 if (enable_pressure_upgrade && level != VMPRESS_LEVEL_CRITICAL) {
Robert Benea3be16142017-09-13 15:20:30 -07002805 // We are swapping too much.
2806 if (mem_pressure < upgrade_pressure) {
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08002807 level = upgrade_level(level);
2808 if (debug_process_killing) {
2809 ALOGI("Event upgraded to %s", level_name[level]);
2810 }
Robert Beneac72b2932017-08-21 15:18:31 -07002811 }
2812 }
2813
Vic Yang65680692018-08-07 10:18:22 -07002814 // If we still have enough swap space available, check if we want to
2815 // ignore/downgrade pressure events.
2816 if (mi.field.free_swap >=
2817 mi.field.total_swap * swap_free_low_percentage / 100) {
2818 // If the pressure is larger than downgrade_pressure lmk will not
2819 // kill any process, since enough memory is available.
2820 if (mem_pressure > downgrade_pressure) {
2821 if (debug_process_killing) {
2822 ALOGI("Ignore %s memory pressure", level_name[level]);
2823 }
2824 return;
2825 } else if (level == VMPRESS_LEVEL_CRITICAL && mem_pressure > upgrade_pressure) {
2826 if (debug_process_killing) {
2827 ALOGI("Downgrade critical memory pressure");
2828 }
2829 // Downgrade event, since enough memory available.
2830 level = downgrade_level(level);
Robert Benea3be16142017-09-13 15:20:30 -07002831 }
Robert Benea3be16142017-09-13 15:20:30 -07002832 }
2833
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08002834do_kill:
Suren Baghdasaryand1d59f82018-04-13 11:45:38 -07002835 if (low_ram_device) {
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002836 /* For Go devices kill only one task */
Suren Baghdasaryan3cc1f132020-09-09 20:19:02 -07002837 if (find_and_kill_process(level_oomadj[level], NONE, NULL, &mi, &wi, &curr_tm) == 0) {
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002838 if (debug_process_killing) {
2839 ALOGI("Nothing to kill");
2840 }
2841 }
2842 } else {
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07002843 int pages_freed;
Suren Baghdasaryan53be36e2018-09-05 15:46:32 -07002844 static struct timespec last_report_tm;
2845 static unsigned long report_skip_count = 0;
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07002846
2847 if (!use_minfree_levels) {
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07002848 /* Free up enough memory to downgrate the memory pressure to low level */
Suren Baghdasaryan85c31b52018-10-26 11:32:15 -07002849 if (mi.field.nr_free_pages >= low_pressure_mem.max_nr_free_pages) {
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07002850 if (debug_process_killing) {
2851 ALOGI("Ignoring pressure since more memory is "
2852 "available (%" PRId64 ") than watermark (%" PRId64 ")",
2853 mi.field.nr_free_pages, low_pressure_mem.max_nr_free_pages);
2854 }
2855 return;
2856 }
2857 min_score_adj = level_oomadj[level];
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002858 }
2859
Suren Baghdasaryan3cc1f132020-09-09 20:19:02 -07002860 pages_freed = find_and_kill_process(min_score_adj, NONE, NULL, &mi, &wi, &curr_tm);
Suren Baghdasaryaneff82332018-05-10 16:10:56 -07002861
Suren Baghdasaryan53be36e2018-09-05 15:46:32 -07002862 if (pages_freed == 0) {
2863 /* Rate limit kill reports when nothing was reclaimed */
2864 if (get_time_diff_ms(&last_report_tm, &curr_tm) < FAIL_REPORT_RLIMIT_MS) {
2865 report_skip_count++;
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -07002866 return;
2867 }
Robert Benea7f68a3f2017-08-11 16:03:20 -07002868 }
Suren Baghdasaryan53be36e2018-09-05 15:46:32 -07002869
Suren Baghdasaryan12cacae2019-09-16 12:06:30 -07002870 /* Log whenever we kill or when report rate limit allows */
Suren Baghdasaryan53be36e2018-09-05 15:46:32 -07002871 if (use_minfree_levels) {
Chris Morin74b4df92021-02-26 00:00:35 -08002872 ALOGI("Reclaimed %ldkB, cache(%ldkB) and free(%" PRId64 "kB)-reserved(%" PRId64 "kB) "
2873 "below min(%ldkB) for oom_score_adj %d",
Suren Baghdasaryan85c31b52018-10-26 11:32:15 -07002874 pages_freed * page_k,
Suren Baghdasaryan53be36e2018-09-05 15:46:32 -07002875 other_file * page_k, mi.field.nr_free_pages * page_k,
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07002876 zi.totalreserve_pages * page_k,
Suren Baghdasaryan53be36e2018-09-05 15:46:32 -07002877 minfree * page_k, min_score_adj);
2878 } else {
Chris Morin74b4df92021-02-26 00:00:35 -08002879 ALOGI("Reclaimed %ldkB at oom_score_adj %d", pages_freed * page_k, min_score_adj);
Suren Baghdasaryan53be36e2018-09-05 15:46:32 -07002880 }
2881
2882 if (report_skip_count > 0) {
2883 ALOGI("Suppressed %lu failed kill reports", report_skip_count);
2884 report_skip_count = 0;
2885 }
2886
2887 last_report_tm = curr_tm;
Colin Cross01db2712014-07-11 17:16:56 -07002888 }
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002889 if (is_waiting_for_kill()) {
2890 /* pause polling if we are waiting for process death notification */
2891 poll_params->update = POLLING_PAUSE;
2892 }
Todd Poynorc58c5142013-07-09 19:35:14 -07002893}
2894
Suren Baghdasaryan2f88e152019-07-15 15:42:09 -07002895static bool init_mp_psi(enum vmpressure_level level, bool use_new_strategy) {
2896 int fd;
2897
2898 /* Do not register a handler if threshold_ms is not set */
2899 if (!psi_thresholds[level].threshold_ms) {
2900 return true;
2901 }
2902
2903 fd = init_psi_monitor(psi_thresholds[level].stall_type,
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08002904 psi_thresholds[level].threshold_ms * US_PER_MS,
2905 PSI_WINDOW_SIZE_MS * US_PER_MS);
2906
2907 if (fd < 0) {
2908 return false;
2909 }
2910
Suren Baghdasaryan2f88e152019-07-15 15:42:09 -07002911 vmpressure_hinfo[level].handler = use_new_strategy ? mp_event_psi : mp_event_common;
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08002912 vmpressure_hinfo[level].data = level;
2913 if (register_psi_monitor(epollfd, fd, &vmpressure_hinfo[level]) < 0) {
2914 destroy_psi_monitor(fd);
2915 return false;
2916 }
2917 maxevents++;
2918 mpevfd[level] = fd;
2919
2920 return true;
2921}
2922
2923static void destroy_mp_psi(enum vmpressure_level level) {
2924 int fd = mpevfd[level];
2925
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07002926 if (fd < 0) {
2927 return;
2928 }
2929
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08002930 if (unregister_psi_monitor(epollfd, fd) < 0) {
2931 ALOGE("Failed to unregister psi monitor for %s memory pressure; errno=%d",
2932 level_name[level], errno);
2933 }
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07002934 maxevents--;
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08002935 destroy_psi_monitor(fd);
2936 mpevfd[level] = -1;
2937}
2938
2939static bool init_psi_monitors() {
Suren Baghdasaryan2f88e152019-07-15 15:42:09 -07002940 /*
2941 * When PSI is used on low-ram devices or on high-end devices without memfree levels
2942 * use new kill strategy based on zone watermarks, free swap and thrashing stats
2943 */
2944 bool use_new_strategy =
2945 property_get_bool("ro.lmk.use_new_strategy", low_ram_device || !use_minfree_levels);
2946
2947 /* In default PSI mode override stall amounts using system properties */
2948 if (use_new_strategy) {
2949 /* Do not use low pressure level */
2950 psi_thresholds[VMPRESS_LEVEL_LOW].threshold_ms = 0;
2951 psi_thresholds[VMPRESS_LEVEL_MEDIUM].threshold_ms = psi_partial_stall_ms;
2952 psi_thresholds[VMPRESS_LEVEL_CRITICAL].threshold_ms = psi_complete_stall_ms;
2953 }
2954
2955 if (!init_mp_psi(VMPRESS_LEVEL_LOW, use_new_strategy)) {
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08002956 return false;
2957 }
Suren Baghdasaryan2f88e152019-07-15 15:42:09 -07002958 if (!init_mp_psi(VMPRESS_LEVEL_MEDIUM, use_new_strategy)) {
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08002959 destroy_mp_psi(VMPRESS_LEVEL_LOW);
2960 return false;
2961 }
Suren Baghdasaryan2f88e152019-07-15 15:42:09 -07002962 if (!init_mp_psi(VMPRESS_LEVEL_CRITICAL, use_new_strategy)) {
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08002963 destroy_mp_psi(VMPRESS_LEVEL_MEDIUM);
2964 destroy_mp_psi(VMPRESS_LEVEL_LOW);
2965 return false;
2966 }
2967 return true;
2968}
2969
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08002970static bool init_mp_common(enum vmpressure_level level) {
Todd Poynorc58c5142013-07-09 19:35:14 -07002971 int mpfd;
2972 int evfd;
2973 int evctlfd;
2974 char buf[256];
2975 struct epoll_event epev;
2976 int ret;
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08002977 int level_idx = (int)level;
2978 const char *levelstr = level_name[level_idx];
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08002979
Mark Salyzyna00ccd82018-04-09 09:50:32 -07002980 /* gid containing AID_SYSTEM required */
Nick Kralevich148d8dd2015-12-18 20:52:37 -08002981 mpfd = open(MEMCG_SYSFS_PATH "memory.pressure_level", O_RDONLY | O_CLOEXEC);
Todd Poynorc58c5142013-07-09 19:35:14 -07002982 if (mpfd < 0) {
2983 ALOGI("No kernel memory.pressure_level support (errno=%d)", errno);
2984 goto err_open_mpfd;
2985 }
2986
Nick Kralevich148d8dd2015-12-18 20:52:37 -08002987 evctlfd = open(MEMCG_SYSFS_PATH "cgroup.event_control", O_WRONLY | O_CLOEXEC);
Todd Poynorc58c5142013-07-09 19:35:14 -07002988 if (evctlfd < 0) {
2989 ALOGI("No kernel memory cgroup event control (errno=%d)", errno);
2990 goto err_open_evctlfd;
2991 }
2992
Nick Kralevich148d8dd2015-12-18 20:52:37 -08002993 evfd = eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC);
Todd Poynorc58c5142013-07-09 19:35:14 -07002994 if (evfd < 0) {
2995 ALOGE("eventfd failed for level %s; errno=%d", levelstr, errno);
2996 goto err_eventfd;
2997 }
2998
2999 ret = snprintf(buf, sizeof(buf), "%d %d %s", evfd, mpfd, levelstr);
3000 if (ret >= (ssize_t)sizeof(buf)) {
3001 ALOGE("cgroup.event_control line overflow for level %s", levelstr);
3002 goto err;
3003 }
3004
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003005 ret = TEMP_FAILURE_RETRY(write(evctlfd, buf, strlen(buf) + 1));
Todd Poynorc58c5142013-07-09 19:35:14 -07003006 if (ret == -1) {
3007 ALOGE("cgroup.event_control write failed for level %s; errno=%d",
3008 levelstr, errno);
3009 goto err;
3010 }
3011
3012 epev.events = EPOLLIN;
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003013 /* use data to store event level */
3014 vmpressure_hinfo[level_idx].data = level_idx;
3015 vmpressure_hinfo[level_idx].handler = mp_event_common;
3016 epev.data.ptr = (void *)&vmpressure_hinfo[level_idx];
Todd Poynorc58c5142013-07-09 19:35:14 -07003017 ret = epoll_ctl(epollfd, EPOLL_CTL_ADD, evfd, &epev);
3018 if (ret == -1) {
3019 ALOGE("epoll_ctl for level %s failed; errno=%d", levelstr, errno);
3020 goto err;
3021 }
3022 maxevents++;
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08003023 mpevfd[level] = evfd;
Suren Baghdasaryanceffaf22018-01-04 08:54:53 -08003024 close(evctlfd);
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08003025 return true;
Todd Poynorc58c5142013-07-09 19:35:14 -07003026
3027err:
3028 close(evfd);
3029err_eventfd:
3030 close(evctlfd);
3031err_open_evctlfd:
3032 close(mpfd);
3033err_open_mpfd:
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08003034 return false;
Robert Benea58d6a132017-06-01 16:32:31 -07003035}
3036
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07003037static void destroy_mp_common(enum vmpressure_level level) {
3038 struct epoll_event epev;
3039 int fd = mpevfd[level];
3040
3041 if (fd < 0) {
3042 return;
3043 }
3044
3045 if (epoll_ctl(epollfd, EPOLL_CTL_DEL, fd, &epev)) {
3046 // Log an error and keep going
3047 ALOGE("epoll_ctl for level %s failed; errno=%d", level_name[level], errno);
3048 }
3049 maxevents--;
3050 close(fd);
3051 mpevfd[level] = -1;
3052}
3053
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07003054static void kernel_event_handler(int data __unused, uint32_t events __unused,
3055 struct polling_params *poll_params __unused) {
Jing Ji5c480962019-12-04 09:22:05 -08003056 poll_kernel(kpoll_fd);
Jim Blackler700b7192019-04-26 11:18:29 +01003057}
3058
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07003059static bool init_monitors() {
3060 /* Try to use psi monitor first if kernel has it */
3061 use_psi_monitors = property_get_bool("ro.lmk.use_psi", true) &&
3062 init_psi_monitors();
3063 /* Fall back to vmpressure */
3064 if (!use_psi_monitors &&
3065 (!init_mp_common(VMPRESS_LEVEL_LOW) ||
3066 !init_mp_common(VMPRESS_LEVEL_MEDIUM) ||
3067 !init_mp_common(VMPRESS_LEVEL_CRITICAL))) {
3068 ALOGE("Kernel does not support memory pressure events or in-kernel low memory killer");
3069 return false;
3070 }
3071 if (use_psi_monitors) {
3072 ALOGI("Using psi monitors for memory pressure detection");
3073 } else {
3074 ALOGI("Using vmpressure for memory pressure detection");
3075 }
3076 return true;
3077}
3078
3079static void destroy_monitors() {
3080 if (use_psi_monitors) {
3081 destroy_mp_psi(VMPRESS_LEVEL_CRITICAL);
3082 destroy_mp_psi(VMPRESS_LEVEL_MEDIUM);
3083 destroy_mp_psi(VMPRESS_LEVEL_LOW);
3084 } else {
3085 destroy_mp_common(VMPRESS_LEVEL_CRITICAL);
3086 destroy_mp_common(VMPRESS_LEVEL_MEDIUM);
3087 destroy_mp_common(VMPRESS_LEVEL_LOW);
3088 }
3089}
3090
Todd Poynorc58c5142013-07-09 19:35:14 -07003091static int init(void) {
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07003092 static struct event_handler_info kernel_poll_hinfo = { 0, kernel_event_handler };
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -07003093 struct reread_data file_data = {
3094 .filename = ZONEINFO_PATH,
3095 .fd = -1,
3096 };
Todd Poynorc58c5142013-07-09 19:35:14 -07003097 struct epoll_event epev;
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003098 int pidfd;
Todd Poynorc58c5142013-07-09 19:35:14 -07003099 int i;
3100 int ret;
3101
3102 page_k = sysconf(_SC_PAGESIZE);
3103 if (page_k == -1)
3104 page_k = PAGE_SIZE;
3105 page_k /= 1024;
3106
3107 epollfd = epoll_create(MAX_EPOLL_EVENTS);
3108 if (epollfd == -1) {
3109 ALOGE("epoll_create failed (errno=%d)", errno);
3110 return -1;
3111 }
3112
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003113 // mark data connections as not connected
3114 for (int i = 0; i < MAX_DATA_CONN; i++) {
3115 data_sock[i].sock = -1;
3116 }
3117
3118 ctrl_sock.sock = android_get_control_socket("lmkd");
3119 if (ctrl_sock.sock < 0) {
Todd Poynorc58c5142013-07-09 19:35:14 -07003120 ALOGE("get lmkd control socket failed");
3121 return -1;
3122 }
3123
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003124 ret = listen(ctrl_sock.sock, MAX_DATA_CONN);
Todd Poynorc58c5142013-07-09 19:35:14 -07003125 if (ret < 0) {
3126 ALOGE("lmkd control socket listen failed (errno=%d)", errno);
3127 return -1;
3128 }
3129
3130 epev.events = EPOLLIN;
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003131 ctrl_sock.handler_info.handler = ctrl_connect_handler;
3132 epev.data.ptr = (void *)&(ctrl_sock.handler_info);
3133 if (epoll_ctl(epollfd, EPOLL_CTL_ADD, ctrl_sock.sock, &epev) == -1) {
Todd Poynorc58c5142013-07-09 19:35:14 -07003134 ALOGE("epoll_ctl for lmkd control socket failed (errno=%d)", errno);
3135 return -1;
3136 }
3137 maxevents++;
3138
Robert Benea7878c9b2017-09-11 16:53:28 -07003139 has_inkernel_module = !access(INKERNEL_MINFREE_PATH, W_OK);
Suren Baghdasaryane6613ea2018-01-18 17:27:30 -08003140 use_inkernel_interface = has_inkernel_module;
Todd Poynorc58c5142013-07-09 19:35:14 -07003141
3142 if (use_inkernel_interface) {
3143 ALOGI("Using in-kernel low memory killer interface");
Jing Ji5c480962019-12-04 09:22:05 -08003144 if (init_poll_kernel()) {
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07003145 epev.events = EPOLLIN;
3146 epev.data.ptr = (void*)&kernel_poll_hinfo;
Jing Ji5c480962019-12-04 09:22:05 -08003147 if (epoll_ctl(epollfd, EPOLL_CTL_ADD, kpoll_fd, &epev) != 0) {
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07003148 ALOGE("epoll_ctl for lmk events failed (errno=%d)", errno);
Jing Ji5c480962019-12-04 09:22:05 -08003149 close(kpoll_fd);
3150 kpoll_fd = -1;
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07003151 } else {
3152 maxevents++;
Jing Ji5c480962019-12-04 09:22:05 -08003153 /* let the others know it does support reporting kills */
3154 property_set("sys.lmk.reportkills", "1");
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07003155 }
Jim Blackler700b7192019-04-26 11:18:29 +01003156 }
Todd Poynorc58c5142013-07-09 19:35:14 -07003157 } else {
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07003158 if (!init_monitors()) {
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08003159 return -1;
3160 }
Jing Ji5c480962019-12-04 09:22:05 -08003161 /* let the others know it does support reporting kills */
3162 property_set("sys.lmk.reportkills", "1");
Todd Poynorc58c5142013-07-09 19:35:14 -07003163 }
3164
Chong Zhang1cd12b52015-10-14 16:19:53 -07003165 for (i = 0; i <= ADJTOSLOT(OOM_SCORE_ADJ_MAX); i++) {
Todd Poynorc58c5142013-07-09 19:35:14 -07003166 procadjslot_list[i].next = &procadjslot_list[i];
3167 procadjslot_list[i].prev = &procadjslot_list[i];
3168 }
3169
Suren Baghdasaryana7394ea2018-10-12 11:07:40 -07003170 memset(killcnt_idx, KILLCNT_INVALID_IDX, sizeof(killcnt_idx));
3171
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -07003172 /*
3173 * Read zoneinfo as the biggest file we read to create and size the initial
3174 * read buffer and avoid memory re-allocations during memory pressure
3175 */
3176 if (reread_file(&file_data) == NULL) {
3177 ALOGE("Failed to read %s: %s", file_data.filename, strerror(errno));
3178 }
3179
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003180 /* check if kernel supports pidfd_open syscall */
Josh Gao84623be2021-03-18 17:16:08 -07003181 pidfd = TEMP_FAILURE_RETRY(pidfd_open(getpid(), 0));
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003182 if (pidfd < 0) {
3183 pidfd_supported = (errno != ENOSYS);
3184 } else {
3185 pidfd_supported = true;
3186 close(pidfd);
3187 }
3188 ALOGI("Process polling is %s", pidfd_supported ? "supported" : "not supported" );
3189
Todd Poynorc58c5142013-07-09 19:35:14 -07003190 return 0;
3191}
3192
Suren Baghdasaryan03dccf32020-04-28 16:02:13 -07003193static bool polling_paused(struct polling_params *poll_params) {
3194 return poll_params->paused_handler != NULL;
3195}
3196
3197static void resume_polling(struct polling_params *poll_params, struct timespec curr_tm) {
3198 poll_params->poll_start_tm = curr_tm;
3199 poll_params->poll_handler = poll_params->paused_handler;
Martin Liu589b5752020-09-02 23:15:18 +08003200 poll_params->polling_interval_ms = PSI_POLL_PERIOD_SHORT_MS;
3201 poll_params->paused_handler = NULL;
Suren Baghdasaryan03dccf32020-04-28 16:02:13 -07003202}
3203
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003204static void call_handler(struct event_handler_info* handler_info,
3205 struct polling_params *poll_params, uint32_t events) {
3206 struct timespec curr_tm;
3207
Suren Baghdasaryan9ca53342020-04-24 16:54:55 -07003208 poll_params->update = POLLING_DO_NOT_CHANGE;
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003209 handler_info->handler(handler_info->data, events, poll_params);
3210 clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm);
Suren Baghdasaryan9ca53342020-04-24 16:54:55 -07003211 if (poll_params->poll_handler == handler_info) {
3212 poll_params->last_poll_tm = curr_tm;
3213 }
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003214
3215 switch (poll_params->update) {
3216 case POLLING_START:
3217 /*
3218 * Poll for the duration of PSI_WINDOW_SIZE_MS after the
3219 * initial PSI event because psi events are rate-limited
3220 * at one per sec.
3221 */
3222 poll_params->poll_start_tm = curr_tm;
Greg Kaiser5e80ed52019-10-10 06:52:23 -07003223 poll_params->poll_handler = handler_info;
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003224 break;
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003225 case POLLING_PAUSE:
3226 poll_params->paused_handler = handler_info;
3227 poll_params->poll_handler = NULL;
3228 break;
3229 case POLLING_RESUME:
Suren Baghdasaryan03dccf32020-04-28 16:02:13 -07003230 resume_polling(poll_params, curr_tm);
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003231 break;
3232 case POLLING_DO_NOT_CHANGE:
3233 if (get_time_diff_ms(&poll_params->poll_start_tm, &curr_tm) > PSI_WINDOW_SIZE_MS) {
3234 /* Polled for the duration of PSI window, time to stop */
3235 poll_params->poll_handler = NULL;
3236 }
Suren Baghdasaryan9ca53342020-04-24 16:54:55 -07003237 break;
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003238 }
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003239}
3240
Todd Poynorc58c5142013-07-09 19:35:14 -07003241static void mainloop(void) {
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003242 struct event_handler_info* handler_info;
Suren Baghdasaryane12a0672019-07-15 14:50:49 -07003243 struct polling_params poll_params;
3244 struct timespec curr_tm;
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003245 struct epoll_event *evt;
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08003246 long delay = -1;
Suren Baghdasaryane12a0672019-07-15 14:50:49 -07003247
3248 poll_params.poll_handler = NULL;
Suren Baghdasaryan9ca53342020-04-24 16:54:55 -07003249 poll_params.paused_handler = NULL;
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003250
Todd Poynorc58c5142013-07-09 19:35:14 -07003251 while (1) {
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07003252 struct epoll_event events[MAX_EPOLL_EVENTS];
Todd Poynorc58c5142013-07-09 19:35:14 -07003253 int nevents;
3254 int i;
3255
Suren Baghdasaryane12a0672019-07-15 14:50:49 -07003256 if (poll_params.poll_handler) {
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003257 bool poll_now;
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08003258
3259 clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm);
Martin Liu589b5752020-09-02 23:15:18 +08003260 if (poll_params.update == POLLING_RESUME) {
3261 /* Just transitioned into POLLING_RESUME, poll immediately. */
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003262 poll_now = true;
3263 nevents = 0;
3264 } else {
3265 /* Calculate next timeout */
3266 delay = get_time_diff_ms(&poll_params.last_poll_tm, &curr_tm);
3267 delay = (delay < poll_params.polling_interval_ms) ?
3268 poll_params.polling_interval_ms - delay : poll_params.polling_interval_ms;
Suren Baghdasaryane12a0672019-07-15 14:50:49 -07003269
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003270 /* Wait for events until the next polling timeout */
3271 nevents = epoll_wait(epollfd, events, maxevents, delay);
3272
3273 /* Update current time after wait */
3274 clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm);
3275 poll_now = (get_time_diff_ms(&poll_params.last_poll_tm, &curr_tm) >=
3276 poll_params.polling_interval_ms);
3277 }
3278 if (poll_now) {
3279 call_handler(poll_params.poll_handler, &poll_params, 0);
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08003280 }
3281 } else {
Suren Baghdasaryan03dccf32020-04-28 16:02:13 -07003282 if (kill_timeout_ms && is_waiting_for_kill()) {
3283 clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm);
3284 delay = kill_timeout_ms - get_time_diff_ms(&last_kill_tm, &curr_tm);
3285 /* Wait for pidfds notification or kill timeout to expire */
3286 nevents = (delay > 0) ? epoll_wait(epollfd, events, maxevents, delay) : 0;
3287 if (nevents == 0) {
3288 /* Kill notification timed out */
3289 stop_wait_for_proc_kill(false);
3290 if (polling_paused(&poll_params)) {
3291 clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm);
Martin Liu589b5752020-09-02 23:15:18 +08003292 poll_params.update = POLLING_RESUME;
Suren Baghdasaryan03dccf32020-04-28 16:02:13 -07003293 resume_polling(&poll_params, curr_tm);
3294 }
3295 }
3296 } else {
3297 /* Wait for events with no timeout */
3298 nevents = epoll_wait(epollfd, events, maxevents, -1);
3299 }
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08003300 }
Todd Poynorc58c5142013-07-09 19:35:14 -07003301
3302 if (nevents == -1) {
3303 if (errno == EINTR)
3304 continue;
3305 ALOGE("epoll_wait failed (errno=%d)", errno);
3306 continue;
3307 }
3308
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003309 /*
3310 * First pass to see if any data socket connections were dropped.
3311 * Dropped connection should be handled before any other events
3312 * to deallocate data connection and correctly handle cases when
3313 * connection gets dropped and reestablished in the same epoll cycle.
3314 * In such cases it's essential to handle connection closures first.
3315 */
3316 for (i = 0, evt = &events[0]; i < nevents; ++i, evt++) {
3317 if ((evt->events & EPOLLHUP) && evt->data.ptr) {
3318 ALOGI("lmkd data connection dropped");
3319 handler_info = (struct event_handler_info*)evt->data.ptr;
3320 ctrl_data_close(handler_info->data);
3321 }
3322 }
3323
3324 /* Second pass to handle all other events */
3325 for (i = 0, evt = &events[0]; i < nevents; ++i, evt++) {
Suren Baghdasaryane12a0672019-07-15 14:50:49 -07003326 if (evt->events & EPOLLERR) {
Todd Poynorc58c5142013-07-09 19:35:14 -07003327 ALOGD("EPOLLERR on event #%d", i);
Suren Baghdasaryane12a0672019-07-15 14:50:49 -07003328 }
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003329 if (evt->events & EPOLLHUP) {
3330 /* This case was handled in the first pass */
3331 continue;
3332 }
3333 if (evt->data.ptr) {
3334 handler_info = (struct event_handler_info*)evt->data.ptr;
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003335 call_handler(handler_info, &poll_params, evt->events);
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003336 }
Todd Poynorc58c5142013-07-09 19:35:14 -07003337 }
3338 }
3339}
3340
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07003341int issue_reinit() {
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07003342 int sock;
Colin Crossd5b510e2014-07-14 14:31:15 -07003343
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07003344 sock = lmkd_connect();
3345 if (sock < 0) {
3346 ALOGE("failed to connect to lmkd: %s", strerror(errno));
3347 return -1;
3348 }
3349
3350 enum update_props_result res = lmkd_update_props(sock);
3351 switch (res) {
3352 case UPDATE_PROPS_SUCCESS:
3353 ALOGI("lmkd updated properties successfully");
3354 break;
3355 case UPDATE_PROPS_SEND_ERR:
3356 ALOGE("failed to send lmkd request: %s", strerror(errno));
3357 break;
3358 case UPDATE_PROPS_RECV_ERR:
3359 ALOGE("failed to receive lmkd reply: %s", strerror(errno));
3360 break;
3361 case UPDATE_PROPS_FORMAT_ERR:
3362 ALOGE("lmkd reply is invalid");
3363 break;
3364 case UPDATE_PROPS_FAIL:
3365 ALOGE("lmkd failed to update its properties");
3366 break;
3367 }
3368
3369 close(sock);
3370 return res == UPDATE_PROPS_SUCCESS ? 0 : -1;
3371}
3372
3373static void update_props() {
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08003374 /* By default disable low level vmpressure events */
3375 level_oomadj[VMPRESS_LEVEL_LOW] =
3376 property_get_int32("ro.lmk.low", OOM_SCORE_ADJ_MAX + 1);
3377 level_oomadj[VMPRESS_LEVEL_MEDIUM] =
3378 property_get_int32("ro.lmk.medium", 800);
3379 level_oomadj[VMPRESS_LEVEL_CRITICAL] =
3380 property_get_int32("ro.lmk.critical", 0);
Robert Benea7f68a3f2017-08-11 16:03:20 -07003381 debug_process_killing = property_get_bool("ro.lmk.debug", false);
Suren Baghdasaryan3faa3032017-12-08 13:08:41 -08003382
3383 /* By default disable upgrade/downgrade logic */
3384 enable_pressure_upgrade =
3385 property_get_bool("ro.lmk.critical_upgrade", false);
3386 upgrade_pressure =
3387 (int64_t)property_get_int32("ro.lmk.upgrade_pressure", 100);
3388 downgrade_pressure =
3389 (int64_t)property_get_int32("ro.lmk.downgrade_pressure", 100);
Suren Baghdasaryaneb7c5492017-12-08 13:17:06 -08003390 kill_heaviest_task =
Suren Baghdasaryan36b2c492018-04-13 11:49:54 -07003391 property_get_bool("ro.lmk.kill_heaviest_task", false);
Suren Baghdasaryand1d59f82018-04-13 11:45:38 -07003392 low_ram_device = property_get_bool("ro.config.low_ram", false);
Suren Baghdasaryan30854e72018-01-17 17:28:01 -08003393 kill_timeout_ms =
Suren Baghdasaryan7d1f4f02020-07-08 11:40:10 -07003394 (unsigned long)property_get_int32("ro.lmk.kill_timeout_ms", 100);
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07003395 use_minfree_levels =
3396 property_get_bool("ro.lmk.use_minfree_levels", false);
Suren Baghdasaryan8389fdb2018-06-19 18:38:12 -07003397 per_app_memcg =
3398 property_get_bool("ro.config.per_app_memcg", low_ram_device);
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07003399 swap_free_low_percentage = clamp(0, 100, property_get_int32("ro.lmk.swap_free_low_percentage",
Suren Baghdasaryanfb1f5922020-05-19 13:07:23 -07003400 DEF_LOW_SWAP));
Suren Baghdasaryan2f88e152019-07-15 15:42:09 -07003401 psi_partial_stall_ms = property_get_int32("ro.lmk.psi_partial_stall_ms",
3402 low_ram_device ? DEF_PARTIAL_STALL_LOWRAM : DEF_PARTIAL_STALL);
3403 psi_complete_stall_ms = property_get_int32("ro.lmk.psi_complete_stall_ms",
3404 DEF_COMPLETE_STALL);
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07003405 thrashing_limit_pct = max(0, property_get_int32("ro.lmk.thrashing_limit",
3406 low_ram_device ? DEF_THRASHING_LOWRAM : DEF_THRASHING));
3407 thrashing_limit_decay_pct = clamp(0, 100, property_get_int32("ro.lmk.thrashing_limit_decay",
3408 low_ram_device ? DEF_THRASHING_DECAY_LOWRAM : DEF_THRASHING_DECAY));
Suren Baghdasaryan0142b3c2021-03-03 11:11:09 -08003409 thrashing_critical_pct = max(0, property_get_int32("ro.lmk.thrashing_limit_critical",
3410 thrashing_limit_pct * 2));
Suren Baghdasaryan51ee4c52020-04-21 12:27:01 -07003411 swap_util_max = clamp(0, 100, property_get_int32("ro.lmk.swap_util_max", 100));
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07003412}
3413
3414int main(int argc, char **argv) {
3415 if ((argc > 1) && argv[1] && !strcmp(argv[1], "--reinit")) {
3416 if (property_set(LMKD_REINIT_PROP, "0")) {
3417 ALOGE("Failed to reset " LMKD_REINIT_PROP " property");
3418 }
3419 return issue_reinit();
3420 }
3421
3422 update_props();
Robert Benea57397dc2017-07-31 17:15:20 -07003423
Suren Baghdasaryan12cacae2019-09-16 12:06:30 -07003424 ctx = create_android_logger(KILLINFO_LOG_TAG);
Suren Baghdasaryan08bfa982018-07-26 16:34:27 -07003425
Mark Salyzyn5cc80b32018-03-21 12:24:58 -07003426 if (!init()) {
3427 if (!use_inkernel_interface) {
3428 /*
3429 * MCL_ONFAULT pins pages as they fault instead of loading
3430 * everything immediately all at once. (Which would be bad,
3431 * because as of this writing, we have a lot of mapped pages we
3432 * never use.) Old kernels will see MCL_ONFAULT and fail with
3433 * EINVAL; we ignore this failure.
3434 *
3435 * N.B. read the man page for mlockall. MCL_CURRENT | MCL_ONFAULT
3436 * pins ⊆ MCL_CURRENT, converging to just MCL_CURRENT as we fault
3437 * in pages.
3438 */
Mark Salyzyna00ccd82018-04-09 09:50:32 -07003439 /* CAP_IPC_LOCK required */
Mark Salyzyn5cc80b32018-03-21 12:24:58 -07003440 if (mlockall(MCL_CURRENT | MCL_FUTURE | MCL_ONFAULT) && (errno != EINVAL)) {
3441 ALOGW("mlockall failed %s", strerror(errno));
3442 }
Daniel Colascione46648332018-01-03 12:01:02 -08003443
Mark Salyzyna00ccd82018-04-09 09:50:32 -07003444 /* CAP_NICE required */
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07003445 struct sched_param param = {
3446 .sched_priority = 1,
3447 };
Mark Salyzyna00ccd82018-04-09 09:50:32 -07003448 if (sched_setscheduler(0, SCHED_FIFO, &param)) {
3449 ALOGW("set SCHED_FIFO failed %s", strerror(errno));
3450 }
Mark Salyzyn5cc80b32018-03-21 12:24:58 -07003451 }
3452
Todd Poynorc58c5142013-07-09 19:35:14 -07003453 mainloop();
Mark Salyzyn5cc80b32018-03-21 12:24:58 -07003454 }
Todd Poynorc58c5142013-07-09 19:35:14 -07003455
Suren Baghdasaryan08bfa982018-07-26 16:34:27 -07003456 android_log_destroy(&ctx);
3457
Todd Poynorc58c5142013-07-09 19:35:14 -07003458 ALOGI("exiting");
3459 return 0;
3460}