blob: 937e63d4488742b60b4b2ae8f530caa248600701 [file] [log] [blame]
Todd Poynorc58c5142013-07-09 19:35:14 -07001/*
2 * Copyright (C) 2013 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "lowmemorykiller"
18
Wei Wangf1ee2e12018-11-21 00:11:44 -080019#include <dirent.h>
Todd Poynorc58c5142013-07-09 19:35:14 -070020#include <errno.h>
Robert Beneac72b2932017-08-21 15:18:31 -070021#include <inttypes.h>
Suren Baghdasaryanbb7747b2018-03-20 16:03:29 -070022#include <pwd.h>
Mark Salyzyna1f5b862016-10-17 14:28:00 -070023#include <sched.h>
Todd Poynorc58c5142013-07-09 19:35:14 -070024#include <signal.h>
Muhammad Qureshied8fe842019-12-09 17:38:47 -080025#include <statslog_lmkd.h>
Suren Baghdasaryanf584fff2018-03-20 13:53:17 -070026#include <stdbool.h>
Todd Poynorc58c5142013-07-09 19:35:14 -070027#include <stdlib.h>
28#include <string.h>
Mark Salyzyneb062742014-04-30 13:36:35 -070029#include <sys/cdefs.h>
Todd Poynorc58c5142013-07-09 19:35:14 -070030#include <sys/epoll.h>
31#include <sys/eventfd.h>
Colin Crossc4059002014-07-11 17:15:44 -070032#include <sys/mman.h>
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 Baghdasaryan03e19872018-01-04 10:43:58 -080056/*
57 * Define LMKD_TRACE_KILLS to record lmkd kills in kernel traces
58 * to profile and correlate with OOM kills
59 */
60#ifdef LMKD_TRACE_KILLS
61
62#define ATRACE_TAG ATRACE_TAG_ALWAYS
63#include <cutils/trace.h>
64
65#define TRACE_KILL_START(pid) ATRACE_INT(__FUNCTION__, pid);
66#define TRACE_KILL_END() ATRACE_INT(__FUNCTION__, 0);
67
68#else /* LMKD_TRACE_KILLS */
69
Daniel Colascione56b95d72018-02-12 11:24:47 -080070#define TRACE_KILL_START(pid) ((void)(pid))
71#define TRACE_KILL_END() ((void)0)
Suren Baghdasaryan03e19872018-01-04 10:43:58 -080072
73#endif /* LMKD_TRACE_KILLS */
74
Mark Salyzyneb062742014-04-30 13:36:35 -070075#ifndef __unused
76#define __unused __attribute__((__unused__))
77#endif
Todd Poynorc58c5142013-07-09 19:35:14 -070078
79#define MEMCG_SYSFS_PATH "/dev/memcg/"
Robert Beneac72b2932017-08-21 15:18:31 -070080#define MEMCG_MEMORY_USAGE "/dev/memcg/memory.usage_in_bytes"
81#define MEMCG_MEMORYSW_USAGE "/dev/memcg/memory.memsw.usage_in_bytes"
Suren Baghdasaryand28a9732018-04-13 13:11:51 -070082#define ZONEINFO_PATH "/proc/zoneinfo"
83#define MEMINFO_PATH "/proc/meminfo"
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -070084#define VMSTAT_PATH "/proc/vmstat"
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -070085#define PROC_STATUS_TGID_FIELD "Tgid:"
Ioannis Ilkos279268a2020-08-01 10:50:40 +010086#define PROC_STATUS_RSS_FIELD "VmRSS:"
87#define PROC_STATUS_SWAP_FIELD "VmSwap:"
Todd Poynorc58c5142013-07-09 19:35:14 -070088#define LINE_MAX 128
89
Suren Baghdasaryan970a26a2019-09-19 15:27:21 -070090#define PERCEPTIBLE_APP_ADJ 200
91
Suren Baghdasaryan08bfa982018-07-26 16:34:27 -070092/* Android Logger event logtags (see event.logtags) */
Suren Baghdasaryan12cacae2019-09-16 12:06:30 -070093#define KILLINFO_LOG_TAG 10195355
Suren Baghdasaryan08bfa982018-07-26 16:34:27 -070094
Mark Salyzyna00ccd82018-04-09 09:50:32 -070095/* gid containing AID_SYSTEM required */
Todd Poynorc58c5142013-07-09 19:35:14 -070096#define INKERNEL_MINFREE_PATH "/sys/module/lowmemorykiller/parameters/minfree"
97#define INKERNEL_ADJ_PATH "/sys/module/lowmemorykiller/parameters/adj"
98
99#define ARRAY_SIZE(x) (sizeof(x) / sizeof(*(x)))
Robert Benea58d6a132017-06-01 16:32:31 -0700100#define EIGHT_MEGA (1 << 23)
Todd Poynorc58c5142013-07-09 19:35:14 -0700101
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -0700102#define TARGET_UPDATE_MIN_INTERVAL_MS 1000
Martin Liu1f72f5f2020-08-21 13:18:50 +0800103#define THRASHING_RESET_INTERVAL_MS 1000
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -0700104
105#define NS_PER_MS (NS_PER_SEC / MS_PER_SEC)
Suren Baghdasaryan55e31502019-01-08 12:54:48 -0800106#define US_PER_MS (US_PER_SEC / MS_PER_SEC)
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -0700107
Suren Baghdasaryanbb7747b2018-03-20 16:03:29 -0700108/* Defined as ProcessList.SYSTEM_ADJ in ProcessList.java */
109#define SYSTEM_ADJ (-900)
110
Greg Kaiserf5b1d142018-03-23 14:16:12 -0700111#define STRINGIFY(x) STRINGIFY_INTERNAL(x)
112#define STRINGIFY_INTERNAL(x) #x
113
Suren Baghdasaryan55e31502019-01-08 12:54:48 -0800114/*
115 * PSI monitor tracking window size.
116 * PSI monitor generates events at most once per window,
117 * therefore we poll memory state for the duration of
118 * PSI_WINDOW_SIZE_MS after the event happens.
119 */
120#define PSI_WINDOW_SIZE_MS 1000
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -0700121/* Polling period after PSI signal when pressure is high */
122#define PSI_POLL_PERIOD_SHORT_MS 10
123/* Polling period after PSI signal when pressure is low */
124#define PSI_POLL_PERIOD_LONG_MS 100
Suren Baghdasaryan55e31502019-01-08 12:54:48 -0800125
Suren Baghdasaryan08bfa982018-07-26 16:34:27 -0700126#define min(a, b) (((a) < (b)) ? (a) : (b))
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -0700127#define max(a, b) (((a) > (b)) ? (a) : (b))
Suren Baghdasaryan08bfa982018-07-26 16:34:27 -0700128
Suren Baghdasaryan53be36e2018-09-05 15:46:32 -0700129#define FAIL_REPORT_RLIMIT_MS 1000
130
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -0700131/*
132 * System property defaults
133 */
134/* ro.lmk.swap_free_low_percentage property defaults */
Suren Baghdasaryanfb1f5922020-05-19 13:07:23 -0700135#define DEF_LOW_SWAP 10
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -0700136/* ro.lmk.thrashing_limit property defaults */
137#define DEF_THRASHING_LOWRAM 30
138#define DEF_THRASHING 100
139/* ro.lmk.thrashing_limit_decay property defaults */
140#define DEF_THRASHING_DECAY_LOWRAM 50
141#define DEF_THRASHING_DECAY 10
Suren Baghdasaryan2f88e152019-07-15 15:42:09 -0700142/* ro.lmk.psi_partial_stall_ms property defaults */
143#define DEF_PARTIAL_STALL_LOWRAM 200
144#define DEF_PARTIAL_STALL 70
145/* ro.lmk.psi_complete_stall_ms property defaults */
146#define DEF_COMPLETE_STALL 700
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -0700147
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -0700148#define LMKD_REINIT_PROP "lmkd.reinit"
149
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -0700150static inline int sys_pidfd_open(pid_t pid, unsigned int flags) {
151 return syscall(__NR_pidfd_open, pid, flags);
152}
153
Suren Baghdasaryana10157c2019-07-19 10:55:39 -0700154static inline int sys_pidfd_send_signal(int pidfd, int sig, siginfo_t *info,
155 unsigned int flags) {
156 return syscall(__NR_pidfd_send_signal, pidfd, sig, info, flags);
157}
158
Todd Poynorc58c5142013-07-09 19:35:14 -0700159/* default to old in-kernel interface if no memory pressure events */
Mark Salyzyn5cc80b32018-03-21 12:24:58 -0700160static bool use_inkernel_interface = true;
Robert Benea7878c9b2017-09-11 16:53:28 -0700161static bool has_inkernel_module;
Todd Poynorc58c5142013-07-09 19:35:14 -0700162
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -0800163/* memory pressure levels */
164enum vmpressure_level {
165 VMPRESS_LEVEL_LOW = 0,
166 VMPRESS_LEVEL_MEDIUM,
167 VMPRESS_LEVEL_CRITICAL,
168 VMPRESS_LEVEL_COUNT
169};
Todd Poynorc58c5142013-07-09 19:35:14 -0700170
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -0800171static const char *level_name[] = {
172 "low",
173 "medium",
174 "critical"
175};
176
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -0800177struct {
Suren Baghdasaryane0f3dd12018-04-13 13:41:12 -0700178 int64_t min_nr_free_pages; /* recorded but not used yet */
179 int64_t max_nr_free_pages;
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -0800180} low_pressure_mem = { -1, -1 };
181
Suren Baghdasaryan55e31502019-01-08 12:54:48 -0800182struct psi_threshold {
183 enum psi_stall_type stall_type;
184 int threshold_ms;
185};
186
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -0800187static int level_oomadj[VMPRESS_LEVEL_COUNT];
Suren Baghdasaryan3e1a8492018-01-04 09:16:21 -0800188static int mpevfd[VMPRESS_LEVEL_COUNT] = { -1, -1, -1 };
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -0700189static bool pidfd_supported;
190static int last_kill_pid_or_fd = -1;
191static struct timespec last_kill_tm;
192
193/* lmkd configurable parameters */
Robert Beneac72b2932017-08-21 15:18:31 -0700194static bool debug_process_killing;
195static bool enable_pressure_upgrade;
196static int64_t upgrade_pressure;
Robert Benea3be16142017-09-13 15:20:30 -0700197static int64_t downgrade_pressure;
Suren Baghdasaryand1d59f82018-04-13 11:45:38 -0700198static bool low_ram_device;
Suren Baghdasaryaneb7c5492017-12-08 13:17:06 -0800199static bool kill_heaviest_task;
Suren Baghdasaryan30854e72018-01-17 17:28:01 -0800200static unsigned long kill_timeout_ms;
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -0700201static bool use_minfree_levels;
Suren Baghdasaryan8389fdb2018-06-19 18:38:12 -0700202static bool per_app_memcg;
Vic Yang65680692018-08-07 10:18:22 -0700203static int swap_free_low_percentage;
Suren Baghdasaryan2f88e152019-07-15 15:42:09 -0700204static int psi_partial_stall_ms;
205static int psi_complete_stall_ms;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -0700206static int thrashing_limit_pct;
207static int thrashing_limit_decay_pct;
Suren Baghdasaryan51ee4c52020-04-21 12:27:01 -0700208static int swap_util_max;
Suren Baghdasaryan55e31502019-01-08 12:54:48 -0800209static bool use_psi_monitors = false;
Jing Ji5c480962019-12-04 09:22:05 -0800210static int kpoll_fd;
Suren Baghdasaryan55e31502019-01-08 12:54:48 -0800211static struct psi_threshold psi_thresholds[VMPRESS_LEVEL_COUNT] = {
212 { PSI_SOME, 70 }, /* 70ms out of 1sec for partial stall */
213 { PSI_SOME, 100 }, /* 100ms out of 1sec for partial stall */
214 { PSI_FULL, 70 }, /* 70ms out of 1sec for complete stall */
215};
Robert Benea57397dc2017-07-31 17:15:20 -0700216
Suren Baghdasaryan08bfa982018-07-26 16:34:27 -0700217static android_log_context ctx;
218
Suren Baghdasaryane12a0672019-07-15 14:50:49 -0700219enum polling_update {
220 POLLING_DO_NOT_CHANGE,
221 POLLING_START,
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -0700222 POLLING_PAUSE,
223 POLLING_RESUME,
Suren Baghdasaryane12a0672019-07-15 14:50:49 -0700224};
225
226/*
227 * Data used for periodic polling for the memory state of the device.
228 * Note that when system is not polling poll_handler is set to NULL,
229 * when polling starts poll_handler gets set and is reset back to
230 * NULL when polling stops.
231 */
232struct polling_params {
233 struct event_handler_info* poll_handler;
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -0700234 struct event_handler_info* paused_handler;
Suren Baghdasaryane12a0672019-07-15 14:50:49 -0700235 struct timespec poll_start_tm;
236 struct timespec last_poll_tm;
237 int polling_interval_ms;
238 enum polling_update update;
239};
240
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -0800241/* data required to handle events */
242struct event_handler_info {
243 int data;
Suren Baghdasaryane12a0672019-07-15 14:50:49 -0700244 void (*handler)(int data, uint32_t events, struct polling_params *poll_params);
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -0800245};
Todd Poynorc58c5142013-07-09 19:35:14 -0700246
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -0800247/* data required to handle socket events */
248struct sock_event_handler_info {
249 int sock;
Suren Baghdasaryan945658a2019-10-18 11:16:52 -0700250 pid_t pid;
Suren Baghdasaryan36baf442019-12-23 11:37:34 -0800251 uint32_t async_event_mask;
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -0800252 struct event_handler_info handler_info;
253};
254
Suren Baghdasaryanf2cbefd2019-10-21 17:59:22 -0700255/* max supported number of data connections (AMS, init, tests) */
256#define MAX_DATA_CONN 3
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -0800257
258/* socket event handler data */
259static struct sock_event_handler_info ctrl_sock;
260static struct sock_event_handler_info data_sock[MAX_DATA_CONN];
261
262/* vmpressure event handler data */
263static struct event_handler_info vmpressure_hinfo[VMPRESS_LEVEL_COUNT];
264
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -0700265/*
Suren Baghdasaryanf2cbefd2019-10-21 17:59:22 -0700266 * 1 ctrl listen socket, 3 ctrl data socket, 3 memory pressure levels,
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -0700267 * 1 lmk events + 1 fd to wait for process death
268 */
269#define MAX_EPOLL_EVENTS (1 + MAX_DATA_CONN + VMPRESS_LEVEL_COUNT + 1 + 1)
Todd Poynorc58c5142013-07-09 19:35:14 -0700270static int epollfd;
271static int maxevents;
272
Chong Zhang1cd12b52015-10-14 16:19:53 -0700273/* OOM score values used by both kernel and framework */
Todd Poynora08c1722013-09-16 19:26:47 -0700274#define OOM_SCORE_ADJ_MIN (-1000)
275#define OOM_SCORE_ADJ_MAX 1000
276
Todd Poynorc58c5142013-07-09 19:35:14 -0700277static int lowmem_adj[MAX_TARGETS];
278static int lowmem_minfree[MAX_TARGETS];
279static int lowmem_targets_size;
280
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700281/* Fields to parse in /proc/zoneinfo */
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -0700282/* zoneinfo per-zone fields */
283enum zoneinfo_zone_field {
284 ZI_ZONE_NR_FREE_PAGES = 0,
285 ZI_ZONE_MIN,
286 ZI_ZONE_LOW,
287 ZI_ZONE_HIGH,
288 ZI_ZONE_PRESENT,
289 ZI_ZONE_NR_FREE_CMA,
290 ZI_ZONE_FIELD_COUNT
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700291};
292
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -0700293static const char* const zoneinfo_zone_field_names[ZI_ZONE_FIELD_COUNT] = {
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700294 "nr_free_pages",
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -0700295 "min",
296 "low",
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700297 "high",
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -0700298 "present",
299 "nr_free_cma",
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700300};
301
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -0700302/* zoneinfo per-zone special fields */
303enum zoneinfo_zone_spec_field {
304 ZI_ZONE_SPEC_PROTECTION = 0,
305 ZI_ZONE_SPEC_PAGESETS,
306 ZI_ZONE_SPEC_FIELD_COUNT,
307};
308
309static const char* const zoneinfo_zone_spec_field_names[ZI_ZONE_SPEC_FIELD_COUNT] = {
310 "protection:",
311 "pagesets",
312};
313
314/* see __MAX_NR_ZONES definition in kernel mmzone.h */
315#define MAX_NR_ZONES 6
316
317union zoneinfo_zone_fields {
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700318 struct {
319 int64_t nr_free_pages;
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -0700320 int64_t min;
321 int64_t low;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700322 int64_t high;
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -0700323 int64_t present;
324 int64_t nr_free_cma;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700325 } field;
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -0700326 int64_t arr[ZI_ZONE_FIELD_COUNT];
327};
328
329struct zoneinfo_zone {
330 union zoneinfo_zone_fields fields;
331 int64_t protection[MAX_NR_ZONES];
332 int64_t max_protection;
333};
334
335/* zoneinfo per-node fields */
336enum zoneinfo_node_field {
337 ZI_NODE_NR_INACTIVE_FILE = 0,
338 ZI_NODE_NR_ACTIVE_FILE,
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -0700339 ZI_NODE_FIELD_COUNT
340};
341
342static const char* const zoneinfo_node_field_names[ZI_NODE_FIELD_COUNT] = {
343 "nr_inactive_file",
344 "nr_active_file",
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -0700345};
346
347union zoneinfo_node_fields {
348 struct {
349 int64_t nr_inactive_file;
350 int64_t nr_active_file;
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -0700351 } field;
352 int64_t arr[ZI_NODE_FIELD_COUNT];
353};
354
355struct zoneinfo_node {
356 int id;
357 int zone_count;
358 struct zoneinfo_zone zones[MAX_NR_ZONES];
359 union zoneinfo_node_fields fields;
360};
361
362/* for now two memory nodes is more than enough */
363#define MAX_NR_NODES 2
364
365struct zoneinfo {
366 int node_count;
367 struct zoneinfo_node nodes[MAX_NR_NODES];
368 int64_t totalreserve_pages;
369 int64_t total_inactive_file;
370 int64_t total_active_file;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700371};
372
373/* Fields to parse in /proc/meminfo */
374enum meminfo_field {
375 MI_NR_FREE_PAGES = 0,
376 MI_CACHED,
377 MI_SWAP_CACHED,
378 MI_BUFFERS,
379 MI_SHMEM,
380 MI_UNEVICTABLE,
Vic Yang65680692018-08-07 10:18:22 -0700381 MI_TOTAL_SWAP,
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700382 MI_FREE_SWAP,
Suren Baghdasaryan08bfa982018-07-26 16:34:27 -0700383 MI_ACTIVE_ANON,
384 MI_INACTIVE_ANON,
385 MI_ACTIVE_FILE,
386 MI_INACTIVE_FILE,
387 MI_SRECLAIMABLE,
388 MI_SUNRECLAIM,
389 MI_KERNEL_STACK,
390 MI_PAGE_TABLES,
391 MI_ION_HELP,
392 MI_ION_HELP_POOL,
393 MI_CMA_FREE,
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700394 MI_FIELD_COUNT
395};
396
397static const char* const meminfo_field_names[MI_FIELD_COUNT] = {
398 "MemFree:",
399 "Cached:",
400 "SwapCached:",
401 "Buffers:",
402 "Shmem:",
403 "Unevictable:",
Vic Yang65680692018-08-07 10:18:22 -0700404 "SwapTotal:",
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700405 "SwapFree:",
Suren Baghdasaryan08bfa982018-07-26 16:34:27 -0700406 "Active(anon):",
407 "Inactive(anon):",
408 "Active(file):",
409 "Inactive(file):",
410 "SReclaimable:",
411 "SUnreclaim:",
412 "KernelStack:",
413 "PageTables:",
414 "ION_heap:",
415 "ION_heap_pool:",
416 "CmaFree:",
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700417};
418
419union meminfo {
420 struct {
421 int64_t nr_free_pages;
422 int64_t cached;
423 int64_t swap_cached;
424 int64_t buffers;
425 int64_t shmem;
426 int64_t unevictable;
Vic Yang65680692018-08-07 10:18:22 -0700427 int64_t total_swap;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700428 int64_t free_swap;
Suren Baghdasaryan08bfa982018-07-26 16:34:27 -0700429 int64_t active_anon;
430 int64_t inactive_anon;
431 int64_t active_file;
432 int64_t inactive_file;
433 int64_t sreclaimable;
434 int64_t sunreclaimable;
435 int64_t kernel_stack;
436 int64_t page_tables;
437 int64_t ion_heap;
438 int64_t ion_heap_pool;
439 int64_t cma_free;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700440 /* fields below are calculated rather than read from the file */
441 int64_t nr_file_pages;
442 } field;
443 int64_t arr[MI_FIELD_COUNT];
444};
445
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -0700446/* Fields to parse in /proc/vmstat */
447enum vmstat_field {
448 VS_FREE_PAGES,
449 VS_INACTIVE_FILE,
450 VS_ACTIVE_FILE,
451 VS_WORKINGSET_REFAULT,
452 VS_PGSCAN_KSWAPD,
453 VS_PGSCAN_DIRECT,
454 VS_PGSCAN_DIRECT_THROTTLE,
455 VS_FIELD_COUNT
456};
457
458static const char* const vmstat_field_names[MI_FIELD_COUNT] = {
459 "nr_free_pages",
460 "nr_inactive_file",
461 "nr_active_file",
462 "workingset_refault",
463 "pgscan_kswapd",
464 "pgscan_direct",
465 "pgscan_direct_throttle",
466};
467
468union vmstat {
469 struct {
470 int64_t nr_free_pages;
471 int64_t nr_inactive_file;
472 int64_t nr_active_file;
473 int64_t workingset_refault;
474 int64_t pgscan_kswapd;
475 int64_t pgscan_direct;
476 int64_t pgscan_direct_throttle;
477 } field;
478 int64_t arr[VS_FIELD_COUNT];
479};
480
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700481enum field_match_result {
482 NO_MATCH,
483 PARSE_FAIL,
484 PARSE_SUCCESS
485};
486
Todd Poynorc58c5142013-07-09 19:35:14 -0700487struct adjslot_list {
488 struct adjslot_list *next;
489 struct adjslot_list *prev;
490};
491
492struct proc {
493 struct adjslot_list asl;
494 int pid;
Suren Baghdasaryana10157c2019-07-19 10:55:39 -0700495 int pidfd;
Colin Cross748d2182014-06-13 14:52:43 -0700496 uid_t uid;
Todd Poynorc58c5142013-07-09 19:35:14 -0700497 int oomadj;
Suren Baghdasaryan945658a2019-10-18 11:16:52 -0700498 pid_t reg_pid; /* PID of the process that registered this record */
Todd Poynorc58c5142013-07-09 19:35:14 -0700499 struct proc *pidhash_next;
500};
501
Suren Baghdasaryan87966742018-04-13 12:43:41 -0700502struct reread_data {
503 const char* const filename;
504 int fd;
505};
506
Todd Poynorc58c5142013-07-09 19:35:14 -0700507#define PIDHASH_SZ 1024
508static struct proc *pidhash[PIDHASH_SZ];
509#define pid_hashfn(x) ((((x) >> 8) ^ (x)) & (PIDHASH_SZ - 1))
510
Chih-Hung Hsieheefa2462016-05-19 16:02:22 -0700511#define ADJTOSLOT(adj) ((adj) + -OOM_SCORE_ADJ_MIN)
Suren Baghdasaryana7394ea2018-10-12 11:07:40 -0700512#define ADJTOSLOT_COUNT (ADJTOSLOT(OOM_SCORE_ADJ_MAX) + 1)
513static struct adjslot_list procadjslot_list[ADJTOSLOT_COUNT];
514
515#define MAX_DISTINCT_OOM_ADJ 32
516#define KILLCNT_INVALID_IDX 0xFF
517/*
518 * Because killcnt array is sparse a two-level indirection is used
519 * to keep the size small. killcnt_idx stores index of the element in
520 * killcnt array. Index KILLCNT_INVALID_IDX indicates an unused slot.
521 */
522static uint8_t killcnt_idx[ADJTOSLOT_COUNT];
523static uint16_t killcnt[MAX_DISTINCT_OOM_ADJ];
524static int killcnt_free_idx = 0;
525static uint32_t killcnt_total = 0;
Todd Poynorc58c5142013-07-09 19:35:14 -0700526
Todd Poynorc58c5142013-07-09 19:35:14 -0700527/* PAGE_SIZE / 1024 */
528static long page_k;
529
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -0700530static void update_props();
531static bool init_monitors();
532static void destroy_monitors();
533
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -0700534static int clamp(int low, int high, int value) {
535 return max(min(value, high), low);
536}
537
Suren Baghdasaryan87966742018-04-13 12:43:41 -0700538static bool parse_int64(const char* str, int64_t* ret) {
539 char* endptr;
540 long long val = strtoll(str, &endptr, 10);
541 if (str == endptr || val > INT64_MAX) {
542 return false;
543 }
544 *ret = (int64_t)val;
545 return true;
546}
547
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -0700548static int find_field(const char* name, const char* const field_names[], int field_count) {
549 for (int i = 0; i < field_count; i++) {
550 if (!strcmp(name, field_names[i])) {
551 return i;
552 }
553 }
554 return -1;
555}
556
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700557static enum field_match_result match_field(const char* cp, const char* ap,
558 const char* const field_names[],
559 int field_count, int64_t* field,
560 int *field_idx) {
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -0700561 int i = find_field(cp, field_names, field_count);
562 if (i < 0) {
563 return NO_MATCH;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700564 }
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -0700565 *field_idx = i;
566 return parse_int64(ap, field) ? PARSE_SUCCESS : PARSE_FAIL;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -0700567}
568
Suren Baghdasaryan87966742018-04-13 12:43:41 -0700569/*
570 * Read file content from the beginning up to max_len bytes or EOF
571 * whichever happens first.
572 */
Colin Crossdba1cc62014-07-11 17:53:27 -0700573static ssize_t read_all(int fd, char *buf, size_t max_len)
574{
575 ssize_t ret = 0;
Suren Baghdasaryan87966742018-04-13 12:43:41 -0700576 off_t offset = 0;
Colin Crossdba1cc62014-07-11 17:53:27 -0700577
578 while (max_len > 0) {
Suren Baghdasaryan87966742018-04-13 12:43:41 -0700579 ssize_t r = TEMP_FAILURE_RETRY(pread(fd, buf, max_len, offset));
Colin Crossdba1cc62014-07-11 17:53:27 -0700580 if (r == 0) {
581 break;
582 }
583 if (r == -1) {
584 return -1;
585 }
586 ret += r;
587 buf += r;
Suren Baghdasaryan87966742018-04-13 12:43:41 -0700588 offset += r;
Colin Crossdba1cc62014-07-11 17:53:27 -0700589 max_len -= r;
590 }
591
592 return ret;
593}
594
Suren Baghdasaryan87966742018-04-13 12:43:41 -0700595/*
596 * Read a new or already opened file from the beginning.
597 * If the file has not been opened yet data->fd should be set to -1.
598 * To be used with files which are read often and possibly during high
599 * memory pressure to minimize file opening which by itself requires kernel
600 * memory allocation and might result in a stall on memory stressed system.
601 */
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -0700602static char *reread_file(struct reread_data *data) {
603 /* start with page-size buffer and increase if needed */
604 static ssize_t buf_size = PAGE_SIZE;
605 static char *new_buf, *buf = NULL;
Suren Baghdasaryan87966742018-04-13 12:43:41 -0700606 ssize_t size;
607
608 if (data->fd == -1) {
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -0700609 /* First-time buffer initialization */
Tom Cherry43f3d2b2019-12-04 12:46:57 -0800610 if (!buf && (buf = static_cast<char*>(malloc(buf_size))) == nullptr) {
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -0700611 return NULL;
612 }
613
614 data->fd = TEMP_FAILURE_RETRY(open(data->filename, O_RDONLY | O_CLOEXEC));
615 if (data->fd < 0) {
Suren Baghdasaryan87966742018-04-13 12:43:41 -0700616 ALOGE("%s open: %s", data->filename, strerror(errno));
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -0700617 return NULL;
Suren Baghdasaryan87966742018-04-13 12:43:41 -0700618 }
619 }
620
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -0700621 while (true) {
622 size = read_all(data->fd, buf, buf_size - 1);
623 if (size < 0) {
624 ALOGE("%s read: %s", data->filename, strerror(errno));
625 close(data->fd);
626 data->fd = -1;
627 return NULL;
628 }
629 if (size < buf_size - 1) {
630 break;
631 }
632 /*
633 * Since we are reading /proc files we can't use fstat to find out
634 * the real size of the file. Double the buffer size and keep retrying.
635 */
Tom Cherry43f3d2b2019-12-04 12:46:57 -0800636 if ((new_buf = static_cast<char*>(realloc(buf, buf_size * 2))) == nullptr) {
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -0700637 errno = ENOMEM;
638 return NULL;
639 }
640 buf = new_buf;
641 buf_size *= 2;
Suren Baghdasaryan87966742018-04-13 12:43:41 -0700642 }
Suren Baghdasaryan87966742018-04-13 12:43:41 -0700643 buf[size] = 0;
644
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -0700645 return buf;
Suren Baghdasaryan87966742018-04-13 12:43:41 -0700646}
647
Jing Ji5c480962019-12-04 09:22:05 -0800648static bool claim_record(struct proc* procp, pid_t pid) {
649 if (procp->reg_pid == pid) {
650 /* Record already belongs to the registrant */
651 return true;
652 }
653 if (procp->reg_pid == 0) {
654 /* Old registrant is gone, claim the record */
655 procp->reg_pid = pid;
656 return true;
657 }
658 /* The record is owned by another registrant */
659 return false;
660}
661
662static void remove_claims(pid_t pid) {
663 int i;
664
665 for (i = 0; i < PIDHASH_SZ; i++) {
666 struct proc* procp = pidhash[i];
667 while (procp) {
668 if (procp->reg_pid == pid) {
669 procp->reg_pid = 0;
670 }
671 procp = procp->pidhash_next;
672 }
673 }
674}
675
676static void ctrl_data_close(int dsock_idx) {
677 struct epoll_event epev;
678
679 ALOGI("closing lmkd data connection");
680 if (epoll_ctl(epollfd, EPOLL_CTL_DEL, data_sock[dsock_idx].sock, &epev) == -1) {
681 // Log a warning and keep going
682 ALOGW("epoll_ctl for data connection socket failed; errno=%d", errno);
683 }
684 maxevents--;
685
686 close(data_sock[dsock_idx].sock);
687 data_sock[dsock_idx].sock = -1;
688
689 /* Mark all records of the old registrant as unclaimed */
690 remove_claims(data_sock[dsock_idx].pid);
691}
692
693static ssize_t ctrl_data_read(int dsock_idx, char* buf, size_t bufsz, struct ucred* sender_cred) {
694 struct iovec iov = {buf, bufsz};
695 char control[CMSG_SPACE(sizeof(struct ucred))];
696 struct msghdr hdr = {
697 NULL, 0, &iov, 1, control, sizeof(control), 0,
698 };
699 ssize_t ret;
700 ret = TEMP_FAILURE_RETRY(recvmsg(data_sock[dsock_idx].sock, &hdr, 0));
701 if (ret == -1) {
702 ALOGE("control data socket read failed; %s", strerror(errno));
703 return -1;
704 }
705 if (ret == 0) {
706 ALOGE("Got EOF on control data socket");
707 return -1;
708 }
709
710 struct ucred* cred = NULL;
711 struct cmsghdr* cmsg = CMSG_FIRSTHDR(&hdr);
712 while (cmsg != NULL) {
713 if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_CREDENTIALS) {
714 cred = (struct ucred*)CMSG_DATA(cmsg);
715 break;
716 }
717 cmsg = CMSG_NXTHDR(&hdr, cmsg);
718 }
719
720 if (cred == NULL) {
721 ALOGE("Failed to retrieve sender credentials");
722 /* Close the connection */
723 ctrl_data_close(dsock_idx);
724 return -1;
725 }
726
727 memcpy(sender_cred, cred, sizeof(struct ucred));
728
729 /* Store PID of the peer */
730 data_sock[dsock_idx].pid = cred->pid;
731
732 return ret;
733}
734
735static int ctrl_data_write(int dsock_idx, char* buf, size_t bufsz) {
736 int ret = 0;
737
738 ret = TEMP_FAILURE_RETRY(write(data_sock[dsock_idx].sock, buf, bufsz));
739
740 if (ret == -1) {
741 ALOGE("control data socket write failed; errno=%d", errno);
742 } else if (ret == 0) {
743 ALOGE("Got EOF on control data socket");
744 ret = -1;
745 }
746
747 return ret;
748}
749
750/*
751 * Write the pid/uid pair over the data socket, note: all active clients
752 * will receive this unsolicited notification.
753 */
754static void ctrl_data_write_lmk_kill_occurred(pid_t pid, uid_t uid) {
755 LMKD_CTRL_PACKET packet;
756 size_t len = lmkd_pack_set_prockills(packet, pid, uid);
757
758 for (int i = 0; i < MAX_DATA_CONN; i++) {
Suren Baghdasaryan36baf442019-12-23 11:37:34 -0800759 if (data_sock[i].sock >= 0 && data_sock[i].async_event_mask & 1 << LMK_ASYNC_EVENT_KILL) {
Jing Ji5c480962019-12-04 09:22:05 -0800760 ctrl_data_write(i, (char*)packet, len);
761 }
762 }
763}
764
765static void poll_kernel(int poll_fd) {
766 if (poll_fd == -1) {
767 // not waiting
768 return;
769 }
770
771 while (1) {
772 char rd_buf[256];
773 int bytes_read = TEMP_FAILURE_RETRY(pread(poll_fd, (void*)rd_buf, sizeof(rd_buf), 0));
774 if (bytes_read <= 0) break;
775 rd_buf[bytes_read] = '\0';
776
777 int64_t pid;
778 int64_t uid;
779 int64_t group_leader_pid;
780 int64_t rss_in_pages;
781 struct memory_stat mem_st = {};
782 int16_t oom_score_adj;
783 int16_t min_score_adj;
784 int64_t starttime;
785 char* taskname = 0;
786
787 int fields_read =
788 sscanf(rd_buf,
789 "%" SCNd64 " %" SCNd64 " %" SCNd64 " %" SCNd64 " %" SCNd64 " %" SCNd64
790 " %" SCNd16 " %" SCNd16 " %" SCNd64 "\n%m[^\n]",
791 &pid, &uid, &group_leader_pid, &mem_st.pgfault, &mem_st.pgmajfault,
792 &rss_in_pages, &oom_score_adj, &min_score_adj, &starttime, &taskname);
793
794 /* only the death of the group leader process is logged */
795 if (fields_read == 10 && group_leader_pid == pid) {
796 ctrl_data_write_lmk_kill_occurred((pid_t)pid, (uid_t)uid);
797 mem_st.process_start_time_ns = starttime * (NS_PER_SEC / sysconf(_SC_CLK_TCK));
798 mem_st.rss_in_bytes = rss_in_pages * PAGE_SIZE;
Suren Baghdasaryan3cc1f132020-09-09 20:19:02 -0700799
800 struct kill_stat kill_st = {
801 .uid = static_cast<int32_t>(uid),
802 .kill_reason = NONE,
803 .oom_score = oom_score_adj,
804 .min_oom_score = min_score_adj,
805 .free_mem_kb = 0,
806 .free_swap_kb = 0,
807 };
808 stats_write_lmk_kill_occurred_pid(pid, &kill_st, &mem_st);
Jing Ji5c480962019-12-04 09:22:05 -0800809 }
810
811 free(taskname);
812 }
813}
814
815static bool init_poll_kernel() {
816 kpoll_fd = TEMP_FAILURE_RETRY(open("/proc/lowmemorykiller", O_RDONLY | O_NONBLOCK | O_CLOEXEC));
817
818 if (kpoll_fd < 0) {
819 ALOGE("kernel lmk event file could not be opened; errno=%d", errno);
820 return false;
821 }
822
823 return true;
824}
825
Todd Poynorc58c5142013-07-09 19:35:14 -0700826static struct proc *pid_lookup(int pid) {
827 struct proc *procp;
828
829 for (procp = pidhash[pid_hashfn(pid)]; procp && procp->pid != pid;
830 procp = procp->pidhash_next)
831 ;
832
833 return procp;
834}
835
Tom Cherry43f3d2b2019-12-04 12:46:57 -0800836static void adjslot_insert(struct adjslot_list *head, struct adjslot_list *new_element)
Todd Poynorc58c5142013-07-09 19:35:14 -0700837{
838 struct adjslot_list *next = head->next;
Tom Cherry43f3d2b2019-12-04 12:46:57 -0800839 new_element->prev = head;
840 new_element->next = next;
841 next->prev = new_element;
842 head->next = new_element;
Todd Poynorc58c5142013-07-09 19:35:14 -0700843}
844
845static void adjslot_remove(struct adjslot_list *old)
846{
847 struct adjslot_list *prev = old->prev;
848 struct adjslot_list *next = old->next;
849 next->prev = prev;
850 prev->next = next;
851}
852
853static struct adjslot_list *adjslot_tail(struct adjslot_list *head) {
854 struct adjslot_list *asl = head->prev;
855
856 return asl == head ? NULL : asl;
857}
858
859static void proc_slot(struct proc *procp) {
860 int adjslot = ADJTOSLOT(procp->oomadj);
861
862 adjslot_insert(&procadjslot_list[adjslot], &procp->asl);
863}
864
865static void proc_unslot(struct proc *procp) {
866 adjslot_remove(&procp->asl);
867}
868
869static void proc_insert(struct proc *procp) {
870 int hval = pid_hashfn(procp->pid);
871
872 procp->pidhash_next = pidhash[hval];
873 pidhash[hval] = procp;
874 proc_slot(procp);
875}
876
877static int pid_remove(int pid) {
878 int hval = pid_hashfn(pid);
879 struct proc *procp;
880 struct proc *prevp;
881
882 for (procp = pidhash[hval], prevp = NULL; procp && procp->pid != pid;
883 procp = procp->pidhash_next)
884 prevp = procp;
885
886 if (!procp)
887 return -1;
888
889 if (!prevp)
890 pidhash[hval] = procp->pidhash_next;
891 else
892 prevp->pidhash_next = procp->pidhash_next;
893
894 proc_unslot(procp);
Suren Baghdasaryana10157c2019-07-19 10:55:39 -0700895 /*
896 * Close pidfd here if we are not waiting for corresponding process to die,
897 * in which case stop_wait_for_proc_kill() will close the pidfd later
898 */
899 if (procp->pidfd >= 0 && procp->pidfd != last_kill_pid_or_fd) {
900 close(procp->pidfd);
901 }
Todd Poynorc58c5142013-07-09 19:35:14 -0700902 free(procp);
903 return 0;
904}
905
Suren Baghdasaryanf584fff2018-03-20 13:53:17 -0700906/*
907 * Write a string to a file.
908 * Returns false if the file does not exist.
909 */
910static bool writefilestring(const char *path, const char *s,
911 bool err_if_missing) {
Nick Kralevich148d8dd2015-12-18 20:52:37 -0800912 int fd = open(path, O_WRONLY | O_CLOEXEC);
Suren Baghdasaryanf584fff2018-03-20 13:53:17 -0700913 ssize_t len = strlen(s);
914 ssize_t ret;
Todd Poynorc58c5142013-07-09 19:35:14 -0700915
916 if (fd < 0) {
Suren Baghdasaryanf584fff2018-03-20 13:53:17 -0700917 if (err_if_missing) {
918 ALOGE("Error opening %s; errno=%d", path, errno);
919 }
920 return false;
Todd Poynorc58c5142013-07-09 19:35:14 -0700921 }
922
Suren Baghdasaryanf584fff2018-03-20 13:53:17 -0700923 ret = TEMP_FAILURE_RETRY(write(fd, s, len));
Todd Poynorc58c5142013-07-09 19:35:14 -0700924 if (ret < 0) {
925 ALOGE("Error writing %s; errno=%d", path, errno);
926 } else if (ret < len) {
Suren Baghdasaryanf584fff2018-03-20 13:53:17 -0700927 ALOGE("Short write on %s; length=%zd", path, ret);
Todd Poynorc58c5142013-07-09 19:35:14 -0700928 }
929
930 close(fd);
Suren Baghdasaryanf584fff2018-03-20 13:53:17 -0700931 return true;
Todd Poynorc58c5142013-07-09 19:35:14 -0700932}
933
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -0700934static inline long get_time_diff_ms(struct timespec *from,
935 struct timespec *to) {
936 return (to->tv_sec - from->tv_sec) * (long)MS_PER_SEC +
937 (to->tv_nsec - from->tv_nsec) / (long)NS_PER_MS;
938}
939
Ioannis Ilkos279268a2020-08-01 10:50:40 +0100940/* Reads /proc/pid/status into buf. */
941static bool read_proc_status(int pid, char *buf, size_t buf_sz) {
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -0700942 char path[PATH_MAX];
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -0700943 int fd;
944 ssize_t size;
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -0700945
946 snprintf(path, PATH_MAX, "/proc/%d/status", pid);
947 fd = open(path, O_RDONLY | O_CLOEXEC);
948 if (fd < 0) {
Ioannis Ilkos279268a2020-08-01 10:50:40 +0100949 return false;
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -0700950 }
951
Ioannis Ilkos279268a2020-08-01 10:50:40 +0100952 size = read_all(fd, buf, buf_sz - 1);
953 close(fd);
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -0700954 if (size < 0) {
Ioannis Ilkos279268a2020-08-01 10:50:40 +0100955 return false;
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -0700956 }
957 buf[size] = 0;
Ioannis Ilkos279268a2020-08-01 10:50:40 +0100958 return true;
959}
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -0700960
Ioannis Ilkos279268a2020-08-01 10:50:40 +0100961/* Looks for tag in buf and parses the first integer */
962static bool parse_status_tag(char *buf, const char *tag, int64_t *out) {
963 char *pos = buf;
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -0700964 while (true) {
Ioannis Ilkos279268a2020-08-01 10:50:40 +0100965 pos = strstr(pos, tag);
966 /* Stop if tag not found or found at the line beginning */
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -0700967 if (pos == NULL || pos == buf || pos[-1] == '\n') {
968 break;
969 }
970 pos++;
971 }
972
973 if (pos == NULL) {
Ioannis Ilkos279268a2020-08-01 10:50:40 +0100974 return false;
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -0700975 }
976
Ioannis Ilkos279268a2020-08-01 10:50:40 +0100977 pos += strlen(tag);
978 while (*pos == ' ') ++pos;
979 return parse_int64(pos, out);
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -0700980}
981
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -0700982static int proc_get_size(int pid) {
983 char path[PATH_MAX];
984 char line[LINE_MAX];
985 int fd;
986 int rss = 0;
987 int total;
988 ssize_t ret;
989
990 /* gid containing AID_READPROC required */
991 snprintf(path, PATH_MAX, "/proc/%d/statm", pid);
992 fd = open(path, O_RDONLY | O_CLOEXEC);
993 if (fd == -1)
994 return -1;
995
996 ret = read_all(fd, line, sizeof(line) - 1);
997 if (ret < 0) {
998 close(fd);
999 return -1;
1000 }
Suren Baghdasaryan632f1c52019-10-04 16:06:55 -07001001 line[ret] = '\0';
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07001002
1003 sscanf(line, "%d %d ", &total, &rss);
1004 close(fd);
1005 return rss;
1006}
1007
Suren Baghdasaryan632f1c52019-10-04 16:06:55 -07001008static char *proc_get_name(int pid, char *buf, size_t buf_size) {
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07001009 char path[PATH_MAX];
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07001010 int fd;
1011 char *cp;
1012 ssize_t ret;
1013
1014 /* gid containing AID_READPROC required */
1015 snprintf(path, PATH_MAX, "/proc/%d/cmdline", pid);
1016 fd = open(path, O_RDONLY | O_CLOEXEC);
1017 if (fd == -1) {
1018 return NULL;
1019 }
Suren Baghdasaryan632f1c52019-10-04 16:06:55 -07001020 ret = read_all(fd, buf, buf_size - 1);
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07001021 close(fd);
1022 if (ret < 0) {
1023 return NULL;
1024 }
Suren Baghdasaryan632f1c52019-10-04 16:06:55 -07001025 buf[ret] = '\0';
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07001026
Suren Baghdasaryan632f1c52019-10-04 16:06:55 -07001027 cp = strchr(buf, ' ');
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07001028 if (cp) {
1029 *cp = '\0';
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07001030 }
1031
Suren Baghdasaryan632f1c52019-10-04 16:06:55 -07001032 return buf;
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07001033}
1034
Suren Baghdasaryana93503e2019-10-22 17:12:01 -07001035static void cmd_procprio(LMKD_CTRL_PACKET packet, int field_count, struct ucred *cred) {
Todd Poynorc58c5142013-07-09 19:35:14 -07001036 struct proc *procp;
Suren Baghdasaryan632f1c52019-10-04 16:06:55 -07001037 char path[LINE_MAX];
Todd Poynorc58c5142013-07-09 19:35:14 -07001038 char val[20];
Robert Benea58d6a132017-06-01 16:32:31 -07001039 int soft_limit_mult;
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -08001040 struct lmk_procprio params;
Suren Baghdasaryanbb7747b2018-03-20 16:03:29 -07001041 bool is_system_server;
1042 struct passwd *pwdrec;
Ioannis Ilkos279268a2020-08-01 10:50:40 +01001043 int64_t tgid;
1044 char buf[PAGE_SIZE];
Todd Poynorc58c5142013-07-09 19:35:14 -07001045
Suren Baghdasaryana93503e2019-10-22 17:12:01 -07001046 lmkd_pack_get_procprio(packet, field_count, &params);
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -08001047
1048 if (params.oomadj < OOM_SCORE_ADJ_MIN ||
1049 params.oomadj > OOM_SCORE_ADJ_MAX) {
1050 ALOGE("Invalid PROCPRIO oomadj argument %d", params.oomadj);
Todd Poynorc58c5142013-07-09 19:35:14 -07001051 return;
1052 }
1053
Suren Baghdasaryana93503e2019-10-22 17:12:01 -07001054 if (params.ptype < PROC_TYPE_FIRST || params.ptype >= PROC_TYPE_COUNT) {
1055 ALOGE("Invalid PROCPRIO process type argument %d", params.ptype);
1056 return;
1057 }
1058
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -07001059 /* Check if registered process is a thread group leader */
Ioannis Ilkos279268a2020-08-01 10:50:40 +01001060 if (read_proc_status(params.pid, buf, sizeof(buf))) {
1061 if (parse_status_tag(buf, PROC_STATUS_TGID_FIELD, &tgid) && tgid != params.pid) {
1062 ALOGE("Attempt to register a task that is not a thread group leader "
1063 "(tid %d, tgid %" PRId64 ")", params.pid, tgid);
1064 return;
1065 }
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -07001066 }
1067
Mark Salyzyna00ccd82018-04-09 09:50:32 -07001068 /* gid containing AID_READPROC required */
1069 /* CAP_SYS_RESOURCE required */
1070 /* CAP_DAC_OVERRIDE required */
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -08001071 snprintf(path, sizeof(path), "/proc/%d/oom_score_adj", params.pid);
1072 snprintf(val, sizeof(val), "%d", params.oomadj);
Suren Baghdasaryanf584fff2018-03-20 13:53:17 -07001073 if (!writefilestring(path, val, false)) {
1074 ALOGW("Failed to open %s; errno=%d: process %d might have been killed",
1075 path, errno, params.pid);
1076 /* If this file does not exist the process is dead. */
1077 return;
1078 }
Todd Poynorc58c5142013-07-09 19:35:14 -07001079
Mark Salyzyn5cc80b32018-03-21 12:24:58 -07001080 if (use_inkernel_interface) {
Jing Ji5c480962019-12-04 09:22:05 -08001081 stats_store_taskname(params.pid, proc_get_name(params.pid, path, sizeof(path)));
Todd Poynorc58c5142013-07-09 19:35:14 -07001082 return;
Mark Salyzyn5cc80b32018-03-21 12:24:58 -07001083 }
Todd Poynorc58c5142013-07-09 19:35:14 -07001084
Suren Baghdasaryana93503e2019-10-22 17:12:01 -07001085 /* lmkd should not change soft limits for services */
1086 if (params.ptype == PROC_TYPE_APP && per_app_memcg) {
Suren Baghdasaryanb0bda552018-05-18 14:42:00 -07001087 if (params.oomadj >= 900) {
1088 soft_limit_mult = 0;
1089 } else if (params.oomadj >= 800) {
1090 soft_limit_mult = 0;
1091 } else if (params.oomadj >= 700) {
1092 soft_limit_mult = 0;
1093 } else if (params.oomadj >= 600) {
1094 // Launcher should be perceptible, don't kill it.
1095 params.oomadj = 200;
1096 soft_limit_mult = 1;
1097 } else if (params.oomadj >= 500) {
1098 soft_limit_mult = 0;
1099 } else if (params.oomadj >= 400) {
1100 soft_limit_mult = 0;
1101 } else if (params.oomadj >= 300) {
1102 soft_limit_mult = 1;
1103 } else if (params.oomadj >= 200) {
Srinivas Paladugua453f0b2018-10-09 14:21:10 -07001104 soft_limit_mult = 8;
Suren Baghdasaryanb0bda552018-05-18 14:42:00 -07001105 } else if (params.oomadj >= 100) {
1106 soft_limit_mult = 10;
1107 } else if (params.oomadj >= 0) {
1108 soft_limit_mult = 20;
1109 } else {
1110 // Persistent processes will have a large
1111 // soft limit 512MB.
1112 soft_limit_mult = 64;
1113 }
Robert Benea58d6a132017-06-01 16:32:31 -07001114
Suren Baghdasaryanbf919ff2018-05-21 19:48:47 -07001115 snprintf(path, sizeof(path), MEMCG_SYSFS_PATH
1116 "apps/uid_%d/pid_%d/memory.soft_limit_in_bytes",
1117 params.uid, params.pid);
Suren Baghdasaryanb0bda552018-05-18 14:42:00 -07001118 snprintf(val, sizeof(val), "%d", soft_limit_mult * EIGHT_MEGA);
Suren Baghdasaryanbf919ff2018-05-21 19:48:47 -07001119
1120 /*
1121 * system_server process has no memcg under /dev/memcg/apps but should be
1122 * registered with lmkd. This is the best way so far to identify it.
1123 */
1124 is_system_server = (params.oomadj == SYSTEM_ADJ &&
1125 (pwdrec = getpwnam("system")) != NULL &&
1126 params.uid == pwdrec->pw_uid);
1127 writefilestring(path, val, !is_system_server);
Robert Benea58d6a132017-06-01 16:32:31 -07001128 }
1129
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -08001130 procp = pid_lookup(params.pid);
Todd Poynorc58c5142013-07-09 19:35:14 -07001131 if (!procp) {
Suren Baghdasaryana10157c2019-07-19 10:55:39 -07001132 int pidfd = -1;
1133
1134 if (pidfd_supported) {
1135 pidfd = TEMP_FAILURE_RETRY(sys_pidfd_open(params.pid, 0));
1136 if (pidfd < 0) {
1137 ALOGE("pidfd_open for pid %d failed; errno=%d", params.pid, errno);
Todd Poynorc58c5142013-07-09 19:35:14 -07001138 return;
1139 }
Suren Baghdasaryana10157c2019-07-19 10:55:39 -07001140 }
Todd Poynorc58c5142013-07-09 19:35:14 -07001141
Tom Cherry43f3d2b2019-12-04 12:46:57 -08001142 procp = static_cast<struct proc*>(calloc(1, sizeof(struct proc)));
Suren Baghdasaryana10157c2019-07-19 10:55:39 -07001143 if (!procp) {
1144 // Oh, the irony. May need to rebuild our state.
1145 return;
1146 }
1147
1148 procp->pid = params.pid;
1149 procp->pidfd = pidfd;
1150 procp->uid = params.uid;
Suren Baghdasaryan945658a2019-10-18 11:16:52 -07001151 procp->reg_pid = cred->pid;
Suren Baghdasaryana10157c2019-07-19 10:55:39 -07001152 procp->oomadj = params.oomadj;
1153 proc_insert(procp);
Todd Poynorc58c5142013-07-09 19:35:14 -07001154 } else {
Suren Baghdasaryan945658a2019-10-18 11:16:52 -07001155 if (!claim_record(procp, cred->pid)) {
1156 char buf[LINE_MAX];
1157 /* Only registrant of the record can remove it */
1158 ALOGE("%s (%d, %d) attempts to modify a process registered by another client",
1159 proc_get_name(cred->pid, buf, sizeof(buf)), cred->uid, cred->pid);
1160 return;
1161 }
Todd Poynorc58c5142013-07-09 19:35:14 -07001162 proc_unslot(procp);
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -08001163 procp->oomadj = params.oomadj;
Todd Poynorc58c5142013-07-09 19:35:14 -07001164 proc_slot(procp);
1165 }
1166}
1167
Suren Baghdasaryan945658a2019-10-18 11:16:52 -07001168static void cmd_procremove(LMKD_CTRL_PACKET packet, struct ucred *cred) {
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -08001169 struct lmk_procremove params;
Suren Baghdasaryan945658a2019-10-18 11:16:52 -07001170 struct proc *procp;
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -08001171
George Burgess IV3b36b902019-10-02 11:22:55 -07001172 lmkd_pack_get_procremove(packet, &params);
Suren Baghdasaryan945658a2019-10-18 11:16:52 -07001173
Mark Salyzyn5cc80b32018-03-21 12:24:58 -07001174 if (use_inkernel_interface) {
Jing Ji5c480962019-12-04 09:22:05 -08001175 /*
1176 * Perform an extra check before the pid is removed, after which it
1177 * will be impossible for poll_kernel to get the taskname. poll_kernel()
1178 * is potentially a long-running blocking function; however this method
1179 * handles AMS requests but does not block AMS.
1180 */
1181 poll_kernel(kpoll_fd);
1182
1183 stats_remove_taskname(params.pid);
Todd Poynorc58c5142013-07-09 19:35:14 -07001184 return;
Mark Salyzyn5cc80b32018-03-21 12:24:58 -07001185 }
Todd Poynorc58c5142013-07-09 19:35:14 -07001186
Suren Baghdasaryan945658a2019-10-18 11:16:52 -07001187 procp = pid_lookup(params.pid);
1188 if (!procp) {
1189 return;
1190 }
1191
1192 if (!claim_record(procp, cred->pid)) {
1193 char buf[LINE_MAX];
1194 /* Only registrant of the record can remove it */
1195 ALOGE("%s (%d, %d) attempts to unregister a process registered by another client",
1196 proc_get_name(cred->pid, buf, sizeof(buf)), cred->uid, cred->pid);
1197 return;
1198 }
1199
Suren Baghdasaryan8b00c6d2018-10-12 11:28:33 -07001200 /*
1201 * WARNING: After pid_remove() procp is freed and can't be used!
1202 * Therefore placed at the end of the function.
1203 */
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -08001204 pid_remove(params.pid);
Todd Poynorc58c5142013-07-09 19:35:14 -07001205}
1206
Suren Baghdasaryan945658a2019-10-18 11:16:52 -07001207static void cmd_procpurge(struct ucred *cred) {
Suren Baghdasaryan83df0082018-10-10 14:17:17 -07001208 int i;
1209 struct proc *procp;
1210 struct proc *next;
1211
1212 if (use_inkernel_interface) {
Jim Blackler90853b62019-09-10 15:30:05 +01001213 stats_purge_tasknames();
Suren Baghdasaryan83df0082018-10-10 14:17:17 -07001214 return;
1215 }
1216
Suren Baghdasaryan83df0082018-10-10 14:17:17 -07001217 for (i = 0; i < PIDHASH_SZ; i++) {
1218 procp = pidhash[i];
1219 while (procp) {
1220 next = procp->pidhash_next;
Suren Baghdasaryan945658a2019-10-18 11:16:52 -07001221 /* Purge only records created by the requestor */
1222 if (claim_record(procp, cred->pid)) {
1223 pid_remove(procp->pid);
1224 }
Suren Baghdasaryan83df0082018-10-10 14:17:17 -07001225 procp = next;
1226 }
1227 }
Suren Baghdasaryan83df0082018-10-10 14:17:17 -07001228}
1229
Suren Baghdasaryan36baf442019-12-23 11:37:34 -08001230static void cmd_subscribe(int dsock_idx, LMKD_CTRL_PACKET packet) {
1231 struct lmk_subscribe params;
1232
1233 lmkd_pack_get_subscribe(packet, &params);
1234 data_sock[dsock_idx].async_event_mask |= 1 << params.evt_type;
1235}
1236
Suren Baghdasaryana7394ea2018-10-12 11:07:40 -07001237static void inc_killcnt(int oomadj) {
1238 int slot = ADJTOSLOT(oomadj);
1239 uint8_t idx = killcnt_idx[slot];
1240
1241 if (idx == KILLCNT_INVALID_IDX) {
1242 /* index is not assigned for this oomadj */
1243 if (killcnt_free_idx < MAX_DISTINCT_OOM_ADJ) {
1244 killcnt_idx[slot] = killcnt_free_idx;
1245 killcnt[killcnt_free_idx] = 1;
1246 killcnt_free_idx++;
1247 } else {
1248 ALOGW("Number of distinct oomadj levels exceeds %d",
1249 MAX_DISTINCT_OOM_ADJ);
1250 }
1251 } else {
1252 /*
1253 * wraparound is highly unlikely and is detectable using total
1254 * counter because it has to be equal to the sum of all counters
1255 */
1256 killcnt[idx]++;
1257 }
1258 /* increment total kill counter */
1259 killcnt_total++;
1260}
1261
1262static int get_killcnt(int min_oomadj, int max_oomadj) {
1263 int slot;
1264 int count = 0;
1265
1266 if (min_oomadj > max_oomadj)
1267 return 0;
1268
1269 /* special case to get total kill count */
1270 if (min_oomadj > OOM_SCORE_ADJ_MAX)
1271 return killcnt_total;
1272
1273 while (min_oomadj <= max_oomadj &&
1274 (slot = ADJTOSLOT(min_oomadj)) < ADJTOSLOT_COUNT) {
1275 uint8_t idx = killcnt_idx[slot];
1276 if (idx != KILLCNT_INVALID_IDX) {
1277 count += killcnt[idx];
1278 }
1279 min_oomadj++;
1280 }
1281
1282 return count;
1283}
1284
1285static int cmd_getkillcnt(LMKD_CTRL_PACKET packet) {
1286 struct lmk_getkillcnt params;
1287
1288 if (use_inkernel_interface) {
1289 /* kernel driver does not expose this information */
1290 return 0;
1291 }
1292
1293 lmkd_pack_get_getkillcnt(packet, &params);
1294
1295 return get_killcnt(params.min_oomadj, params.max_oomadj);
1296}
1297
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -08001298static void cmd_target(int ntargets, LMKD_CTRL_PACKET packet) {
Todd Poynorc58c5142013-07-09 19:35:14 -07001299 int i;
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -08001300 struct lmk_target target;
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -07001301 char minfree_str[PROPERTY_VALUE_MAX];
1302 char *pstr = minfree_str;
1303 char *pend = minfree_str + sizeof(minfree_str);
1304 static struct timespec last_req_tm;
1305 struct timespec curr_tm;
Todd Poynorc58c5142013-07-09 19:35:14 -07001306
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -07001307 if (ntargets < 1 || ntargets > (int)ARRAY_SIZE(lowmem_adj))
Todd Poynorc58c5142013-07-09 19:35:14 -07001308 return;
1309
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -07001310 /*
1311 * Ratelimit minfree updates to once per TARGET_UPDATE_MIN_INTERVAL_MS
1312 * to prevent DoS attacks
1313 */
1314 if (clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm) != 0) {
1315 ALOGE("Failed to get current time");
1316 return;
1317 }
1318
1319 if (get_time_diff_ms(&last_req_tm, &curr_tm) <
1320 TARGET_UPDATE_MIN_INTERVAL_MS) {
1321 ALOGE("Ignoring frequent updated to lmkd limits");
1322 return;
1323 }
1324
1325 last_req_tm = curr_tm;
1326
Todd Poynorc58c5142013-07-09 19:35:14 -07001327 for (i = 0; i < ntargets; i++) {
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -08001328 lmkd_pack_get_target(packet, i, &target);
1329 lowmem_minfree[i] = target.minfree;
1330 lowmem_adj[i] = target.oom_adj_score;
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -07001331
1332 pstr += snprintf(pstr, pend - pstr, "%d:%d,", target.minfree,
1333 target.oom_adj_score);
1334 if (pstr >= pend) {
1335 /* if no more space in the buffer then terminate the loop */
1336 pstr = pend;
1337 break;
1338 }
Todd Poynorc58c5142013-07-09 19:35:14 -07001339 }
1340
1341 lowmem_targets_size = ntargets;
1342
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -07001343 /* Override the last extra comma */
1344 pstr[-1] = '\0';
1345 property_set("sys.lmk.minfree_levels", minfree_str);
1346
Robert Benea7878c9b2017-09-11 16:53:28 -07001347 if (has_inkernel_module) {
Todd Poynorc58c5142013-07-09 19:35:14 -07001348 char minfreestr[128];
1349 char killpriostr[128];
1350
1351 minfreestr[0] = '\0';
1352 killpriostr[0] = '\0';
1353
1354 for (i = 0; i < lowmem_targets_size; i++) {
1355 char val[40];
1356
1357 if (i) {
1358 strlcat(minfreestr, ",", sizeof(minfreestr));
1359 strlcat(killpriostr, ",", sizeof(killpriostr));
1360 }
1361
Robert Benea7878c9b2017-09-11 16:53:28 -07001362 snprintf(val, sizeof(val), "%d", use_inkernel_interface ? lowmem_minfree[i] : 0);
Todd Poynorc58c5142013-07-09 19:35:14 -07001363 strlcat(minfreestr, val, sizeof(minfreestr));
Robert Benea7878c9b2017-09-11 16:53:28 -07001364 snprintf(val, sizeof(val), "%d", use_inkernel_interface ? lowmem_adj[i] : 0);
Todd Poynorc58c5142013-07-09 19:35:14 -07001365 strlcat(killpriostr, val, sizeof(killpriostr));
1366 }
1367
Suren Baghdasaryanf584fff2018-03-20 13:53:17 -07001368 writefilestring(INKERNEL_MINFREE_PATH, minfreestr, true);
1369 writefilestring(INKERNEL_ADJ_PATH, killpriostr, true);
Todd Poynorc58c5142013-07-09 19:35:14 -07001370 }
1371}
1372
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08001373static void ctrl_command_handler(int dsock_idx) {
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -08001374 LMKD_CTRL_PACKET packet;
Suren Baghdasaryan945658a2019-10-18 11:16:52 -07001375 struct ucred cred;
Todd Poynorc58c5142013-07-09 19:35:14 -07001376 int len;
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -08001377 enum lmk_cmd cmd;
Todd Poynorc58c5142013-07-09 19:35:14 -07001378 int nargs;
1379 int targets;
Suren Baghdasaryana7394ea2018-10-12 11:07:40 -07001380 int kill_cnt;
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07001381 int result;
Todd Poynorc58c5142013-07-09 19:35:14 -07001382
Suren Baghdasaryan945658a2019-10-18 11:16:52 -07001383 len = ctrl_data_read(dsock_idx, (char *)packet, CTRL_PACKET_MAX_SIZE, &cred);
Todd Poynorc58c5142013-07-09 19:35:14 -07001384 if (len <= 0)
1385 return;
1386
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -08001387 if (len < (int)sizeof(int)) {
1388 ALOGE("Wrong control socket read length len=%d", len);
1389 return;
1390 }
1391
1392 cmd = lmkd_pack_get_cmd(packet);
Todd Poynorc58c5142013-07-09 19:35:14 -07001393 nargs = len / sizeof(int) - 1;
1394 if (nargs < 0)
1395 goto wronglen;
1396
Todd Poynorc58c5142013-07-09 19:35:14 -07001397 switch(cmd) {
1398 case LMK_TARGET:
1399 targets = nargs / 2;
1400 if (nargs & 0x1 || targets > (int)ARRAY_SIZE(lowmem_adj))
1401 goto wronglen;
Suren Baghdasaryanf7932e52018-01-24 16:51:41 -08001402 cmd_target(targets, packet);
Todd Poynorc58c5142013-07-09 19:35:14 -07001403 break;
1404 case LMK_PROCPRIO:
Suren Baghdasaryana93503e2019-10-22 17:12:01 -07001405 /* process type field is optional for backward compatibility */
1406 if (nargs < 3 || nargs > 4)
Todd Poynorc58c5142013-07-09 19:35:14 -07001407 goto wronglen;
Suren Baghdasaryana93503e2019-10-22 17:12:01 -07001408 cmd_procprio(packet, nargs, &cred);
Todd Poynorc58c5142013-07-09 19:35:14 -07001409 break;
1410 case LMK_PROCREMOVE:
1411 if (nargs != 1)
1412 goto wronglen;
Suren Baghdasaryan945658a2019-10-18 11:16:52 -07001413 cmd_procremove(packet, &cred);
Todd Poynorc58c5142013-07-09 19:35:14 -07001414 break;
Suren Baghdasaryan83df0082018-10-10 14:17:17 -07001415 case LMK_PROCPURGE:
1416 if (nargs != 0)
1417 goto wronglen;
Suren Baghdasaryan945658a2019-10-18 11:16:52 -07001418 cmd_procpurge(&cred);
Suren Baghdasaryan83df0082018-10-10 14:17:17 -07001419 break;
Suren Baghdasaryana7394ea2018-10-12 11:07:40 -07001420 case LMK_GETKILLCNT:
1421 if (nargs != 2)
1422 goto wronglen;
1423 kill_cnt = cmd_getkillcnt(packet);
1424 len = lmkd_pack_set_getkillcnt_repl(packet, kill_cnt);
1425 if (ctrl_data_write(dsock_idx, (char *)packet, len) != len)
1426 return;
1427 break;
Suren Baghdasaryan36baf442019-12-23 11:37:34 -08001428 case LMK_SUBSCRIBE:
1429 if (nargs != 1)
1430 goto wronglen;
1431 cmd_subscribe(dsock_idx, packet);
1432 break;
Jing Ji5c480962019-12-04 09:22:05 -08001433 case LMK_PROCKILL:
1434 /* This command code is NOT expected at all */
1435 ALOGE("Received unexpected command code %d", cmd);
1436 break;
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07001437 case LMK_UPDATE_PROPS:
1438 if (nargs != 0)
1439 goto wronglen;
1440 update_props();
1441 if (!use_inkernel_interface) {
1442 /* Reinitialize monitors to apply new settings */
1443 destroy_monitors();
1444 result = init_monitors() ? 0 : -1;
1445 } else {
1446 result = 0;
1447 }
1448 len = lmkd_pack_set_update_props_repl(packet, result);
1449 if (ctrl_data_write(dsock_idx, (char *)packet, len) != len) {
1450 ALOGE("Failed to report operation results");
1451 }
1452 if (!result) {
1453 ALOGI("Properties reinitilized");
1454 } else {
1455 /* New settings can't be supported, crash to be restarted */
1456 ALOGE("New configuration is not supported. Exiting...");
1457 exit(1);
1458 }
1459 break;
Todd Poynorc58c5142013-07-09 19:35:14 -07001460 default:
1461 ALOGE("Received unknown command code %d", cmd);
1462 return;
1463 }
1464
1465 return;
1466
1467wronglen:
1468 ALOGE("Wrong control socket read length cmd=%d len=%d", cmd, len);
1469}
1470
Suren Baghdasaryane12a0672019-07-15 14:50:49 -07001471static void ctrl_data_handler(int data, uint32_t events,
1472 struct polling_params *poll_params __unused) {
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08001473 if (events & EPOLLIN) {
1474 ctrl_command_handler(data);
Todd Poynorc58c5142013-07-09 19:35:14 -07001475 }
1476}
1477
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08001478static int get_free_dsock() {
1479 for (int i = 0; i < MAX_DATA_CONN; i++) {
1480 if (data_sock[i].sock < 0) {
1481 return i;
1482 }
1483 }
1484 return -1;
1485}
Todd Poynorc58c5142013-07-09 19:35:14 -07001486
Suren Baghdasaryane12a0672019-07-15 14:50:49 -07001487static void ctrl_connect_handler(int data __unused, uint32_t events __unused,
1488 struct polling_params *poll_params __unused) {
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08001489 struct epoll_event epev;
1490 int free_dscock_idx = get_free_dsock();
1491
1492 if (free_dscock_idx < 0) {
1493 /*
1494 * Number of data connections exceeded max supported. This should not
1495 * happen but if it does we drop all existing connections and accept
1496 * the new one. This prevents inactive connections from monopolizing
1497 * data socket and if we drop ActivityManager connection it will
1498 * immediately reconnect.
1499 */
1500 for (int i = 0; i < MAX_DATA_CONN; i++) {
1501 ctrl_data_close(i);
1502 }
1503 free_dscock_idx = 0;
Todd Poynorc58c5142013-07-09 19:35:14 -07001504 }
1505
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08001506 data_sock[free_dscock_idx].sock = accept(ctrl_sock.sock, NULL, NULL);
1507 if (data_sock[free_dscock_idx].sock < 0) {
Todd Poynorc58c5142013-07-09 19:35:14 -07001508 ALOGE("lmkd control socket accept failed; errno=%d", errno);
1509 return;
1510 }
1511
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08001512 ALOGI("lmkd data connection established");
1513 /* use data to store data connection idx */
1514 data_sock[free_dscock_idx].handler_info.data = free_dscock_idx;
1515 data_sock[free_dscock_idx].handler_info.handler = ctrl_data_handler;
Suren Baghdasaryan36baf442019-12-23 11:37:34 -08001516 data_sock[free_dscock_idx].async_event_mask = 0;
Todd Poynorc58c5142013-07-09 19:35:14 -07001517 epev.events = EPOLLIN;
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08001518 epev.data.ptr = (void *)&(data_sock[free_dscock_idx].handler_info);
1519 if (epoll_ctl(epollfd, EPOLL_CTL_ADD, data_sock[free_dscock_idx].sock, &epev) == -1) {
Todd Poynorc58c5142013-07-09 19:35:14 -07001520 ALOGE("epoll_ctl for data connection socket failed; errno=%d", errno);
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08001521 ctrl_data_close(free_dscock_idx);
Todd Poynorc58c5142013-07-09 19:35:14 -07001522 return;
1523 }
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08001524 maxevents++;
Todd Poynorc58c5142013-07-09 19:35:14 -07001525}
1526
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001527/*
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07001528 * /proc/zoneinfo parsing routines
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001529 * Expected file format is:
1530 *
1531 * Node <node_id>, zone <zone_name>
1532 * (
1533 * per-node stats
1534 * (<per-node field name> <value>)+
1535 * )?
1536 * (pages free <value>
1537 * (<per-zone field name> <value>)+
1538 * pagesets
1539 * (<unused fields>)*
1540 * )+
1541 * ...
1542 */
1543static void zoneinfo_parse_protection(char *buf, struct zoneinfo_zone *zone) {
1544 int zone_idx;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001545 int64_t max = 0;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001546 char *save_ptr;
1547
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001548 for (buf = strtok_r(buf, "(), ", &save_ptr), zone_idx = 0;
1549 buf && zone_idx < MAX_NR_ZONES;
1550 buf = strtok_r(NULL, "), ", &save_ptr), zone_idx++) {
1551 long long zoneval = strtoll(buf, &buf, 0);
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001552 if (zoneval > max) {
1553 max = (zoneval > INT64_MAX) ? INT64_MAX : zoneval;
1554 }
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001555 zone->protection[zone_idx] = zoneval;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001556 }
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001557 zone->max_protection = max;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001558}
1559
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001560static int zoneinfo_parse_zone(char **buf, struct zoneinfo_zone *zone) {
1561 for (char *line = strtok_r(NULL, "\n", buf); line;
1562 line = strtok_r(NULL, "\n", buf)) {
1563 char *cp;
1564 char *ap;
1565 char *save_ptr;
1566 int64_t val;
1567 int field_idx;
1568 enum field_match_result match_res;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001569
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001570 cp = strtok_r(line, " ", &save_ptr);
1571 if (!cp) {
1572 return false;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001573 }
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001574
1575 field_idx = find_field(cp, zoneinfo_zone_spec_field_names, ZI_ZONE_SPEC_FIELD_COUNT);
1576 if (field_idx >= 0) {
1577 /* special field */
1578 if (field_idx == ZI_ZONE_SPEC_PAGESETS) {
1579 /* no mode fields we are interested in */
1580 return true;
1581 }
1582
1583 /* protection field */
1584 ap = strtok_r(NULL, ")", &save_ptr);
1585 if (ap) {
1586 zoneinfo_parse_protection(ap, zone);
1587 }
1588 continue;
1589 }
1590
1591 ap = strtok_r(NULL, " ", &save_ptr);
1592 if (!ap) {
1593 continue;
1594 }
1595
1596 match_res = match_field(cp, ap, zoneinfo_zone_field_names, ZI_ZONE_FIELD_COUNT,
1597 &val, &field_idx);
1598 if (match_res == PARSE_FAIL) {
1599 return false;
1600 }
1601 if (match_res == PARSE_SUCCESS) {
1602 zone->fields.arr[field_idx] = val;
1603 }
1604 if (field_idx == ZI_ZONE_PRESENT && val == 0) {
1605 /* zone is not populated, stop parsing it */
1606 return true;
1607 }
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001608 }
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001609 return false;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001610}
1611
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001612static int zoneinfo_parse_node(char **buf, struct zoneinfo_node *node) {
1613 int fields_to_match = ZI_NODE_FIELD_COUNT;
1614
1615 for (char *line = strtok_r(NULL, "\n", buf); line;
1616 line = strtok_r(NULL, "\n", buf)) {
1617 char *cp;
1618 char *ap;
1619 char *save_ptr;
1620 int64_t val;
1621 int field_idx;
1622 enum field_match_result match_res;
1623
1624 cp = strtok_r(line, " ", &save_ptr);
1625 if (!cp) {
1626 return false;
1627 }
1628
1629 ap = strtok_r(NULL, " ", &save_ptr);
1630 if (!ap) {
1631 return false;
1632 }
1633
1634 match_res = match_field(cp, ap, zoneinfo_node_field_names, ZI_NODE_FIELD_COUNT,
1635 &val, &field_idx);
1636 if (match_res == PARSE_FAIL) {
1637 return false;
1638 }
1639 if (match_res == PARSE_SUCCESS) {
1640 node->fields.arr[field_idx] = val;
1641 fields_to_match--;
1642 if (!fields_to_match) {
1643 return true;
1644 }
1645 }
1646 }
1647 return false;
1648}
1649
1650static int zoneinfo_parse(struct zoneinfo *zi) {
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001651 static struct reread_data file_data = {
1652 .filename = ZONEINFO_PATH,
1653 .fd = -1,
1654 };
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -07001655 char *buf;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001656 char *save_ptr;
1657 char *line;
Greg Kaiser259984f2019-10-02 07:07:32 -07001658 char zone_name[LINE_MAX + 1];
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001659 struct zoneinfo_node *node = NULL;
1660 int node_idx = 0;
1661 int zone_idx = 0;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001662
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001663 memset(zi, 0, sizeof(struct zoneinfo));
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001664
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -07001665 if ((buf = reread_file(&file_data)) == NULL) {
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001666 return -1;
1667 }
1668
1669 for (line = strtok_r(buf, "\n", &save_ptr); line;
1670 line = strtok_r(NULL, "\n", &save_ptr)) {
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001671 int node_id;
1672 if (sscanf(line, "Node %d, zone %" STRINGIFY(LINE_MAX) "s", &node_id, zone_name) == 2) {
1673 if (!node || node->id != node_id) {
1674 /* new node is found */
1675 if (node) {
1676 node->zone_count = zone_idx + 1;
1677 node_idx++;
1678 if (node_idx == MAX_NR_NODES) {
1679 /* max node count exceeded */
1680 ALOGE("%s parse error", file_data.filename);
1681 return -1;
1682 }
1683 }
1684 node = &zi->nodes[node_idx];
1685 node->id = node_id;
1686 zone_idx = 0;
1687 if (!zoneinfo_parse_node(&save_ptr, node)) {
1688 ALOGE("%s parse error", file_data.filename);
1689 return -1;
1690 }
1691 } else {
1692 /* new zone is found */
1693 zone_idx++;
1694 }
1695 if (!zoneinfo_parse_zone(&save_ptr, &node->zones[zone_idx])) {
1696 ALOGE("%s parse error", file_data.filename);
1697 return -1;
1698 }
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001699 }
1700 }
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001701 if (!node) {
1702 ALOGE("%s parse error", file_data.filename);
1703 return -1;
1704 }
1705 node->zone_count = zone_idx + 1;
1706 zi->node_count = node_idx + 1;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001707
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001708 /* calculate totals fields */
1709 for (node_idx = 0; node_idx < zi->node_count; node_idx++) {
1710 node = &zi->nodes[node_idx];
1711 for (zone_idx = 0; zone_idx < node->zone_count; zone_idx++) {
1712 struct zoneinfo_zone *zone = &zi->nodes[node_idx].zones[zone_idx];
1713 zi->totalreserve_pages += zone->max_protection + zone->fields.field.high;
1714 }
1715 zi->total_inactive_file += node->fields.field.nr_inactive_file;
1716 zi->total_active_file += node->fields.field.nr_active_file;
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07001717 }
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001718 return 0;
1719}
1720
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07001721/* /proc/meminfo parsing routines */
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001722static bool meminfo_parse_line(char *line, union meminfo *mi) {
1723 char *cp = line;
1724 char *ap;
1725 char *save_ptr;
1726 int64_t val;
1727 int field_idx;
1728 enum field_match_result match_res;
1729
1730 cp = strtok_r(line, " ", &save_ptr);
1731 if (!cp) {
1732 return false;
1733 }
1734
1735 ap = strtok_r(NULL, " ", &save_ptr);
1736 if (!ap) {
1737 return false;
1738 }
1739
1740 match_res = match_field(cp, ap, meminfo_field_names, MI_FIELD_COUNT,
1741 &val, &field_idx);
1742 if (match_res == PARSE_SUCCESS) {
1743 mi->arr[field_idx] = val / page_k;
1744 }
1745 return (match_res != PARSE_FAIL);
1746}
1747
1748static int meminfo_parse(union meminfo *mi) {
1749 static struct reread_data file_data = {
1750 .filename = MEMINFO_PATH,
1751 .fd = -1,
1752 };
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -07001753 char *buf;
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001754 char *save_ptr;
1755 char *line;
1756
1757 memset(mi, 0, sizeof(union meminfo));
1758
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -07001759 if ((buf = reread_file(&file_data)) == NULL) {
Suren Baghdasaryand28a9732018-04-13 13:11:51 -07001760 return -1;
1761 }
1762
1763 for (line = strtok_r(buf, "\n", &save_ptr); line;
1764 line = strtok_r(NULL, "\n", &save_ptr)) {
1765 if (!meminfo_parse_line(line, mi)) {
1766 ALOGE("%s parse error", file_data.filename);
1767 return -1;
1768 }
1769 }
1770 mi->field.nr_file_pages = mi->field.cached + mi->field.swap_cached +
1771 mi->field.buffers;
1772
1773 return 0;
1774}
1775
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07001776/* /proc/vmstat parsing routines */
1777static bool vmstat_parse_line(char *line, union vmstat *vs) {
1778 char *cp;
1779 char *ap;
1780 char *save_ptr;
1781 int64_t val;
1782 int field_idx;
1783 enum field_match_result match_res;
1784
1785 cp = strtok_r(line, " ", &save_ptr);
1786 if (!cp) {
1787 return false;
1788 }
1789
1790 ap = strtok_r(NULL, " ", &save_ptr);
1791 if (!ap) {
1792 return false;
1793 }
1794
1795 match_res = match_field(cp, ap, vmstat_field_names, VS_FIELD_COUNT,
1796 &val, &field_idx);
1797 if (match_res == PARSE_SUCCESS) {
1798 vs->arr[field_idx] = val;
1799 }
1800 return (match_res != PARSE_FAIL);
1801}
1802
1803static int vmstat_parse(union vmstat *vs) {
1804 static struct reread_data file_data = {
1805 .filename = VMSTAT_PATH,
1806 .fd = -1,
1807 };
1808 char *buf;
1809 char *save_ptr;
1810 char *line;
1811
1812 memset(vs, 0, sizeof(union vmstat));
1813
1814 if ((buf = reread_file(&file_data)) == NULL) {
1815 return -1;
1816 }
1817
1818 for (line = strtok_r(buf, "\n", &save_ptr); line;
1819 line = strtok_r(NULL, "\n", &save_ptr)) {
1820 if (!vmstat_parse_line(line, vs)) {
1821 ALOGE("%s parse error", file_data.filename);
1822 return -1;
1823 }
1824 }
1825
1826 return 0;
1827}
1828
Suren Baghdasaryand7b4fcb2020-07-23 18:00:43 -07001829enum wakeup_reason {
1830 Event,
1831 Polling
1832};
1833
1834struct wakeup_info {
1835 struct timespec wakeup_tm;
1836 struct timespec prev_wakeup_tm;
1837 struct timespec last_event_tm;
1838 int wakeups_since_event;
1839 int skipped_wakeups;
1840};
1841
1842/*
1843 * After the initial memory pressure event is received lmkd schedules periodic wakeups to check
1844 * the memory conditions and kill if needed (polling). This is done because pressure events are
1845 * rate-limited and memory conditions can change in between events. Therefore after the initial
1846 * event there might be multiple wakeups. This function records the wakeup information such as the
1847 * timestamps of the last event and the last wakeup, the number of wakeups since the last event
1848 * and how many of those wakeups were skipped (some wakeups are skipped if previously killed
1849 * process is still freeing its memory).
1850 */
1851static void record_wakeup_time(struct timespec *tm, enum wakeup_reason reason,
1852 struct wakeup_info *wi) {
1853 wi->prev_wakeup_tm = wi->wakeup_tm;
1854 wi->wakeup_tm = *tm;
1855 if (reason == Event) {
1856 wi->last_event_tm = *tm;
1857 wi->wakeups_since_event = 0;
1858 wi->skipped_wakeups = 0;
1859 } else {
1860 wi->wakeups_since_event++;
1861 }
1862}
1863
Ioannis Ilkos279268a2020-08-01 10:50:40 +01001864static void killinfo_log(struct proc* procp, int min_oom_score, int rss_kb,
Suren Baghdasaryand7b4fcb2020-07-23 18:00:43 -07001865 int kill_reason, union meminfo *mi,
1866 struct wakeup_info *wi, struct timespec *tm) {
Suren Baghdasaryan12cacae2019-09-16 12:06:30 -07001867 /* log process information */
1868 android_log_write_int32(ctx, procp->pid);
1869 android_log_write_int32(ctx, procp->uid);
1870 android_log_write_int32(ctx, procp->oomadj);
1871 android_log_write_int32(ctx, min_oom_score);
Ioannis Ilkos279268a2020-08-01 10:50:40 +01001872 android_log_write_int32(ctx, (int32_t)min(rss_kb, INT32_MAX));
Suren Baghdasaryan12cacae2019-09-16 12:06:30 -07001873 android_log_write_int32(ctx, kill_reason);
1874
1875 /* log meminfo fields */
Suren Baghdasaryan08bfa982018-07-26 16:34:27 -07001876 for (int field_idx = 0; field_idx < MI_FIELD_COUNT; field_idx++) {
1877 android_log_write_int32(ctx, (int32_t)min(mi->arr[field_idx] * page_k, INT32_MAX));
1878 }
1879
Suren Baghdasaryand7b4fcb2020-07-23 18:00:43 -07001880 /* log lmkd wakeup information */
1881 android_log_write_int32(ctx, (int32_t)get_time_diff_ms(&wi->last_event_tm, tm));
1882 android_log_write_int32(ctx, (int32_t)get_time_diff_ms(&wi->prev_wakeup_tm, tm));
1883 android_log_write_int32(ctx, wi->wakeups_since_event);
1884 android_log_write_int32(ctx, wi->skipped_wakeups);
1885
Suren Baghdasaryan08bfa982018-07-26 16:34:27 -07001886 android_log_write_list(ctx, LOG_ID_EVENTS);
1887 android_log_reset(ctx);
1888}
1889
Todd Poynorc58c5142013-07-09 19:35:14 -07001890static struct proc *proc_adj_lru(int oomadj) {
1891 return (struct proc *)adjslot_tail(&procadjslot_list[ADJTOSLOT(oomadj)]);
1892}
1893
Suren Baghdasaryaneb7c5492017-12-08 13:17:06 -08001894static struct proc *proc_get_heaviest(int oomadj) {
1895 struct adjslot_list *head = &procadjslot_list[ADJTOSLOT(oomadj)];
1896 struct adjslot_list *curr = head->next;
1897 struct proc *maxprocp = NULL;
1898 int maxsize = 0;
1899 while (curr != head) {
1900 int pid = ((struct proc *)curr)->pid;
1901 int tasksize = proc_get_size(pid);
1902 if (tasksize <= 0) {
1903 struct adjslot_list *next = curr->next;
1904 pid_remove(pid);
1905 curr = next;
1906 } else {
1907 if (tasksize > maxsize) {
1908 maxsize = tasksize;
1909 maxprocp = (struct proc *)curr;
1910 }
1911 curr = curr->next;
1912 }
1913 }
1914 return maxprocp;
1915}
1916
Wei Wangf1ee2e12018-11-21 00:11:44 -08001917static void set_process_group_and_prio(int pid, SchedPolicy sp, int prio) {
1918 DIR* d;
1919 char proc_path[PATH_MAX];
1920 struct dirent* de;
1921
1922 snprintf(proc_path, sizeof(proc_path), "/proc/%d/task", pid);
1923 if (!(d = opendir(proc_path))) {
1924 ALOGW("Failed to open %s; errno=%d: process pid(%d) might have died", proc_path, errno,
1925 pid);
1926 return;
1927 }
1928
1929 while ((de = readdir(d))) {
1930 int t_pid;
1931
1932 if (de->d_name[0] == '.') continue;
1933 t_pid = atoi(de->d_name);
1934
1935 if (!t_pid) {
1936 ALOGW("Failed to get t_pid for '%s' of pid(%d)", de->d_name, pid);
1937 continue;
1938 }
1939
1940 if (setpriority(PRIO_PROCESS, t_pid, prio) && errno != ESRCH) {
1941 ALOGW("Unable to raise priority of killing t_pid (%d): errno=%d", t_pid, errno);
1942 }
1943
1944 if (set_cpuset_policy(t_pid, sp)) {
1945 ALOGW("Failed to set_cpuset_policy on pid(%d) t_pid(%d) to %d", pid, t_pid, (int)sp);
1946 continue;
1947 }
1948 }
1949 closedir(d);
1950}
1951
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07001952static bool is_kill_pending(void) {
1953 char buf[24];
1954
1955 if (last_kill_pid_or_fd < 0) {
1956 return false;
1957 }
1958
1959 if (pidfd_supported) {
1960 return true;
1961 }
1962
1963 /* when pidfd is not supported base the decision on /proc/<pid> existence */
1964 snprintf(buf, sizeof(buf), "/proc/%d/", last_kill_pid_or_fd);
1965 if (access(buf, F_OK) == 0) {
1966 return true;
1967 }
1968
1969 return false;
1970}
1971
1972static bool is_waiting_for_kill(void) {
1973 return pidfd_supported && last_kill_pid_or_fd >= 0;
1974}
1975
1976static void stop_wait_for_proc_kill(bool finished) {
1977 struct epoll_event epev;
1978
1979 if (last_kill_pid_or_fd < 0) {
1980 return;
1981 }
1982
1983 if (debug_process_killing) {
1984 struct timespec curr_tm;
1985
1986 if (clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm) != 0) {
1987 /*
1988 * curr_tm is used here merely to report kill duration, so this failure is not fatal.
1989 * Log an error and continue.
1990 */
1991 ALOGE("Failed to get current time");
1992 }
1993
1994 if (finished) {
1995 ALOGI("Process got killed in %ldms",
1996 get_time_diff_ms(&last_kill_tm, &curr_tm));
1997 } else {
1998 ALOGI("Stop waiting for process kill after %ldms",
1999 get_time_diff_ms(&last_kill_tm, &curr_tm));
2000 }
2001 }
2002
2003 if (pidfd_supported) {
2004 /* unregister fd */
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07002005 if (epoll_ctl(epollfd, EPOLL_CTL_DEL, last_kill_pid_or_fd, &epev)) {
2006 // Log an error and keep going
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002007 ALOGE("epoll_ctl for last killed process failed; errno=%d", errno);
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002008 }
2009 maxevents--;
2010 close(last_kill_pid_or_fd);
2011 }
2012
2013 last_kill_pid_or_fd = -1;
2014}
2015
2016static void kill_done_handler(int data __unused, uint32_t events __unused,
2017 struct polling_params *poll_params) {
2018 stop_wait_for_proc_kill(true);
2019 poll_params->update = POLLING_RESUME;
2020}
2021
Suren Baghdasaryana10157c2019-07-19 10:55:39 -07002022static void start_wait_for_proc_kill(int pid_or_fd) {
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002023 static struct event_handler_info kill_done_hinfo = { 0, kill_done_handler };
2024 struct epoll_event epev;
2025
2026 if (last_kill_pid_or_fd >= 0) {
2027 /* Should not happen but if it does we should stop previous wait */
2028 ALOGE("Attempt to wait for a kill while another wait is in progress");
2029 stop_wait_for_proc_kill(false);
2030 }
2031
Suren Baghdasaryana10157c2019-07-19 10:55:39 -07002032 last_kill_pid_or_fd = pid_or_fd;
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002033
Suren Baghdasaryana10157c2019-07-19 10:55:39 -07002034 if (!pidfd_supported) {
2035 /* If pidfd is not supported just store PID and exit */
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002036 return;
2037 }
2038
2039 epev.events = EPOLLIN;
2040 epev.data.ptr = (void *)&kill_done_hinfo;
2041 if (epoll_ctl(epollfd, EPOLL_CTL_ADD, last_kill_pid_or_fd, &epev) != 0) {
2042 ALOGE("epoll_ctl for last kill failed; errno=%d", errno);
2043 close(last_kill_pid_or_fd);
2044 last_kill_pid_or_fd = -1;
2045 return;
2046 }
2047 maxevents++;
2048}
Tim Murraya79ec0f2018-10-25 17:05:41 -07002049
Ioannis Ilkos279268a2020-08-01 10:50:40 +01002050/* Kill one process specified by procp. Returns the size (in pages) of the process killed */
Suren Baghdasaryan3cc1f132020-09-09 20:19:02 -07002051static int kill_one_process(struct proc* procp, int min_oom_score, enum kill_reasons kill_reason,
Suren Baghdasaryand7b4fcb2020-07-23 18:00:43 -07002052 const char *kill_desc, union meminfo *mi, struct wakeup_info *wi,
2053 struct timespec *tm) {
Colin Cross3d57a512014-07-14 12:39:56 -07002054 int pid = procp->pid;
Suren Baghdasaryana10157c2019-07-19 10:55:39 -07002055 int pidfd = procp->pidfd;
Colin Cross3d57a512014-07-14 12:39:56 -07002056 uid_t uid = procp->uid;
2057 char *taskname;
Colin Cross3d57a512014-07-14 12:39:56 -07002058 int r;
Suren Baghdasaryan8b00c6d2018-10-12 11:28:33 -07002059 int result = -1;
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07002060 struct memory_stat *mem_st;
Suren Baghdasaryan3cc1f132020-09-09 20:19:02 -07002061 struct kill_stat kill_st;
Ioannis Ilkos279268a2020-08-01 10:50:40 +01002062 int64_t tgid;
2063 int64_t rss_kb;
2064 int64_t swap_kb;
2065 char buf[PAGE_SIZE];
Rajeev Kumar4aba9152018-01-31 17:54:56 -08002066
Ioannis Ilkos279268a2020-08-01 10:50:40 +01002067 if (!read_proc_status(pid, buf, sizeof(buf))) {
2068 goto out;
2069 }
2070 if (!parse_status_tag(buf, PROC_STATUS_TGID_FIELD, &tgid)) {
2071 ALOGE("Unable to parse tgid from /proc/%d/status", pid);
2072 goto out;
2073 }
2074 if (tgid != pid) {
2075 ALOGE("Possible pid reuse detected (pid %d, tgid %" PRId64 ")!", pid, tgid);
2076 goto out;
2077 }
2078 // Zombie processes will not have RSS / Swap fields.
2079 if (!parse_status_tag(buf, PROC_STATUS_RSS_FIELD, &rss_kb)) {
2080 goto out;
2081 }
2082 if (!parse_status_tag(buf, PROC_STATUS_SWAP_FIELD, &swap_kb)) {
Suren Baghdasaryan3ee11d42019-07-02 15:52:07 -07002083 goto out;
2084 }
2085
Suren Baghdasaryan632f1c52019-10-04 16:06:55 -07002086 taskname = proc_get_name(pid, buf, sizeof(buf));
Ioannis Ilkos279268a2020-08-01 10:50:40 +01002087 // taskname will point inside buf, do not reuse buf onwards.
Colin Cross3d57a512014-07-14 12:39:56 -07002088 if (!taskname) {
Suren Baghdasaryan8b00c6d2018-10-12 11:28:33 -07002089 goto out;
Colin Cross3d57a512014-07-14 12:39:56 -07002090 }
2091
Ioannis Ilkos279268a2020-08-01 10:50:40 +01002092 mem_st = stats_read_memory_stat(per_app_memcg, pid, uid, rss_kb * 1024, swap_kb * 1024);
Rajeev Kumar4aba9152018-01-31 17:54:56 -08002093
Suren Baghdasaryan03e19872018-01-04 10:43:58 -08002094 TRACE_KILL_START(pid);
2095
Mark Salyzyna00ccd82018-04-09 09:50:32 -07002096 /* CAP_KILL required */
Suren Baghdasaryana10157c2019-07-19 10:55:39 -07002097 if (pidfd < 0) {
2098 start_wait_for_proc_kill(pid);
2099 r = kill(pid, SIGKILL);
2100 } else {
2101 start_wait_for_proc_kill(pidfd);
2102 r = sys_pidfd_send_signal(pidfd, SIGKILL, NULL, 0);
2103 }
Wei Wangf1ee2e12018-11-21 00:11:44 -08002104
Suren Baghdasaryanc2e05b62019-09-04 16:44:47 -07002105 TRACE_KILL_END();
2106
2107 if (r) {
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002108 stop_wait_for_proc_kill(false);
Suren Baghdasaryanc2e05b62019-09-04 16:44:47 -07002109 ALOGE("kill(%d): errno=%d", pid, errno);
2110 /* Delete process record even when we fail to kill so that we don't get stuck on it */
2111 goto out;
2112 }
2113
Wei Wangf1ee2e12018-11-21 00:11:44 -08002114 set_process_group_and_prio(pid, SP_FOREGROUND, ANDROID_PRIORITY_HIGHEST);
2115
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002116 last_kill_tm = *tm;
2117
Suren Baghdasaryana7394ea2018-10-12 11:07:40 -07002118 inc_killcnt(procp->oomadj);
Suren Baghdasaryan12cacae2019-09-16 12:06:30 -07002119
Ioannis Ilkos279268a2020-08-01 10:50:40 +01002120 killinfo_log(procp, min_oom_score, rss_kb, kill_reason, mi, wi, tm);
Suren Baghdasaryan12cacae2019-09-16 12:06:30 -07002121
2122 if (kill_desc) {
Ioannis Ilkos279268a2020-08-01 10:50:40 +01002123 ALOGI("Kill '%s' (%d), uid %d, oom_adj %d to free %" PRId64 "kB; reason: %s", taskname, pid,
2124 uid, procp->oomadj, rss_kb, kill_desc);
Suren Baghdasaryan89454e62019-07-15 15:50:17 -07002125 } else {
Ioannis Ilkos279268a2020-08-01 10:50:40 +01002126 ALOGI("Kill '%s' (%d), uid %d, oom_adj %d to free %" PRId64 "kB", taskname, pid,
2127 uid, procp->oomadj, rss_kb);
Suren Baghdasaryan89454e62019-07-15 15:50:17 -07002128 }
Colin Cross3d57a512014-07-14 12:39:56 -07002129
Suren Baghdasaryan3cc1f132020-09-09 20:19:02 -07002130 kill_st.uid = static_cast<int32_t>(uid);
2131 kill_st.taskname = taskname;
2132 kill_st.kill_reason = kill_reason;
2133 kill_st.oom_score = procp->oomadj;
2134 kill_st.min_oom_score = min_oom_score;
2135 kill_st.free_mem_kb = mi->field.nr_free_pages * page_k;
2136 kill_st.free_swap_kb = mi->field.free_swap * page_k;
2137 stats_write_lmk_kill_occurred(&kill_st, mem_st);
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07002138
Jing Ji5c480962019-12-04 09:22:05 -08002139 ctrl_data_write_lmk_kill_occurred((pid_t)pid, uid);
2140
Ioannis Ilkos279268a2020-08-01 10:50:40 +01002141 result = rss_kb / page_k;
Mark Salyzyn1d5fdf32018-02-04 15:27:23 -08002142
Suren Baghdasaryan8b00c6d2018-10-12 11:28:33 -07002143out:
2144 /*
2145 * WARNING: After pid_remove() procp is freed and can't be used!
2146 * Therefore placed at the end of the function.
2147 */
2148 pid_remove(pid);
2149 return result;
Colin Cross3d57a512014-07-14 12:39:56 -07002150}
2151
2152/*
Suren Baghdasaryan85c31b52018-10-26 11:32:15 -07002153 * Find one process to kill at or above the given oom_adj level.
2154 * Returns size of the killed process.
Colin Cross3d57a512014-07-14 12:39:56 -07002155 */
Suren Baghdasaryan3cc1f132020-09-09 20:19:02 -07002156static int find_and_kill_process(int min_score_adj, enum kill_reasons kill_reason,
2157 const char *kill_desc, union meminfo *mi,
2158 struct wakeup_info *wi, struct timespec *tm) {
Colin Cross3d57a512014-07-14 12:39:56 -07002159 int i;
Suren Baghdasaryan85c31b52018-10-26 11:32:15 -07002160 int killed_size = 0;
Yang Lu5dfffbc2018-05-15 04:59:44 +00002161 bool lmk_state_change_start = false;
Rajeev Kumar4aba9152018-01-31 17:54:56 -08002162
Chong Zhang1cd12b52015-10-14 16:19:53 -07002163 for (i = OOM_SCORE_ADJ_MAX; i >= min_score_adj; i--) {
Colin Cross3d57a512014-07-14 12:39:56 -07002164 struct proc *procp;
2165
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002166 while (true) {
Suren Baghdasaryan36b2c492018-04-13 11:49:54 -07002167 procp = kill_heaviest_task ?
2168 proc_get_heaviest(i) : proc_adj_lru(i);
Colin Cross3d57a512014-07-14 12:39:56 -07002169
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002170 if (!procp)
2171 break;
2172
Suren Baghdasaryand7b4fcb2020-07-23 18:00:43 -07002173 killed_size = kill_one_process(procp, min_score_adj, kill_reason, kill_desc,
2174 mi, wi, tm);
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002175 if (killed_size >= 0) {
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07002176 if (!lmk_state_change_start) {
Yang Lu5dfffbc2018-05-15 04:59:44 +00002177 lmk_state_change_start = true;
Muhammad Qureshied8fe842019-12-09 17:38:47 -08002178 stats_write_lmk_state_changed(
2179 android::lmkd::stats::LMK_STATE_CHANGED__STATE__START);
Yang Lu5dfffbc2018-05-15 04:59:44 +00002180 }
Suren Baghdasaryan85c31b52018-10-26 11:32:15 -07002181 break;
Colin Cross3d57a512014-07-14 12:39:56 -07002182 }
2183 }
Suren Baghdasaryan85c31b52018-10-26 11:32:15 -07002184 if (killed_size) {
2185 break;
2186 }
Colin Cross3d57a512014-07-14 12:39:56 -07002187 }
2188
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07002189 if (lmk_state_change_start) {
Muhammad Qureshied8fe842019-12-09 17:38:47 -08002190 stats_write_lmk_state_changed(android::lmkd::stats::LMK_STATE_CHANGED__STATE__STOP);
Rajeev Kumar4aba9152018-01-31 17:54:56 -08002191 }
Rajeev Kumar4aba9152018-01-31 17:54:56 -08002192
Suren Baghdasaryan85c31b52018-10-26 11:32:15 -07002193 return killed_size;
Colin Cross3d57a512014-07-14 12:39:56 -07002194}
2195
Suren Baghdasaryan87966742018-04-13 12:43:41 -07002196static int64_t get_memory_usage(struct reread_data *file_data) {
Robert Beneac72b2932017-08-21 15:18:31 -07002197 int64_t mem_usage;
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -07002198 char *buf;
Suren Baghdasaryan87966742018-04-13 12:43:41 -07002199
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -07002200 if ((buf = reread_file(file_data)) == NULL) {
Robert Beneac72b2932017-08-21 15:18:31 -07002201 return -1;
2202 }
2203
Suren Baghdasaryan87966742018-04-13 12:43:41 -07002204 if (!parse_int64(buf, &mem_usage)) {
2205 ALOGE("%s parse error", file_data->filename);
Robert Beneac72b2932017-08-21 15:18:31 -07002206 return -1;
2207 }
Robert Beneac72b2932017-08-21 15:18:31 -07002208 if (mem_usage == 0) {
2209 ALOGE("No memory!");
2210 return -1;
2211 }
2212 return mem_usage;
2213}
2214
Suren Baghdasaryane0f3dd12018-04-13 13:41:12 -07002215void record_low_pressure_levels(union meminfo *mi) {
2216 if (low_pressure_mem.min_nr_free_pages == -1 ||
2217 low_pressure_mem.min_nr_free_pages > mi->field.nr_free_pages) {
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002218 if (debug_process_killing) {
Suren Baghdasaryane0f3dd12018-04-13 13:41:12 -07002219 ALOGI("Low pressure min memory update from %" PRId64 " to %" PRId64,
2220 low_pressure_mem.min_nr_free_pages, mi->field.nr_free_pages);
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002221 }
Suren Baghdasaryane0f3dd12018-04-13 13:41:12 -07002222 low_pressure_mem.min_nr_free_pages = mi->field.nr_free_pages;
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002223 }
2224 /*
2225 * Free memory at low vmpressure events occasionally gets spikes,
2226 * possibly a stale low vmpressure event with memory already
2227 * freed up (no memory pressure should have been reported).
Suren Baghdasaryane0f3dd12018-04-13 13:41:12 -07002228 * Ignore large jumps in max_nr_free_pages that would mess up our stats.
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002229 */
Suren Baghdasaryane0f3dd12018-04-13 13:41:12 -07002230 if (low_pressure_mem.max_nr_free_pages == -1 ||
2231 (low_pressure_mem.max_nr_free_pages < mi->field.nr_free_pages &&
2232 mi->field.nr_free_pages - low_pressure_mem.max_nr_free_pages <
2233 low_pressure_mem.max_nr_free_pages * 0.1)) {
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002234 if (debug_process_killing) {
Suren Baghdasaryane0f3dd12018-04-13 13:41:12 -07002235 ALOGI("Low pressure max memory update from %" PRId64 " to %" PRId64,
2236 low_pressure_mem.max_nr_free_pages, mi->field.nr_free_pages);
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002237 }
Suren Baghdasaryane0f3dd12018-04-13 13:41:12 -07002238 low_pressure_mem.max_nr_free_pages = mi->field.nr_free_pages;
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002239 }
2240}
2241
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08002242enum vmpressure_level upgrade_level(enum vmpressure_level level) {
2243 return (enum vmpressure_level)((level < VMPRESS_LEVEL_CRITICAL) ?
2244 level + 1 : level);
2245}
2246
2247enum vmpressure_level downgrade_level(enum vmpressure_level level) {
2248 return (enum vmpressure_level)((level > VMPRESS_LEVEL_LOW) ?
2249 level - 1 : level);
2250}
2251
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002252enum zone_watermark {
2253 WMARK_MIN = 0,
2254 WMARK_LOW,
2255 WMARK_HIGH,
2256 WMARK_NONE
2257};
2258
Suren Baghdasaryan81c75b22019-08-14 09:48:35 -07002259struct zone_watermarks {
2260 long high_wmark;
2261 long low_wmark;
2262 long min_wmark;
2263};
2264
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002265/*
2266 * Returns lowest breached watermark or WMARK_NONE.
2267 */
Suren Baghdasaryan81c75b22019-08-14 09:48:35 -07002268static enum zone_watermark get_lowest_watermark(union meminfo *mi,
2269 struct zone_watermarks *watermarks)
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002270{
Suren Baghdasaryan81c75b22019-08-14 09:48:35 -07002271 int64_t nr_free_pages = mi->field.nr_free_pages - mi->field.cma_free;
2272
2273 if (nr_free_pages < watermarks->min_wmark) {
2274 return WMARK_MIN;
2275 }
2276 if (nr_free_pages < watermarks->low_wmark) {
2277 return WMARK_LOW;
2278 }
2279 if (nr_free_pages < watermarks->high_wmark) {
2280 return WMARK_HIGH;
2281 }
2282 return WMARK_NONE;
2283}
2284
2285void calc_zone_watermarks(struct zoneinfo *zi, struct zone_watermarks *watermarks) {
2286 memset(watermarks, 0, sizeof(struct zone_watermarks));
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002287
2288 for (int node_idx = 0; node_idx < zi->node_count; node_idx++) {
2289 struct zoneinfo_node *node = &zi->nodes[node_idx];
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002290 for (int zone_idx = 0; zone_idx < node->zone_count; zone_idx++) {
2291 struct zoneinfo_zone *zone = &node->zones[zone_idx];
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002292
2293 if (!zone->fields.field.present) {
2294 continue;
2295 }
2296
Suren Baghdasaryan81c75b22019-08-14 09:48:35 -07002297 watermarks->high_wmark += zone->max_protection + zone->fields.field.high;
2298 watermarks->low_wmark += zone->max_protection + zone->fields.field.low;
2299 watermarks->min_wmark += zone->max_protection + zone->fields.field.min;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002300 }
2301 }
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002302}
2303
Suren Baghdasaryan51ee4c52020-04-21 12:27:01 -07002304static int calc_swap_utilization(union meminfo *mi) {
2305 int64_t swap_used = mi->field.total_swap - mi->field.free_swap;
2306 int64_t total_swappable = mi->field.active_anon + mi->field.inactive_anon +
2307 mi->field.shmem + swap_used;
2308 return total_swappable > 0 ? (swap_used * 100) / total_swappable : 0;
2309}
2310
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002311static void mp_event_psi(int data, uint32_t events, struct polling_params *poll_params) {
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002312 enum reclaim_state {
2313 NO_RECLAIM = 0,
2314 KSWAPD_RECLAIM,
2315 DIRECT_RECLAIM,
2316 };
2317 static int64_t init_ws_refault;
Martin Liu1f72f5f2020-08-21 13:18:50 +08002318 static int64_t prev_workingset_refault;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002319 static int64_t base_file_lru;
2320 static int64_t init_pgscan_kswapd;
2321 static int64_t init_pgscan_direct;
2322 static int64_t swap_low_threshold;
2323 static bool killing;
Martin Liu1f72f5f2020-08-21 13:18:50 +08002324 static int thrashing_limit = thrashing_limit_pct;
Suren Baghdasaryan81c75b22019-08-14 09:48:35 -07002325 static struct zone_watermarks watermarks;
2326 static struct timespec wmark_update_tm;
Suren Baghdasaryand7b4fcb2020-07-23 18:00:43 -07002327 static struct wakeup_info wi;
Martin Liu1f72f5f2020-08-21 13:18:50 +08002328 static struct timespec thrashing_reset_tm;
2329 static int64_t prev_thrash_growth = 0;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002330
2331 union meminfo mi;
2332 union vmstat vs;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002333 struct timespec curr_tm;
2334 int64_t thrashing = 0;
2335 bool swap_is_low = false;
2336 enum vmpressure_level level = (enum vmpressure_level)data;
2337 enum kill_reasons kill_reason = NONE;
2338 bool cycle_after_kill = false;
2339 enum reclaim_state reclaim = NO_RECLAIM;
2340 enum zone_watermark wmark = WMARK_NONE;
Suren Baghdasaryan89454e62019-07-15 15:50:17 -07002341 char kill_desc[LINE_MAX];
Suren Baghdasaryan970a26a2019-09-19 15:27:21 -07002342 bool cut_thrashing_limit = false;
2343 int min_score_adj = 0;
Suren Baghdasaryan51ee4c52020-04-21 12:27:01 -07002344 int swap_util = 0;
Martin Liu1f72f5f2020-08-21 13:18:50 +08002345 long since_thrashing_reset_ms;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002346
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002347 if (clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm) != 0) {
2348 ALOGE("Failed to get current time");
2349 return;
2350 }
2351
Suren Baghdasaryand7b4fcb2020-07-23 18:00:43 -07002352 record_wakeup_time(&curr_tm, events ? Event : Polling, &wi);
2353
Suren Baghdasaryan03dccf32020-04-28 16:02:13 -07002354 bool kill_pending = is_kill_pending();
Suren Baghdasaryaned715a32020-05-11 16:31:57 -07002355 if (kill_pending && (kill_timeout_ms == 0 ||
2356 get_time_diff_ms(&last_kill_tm, &curr_tm) < static_cast<long>(kill_timeout_ms))) {
Suren Baghdasaryan03dccf32020-04-28 16:02:13 -07002357 /* Skip while still killing a process */
Suren Baghdasaryand7b4fcb2020-07-23 18:00:43 -07002358 wi.skipped_wakeups++;
Suren Baghdasaryan03dccf32020-04-28 16:02:13 -07002359 goto no_kill;
2360 }
2361 /*
2362 * Process is dead or kill timeout is over, stop waiting. This has no effect if pidfds are
2363 * supported and death notification already caused waiting to stop.
2364 */
2365 stop_wait_for_proc_kill(!kill_pending);
2366
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002367 if (vmstat_parse(&vs) < 0) {
2368 ALOGE("Failed to parse vmstat!");
2369 return;
2370 }
2371
2372 if (meminfo_parse(&mi) < 0) {
2373 ALOGE("Failed to parse meminfo!");
2374 return;
2375 }
2376
2377 /* Reset states after process got killed */
2378 if (killing) {
2379 killing = false;
2380 cycle_after_kill = true;
2381 /* Reset file-backed pagecache size and refault amounts after a kill */
2382 base_file_lru = vs.field.nr_inactive_file + vs.field.nr_active_file;
2383 init_ws_refault = vs.field.workingset_refault;
Martin Liu1f72f5f2020-08-21 13:18:50 +08002384 thrashing_reset_tm = curr_tm;
2385 prev_thrash_growth = 0;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002386 }
2387
2388 /* Check free swap levels */
2389 if (swap_free_low_percentage) {
2390 if (!swap_low_threshold) {
2391 swap_low_threshold = mi.field.total_swap * swap_free_low_percentage / 100;
2392 }
2393 swap_is_low = mi.field.free_swap < swap_low_threshold;
2394 }
2395
2396 /* Identify reclaim state */
2397 if (vs.field.pgscan_direct > init_pgscan_direct) {
2398 init_pgscan_direct = vs.field.pgscan_direct;
2399 init_pgscan_kswapd = vs.field.pgscan_kswapd;
2400 reclaim = DIRECT_RECLAIM;
2401 } else if (vs.field.pgscan_kswapd > init_pgscan_kswapd) {
2402 init_pgscan_kswapd = vs.field.pgscan_kswapd;
2403 reclaim = KSWAPD_RECLAIM;
Martin Liu1f72f5f2020-08-21 13:18:50 +08002404 } else if (vs.field.workingset_refault == prev_workingset_refault) {
2405 /* Device is not thrashing and not reclaiming, bail out early until we see these stats changing*/
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002406 goto no_kill;
2407 }
2408
Martin Liu1f72f5f2020-08-21 13:18:50 +08002409 prev_workingset_refault = vs.field.workingset_refault;
2410
2411 /*
2412 * It's possible we fail to find an eligible process to kill (ex. no process is
2413 * above oom_adj_min). When this happens, we should retry to find a new process
2414 * for a kill whenever a new eligible process is available. This is especially
2415 * important for a slow growing refault case. While retrying, we should keep
2416 * monitoring new thrashing counter as someone could release the memory to mitigate
2417 * the thrashing. Thus, when thrashing reset window comes, we decay the prev thrashing
2418 * counter by window counts. if the counter is still greater than thrashing limit,
2419 * we preserve the current prev_thrash counter so we will retry kill again. Otherwise,
2420 * we reset the prev_thrash counter so we will stop retrying.
2421 */
2422 since_thrashing_reset_ms = get_time_diff_ms(&thrashing_reset_tm, &curr_tm);
2423 if (since_thrashing_reset_ms > THRASHING_RESET_INTERVAL_MS) {
2424 long windows_passed;
2425 /* Calculate prev_thrash_growth if we crossed THRASHING_RESET_INTERVAL_MS */
Martin Liuc3108412020-09-03 22:12:14 +08002426 prev_thrash_growth = (vs.field.workingset_refault - init_ws_refault) * 100
2427 / (base_file_lru + 1);
Martin Liu1f72f5f2020-08-21 13:18:50 +08002428 windows_passed = (since_thrashing_reset_ms / THRASHING_RESET_INTERVAL_MS);
2429 /*
2430 * Decay prev_thrashing unless over-the-limit thrashing was registered in the window we
2431 * just crossed, which means there were no eligible processes to kill. We preserve the
2432 * counter in that case to ensure a kill if a new eligible process appears.
2433 */
2434 if (windows_passed > 1 || prev_thrash_growth < thrashing_limit) {
2435 prev_thrash_growth >>= windows_passed;
2436 }
2437
2438 /* Record file-backed pagecache size when crossing THRASHING_RESET_INTERVAL_MS */
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002439 base_file_lru = vs.field.nr_inactive_file + vs.field.nr_active_file;
2440 init_ws_refault = vs.field.workingset_refault;
Martin Liu1f72f5f2020-08-21 13:18:50 +08002441 thrashing_reset_tm = curr_tm;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002442 thrashing_limit = thrashing_limit_pct;
2443 } else {
2444 /* Calculate what % of the file-backed pagecache refaulted so far */
Martin Liuc3108412020-09-03 22:12:14 +08002445 thrashing = (vs.field.workingset_refault - init_ws_refault) * 100 / (base_file_lru + 1);
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002446 }
Martin Liu1f72f5f2020-08-21 13:18:50 +08002447 /* Add previous cycle's decayed thrashing amount */
2448 thrashing += prev_thrash_growth;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002449
Suren Baghdasaryan81c75b22019-08-14 09:48:35 -07002450 /*
2451 * Refresh watermarks once per min in case user updated one of the margins.
2452 * TODO: b/140521024 replace this periodic update with an API for AMS to notify LMKD
2453 * that zone watermarks were changed by the system software.
2454 */
2455 if (watermarks.high_wmark == 0 || get_time_diff_ms(&wmark_update_tm, &curr_tm) > 60000) {
2456 struct zoneinfo zi;
2457
2458 if (zoneinfo_parse(&zi) < 0) {
2459 ALOGE("Failed to parse zoneinfo!");
2460 return;
2461 }
2462
2463 calc_zone_watermarks(&zi, &watermarks);
2464 wmark_update_tm = curr_tm;
Martin Liu1f72f5f2020-08-21 13:18:50 +08002465 }
Suren Baghdasaryan81c75b22019-08-14 09:48:35 -07002466
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002467 /* Find out which watermark is breached if any */
Suren Baghdasaryan81c75b22019-08-14 09:48:35 -07002468 wmark = get_lowest_watermark(&mi, &watermarks);
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002469
2470 /*
2471 * TODO: move this logic into a separate function
2472 * Decide if killing a process is necessary and record the reason
2473 */
2474 if (cycle_after_kill && wmark < WMARK_LOW) {
2475 /*
2476 * Prevent kills not freeing enough memory which might lead to OOM kill.
2477 * This might happen when a process is consuming memory faster than reclaim can
2478 * free even after a kill. Mostly happens when running memory stress tests.
2479 */
2480 kill_reason = PRESSURE_AFTER_KILL;
Suren Baghdasaryan89454e62019-07-15 15:50:17 -07002481 strncpy(kill_desc, "min watermark is breached even after kill", sizeof(kill_desc));
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002482 } else if (level == VMPRESS_LEVEL_CRITICAL && events != 0) {
2483 /*
2484 * Device is too busy reclaiming memory which might lead to ANR.
2485 * Critical level is triggered when PSI complete stall (all tasks are blocked because
2486 * of the memory congestion) breaches the configured threshold.
2487 */
2488 kill_reason = NOT_RESPONDING;
Suren Baghdasaryan89454e62019-07-15 15:50:17 -07002489 strncpy(kill_desc, "device is not responding", sizeof(kill_desc));
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002490 } else if (swap_is_low && thrashing > thrashing_limit_pct) {
2491 /* Page cache is thrashing while swap is low */
2492 kill_reason = LOW_SWAP_AND_THRASHING;
Suren Baghdasaryan89454e62019-07-15 15:50:17 -07002493 snprintf(kill_desc, sizeof(kill_desc), "device is low on swap (%" PRId64
2494 "kB < %" PRId64 "kB) and thrashing (%" PRId64 "%%)",
2495 mi.field.free_swap * page_k, swap_low_threshold * page_k, thrashing);
Suren Baghdasaryan48135c42020-05-19 12:59:18 -07002496 /* Do not kill perceptible apps unless below min watermark */
Martin Liu3185c2d2020-06-02 13:05:51 +08002497 if (wmark > WMARK_MIN) {
Suren Baghdasaryan48135c42020-05-19 12:59:18 -07002498 min_score_adj = PERCEPTIBLE_APP_ADJ + 1;
2499 }
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002500 } else if (swap_is_low && wmark < WMARK_HIGH) {
2501 /* Both free memory and swap are low */
2502 kill_reason = LOW_MEM_AND_SWAP;
Suren Baghdasaryan89454e62019-07-15 15:50:17 -07002503 snprintf(kill_desc, sizeof(kill_desc), "%s watermark is breached and swap is low (%"
2504 PRId64 "kB < %" PRId64 "kB)", wmark > WMARK_LOW ? "min" : "low",
2505 mi.field.free_swap * page_k, swap_low_threshold * page_k);
Suren Baghdasaryan48135c42020-05-19 12:59:18 -07002506 /* Do not kill perceptible apps unless below min watermark */
Martin Liu3185c2d2020-06-02 13:05:51 +08002507 if (wmark > WMARK_MIN) {
Suren Baghdasaryan48135c42020-05-19 12:59:18 -07002508 min_score_adj = PERCEPTIBLE_APP_ADJ + 1;
2509 }
Suren Baghdasaryan51ee4c52020-04-21 12:27:01 -07002510 } else if (wmark < WMARK_HIGH && swap_util_max < 100 &&
2511 (swap_util = calc_swap_utilization(&mi)) > swap_util_max) {
2512 /*
2513 * Too much anon memory is swapped out but swap is not low.
2514 * Non-swappable allocations created memory pressure.
2515 */
2516 kill_reason = LOW_MEM_AND_SWAP_UTIL;
2517 snprintf(kill_desc, sizeof(kill_desc), "%s watermark is breached and swap utilization"
2518 " is high (%d%% > %d%%)", wmark > WMARK_LOW ? "min" : "low",
2519 swap_util, swap_util_max);
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002520 } else if (wmark < WMARK_HIGH && thrashing > thrashing_limit) {
2521 /* Page cache is thrashing while memory is low */
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002522 kill_reason = LOW_MEM_AND_THRASHING;
Suren Baghdasaryan89454e62019-07-15 15:50:17 -07002523 snprintf(kill_desc, sizeof(kill_desc), "%s watermark is breached and thrashing (%"
2524 PRId64 "%%)", wmark > WMARK_LOW ? "min" : "low", thrashing);
Suren Baghdasaryan970a26a2019-09-19 15:27:21 -07002525 cut_thrashing_limit = true;
2526 /* Do not kill perceptible apps because of thrashing */
Suren Baghdasaryan5c039b52020-05-19 12:44:31 -07002527 min_score_adj = PERCEPTIBLE_APP_ADJ + 1;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002528 } else if (reclaim == DIRECT_RECLAIM && thrashing > thrashing_limit) {
2529 /* Page cache is thrashing while in direct reclaim (mostly happens on lowram devices) */
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002530 kill_reason = DIRECT_RECL_AND_THRASHING;
Suren Baghdasaryan89454e62019-07-15 15:50:17 -07002531 snprintf(kill_desc, sizeof(kill_desc), "device is in direct reclaim and thrashing (%"
2532 PRId64 "%%)", thrashing);
Suren Baghdasaryan970a26a2019-09-19 15:27:21 -07002533 cut_thrashing_limit = true;
2534 /* Do not kill perceptible apps because of thrashing */
Suren Baghdasaryan5c039b52020-05-19 12:44:31 -07002535 min_score_adj = PERCEPTIBLE_APP_ADJ + 1;
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002536 }
2537
2538 /* Kill a process if necessary */
2539 if (kill_reason != NONE) {
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002540 int pages_freed = find_and_kill_process(min_score_adj, kill_reason, kill_desc, &mi,
Suren Baghdasaryand7b4fcb2020-07-23 18:00:43 -07002541 &wi, &curr_tm);
Suren Baghdasaryan970a26a2019-09-19 15:27:21 -07002542 if (pages_freed > 0) {
2543 killing = true;
2544 if (cut_thrashing_limit) {
2545 /*
2546 * Cut thrasing limit by thrashing_limit_decay_pct percentage of the current
2547 * thrashing limit until the system stops thrashing.
2548 */
2549 thrashing_limit = (thrashing_limit * (100 - thrashing_limit_decay_pct)) / 100;
2550 }
2551 }
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002552 }
2553
2554no_kill:
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002555 /* Do not poll if kernel supports pidfd waiting */
2556 if (is_waiting_for_kill()) {
2557 /* Pause polling if we are waiting for process death notification */
2558 poll_params->update = POLLING_PAUSE;
2559 return;
2560 }
2561
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002562 /*
2563 * Start polling after initial PSI event;
2564 * extend polling while device is in direct reclaim or process is being killed;
2565 * do not extend when kswapd reclaims because that might go on for a long time
2566 * without causing memory pressure
2567 */
2568 if (events || killing || reclaim == DIRECT_RECLAIM) {
2569 poll_params->update = POLLING_START;
2570 }
2571
2572 /* Decide the polling interval */
2573 if (swap_is_low || killing) {
2574 /* Fast polling during and after a kill or when swap is low */
2575 poll_params->polling_interval_ms = PSI_POLL_PERIOD_SHORT_MS;
2576 } else {
2577 /* By default use long intervals */
2578 poll_params->polling_interval_ms = PSI_POLL_PERIOD_LONG_MS;
2579 }
2580}
2581
Suren Baghdasaryane12a0672019-07-15 14:50:49 -07002582static void mp_event_common(int data, uint32_t events, struct polling_params *poll_params) {
Todd Poynorc58c5142013-07-09 19:35:14 -07002583 unsigned long long evcount;
Robert Beneac72b2932017-08-21 15:18:31 -07002584 int64_t mem_usage, memsw_usage;
Robert Benea3be16142017-09-13 15:20:30 -07002585 int64_t mem_pressure;
Suren Baghdasaryane0f3dd12018-04-13 13:41:12 -07002586 union meminfo mi;
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07002587 struct zoneinfo zi;
Suren Baghdasaryan53be36e2018-09-05 15:46:32 -07002588 struct timespec curr_tm;
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -07002589 static unsigned long kill_skip_count = 0;
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08002590 enum vmpressure_level level = (enum vmpressure_level)data;
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07002591 long other_free = 0, other_file = 0;
2592 int min_score_adj;
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07002593 int minfree = 0;
Suren Baghdasaryan87966742018-04-13 12:43:41 -07002594 static struct reread_data mem_usage_file_data = {
2595 .filename = MEMCG_MEMORY_USAGE,
2596 .fd = -1,
2597 };
2598 static struct reread_data memsw_usage_file_data = {
2599 .filename = MEMCG_MEMORYSW_USAGE,
2600 .fd = -1,
2601 };
Suren Baghdasaryand7b4fcb2020-07-23 18:00:43 -07002602 static struct wakeup_info wi;
Todd Poynorc58c5142013-07-09 19:35:14 -07002603
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08002604 if (debug_process_killing) {
2605 ALOGI("%s memory pressure event is triggered", level_name[level]);
2606 }
2607
2608 if (!use_psi_monitors) {
2609 /*
2610 * Check all event counters from low to critical
2611 * and upgrade to the highest priority one. By reading
2612 * eventfd we also reset the event counters.
2613 */
Tom Cherry43f3d2b2019-12-04 12:46:57 -08002614 for (int lvl = VMPRESS_LEVEL_LOW; lvl < VMPRESS_LEVEL_COUNT; lvl++) {
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08002615 if (mpevfd[lvl] != -1 &&
2616 TEMP_FAILURE_RETRY(read(mpevfd[lvl],
2617 &evcount, sizeof(evcount))) > 0 &&
2618 evcount > 0 && lvl > level) {
Tom Cherry43f3d2b2019-12-04 12:46:57 -08002619 level = static_cast<vmpressure_level>(lvl);
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08002620 }
Suren Baghdasaryan3e1a8492018-01-04 09:16:21 -08002621 }
2622 }
Todd Poynorc58c5142013-07-09 19:35:14 -07002623
Suren Baghdasaryane12a0672019-07-15 14:50:49 -07002624 /* Start polling after initial PSI event */
2625 if (use_psi_monitors && events) {
2626 /* Override polling params only if current event is more critical */
2627 if (!poll_params->poll_handler || data > poll_params->poll_handler->data) {
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07002628 poll_params->polling_interval_ms = PSI_POLL_PERIOD_SHORT_MS;
Suren Baghdasaryane12a0672019-07-15 14:50:49 -07002629 poll_params->update = POLLING_START;
2630 }
2631 }
2632
Suren Baghdasaryan53be36e2018-09-05 15:46:32 -07002633 if (clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm) != 0) {
2634 ALOGE("Failed to get current time");
2635 return;
2636 }
2637
Suren Baghdasaryand7b4fcb2020-07-23 18:00:43 -07002638 record_wakeup_time(&curr_tm, events ? Event : Polling, &wi);
2639
Suren Baghdasaryaned715a32020-05-11 16:31:57 -07002640 if (kill_timeout_ms &&
2641 get_time_diff_ms(&last_kill_tm, &curr_tm) < static_cast<long>(kill_timeout_ms)) {
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002642 /*
2643 * If we're within the no-kill timeout, see if there's pending reclaim work
2644 * from the last killed process. If so, skip killing for now.
2645 */
2646 if (is_kill_pending()) {
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -07002647 kill_skip_count++;
Suren Baghdasaryand7b4fcb2020-07-23 18:00:43 -07002648 wi.skipped_wakeups++;
Suren Baghdasaryan30854e72018-01-17 17:28:01 -08002649 return;
2650 }
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002651 /*
2652 * Process is dead, stop waiting. This has no effect if pidfds are supported and
2653 * death notification already caused waiting to stop.
2654 */
2655 stop_wait_for_proc_kill(true);
2656 } else {
2657 /*
2658 * Killing took longer than no-kill timeout. Stop waiting for the last process
2659 * to die because we are ready to kill again.
2660 */
2661 stop_wait_for_proc_kill(false);
Suren Baghdasaryan30854e72018-01-17 17:28:01 -08002662 }
2663
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -07002664 if (kill_skip_count > 0) {
Suren Baghdasaryaneff82332018-05-10 16:10:56 -07002665 ALOGI("%lu memory pressure events were skipped after a kill!",
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -07002666 kill_skip_count);
2667 kill_skip_count = 0;
Suren Baghdasaryan30854e72018-01-17 17:28:01 -08002668 }
2669
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07002670 if (meminfo_parse(&mi) < 0 || zoneinfo_parse(&zi) < 0) {
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002671 ALOGE("Failed to get free memory!");
2672 return;
2673 }
2674
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07002675 if (use_minfree_levels) {
2676 int i;
2677
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07002678 other_free = mi.field.nr_free_pages - zi.totalreserve_pages;
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07002679 if (mi.field.nr_file_pages > (mi.field.shmem + mi.field.unevictable + mi.field.swap_cached)) {
2680 other_file = (mi.field.nr_file_pages - mi.field.shmem -
2681 mi.field.unevictable - mi.field.swap_cached);
2682 } else {
2683 other_file = 0;
2684 }
2685
2686 min_score_adj = OOM_SCORE_ADJ_MAX + 1;
2687 for (i = 0; i < lowmem_targets_size; i++) {
2688 minfree = lowmem_minfree[i];
2689 if (other_free < minfree && other_file < minfree) {
2690 min_score_adj = lowmem_adj[i];
2691 break;
2692 }
2693 }
2694
Suren Baghdasaryanb0bda552018-05-18 14:42:00 -07002695 if (min_score_adj == OOM_SCORE_ADJ_MAX + 1) {
2696 if (debug_process_killing) {
2697 ALOGI("Ignore %s memory pressure event "
2698 "(free memory=%ldkB, cache=%ldkB, limit=%ldkB)",
2699 level_name[level], other_free * page_k, other_file * page_k,
2700 (long)lowmem_minfree[lowmem_targets_size - 1] * page_k);
2701 }
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07002702 return;
Suren Baghdasaryanb0bda552018-05-18 14:42:00 -07002703 }
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07002704
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07002705 goto do_kill;
2706 }
2707
Suren Baghdasaryane0f3dd12018-04-13 13:41:12 -07002708 if (level == VMPRESS_LEVEL_LOW) {
2709 record_low_pressure_levels(&mi);
2710 }
2711
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002712 if (level_oomadj[level] > OOM_SCORE_ADJ_MAX) {
2713 /* Do not monitor this pressure level */
2714 return;
2715 }
2716
Suren Baghdasaryan87966742018-04-13 12:43:41 -07002717 if ((mem_usage = get_memory_usage(&mem_usage_file_data)) < 0) {
2718 goto do_kill;
2719 }
2720 if ((memsw_usage = get_memory_usage(&memsw_usage_file_data)) < 0) {
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08002721 goto do_kill;
Robert Benea3be16142017-09-13 15:20:30 -07002722 }
Robert Beneac72b2932017-08-21 15:18:31 -07002723
Robert Benea3be16142017-09-13 15:20:30 -07002724 // Calculate percent for swappinness.
2725 mem_pressure = (mem_usage * 100) / memsw_usage;
2726
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08002727 if (enable_pressure_upgrade && level != VMPRESS_LEVEL_CRITICAL) {
Robert Benea3be16142017-09-13 15:20:30 -07002728 // We are swapping too much.
2729 if (mem_pressure < upgrade_pressure) {
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08002730 level = upgrade_level(level);
2731 if (debug_process_killing) {
2732 ALOGI("Event upgraded to %s", level_name[level]);
2733 }
Robert Beneac72b2932017-08-21 15:18:31 -07002734 }
2735 }
2736
Vic Yang65680692018-08-07 10:18:22 -07002737 // If we still have enough swap space available, check if we want to
2738 // ignore/downgrade pressure events.
2739 if (mi.field.free_swap >=
2740 mi.field.total_swap * swap_free_low_percentage / 100) {
2741 // If the pressure is larger than downgrade_pressure lmk will not
2742 // kill any process, since enough memory is available.
2743 if (mem_pressure > downgrade_pressure) {
2744 if (debug_process_killing) {
2745 ALOGI("Ignore %s memory pressure", level_name[level]);
2746 }
2747 return;
2748 } else if (level == VMPRESS_LEVEL_CRITICAL && mem_pressure > upgrade_pressure) {
2749 if (debug_process_killing) {
2750 ALOGI("Downgrade critical memory pressure");
2751 }
2752 // Downgrade event, since enough memory available.
2753 level = downgrade_level(level);
Robert Benea3be16142017-09-13 15:20:30 -07002754 }
Robert Benea3be16142017-09-13 15:20:30 -07002755 }
2756
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08002757do_kill:
Suren Baghdasaryand1d59f82018-04-13 11:45:38 -07002758 if (low_ram_device) {
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002759 /* For Go devices kill only one task */
Suren Baghdasaryan3cc1f132020-09-09 20:19:02 -07002760 if (find_and_kill_process(level_oomadj[level], NONE, NULL, &mi, &wi, &curr_tm) == 0) {
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002761 if (debug_process_killing) {
2762 ALOGI("Nothing to kill");
2763 }
2764 }
2765 } else {
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07002766 int pages_freed;
Suren Baghdasaryan53be36e2018-09-05 15:46:32 -07002767 static struct timespec last_report_tm;
2768 static unsigned long report_skip_count = 0;
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07002769
2770 if (!use_minfree_levels) {
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07002771 /* Free up enough memory to downgrate the memory pressure to low level */
Suren Baghdasaryan85c31b52018-10-26 11:32:15 -07002772 if (mi.field.nr_free_pages >= low_pressure_mem.max_nr_free_pages) {
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07002773 if (debug_process_killing) {
2774 ALOGI("Ignoring pressure since more memory is "
2775 "available (%" PRId64 ") than watermark (%" PRId64 ")",
2776 mi.field.nr_free_pages, low_pressure_mem.max_nr_free_pages);
2777 }
2778 return;
2779 }
2780 min_score_adj = level_oomadj[level];
Suren Baghdasaryan94ccd722018-01-17 17:17:44 -08002781 }
2782
Suren Baghdasaryan3cc1f132020-09-09 20:19:02 -07002783 pages_freed = find_and_kill_process(min_score_adj, NONE, NULL, &mi, &wi, &curr_tm);
Suren Baghdasaryaneff82332018-05-10 16:10:56 -07002784
Suren Baghdasaryan53be36e2018-09-05 15:46:32 -07002785 if (pages_freed == 0) {
2786 /* Rate limit kill reports when nothing was reclaimed */
2787 if (get_time_diff_ms(&last_report_tm, &curr_tm) < FAIL_REPORT_RLIMIT_MS) {
2788 report_skip_count++;
Suren Baghdasaryan1ed0db12018-07-24 17:13:06 -07002789 return;
2790 }
Robert Benea7f68a3f2017-08-11 16:03:20 -07002791 }
Suren Baghdasaryan53be36e2018-09-05 15:46:32 -07002792
Suren Baghdasaryan12cacae2019-09-16 12:06:30 -07002793 /* Log whenever we kill or when report rate limit allows */
Suren Baghdasaryan53be36e2018-09-05 15:46:32 -07002794 if (use_minfree_levels) {
Suren Baghdasaryan85c31b52018-10-26 11:32:15 -07002795 ALOGI("Reclaimed %ldkB, cache(%ldkB) and "
Suren Baghdasaryan53be36e2018-09-05 15:46:32 -07002796 "free(%" PRId64 "kB)-reserved(%" PRId64 "kB) below min(%ldkB) for oom_adj %d",
Suren Baghdasaryan85c31b52018-10-26 11:32:15 -07002797 pages_freed * page_k,
Suren Baghdasaryan53be36e2018-09-05 15:46:32 -07002798 other_file * page_k, mi.field.nr_free_pages * page_k,
Suren Baghdasaryan92d0eec2019-07-15 13:54:20 -07002799 zi.totalreserve_pages * page_k,
Suren Baghdasaryan53be36e2018-09-05 15:46:32 -07002800 minfree * page_k, min_score_adj);
2801 } else {
Suren Baghdasaryan85c31b52018-10-26 11:32:15 -07002802 ALOGI("Reclaimed %ldkB at oom_adj %d",
2803 pages_freed * page_k, min_score_adj);
Suren Baghdasaryan53be36e2018-09-05 15:46:32 -07002804 }
2805
2806 if (report_skip_count > 0) {
2807 ALOGI("Suppressed %lu failed kill reports", report_skip_count);
2808 report_skip_count = 0;
2809 }
2810
2811 last_report_tm = curr_tm;
Colin Cross01db2712014-07-11 17:16:56 -07002812 }
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07002813 if (is_waiting_for_kill()) {
2814 /* pause polling if we are waiting for process death notification */
2815 poll_params->update = POLLING_PAUSE;
2816 }
Todd Poynorc58c5142013-07-09 19:35:14 -07002817}
2818
Suren Baghdasaryan2f88e152019-07-15 15:42:09 -07002819static bool init_mp_psi(enum vmpressure_level level, bool use_new_strategy) {
2820 int fd;
2821
2822 /* Do not register a handler if threshold_ms is not set */
2823 if (!psi_thresholds[level].threshold_ms) {
2824 return true;
2825 }
2826
2827 fd = init_psi_monitor(psi_thresholds[level].stall_type,
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08002828 psi_thresholds[level].threshold_ms * US_PER_MS,
2829 PSI_WINDOW_SIZE_MS * US_PER_MS);
2830
2831 if (fd < 0) {
2832 return false;
2833 }
2834
Suren Baghdasaryan2f88e152019-07-15 15:42:09 -07002835 vmpressure_hinfo[level].handler = use_new_strategy ? mp_event_psi : mp_event_common;
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08002836 vmpressure_hinfo[level].data = level;
2837 if (register_psi_monitor(epollfd, fd, &vmpressure_hinfo[level]) < 0) {
2838 destroy_psi_monitor(fd);
2839 return false;
2840 }
2841 maxevents++;
2842 mpevfd[level] = fd;
2843
2844 return true;
2845}
2846
2847static void destroy_mp_psi(enum vmpressure_level level) {
2848 int fd = mpevfd[level];
2849
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07002850 if (fd < 0) {
2851 return;
2852 }
2853
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08002854 if (unregister_psi_monitor(epollfd, fd) < 0) {
2855 ALOGE("Failed to unregister psi monitor for %s memory pressure; errno=%d",
2856 level_name[level], errno);
2857 }
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07002858 maxevents--;
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08002859 destroy_psi_monitor(fd);
2860 mpevfd[level] = -1;
2861}
2862
2863static bool init_psi_monitors() {
Suren Baghdasaryan2f88e152019-07-15 15:42:09 -07002864 /*
2865 * When PSI is used on low-ram devices or on high-end devices without memfree levels
2866 * use new kill strategy based on zone watermarks, free swap and thrashing stats
2867 */
2868 bool use_new_strategy =
2869 property_get_bool("ro.lmk.use_new_strategy", low_ram_device || !use_minfree_levels);
2870
2871 /* In default PSI mode override stall amounts using system properties */
2872 if (use_new_strategy) {
2873 /* Do not use low pressure level */
2874 psi_thresholds[VMPRESS_LEVEL_LOW].threshold_ms = 0;
2875 psi_thresholds[VMPRESS_LEVEL_MEDIUM].threshold_ms = psi_partial_stall_ms;
2876 psi_thresholds[VMPRESS_LEVEL_CRITICAL].threshold_ms = psi_complete_stall_ms;
2877 }
2878
2879 if (!init_mp_psi(VMPRESS_LEVEL_LOW, use_new_strategy)) {
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08002880 return false;
2881 }
Suren Baghdasaryan2f88e152019-07-15 15:42:09 -07002882 if (!init_mp_psi(VMPRESS_LEVEL_MEDIUM, use_new_strategy)) {
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08002883 destroy_mp_psi(VMPRESS_LEVEL_LOW);
2884 return false;
2885 }
Suren Baghdasaryan2f88e152019-07-15 15:42:09 -07002886 if (!init_mp_psi(VMPRESS_LEVEL_CRITICAL, use_new_strategy)) {
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08002887 destroy_mp_psi(VMPRESS_LEVEL_MEDIUM);
2888 destroy_mp_psi(VMPRESS_LEVEL_LOW);
2889 return false;
2890 }
2891 return true;
2892}
2893
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08002894static bool init_mp_common(enum vmpressure_level level) {
Todd Poynorc58c5142013-07-09 19:35:14 -07002895 int mpfd;
2896 int evfd;
2897 int evctlfd;
2898 char buf[256];
2899 struct epoll_event epev;
2900 int ret;
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08002901 int level_idx = (int)level;
2902 const char *levelstr = level_name[level_idx];
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08002903
Mark Salyzyna00ccd82018-04-09 09:50:32 -07002904 /* gid containing AID_SYSTEM required */
Nick Kralevich148d8dd2015-12-18 20:52:37 -08002905 mpfd = open(MEMCG_SYSFS_PATH "memory.pressure_level", O_RDONLY | O_CLOEXEC);
Todd Poynorc58c5142013-07-09 19:35:14 -07002906 if (mpfd < 0) {
2907 ALOGI("No kernel memory.pressure_level support (errno=%d)", errno);
2908 goto err_open_mpfd;
2909 }
2910
Nick Kralevich148d8dd2015-12-18 20:52:37 -08002911 evctlfd = open(MEMCG_SYSFS_PATH "cgroup.event_control", O_WRONLY | O_CLOEXEC);
Todd Poynorc58c5142013-07-09 19:35:14 -07002912 if (evctlfd < 0) {
2913 ALOGI("No kernel memory cgroup event control (errno=%d)", errno);
2914 goto err_open_evctlfd;
2915 }
2916
Nick Kralevich148d8dd2015-12-18 20:52:37 -08002917 evfd = eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC);
Todd Poynorc58c5142013-07-09 19:35:14 -07002918 if (evfd < 0) {
2919 ALOGE("eventfd failed for level %s; errno=%d", levelstr, errno);
2920 goto err_eventfd;
2921 }
2922
2923 ret = snprintf(buf, sizeof(buf), "%d %d %s", evfd, mpfd, levelstr);
2924 if (ret >= (ssize_t)sizeof(buf)) {
2925 ALOGE("cgroup.event_control line overflow for level %s", levelstr);
2926 goto err;
2927 }
2928
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08002929 ret = TEMP_FAILURE_RETRY(write(evctlfd, buf, strlen(buf) + 1));
Todd Poynorc58c5142013-07-09 19:35:14 -07002930 if (ret == -1) {
2931 ALOGE("cgroup.event_control write failed for level %s; errno=%d",
2932 levelstr, errno);
2933 goto err;
2934 }
2935
2936 epev.events = EPOLLIN;
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08002937 /* use data to store event level */
2938 vmpressure_hinfo[level_idx].data = level_idx;
2939 vmpressure_hinfo[level_idx].handler = mp_event_common;
2940 epev.data.ptr = (void *)&vmpressure_hinfo[level_idx];
Todd Poynorc58c5142013-07-09 19:35:14 -07002941 ret = epoll_ctl(epollfd, EPOLL_CTL_ADD, evfd, &epev);
2942 if (ret == -1) {
2943 ALOGE("epoll_ctl for level %s failed; errno=%d", levelstr, errno);
2944 goto err;
2945 }
2946 maxevents++;
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08002947 mpevfd[level] = evfd;
Suren Baghdasaryanceffaf22018-01-04 08:54:53 -08002948 close(evctlfd);
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08002949 return true;
Todd Poynorc58c5142013-07-09 19:35:14 -07002950
2951err:
2952 close(evfd);
2953err_eventfd:
2954 close(evctlfd);
2955err_open_evctlfd:
2956 close(mpfd);
2957err_open_mpfd:
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08002958 return false;
Robert Benea58d6a132017-06-01 16:32:31 -07002959}
2960
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07002961static void destroy_mp_common(enum vmpressure_level level) {
2962 struct epoll_event epev;
2963 int fd = mpevfd[level];
2964
2965 if (fd < 0) {
2966 return;
2967 }
2968
2969 if (epoll_ctl(epollfd, EPOLL_CTL_DEL, fd, &epev)) {
2970 // Log an error and keep going
2971 ALOGE("epoll_ctl for level %s failed; errno=%d", level_name[level], errno);
2972 }
2973 maxevents--;
2974 close(fd);
2975 mpevfd[level] = -1;
2976}
2977
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07002978static void kernel_event_handler(int data __unused, uint32_t events __unused,
2979 struct polling_params *poll_params __unused) {
Jing Ji5c480962019-12-04 09:22:05 -08002980 poll_kernel(kpoll_fd);
Jim Blackler700b7192019-04-26 11:18:29 +01002981}
2982
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07002983static bool init_monitors() {
2984 /* Try to use psi monitor first if kernel has it */
2985 use_psi_monitors = property_get_bool("ro.lmk.use_psi", true) &&
2986 init_psi_monitors();
2987 /* Fall back to vmpressure */
2988 if (!use_psi_monitors &&
2989 (!init_mp_common(VMPRESS_LEVEL_LOW) ||
2990 !init_mp_common(VMPRESS_LEVEL_MEDIUM) ||
2991 !init_mp_common(VMPRESS_LEVEL_CRITICAL))) {
2992 ALOGE("Kernel does not support memory pressure events or in-kernel low memory killer");
2993 return false;
2994 }
2995 if (use_psi_monitors) {
2996 ALOGI("Using psi monitors for memory pressure detection");
2997 } else {
2998 ALOGI("Using vmpressure for memory pressure detection");
2999 }
3000 return true;
3001}
3002
3003static void destroy_monitors() {
3004 if (use_psi_monitors) {
3005 destroy_mp_psi(VMPRESS_LEVEL_CRITICAL);
3006 destroy_mp_psi(VMPRESS_LEVEL_MEDIUM);
3007 destroy_mp_psi(VMPRESS_LEVEL_LOW);
3008 } else {
3009 destroy_mp_common(VMPRESS_LEVEL_CRITICAL);
3010 destroy_mp_common(VMPRESS_LEVEL_MEDIUM);
3011 destroy_mp_common(VMPRESS_LEVEL_LOW);
3012 }
3013}
3014
Todd Poynorc58c5142013-07-09 19:35:14 -07003015static int init(void) {
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07003016 static struct event_handler_info kernel_poll_hinfo = { 0, kernel_event_handler };
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -07003017 struct reread_data file_data = {
3018 .filename = ZONEINFO_PATH,
3019 .fd = -1,
3020 };
Todd Poynorc58c5142013-07-09 19:35:14 -07003021 struct epoll_event epev;
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003022 int pidfd;
Todd Poynorc58c5142013-07-09 19:35:14 -07003023 int i;
3024 int ret;
3025
3026 page_k = sysconf(_SC_PAGESIZE);
3027 if (page_k == -1)
3028 page_k = PAGE_SIZE;
3029 page_k /= 1024;
3030
3031 epollfd = epoll_create(MAX_EPOLL_EVENTS);
3032 if (epollfd == -1) {
3033 ALOGE("epoll_create failed (errno=%d)", errno);
3034 return -1;
3035 }
3036
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003037 // mark data connections as not connected
3038 for (int i = 0; i < MAX_DATA_CONN; i++) {
3039 data_sock[i].sock = -1;
3040 }
3041
3042 ctrl_sock.sock = android_get_control_socket("lmkd");
3043 if (ctrl_sock.sock < 0) {
Todd Poynorc58c5142013-07-09 19:35:14 -07003044 ALOGE("get lmkd control socket failed");
3045 return -1;
3046 }
3047
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003048 ret = listen(ctrl_sock.sock, MAX_DATA_CONN);
Todd Poynorc58c5142013-07-09 19:35:14 -07003049 if (ret < 0) {
3050 ALOGE("lmkd control socket listen failed (errno=%d)", errno);
3051 return -1;
3052 }
3053
3054 epev.events = EPOLLIN;
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003055 ctrl_sock.handler_info.handler = ctrl_connect_handler;
3056 epev.data.ptr = (void *)&(ctrl_sock.handler_info);
3057 if (epoll_ctl(epollfd, EPOLL_CTL_ADD, ctrl_sock.sock, &epev) == -1) {
Todd Poynorc58c5142013-07-09 19:35:14 -07003058 ALOGE("epoll_ctl for lmkd control socket failed (errno=%d)", errno);
3059 return -1;
3060 }
3061 maxevents++;
3062
Robert Benea7878c9b2017-09-11 16:53:28 -07003063 has_inkernel_module = !access(INKERNEL_MINFREE_PATH, W_OK);
Suren Baghdasaryane6613ea2018-01-18 17:27:30 -08003064 use_inkernel_interface = has_inkernel_module;
Todd Poynorc58c5142013-07-09 19:35:14 -07003065
3066 if (use_inkernel_interface) {
3067 ALOGI("Using in-kernel low memory killer interface");
Jing Ji5c480962019-12-04 09:22:05 -08003068 if (init_poll_kernel()) {
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07003069 epev.events = EPOLLIN;
3070 epev.data.ptr = (void*)&kernel_poll_hinfo;
Jing Ji5c480962019-12-04 09:22:05 -08003071 if (epoll_ctl(epollfd, EPOLL_CTL_ADD, kpoll_fd, &epev) != 0) {
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07003072 ALOGE("epoll_ctl for lmk events failed (errno=%d)", errno);
Jing Ji5c480962019-12-04 09:22:05 -08003073 close(kpoll_fd);
3074 kpoll_fd = -1;
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07003075 } else {
3076 maxevents++;
Jing Ji5c480962019-12-04 09:22:05 -08003077 /* let the others know it does support reporting kills */
3078 property_set("sys.lmk.reportkills", "1");
Suren Baghdasaryan8b016be2019-09-04 19:12:29 -07003079 }
Jim Blackler700b7192019-04-26 11:18:29 +01003080 }
Todd Poynorc58c5142013-07-09 19:35:14 -07003081 } else {
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07003082 if (!init_monitors()) {
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08003083 return -1;
3084 }
Jing Ji5c480962019-12-04 09:22:05 -08003085 /* let the others know it does support reporting kills */
3086 property_set("sys.lmk.reportkills", "1");
Todd Poynorc58c5142013-07-09 19:35:14 -07003087 }
3088
Chong Zhang1cd12b52015-10-14 16:19:53 -07003089 for (i = 0; i <= ADJTOSLOT(OOM_SCORE_ADJ_MAX); i++) {
Todd Poynorc58c5142013-07-09 19:35:14 -07003090 procadjslot_list[i].next = &procadjslot_list[i];
3091 procadjslot_list[i].prev = &procadjslot_list[i];
3092 }
3093
Suren Baghdasaryana7394ea2018-10-12 11:07:40 -07003094 memset(killcnt_idx, KILLCNT_INVALID_IDX, sizeof(killcnt_idx));
3095
Suren Baghdasaryan03cb8362019-07-15 13:35:04 -07003096 /*
3097 * Read zoneinfo as the biggest file we read to create and size the initial
3098 * read buffer and avoid memory re-allocations during memory pressure
3099 */
3100 if (reread_file(&file_data) == NULL) {
3101 ALOGE("Failed to read %s: %s", file_data.filename, strerror(errno));
3102 }
3103
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003104 /* check if kernel supports pidfd_open syscall */
3105 pidfd = TEMP_FAILURE_RETRY(sys_pidfd_open(getpid(), 0));
3106 if (pidfd < 0) {
3107 pidfd_supported = (errno != ENOSYS);
3108 } else {
3109 pidfd_supported = true;
3110 close(pidfd);
3111 }
3112 ALOGI("Process polling is %s", pidfd_supported ? "supported" : "not supported" );
3113
Todd Poynorc58c5142013-07-09 19:35:14 -07003114 return 0;
3115}
3116
Suren Baghdasaryan03dccf32020-04-28 16:02:13 -07003117static bool polling_paused(struct polling_params *poll_params) {
3118 return poll_params->paused_handler != NULL;
3119}
3120
3121static void resume_polling(struct polling_params *poll_params, struct timespec curr_tm) {
3122 poll_params->poll_start_tm = curr_tm;
3123 poll_params->poll_handler = poll_params->paused_handler;
Martin Liu589b5752020-09-02 23:15:18 +08003124 poll_params->polling_interval_ms = PSI_POLL_PERIOD_SHORT_MS;
3125 poll_params->paused_handler = NULL;
Suren Baghdasaryan03dccf32020-04-28 16:02:13 -07003126}
3127
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003128static void call_handler(struct event_handler_info* handler_info,
3129 struct polling_params *poll_params, uint32_t events) {
3130 struct timespec curr_tm;
3131
Suren Baghdasaryan9ca53342020-04-24 16:54:55 -07003132 poll_params->update = POLLING_DO_NOT_CHANGE;
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003133 handler_info->handler(handler_info->data, events, poll_params);
3134 clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm);
Suren Baghdasaryan9ca53342020-04-24 16:54:55 -07003135 if (poll_params->poll_handler == handler_info) {
3136 poll_params->last_poll_tm = curr_tm;
3137 }
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003138
3139 switch (poll_params->update) {
3140 case POLLING_START:
3141 /*
3142 * Poll for the duration of PSI_WINDOW_SIZE_MS after the
3143 * initial PSI event because psi events are rate-limited
3144 * at one per sec.
3145 */
3146 poll_params->poll_start_tm = curr_tm;
Greg Kaiser5e80ed52019-10-10 06:52:23 -07003147 poll_params->poll_handler = handler_info;
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003148 break;
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003149 case POLLING_PAUSE:
3150 poll_params->paused_handler = handler_info;
3151 poll_params->poll_handler = NULL;
3152 break;
3153 case POLLING_RESUME:
Suren Baghdasaryan03dccf32020-04-28 16:02:13 -07003154 resume_polling(poll_params, curr_tm);
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003155 break;
3156 case POLLING_DO_NOT_CHANGE:
3157 if (get_time_diff_ms(&poll_params->poll_start_tm, &curr_tm) > PSI_WINDOW_SIZE_MS) {
3158 /* Polled for the duration of PSI window, time to stop */
3159 poll_params->poll_handler = NULL;
3160 }
Suren Baghdasaryan9ca53342020-04-24 16:54:55 -07003161 break;
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003162 }
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003163}
3164
Todd Poynorc58c5142013-07-09 19:35:14 -07003165static void mainloop(void) {
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003166 struct event_handler_info* handler_info;
Suren Baghdasaryane12a0672019-07-15 14:50:49 -07003167 struct polling_params poll_params;
3168 struct timespec curr_tm;
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003169 struct epoll_event *evt;
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08003170 long delay = -1;
Suren Baghdasaryane12a0672019-07-15 14:50:49 -07003171
3172 poll_params.poll_handler = NULL;
Suren Baghdasaryan9ca53342020-04-24 16:54:55 -07003173 poll_params.paused_handler = NULL;
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003174
Todd Poynorc58c5142013-07-09 19:35:14 -07003175 while (1) {
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07003176 struct epoll_event events[MAX_EPOLL_EVENTS];
Todd Poynorc58c5142013-07-09 19:35:14 -07003177 int nevents;
3178 int i;
3179
Suren Baghdasaryane12a0672019-07-15 14:50:49 -07003180 if (poll_params.poll_handler) {
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003181 bool poll_now;
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08003182
3183 clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm);
Martin Liu589b5752020-09-02 23:15:18 +08003184 if (poll_params.update == POLLING_RESUME) {
3185 /* Just transitioned into POLLING_RESUME, poll immediately. */
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003186 poll_now = true;
3187 nevents = 0;
3188 } else {
3189 /* Calculate next timeout */
3190 delay = get_time_diff_ms(&poll_params.last_poll_tm, &curr_tm);
3191 delay = (delay < poll_params.polling_interval_ms) ?
3192 poll_params.polling_interval_ms - delay : poll_params.polling_interval_ms;
Suren Baghdasaryane12a0672019-07-15 14:50:49 -07003193
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003194 /* Wait for events until the next polling timeout */
3195 nevents = epoll_wait(epollfd, events, maxevents, delay);
3196
3197 /* Update current time after wait */
3198 clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm);
3199 poll_now = (get_time_diff_ms(&poll_params.last_poll_tm, &curr_tm) >=
3200 poll_params.polling_interval_ms);
3201 }
3202 if (poll_now) {
3203 call_handler(poll_params.poll_handler, &poll_params, 0);
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08003204 }
3205 } else {
Suren Baghdasaryan03dccf32020-04-28 16:02:13 -07003206 if (kill_timeout_ms && is_waiting_for_kill()) {
3207 clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm);
3208 delay = kill_timeout_ms - get_time_diff_ms(&last_kill_tm, &curr_tm);
3209 /* Wait for pidfds notification or kill timeout to expire */
3210 nevents = (delay > 0) ? epoll_wait(epollfd, events, maxevents, delay) : 0;
3211 if (nevents == 0) {
3212 /* Kill notification timed out */
3213 stop_wait_for_proc_kill(false);
3214 if (polling_paused(&poll_params)) {
3215 clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm);
Martin Liu589b5752020-09-02 23:15:18 +08003216 poll_params.update = POLLING_RESUME;
Suren Baghdasaryan03dccf32020-04-28 16:02:13 -07003217 resume_polling(&poll_params, curr_tm);
3218 }
3219 }
3220 } else {
3221 /* Wait for events with no timeout */
3222 nevents = epoll_wait(epollfd, events, maxevents, -1);
3223 }
Suren Baghdasaryan55e31502019-01-08 12:54:48 -08003224 }
Todd Poynorc58c5142013-07-09 19:35:14 -07003225
3226 if (nevents == -1) {
3227 if (errno == EINTR)
3228 continue;
3229 ALOGE("epoll_wait failed (errno=%d)", errno);
3230 continue;
3231 }
3232
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003233 /*
3234 * First pass to see if any data socket connections were dropped.
3235 * Dropped connection should be handled before any other events
3236 * to deallocate data connection and correctly handle cases when
3237 * connection gets dropped and reestablished in the same epoll cycle.
3238 * In such cases it's essential to handle connection closures first.
3239 */
3240 for (i = 0, evt = &events[0]; i < nevents; ++i, evt++) {
3241 if ((evt->events & EPOLLHUP) && evt->data.ptr) {
3242 ALOGI("lmkd data connection dropped");
3243 handler_info = (struct event_handler_info*)evt->data.ptr;
3244 ctrl_data_close(handler_info->data);
3245 }
3246 }
3247
3248 /* Second pass to handle all other events */
3249 for (i = 0, evt = &events[0]; i < nevents; ++i, evt++) {
Suren Baghdasaryane12a0672019-07-15 14:50:49 -07003250 if (evt->events & EPOLLERR) {
Todd Poynorc58c5142013-07-09 19:35:14 -07003251 ALOGD("EPOLLERR on event #%d", i);
Suren Baghdasaryane12a0672019-07-15 14:50:49 -07003252 }
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003253 if (evt->events & EPOLLHUP) {
3254 /* This case was handled in the first pass */
3255 continue;
3256 }
3257 if (evt->data.ptr) {
3258 handler_info = (struct event_handler_info*)evt->data.ptr;
Suren Baghdasaryanbc99e1b2019-06-26 17:56:01 -07003259 call_handler(handler_info, &poll_params, evt->events);
Suren Baghdasaryanef8e7012018-01-26 12:51:19 -08003260 }
Todd Poynorc58c5142013-07-09 19:35:14 -07003261 }
3262 }
3263}
3264
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07003265int issue_reinit() {
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07003266 int sock;
Colin Crossd5b510e2014-07-14 14:31:15 -07003267
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07003268 sock = lmkd_connect();
3269 if (sock < 0) {
3270 ALOGE("failed to connect to lmkd: %s", strerror(errno));
3271 return -1;
3272 }
3273
3274 enum update_props_result res = lmkd_update_props(sock);
3275 switch (res) {
3276 case UPDATE_PROPS_SUCCESS:
3277 ALOGI("lmkd updated properties successfully");
3278 break;
3279 case UPDATE_PROPS_SEND_ERR:
3280 ALOGE("failed to send lmkd request: %s", strerror(errno));
3281 break;
3282 case UPDATE_PROPS_RECV_ERR:
3283 ALOGE("failed to receive lmkd reply: %s", strerror(errno));
3284 break;
3285 case UPDATE_PROPS_FORMAT_ERR:
3286 ALOGE("lmkd reply is invalid");
3287 break;
3288 case UPDATE_PROPS_FAIL:
3289 ALOGE("lmkd failed to update its properties");
3290 break;
3291 }
3292
3293 close(sock);
3294 return res == UPDATE_PROPS_SUCCESS ? 0 : -1;
3295}
3296
3297static void update_props() {
Suren Baghdasaryanb2e00602017-12-08 12:58:52 -08003298 /* By default disable low level vmpressure events */
3299 level_oomadj[VMPRESS_LEVEL_LOW] =
3300 property_get_int32("ro.lmk.low", OOM_SCORE_ADJ_MAX + 1);
3301 level_oomadj[VMPRESS_LEVEL_MEDIUM] =
3302 property_get_int32("ro.lmk.medium", 800);
3303 level_oomadj[VMPRESS_LEVEL_CRITICAL] =
3304 property_get_int32("ro.lmk.critical", 0);
Robert Benea7f68a3f2017-08-11 16:03:20 -07003305 debug_process_killing = property_get_bool("ro.lmk.debug", false);
Suren Baghdasaryan3faa3032017-12-08 13:08:41 -08003306
3307 /* By default disable upgrade/downgrade logic */
3308 enable_pressure_upgrade =
3309 property_get_bool("ro.lmk.critical_upgrade", false);
3310 upgrade_pressure =
3311 (int64_t)property_get_int32("ro.lmk.upgrade_pressure", 100);
3312 downgrade_pressure =
3313 (int64_t)property_get_int32("ro.lmk.downgrade_pressure", 100);
Suren Baghdasaryaneb7c5492017-12-08 13:17:06 -08003314 kill_heaviest_task =
Suren Baghdasaryan36b2c492018-04-13 11:49:54 -07003315 property_get_bool("ro.lmk.kill_heaviest_task", false);
Suren Baghdasaryand1d59f82018-04-13 11:45:38 -07003316 low_ram_device = property_get_bool("ro.config.low_ram", false);
Suren Baghdasaryan30854e72018-01-17 17:28:01 -08003317 kill_timeout_ms =
Suren Baghdasaryan7d1f4f02020-07-08 11:40:10 -07003318 (unsigned long)property_get_int32("ro.lmk.kill_timeout_ms", 100);
Suren Baghdasaryan2c4611a2018-04-13 13:53:43 -07003319 use_minfree_levels =
3320 property_get_bool("ro.lmk.use_minfree_levels", false);
Suren Baghdasaryan8389fdb2018-06-19 18:38:12 -07003321 per_app_memcg =
3322 property_get_bool("ro.config.per_app_memcg", low_ram_device);
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07003323 swap_free_low_percentage = clamp(0, 100, property_get_int32("ro.lmk.swap_free_low_percentage",
Suren Baghdasaryanfb1f5922020-05-19 13:07:23 -07003324 DEF_LOW_SWAP));
Suren Baghdasaryan2f88e152019-07-15 15:42:09 -07003325 psi_partial_stall_ms = property_get_int32("ro.lmk.psi_partial_stall_ms",
3326 low_ram_device ? DEF_PARTIAL_STALL_LOWRAM : DEF_PARTIAL_STALL);
3327 psi_complete_stall_ms = property_get_int32("ro.lmk.psi_complete_stall_ms",
3328 DEF_COMPLETE_STALL);
Suren Baghdasaryanaf2be4c2019-07-15 15:35:44 -07003329 thrashing_limit_pct = max(0, property_get_int32("ro.lmk.thrashing_limit",
3330 low_ram_device ? DEF_THRASHING_LOWRAM : DEF_THRASHING));
3331 thrashing_limit_decay_pct = clamp(0, 100, property_get_int32("ro.lmk.thrashing_limit_decay",
3332 low_ram_device ? DEF_THRASHING_DECAY_LOWRAM : DEF_THRASHING_DECAY));
Suren Baghdasaryan51ee4c52020-04-21 12:27:01 -07003333 swap_util_max = clamp(0, 100, property_get_int32("ro.lmk.swap_util_max", 100));
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07003334}
3335
3336int main(int argc, char **argv) {
3337 if ((argc > 1) && argv[1] && !strcmp(argv[1], "--reinit")) {
3338 if (property_set(LMKD_REINIT_PROP, "0")) {
3339 ALOGE("Failed to reset " LMKD_REINIT_PROP " property");
3340 }
3341 return issue_reinit();
3342 }
3343
3344 update_props();
Robert Benea57397dc2017-07-31 17:15:20 -07003345
Suren Baghdasaryan12cacae2019-09-16 12:06:30 -07003346 ctx = create_android_logger(KILLINFO_LOG_TAG);
Suren Baghdasaryan08bfa982018-07-26 16:34:27 -07003347
Mark Salyzyn5cc80b32018-03-21 12:24:58 -07003348 if (!init()) {
3349 if (!use_inkernel_interface) {
3350 /*
3351 * MCL_ONFAULT pins pages as they fault instead of loading
3352 * everything immediately all at once. (Which would be bad,
3353 * because as of this writing, we have a lot of mapped pages we
3354 * never use.) Old kernels will see MCL_ONFAULT and fail with
3355 * EINVAL; we ignore this failure.
3356 *
3357 * N.B. read the man page for mlockall. MCL_CURRENT | MCL_ONFAULT
3358 * pins ⊆ MCL_CURRENT, converging to just MCL_CURRENT as we fault
3359 * in pages.
3360 */
Mark Salyzyna00ccd82018-04-09 09:50:32 -07003361 /* CAP_IPC_LOCK required */
Mark Salyzyn5cc80b32018-03-21 12:24:58 -07003362 if (mlockall(MCL_CURRENT | MCL_FUTURE | MCL_ONFAULT) && (errno != EINVAL)) {
3363 ALOGW("mlockall failed %s", strerror(errno));
3364 }
Daniel Colascione46648332018-01-03 12:01:02 -08003365
Mark Salyzyna00ccd82018-04-09 09:50:32 -07003366 /* CAP_NICE required */
Suren Baghdasaryan1d0ebea2020-04-28 15:52:29 -07003367 struct sched_param param = {
3368 .sched_priority = 1,
3369 };
Mark Salyzyna00ccd82018-04-09 09:50:32 -07003370 if (sched_setscheduler(0, SCHED_FIFO, &param)) {
3371 ALOGW("set SCHED_FIFO failed %s", strerror(errno));
3372 }
Mark Salyzyn5cc80b32018-03-21 12:24:58 -07003373 }
3374
Todd Poynorc58c5142013-07-09 19:35:14 -07003375 mainloop();
Mark Salyzyn5cc80b32018-03-21 12:24:58 -07003376 }
Todd Poynorc58c5142013-07-09 19:35:14 -07003377
Suren Baghdasaryan08bfa982018-07-26 16:34:27 -07003378 android_log_destroy(&ctx);
3379
Todd Poynorc58c5142013-07-09 19:35:14 -07003380 ALOGI("exiting");
3381 return 0;
3382}