blob: 4352498065d8260a7389a9574a39a4ef68c2e92b [file] [log] [blame]
Todd Poynor3948f802013-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 Wang2d95c102018-11-21 00:11:44 -080019#include <dirent.h>
Todd Poynor3948f802013-07-09 19:35:14 -070020#include <errno.h>
Robert Beneac47f2992017-08-21 15:18:31 -070021#include <inttypes.h>
Suren Baghdasaryan4311d1e2018-03-20 16:03:29 -070022#include <pwd.h>
Mark Salyzyncfd5b082016-10-17 14:28:00 -070023#include <sched.h>
Todd Poynor3948f802013-07-09 19:35:14 -070024#include <signal.h>
Suren Baghdasaryan1ffa2462018-03-20 13:53:17 -070025#include <stdbool.h>
Todd Poynor3948f802013-07-09 19:35:14 -070026#include <stdlib.h>
27#include <string.h>
Mark Salyzyne6ed68b2014-04-30 13:36:35 -070028#include <sys/cdefs.h>
Todd Poynor3948f802013-07-09 19:35:14 -070029#include <sys/epoll.h>
30#include <sys/eventfd.h>
Colin Crossb28ff912014-07-11 17:15:44 -070031#include <sys/mman.h>
Wei Wang2d95c102018-11-21 00:11:44 -080032#include <sys/resource.h>
Todd Poynor3948f802013-07-09 19:35:14 -070033#include <sys/socket.h>
Suren Baghdasaryanf2081a92019-06-26 17:56:01 -070034#include <sys/syscall.h>
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -080035#include <sys/sysinfo.h>
Wei Wang2d95c102018-11-21 00:11:44 -080036#include <sys/time.h>
Mark Salyzyn721d7c72018-03-21 12:24:58 -070037#include <sys/types.h>
Suren Baghdasaryan314a5052018-07-24 17:13:06 -070038#include <time.h>
Mark Salyzyne6ed68b2014-04-30 13:36:35 -070039#include <unistd.h>
40
Robert Benea58891d52017-07-31 17:15:20 -070041#include <cutils/properties.h>
Wei Wang2d95c102018-11-21 00:11:44 -080042#include <cutils/sched_policy.h>
Todd Poynor3948f802013-07-09 19:35:14 -070043#include <cutils/sockets.h>
Suren Baghdasaryan0f100512018-01-24 16:51:41 -080044#include <lmkd.h>
Mark Salyzyn30f991f2017-01-10 13:19:54 -080045#include <log/log.h>
Suren Baghdasaryan282ad1a2018-07-26 16:34:27 -070046#include <log/log_event_list.h>
Suren Baghdasaryan314a5052018-07-24 17:13:06 -070047#include <log/log_time.h>
Suren Baghdasaryan12ab1872019-10-18 11:16:52 -070048#include <private/android_filesystem_config.h>
Suren Baghdasaryan77122e52019-01-08 12:54:48 -080049#include <psi/psi.h>
Wei Wang2d95c102018-11-21 00:11:44 -080050#include <system/thread_defs.h>
Mark Salyzyne6ed68b2014-04-30 13:36:35 -070051
Yao Chen389aee12018-05-02 11:19:27 -070052#include "statslog.h"
Rajeev Kumar70450032018-01-31 17:54:56 -080053
Suren Baghdasaryanc7135592018-01-04 10:43:58 -080054/*
55 * Define LMKD_TRACE_KILLS to record lmkd kills in kernel traces
56 * to profile and correlate with OOM kills
57 */
58#ifdef LMKD_TRACE_KILLS
59
60#define ATRACE_TAG ATRACE_TAG_ALWAYS
61#include <cutils/trace.h>
62
63#define TRACE_KILL_START(pid) ATRACE_INT(__FUNCTION__, pid);
64#define TRACE_KILL_END() ATRACE_INT(__FUNCTION__, 0);
65
66#else /* LMKD_TRACE_KILLS */
67
Daniel Colascione347f6b42018-02-12 11:24:47 -080068#define TRACE_KILL_START(pid) ((void)(pid))
69#define TRACE_KILL_END() ((void)0)
Suren Baghdasaryanc7135592018-01-04 10:43:58 -080070
71#endif /* LMKD_TRACE_KILLS */
72
Mark Salyzyne6ed68b2014-04-30 13:36:35 -070073#ifndef __unused
74#define __unused __attribute__((__unused__))
75#endif
Todd Poynor3948f802013-07-09 19:35:14 -070076
77#define MEMCG_SYSFS_PATH "/dev/memcg/"
Robert Beneac47f2992017-08-21 15:18:31 -070078#define MEMCG_MEMORY_USAGE "/dev/memcg/memory.usage_in_bytes"
79#define MEMCG_MEMORYSW_USAGE "/dev/memcg/memory.memsw.usage_in_bytes"
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -070080#define ZONEINFO_PATH "/proc/zoneinfo"
81#define MEMINFO_PATH "/proc/meminfo"
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -070082#define VMSTAT_PATH "/proc/vmstat"
Suren Baghdasaryan0082ef12019-07-02 15:52:07 -070083#define PROC_STATUS_TGID_FIELD "Tgid:"
Todd Poynor3948f802013-07-09 19:35:14 -070084#define LINE_MAX 128
85
Suren Baghdasaryan4b750882019-09-19 15:27:21 -070086#define PERCEPTIBLE_APP_ADJ 200
87
Suren Baghdasaryan282ad1a2018-07-26 16:34:27 -070088/* Android Logger event logtags (see event.logtags) */
Suren Baghdasaryana7ac5782019-09-16 12:06:30 -070089#define KILLINFO_LOG_TAG 10195355
Suren Baghdasaryan282ad1a2018-07-26 16:34:27 -070090
Mark Salyzyn64d97d82018-04-09 09:50:32 -070091/* gid containing AID_SYSTEM required */
Todd Poynor3948f802013-07-09 19:35:14 -070092#define INKERNEL_MINFREE_PATH "/sys/module/lowmemorykiller/parameters/minfree"
93#define INKERNEL_ADJ_PATH "/sys/module/lowmemorykiller/parameters/adj"
94
95#define ARRAY_SIZE(x) (sizeof(x) / sizeof(*(x)))
Robert Benea673e2762017-06-01 16:32:31 -070096#define EIGHT_MEGA (1 << 23)
Todd Poynor3948f802013-07-09 19:35:14 -070097
Suren Baghdasaryan314a5052018-07-24 17:13:06 -070098#define TARGET_UPDATE_MIN_INTERVAL_MS 1000
99
100#define NS_PER_MS (NS_PER_SEC / MS_PER_SEC)
Suren Baghdasaryan77122e52019-01-08 12:54:48 -0800101#define US_PER_MS (US_PER_SEC / MS_PER_SEC)
Suren Baghdasaryan314a5052018-07-24 17:13:06 -0700102
Suren Baghdasaryan4311d1e2018-03-20 16:03:29 -0700103/* Defined as ProcessList.SYSTEM_ADJ in ProcessList.java */
104#define SYSTEM_ADJ (-900)
105
Greg Kaiserf0da9b02018-03-23 14:16:12 -0700106#define STRINGIFY(x) STRINGIFY_INTERNAL(x)
107#define STRINGIFY_INTERNAL(x) #x
108
Suren Baghdasaryan77122e52019-01-08 12:54:48 -0800109/*
110 * PSI monitor tracking window size.
111 * PSI monitor generates events at most once per window,
112 * therefore we poll memory state for the duration of
113 * PSI_WINDOW_SIZE_MS after the event happens.
114 */
115#define PSI_WINDOW_SIZE_MS 1000
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -0700116/* Polling period after PSI signal when pressure is high */
117#define PSI_POLL_PERIOD_SHORT_MS 10
118/* Polling period after PSI signal when pressure is low */
119#define PSI_POLL_PERIOD_LONG_MS 100
Suren Baghdasaryan77122e52019-01-08 12:54:48 -0800120
Suren Baghdasaryan282ad1a2018-07-26 16:34:27 -0700121#define min(a, b) (((a) < (b)) ? (a) : (b))
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -0700122#define max(a, b) (((a) > (b)) ? (a) : (b))
Suren Baghdasaryan282ad1a2018-07-26 16:34:27 -0700123
Suren Baghdasaryan36934412018-09-05 15:46:32 -0700124#define FAIL_REPORT_RLIMIT_MS 1000
125
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -0700126/*
127 * System property defaults
128 */
129/* ro.lmk.swap_free_low_percentage property defaults */
130#define DEF_LOW_SWAP_LOWRAM 10
131#define DEF_LOW_SWAP 20
132/* ro.lmk.thrashing_limit property defaults */
133#define DEF_THRASHING_LOWRAM 30
134#define DEF_THRASHING 100
135/* ro.lmk.thrashing_limit_decay property defaults */
136#define DEF_THRASHING_DECAY_LOWRAM 50
137#define DEF_THRASHING_DECAY 10
Suren Baghdasaryan844f26b2019-07-15 15:42:09 -0700138/* ro.lmk.psi_partial_stall_ms property defaults */
139#define DEF_PARTIAL_STALL_LOWRAM 200
140#define DEF_PARTIAL_STALL 70
141/* ro.lmk.psi_complete_stall_ms property defaults */
142#define DEF_COMPLETE_STALL 700
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -0700143
Suren Baghdasaryanf2081a92019-06-26 17:56:01 -0700144static inline int sys_pidfd_open(pid_t pid, unsigned int flags) {
145 return syscall(__NR_pidfd_open, pid, flags);
146}
147
Suren Baghdasaryan11dc7342019-07-19 10:55:39 -0700148static inline int sys_pidfd_send_signal(int pidfd, int sig, siginfo_t *info,
149 unsigned int flags) {
150 return syscall(__NR_pidfd_send_signal, pidfd, sig, info, flags);
151}
152
Todd Poynor3948f802013-07-09 19:35:14 -0700153/* default to old in-kernel interface if no memory pressure events */
Mark Salyzyn721d7c72018-03-21 12:24:58 -0700154static bool use_inkernel_interface = true;
Robert Benea164baeb2017-09-11 16:53:28 -0700155static bool has_inkernel_module;
Todd Poynor3948f802013-07-09 19:35:14 -0700156
Suren Baghdasaryan96bf3a62017-12-08 12:58:52 -0800157/* memory pressure levels */
158enum vmpressure_level {
159 VMPRESS_LEVEL_LOW = 0,
160 VMPRESS_LEVEL_MEDIUM,
161 VMPRESS_LEVEL_CRITICAL,
162 VMPRESS_LEVEL_COUNT
163};
Todd Poynor3948f802013-07-09 19:35:14 -0700164
Suren Baghdasaryan96bf3a62017-12-08 12:58:52 -0800165static const char *level_name[] = {
166 "low",
167 "medium",
168 "critical"
169};
170
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -0800171struct {
Suren Baghdasaryan9926e572018-04-13 13:41:12 -0700172 int64_t min_nr_free_pages; /* recorded but not used yet */
173 int64_t max_nr_free_pages;
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -0800174} low_pressure_mem = { -1, -1 };
175
Suren Baghdasaryan77122e52019-01-08 12:54:48 -0800176struct psi_threshold {
177 enum psi_stall_type stall_type;
178 int threshold_ms;
179};
180
Suren Baghdasaryan96bf3a62017-12-08 12:58:52 -0800181static int level_oomadj[VMPRESS_LEVEL_COUNT];
Suren Baghdasaryane82e15c2018-01-04 09:16:21 -0800182static int mpevfd[VMPRESS_LEVEL_COUNT] = { -1, -1, -1 };
Suren Baghdasaryanf2081a92019-06-26 17:56:01 -0700183static bool pidfd_supported;
184static int last_kill_pid_or_fd = -1;
185static struct timespec last_kill_tm;
186
187/* lmkd configurable parameters */
Robert Beneac47f2992017-08-21 15:18:31 -0700188static bool debug_process_killing;
189static bool enable_pressure_upgrade;
190static int64_t upgrade_pressure;
Robert Benea6e8e7102017-09-13 15:20:30 -0700191static int64_t downgrade_pressure;
Suren Baghdasaryanff61afb2018-04-13 11:45:38 -0700192static bool low_ram_device;
Suren Baghdasaryan662492a2017-12-08 13:17:06 -0800193static bool kill_heaviest_task;
Suren Baghdasaryancaa2dc52018-01-17 17:28:01 -0800194static unsigned long kill_timeout_ms;
Suren Baghdasaryanffdc4dd2018-04-13 13:53:43 -0700195static bool use_minfree_levels;
Suren Baghdasaryance13cb52018-06-19 18:38:12 -0700196static bool per_app_memcg;
Vic Yang360a1132018-08-07 10:18:22 -0700197static int swap_free_low_percentage;
Suren Baghdasaryan844f26b2019-07-15 15:42:09 -0700198static int psi_partial_stall_ms;
199static int psi_complete_stall_ms;
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -0700200static int thrashing_limit_pct;
201static int thrashing_limit_decay_pct;
Suren Baghdasaryan77122e52019-01-08 12:54:48 -0800202static bool use_psi_monitors = false;
Suren Baghdasaryanb72c6652019-09-04 19:12:29 -0700203static struct kernel_poll_info kpoll_info;
Suren Baghdasaryan77122e52019-01-08 12:54:48 -0800204static struct psi_threshold psi_thresholds[VMPRESS_LEVEL_COUNT] = {
205 { PSI_SOME, 70 }, /* 70ms out of 1sec for partial stall */
206 { PSI_SOME, 100 }, /* 100ms out of 1sec for partial stall */
207 { PSI_FULL, 70 }, /* 70ms out of 1sec for complete stall */
208};
Robert Benea58891d52017-07-31 17:15:20 -0700209
Suren Baghdasaryan282ad1a2018-07-26 16:34:27 -0700210static android_log_context ctx;
211
Suren Baghdasaryanef3650f2019-07-15 14:50:49 -0700212enum polling_update {
213 POLLING_DO_NOT_CHANGE,
214 POLLING_START,
215 POLLING_STOP,
Suren Baghdasaryanf2081a92019-06-26 17:56:01 -0700216 POLLING_PAUSE,
217 POLLING_RESUME,
Suren Baghdasaryanef3650f2019-07-15 14:50:49 -0700218};
219
220/*
221 * Data used for periodic polling for the memory state of the device.
222 * Note that when system is not polling poll_handler is set to NULL,
223 * when polling starts poll_handler gets set and is reset back to
224 * NULL when polling stops.
225 */
226struct polling_params {
227 struct event_handler_info* poll_handler;
Suren Baghdasaryanf2081a92019-06-26 17:56:01 -0700228 struct event_handler_info* paused_handler;
Suren Baghdasaryanef3650f2019-07-15 14:50:49 -0700229 struct timespec poll_start_tm;
230 struct timespec last_poll_tm;
231 int polling_interval_ms;
232 enum polling_update update;
233};
234
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -0800235/* data required to handle events */
236struct event_handler_info {
237 int data;
Suren Baghdasaryanef3650f2019-07-15 14:50:49 -0700238 void (*handler)(int data, uint32_t events, struct polling_params *poll_params);
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -0800239};
Todd Poynor3948f802013-07-09 19:35:14 -0700240
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -0800241/* data required to handle socket events */
242struct sock_event_handler_info {
243 int sock;
Suren Baghdasaryan12ab1872019-10-18 11:16:52 -0700244 pid_t pid;
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -0800245 struct event_handler_info handler_info;
246};
247
Suren Baghdasaryanadb54f82019-10-21 17:59:22 -0700248/* max supported number of data connections (AMS, init, tests) */
249#define MAX_DATA_CONN 3
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -0800250
251/* socket event handler data */
252static struct sock_event_handler_info ctrl_sock;
253static struct sock_event_handler_info data_sock[MAX_DATA_CONN];
254
255/* vmpressure event handler data */
256static struct event_handler_info vmpressure_hinfo[VMPRESS_LEVEL_COUNT];
257
Suren Baghdasaryanf2081a92019-06-26 17:56:01 -0700258/*
Suren Baghdasaryanadb54f82019-10-21 17:59:22 -0700259 * 1 ctrl listen socket, 3 ctrl data socket, 3 memory pressure levels,
Suren Baghdasaryanf2081a92019-06-26 17:56:01 -0700260 * 1 lmk events + 1 fd to wait for process death
261 */
262#define MAX_EPOLL_EVENTS (1 + MAX_DATA_CONN + VMPRESS_LEVEL_COUNT + 1 + 1)
Todd Poynor3948f802013-07-09 19:35:14 -0700263static int epollfd;
264static int maxevents;
265
Chong Zhang0a4acdf2015-10-14 16:19:53 -0700266/* OOM score values used by both kernel and framework */
Todd Poynor16b60992013-09-16 19:26:47 -0700267#define OOM_SCORE_ADJ_MIN (-1000)
268#define OOM_SCORE_ADJ_MAX 1000
269
Todd Poynor3948f802013-07-09 19:35:14 -0700270static int lowmem_adj[MAX_TARGETS];
271static int lowmem_minfree[MAX_TARGETS];
272static int lowmem_targets_size;
273
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -0700274/* Fields to parse in /proc/zoneinfo */
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -0700275/* zoneinfo per-zone fields */
276enum zoneinfo_zone_field {
277 ZI_ZONE_NR_FREE_PAGES = 0,
278 ZI_ZONE_MIN,
279 ZI_ZONE_LOW,
280 ZI_ZONE_HIGH,
281 ZI_ZONE_PRESENT,
282 ZI_ZONE_NR_FREE_CMA,
283 ZI_ZONE_FIELD_COUNT
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -0700284};
285
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -0700286static const char* const zoneinfo_zone_field_names[ZI_ZONE_FIELD_COUNT] = {
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -0700287 "nr_free_pages",
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -0700288 "min",
289 "low",
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -0700290 "high",
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -0700291 "present",
292 "nr_free_cma",
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -0700293};
294
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -0700295/* zoneinfo per-zone special fields */
296enum zoneinfo_zone_spec_field {
297 ZI_ZONE_SPEC_PROTECTION = 0,
298 ZI_ZONE_SPEC_PAGESETS,
299 ZI_ZONE_SPEC_FIELD_COUNT,
300};
301
302static const char* const zoneinfo_zone_spec_field_names[ZI_ZONE_SPEC_FIELD_COUNT] = {
303 "protection:",
304 "pagesets",
305};
306
307/* see __MAX_NR_ZONES definition in kernel mmzone.h */
308#define MAX_NR_ZONES 6
309
310union zoneinfo_zone_fields {
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -0700311 struct {
312 int64_t nr_free_pages;
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -0700313 int64_t min;
314 int64_t low;
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -0700315 int64_t high;
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -0700316 int64_t present;
317 int64_t nr_free_cma;
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -0700318 } field;
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -0700319 int64_t arr[ZI_ZONE_FIELD_COUNT];
320};
321
322struct zoneinfo_zone {
323 union zoneinfo_zone_fields fields;
324 int64_t protection[MAX_NR_ZONES];
325 int64_t max_protection;
326};
327
328/* zoneinfo per-node fields */
329enum zoneinfo_node_field {
330 ZI_NODE_NR_INACTIVE_FILE = 0,
331 ZI_NODE_NR_ACTIVE_FILE,
332 ZI_NODE_WORKINGSET_REFAULT,
333 ZI_NODE_FIELD_COUNT
334};
335
336static const char* const zoneinfo_node_field_names[ZI_NODE_FIELD_COUNT] = {
337 "nr_inactive_file",
338 "nr_active_file",
339 "workingset_refault",
340};
341
342union zoneinfo_node_fields {
343 struct {
344 int64_t nr_inactive_file;
345 int64_t nr_active_file;
346 int64_t workingset_refault;
347 } field;
348 int64_t arr[ZI_NODE_FIELD_COUNT];
349};
350
351struct zoneinfo_node {
352 int id;
353 int zone_count;
354 struct zoneinfo_zone zones[MAX_NR_ZONES];
355 union zoneinfo_node_fields fields;
356};
357
358/* for now two memory nodes is more than enough */
359#define MAX_NR_NODES 2
360
361struct zoneinfo {
362 int node_count;
363 struct zoneinfo_node nodes[MAX_NR_NODES];
364 int64_t totalreserve_pages;
365 int64_t total_inactive_file;
366 int64_t total_active_file;
367 int64_t total_workingset_refault;
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -0700368};
369
370/* Fields to parse in /proc/meminfo */
371enum meminfo_field {
372 MI_NR_FREE_PAGES = 0,
373 MI_CACHED,
374 MI_SWAP_CACHED,
375 MI_BUFFERS,
376 MI_SHMEM,
377 MI_UNEVICTABLE,
Vic Yang360a1132018-08-07 10:18:22 -0700378 MI_TOTAL_SWAP,
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -0700379 MI_FREE_SWAP,
Suren Baghdasaryan282ad1a2018-07-26 16:34:27 -0700380 MI_ACTIVE_ANON,
381 MI_INACTIVE_ANON,
382 MI_ACTIVE_FILE,
383 MI_INACTIVE_FILE,
384 MI_SRECLAIMABLE,
385 MI_SUNRECLAIM,
386 MI_KERNEL_STACK,
387 MI_PAGE_TABLES,
388 MI_ION_HELP,
389 MI_ION_HELP_POOL,
390 MI_CMA_FREE,
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -0700391 MI_FIELD_COUNT
392};
393
394static const char* const meminfo_field_names[MI_FIELD_COUNT] = {
395 "MemFree:",
396 "Cached:",
397 "SwapCached:",
398 "Buffers:",
399 "Shmem:",
400 "Unevictable:",
Vic Yang360a1132018-08-07 10:18:22 -0700401 "SwapTotal:",
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -0700402 "SwapFree:",
Suren Baghdasaryan282ad1a2018-07-26 16:34:27 -0700403 "Active(anon):",
404 "Inactive(anon):",
405 "Active(file):",
406 "Inactive(file):",
407 "SReclaimable:",
408 "SUnreclaim:",
409 "KernelStack:",
410 "PageTables:",
411 "ION_heap:",
412 "ION_heap_pool:",
413 "CmaFree:",
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -0700414};
415
416union meminfo {
417 struct {
418 int64_t nr_free_pages;
419 int64_t cached;
420 int64_t swap_cached;
421 int64_t buffers;
422 int64_t shmem;
423 int64_t unevictable;
Vic Yang360a1132018-08-07 10:18:22 -0700424 int64_t total_swap;
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -0700425 int64_t free_swap;
Suren Baghdasaryan282ad1a2018-07-26 16:34:27 -0700426 int64_t active_anon;
427 int64_t inactive_anon;
428 int64_t active_file;
429 int64_t inactive_file;
430 int64_t sreclaimable;
431 int64_t sunreclaimable;
432 int64_t kernel_stack;
433 int64_t page_tables;
434 int64_t ion_heap;
435 int64_t ion_heap_pool;
436 int64_t cma_free;
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -0700437 /* fields below are calculated rather than read from the file */
438 int64_t nr_file_pages;
439 } field;
440 int64_t arr[MI_FIELD_COUNT];
441};
442
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -0700443/* Fields to parse in /proc/vmstat */
444enum vmstat_field {
445 VS_FREE_PAGES,
446 VS_INACTIVE_FILE,
447 VS_ACTIVE_FILE,
448 VS_WORKINGSET_REFAULT,
449 VS_PGSCAN_KSWAPD,
450 VS_PGSCAN_DIRECT,
451 VS_PGSCAN_DIRECT_THROTTLE,
452 VS_FIELD_COUNT
453};
454
455static const char* const vmstat_field_names[MI_FIELD_COUNT] = {
456 "nr_free_pages",
457 "nr_inactive_file",
458 "nr_active_file",
459 "workingset_refault",
460 "pgscan_kswapd",
461 "pgscan_direct",
462 "pgscan_direct_throttle",
463};
464
465union vmstat {
466 struct {
467 int64_t nr_free_pages;
468 int64_t nr_inactive_file;
469 int64_t nr_active_file;
470 int64_t workingset_refault;
471 int64_t pgscan_kswapd;
472 int64_t pgscan_direct;
473 int64_t pgscan_direct_throttle;
474 } field;
475 int64_t arr[VS_FIELD_COUNT];
476};
477
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -0700478enum field_match_result {
479 NO_MATCH,
480 PARSE_FAIL,
481 PARSE_SUCCESS
482};
483
Todd Poynor3948f802013-07-09 19:35:14 -0700484struct adjslot_list {
485 struct adjslot_list *next;
486 struct adjslot_list *prev;
487};
488
489struct proc {
490 struct adjslot_list asl;
491 int pid;
Suren Baghdasaryan11dc7342019-07-19 10:55:39 -0700492 int pidfd;
Colin Crossfbb78c62014-06-13 14:52:43 -0700493 uid_t uid;
Todd Poynor3948f802013-07-09 19:35:14 -0700494 int oomadj;
Suren Baghdasaryan12ab1872019-10-18 11:16:52 -0700495 pid_t reg_pid; /* PID of the process that registered this record */
Todd Poynor3948f802013-07-09 19:35:14 -0700496 struct proc *pidhash_next;
497};
498
Suren Baghdasaryan6499e5e2018-04-13 12:43:41 -0700499struct reread_data {
500 const char* const filename;
501 int fd;
502};
503
Todd Poynor3948f802013-07-09 19:35:14 -0700504#define PIDHASH_SZ 1024
505static struct proc *pidhash[PIDHASH_SZ];
506#define pid_hashfn(x) ((((x) >> 8) ^ (x)) & (PIDHASH_SZ - 1))
507
Chih-Hung Hsiehdaa13ea2016-05-19 16:02:22 -0700508#define ADJTOSLOT(adj) ((adj) + -OOM_SCORE_ADJ_MIN)
Suren Baghdasaryand4a29902018-10-12 11:07:40 -0700509#define ADJTOSLOT_COUNT (ADJTOSLOT(OOM_SCORE_ADJ_MAX) + 1)
510static struct adjslot_list procadjslot_list[ADJTOSLOT_COUNT];
511
512#define MAX_DISTINCT_OOM_ADJ 32
513#define KILLCNT_INVALID_IDX 0xFF
514/*
515 * Because killcnt array is sparse a two-level indirection is used
516 * to keep the size small. killcnt_idx stores index of the element in
517 * killcnt array. Index KILLCNT_INVALID_IDX indicates an unused slot.
518 */
519static uint8_t killcnt_idx[ADJTOSLOT_COUNT];
520static uint16_t killcnt[MAX_DISTINCT_OOM_ADJ];
521static int killcnt_free_idx = 0;
522static uint32_t killcnt_total = 0;
Todd Poynor3948f802013-07-09 19:35:14 -0700523
Todd Poynor3948f802013-07-09 19:35:14 -0700524/* PAGE_SIZE / 1024 */
525static long page_k;
526
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -0700527static int clamp(int low, int high, int value) {
528 return max(min(value, high), low);
529}
530
Suren Baghdasaryan6499e5e2018-04-13 12:43:41 -0700531static bool parse_int64(const char* str, int64_t* ret) {
532 char* endptr;
533 long long val = strtoll(str, &endptr, 10);
534 if (str == endptr || val > INT64_MAX) {
535 return false;
536 }
537 *ret = (int64_t)val;
538 return true;
539}
540
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -0700541static int find_field(const char* name, const char* const field_names[], int field_count) {
542 for (int i = 0; i < field_count; i++) {
543 if (!strcmp(name, field_names[i])) {
544 return i;
545 }
546 }
547 return -1;
548}
549
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -0700550static enum field_match_result match_field(const char* cp, const char* ap,
551 const char* const field_names[],
552 int field_count, int64_t* field,
553 int *field_idx) {
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -0700554 int i = find_field(cp, field_names, field_count);
555 if (i < 0) {
556 return NO_MATCH;
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -0700557 }
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -0700558 *field_idx = i;
559 return parse_int64(ap, field) ? PARSE_SUCCESS : PARSE_FAIL;
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -0700560}
561
Suren Baghdasaryan6499e5e2018-04-13 12:43:41 -0700562/*
563 * Read file content from the beginning up to max_len bytes or EOF
564 * whichever happens first.
565 */
Colin Crossce85d952014-07-11 17:53:27 -0700566static ssize_t read_all(int fd, char *buf, size_t max_len)
567{
568 ssize_t ret = 0;
Suren Baghdasaryan6499e5e2018-04-13 12:43:41 -0700569 off_t offset = 0;
Colin Crossce85d952014-07-11 17:53:27 -0700570
571 while (max_len > 0) {
Suren Baghdasaryan6499e5e2018-04-13 12:43:41 -0700572 ssize_t r = TEMP_FAILURE_RETRY(pread(fd, buf, max_len, offset));
Colin Crossce85d952014-07-11 17:53:27 -0700573 if (r == 0) {
574 break;
575 }
576 if (r == -1) {
577 return -1;
578 }
579 ret += r;
580 buf += r;
Suren Baghdasaryan6499e5e2018-04-13 12:43:41 -0700581 offset += r;
Colin Crossce85d952014-07-11 17:53:27 -0700582 max_len -= r;
583 }
584
585 return ret;
586}
587
Suren Baghdasaryan6499e5e2018-04-13 12:43:41 -0700588/*
589 * Read a new or already opened file from the beginning.
590 * If the file has not been opened yet data->fd should be set to -1.
591 * To be used with files which are read often and possibly during high
592 * memory pressure to minimize file opening which by itself requires kernel
593 * memory allocation and might result in a stall on memory stressed system.
594 */
Suren Baghdasaryana77b3272019-07-15 13:35:04 -0700595static char *reread_file(struct reread_data *data) {
596 /* start with page-size buffer and increase if needed */
597 static ssize_t buf_size = PAGE_SIZE;
598 static char *new_buf, *buf = NULL;
Suren Baghdasaryan6499e5e2018-04-13 12:43:41 -0700599 ssize_t size;
600
601 if (data->fd == -1) {
Suren Baghdasaryana77b3272019-07-15 13:35:04 -0700602 /* First-time buffer initialization */
603 if (!buf && (buf = malloc(buf_size)) == NULL) {
604 return NULL;
605 }
606
607 data->fd = TEMP_FAILURE_RETRY(open(data->filename, O_RDONLY | O_CLOEXEC));
608 if (data->fd < 0) {
Suren Baghdasaryan6499e5e2018-04-13 12:43:41 -0700609 ALOGE("%s open: %s", data->filename, strerror(errno));
Suren Baghdasaryana77b3272019-07-15 13:35:04 -0700610 return NULL;
Suren Baghdasaryan6499e5e2018-04-13 12:43:41 -0700611 }
612 }
613
Suren Baghdasaryana77b3272019-07-15 13:35:04 -0700614 while (true) {
615 size = read_all(data->fd, buf, buf_size - 1);
616 if (size < 0) {
617 ALOGE("%s read: %s", data->filename, strerror(errno));
618 close(data->fd);
619 data->fd = -1;
620 return NULL;
621 }
622 if (size < buf_size - 1) {
623 break;
624 }
625 /*
626 * Since we are reading /proc files we can't use fstat to find out
627 * the real size of the file. Double the buffer size and keep retrying.
628 */
629 if ((new_buf = realloc(buf, buf_size * 2)) == NULL) {
630 errno = ENOMEM;
631 return NULL;
632 }
633 buf = new_buf;
634 buf_size *= 2;
Suren Baghdasaryan6499e5e2018-04-13 12:43:41 -0700635 }
Suren Baghdasaryan6499e5e2018-04-13 12:43:41 -0700636 buf[size] = 0;
637
Suren Baghdasaryana77b3272019-07-15 13:35:04 -0700638 return buf;
Suren Baghdasaryan6499e5e2018-04-13 12:43:41 -0700639}
640
Todd Poynor3948f802013-07-09 19:35:14 -0700641static struct proc *pid_lookup(int pid) {
642 struct proc *procp;
643
644 for (procp = pidhash[pid_hashfn(pid)]; procp && procp->pid != pid;
645 procp = procp->pidhash_next)
646 ;
647
648 return procp;
649}
650
651static void adjslot_insert(struct adjslot_list *head, struct adjslot_list *new)
652{
653 struct adjslot_list *next = head->next;
654 new->prev = head;
655 new->next = next;
656 next->prev = new;
657 head->next = new;
658}
659
660static void adjslot_remove(struct adjslot_list *old)
661{
662 struct adjslot_list *prev = old->prev;
663 struct adjslot_list *next = old->next;
664 next->prev = prev;
665 prev->next = next;
666}
667
668static struct adjslot_list *adjslot_tail(struct adjslot_list *head) {
669 struct adjslot_list *asl = head->prev;
670
671 return asl == head ? NULL : asl;
672}
673
674static void proc_slot(struct proc *procp) {
675 int adjslot = ADJTOSLOT(procp->oomadj);
676
677 adjslot_insert(&procadjslot_list[adjslot], &procp->asl);
678}
679
680static void proc_unslot(struct proc *procp) {
681 adjslot_remove(&procp->asl);
682}
683
684static void proc_insert(struct proc *procp) {
685 int hval = pid_hashfn(procp->pid);
686
687 procp->pidhash_next = pidhash[hval];
688 pidhash[hval] = procp;
689 proc_slot(procp);
690}
691
692static int pid_remove(int pid) {
693 int hval = pid_hashfn(pid);
694 struct proc *procp;
695 struct proc *prevp;
696
697 for (procp = pidhash[hval], prevp = NULL; procp && procp->pid != pid;
698 procp = procp->pidhash_next)
699 prevp = procp;
700
701 if (!procp)
702 return -1;
703
704 if (!prevp)
705 pidhash[hval] = procp->pidhash_next;
706 else
707 prevp->pidhash_next = procp->pidhash_next;
708
709 proc_unslot(procp);
Suren Baghdasaryan11dc7342019-07-19 10:55:39 -0700710 /*
711 * Close pidfd here if we are not waiting for corresponding process to die,
712 * in which case stop_wait_for_proc_kill() will close the pidfd later
713 */
714 if (procp->pidfd >= 0 && procp->pidfd != last_kill_pid_or_fd) {
715 close(procp->pidfd);
716 }
Todd Poynor3948f802013-07-09 19:35:14 -0700717 free(procp);
718 return 0;
719}
720
Suren Baghdasaryan1ffa2462018-03-20 13:53:17 -0700721/*
722 * Write a string to a file.
723 * Returns false if the file does not exist.
724 */
725static bool writefilestring(const char *path, const char *s,
726 bool err_if_missing) {
Nick Kralevichc68c8862015-12-18 20:52:37 -0800727 int fd = open(path, O_WRONLY | O_CLOEXEC);
Suren Baghdasaryan1ffa2462018-03-20 13:53:17 -0700728 ssize_t len = strlen(s);
729 ssize_t ret;
Todd Poynor3948f802013-07-09 19:35:14 -0700730
731 if (fd < 0) {
Suren Baghdasaryan1ffa2462018-03-20 13:53:17 -0700732 if (err_if_missing) {
733 ALOGE("Error opening %s; errno=%d", path, errno);
734 }
735 return false;
Todd Poynor3948f802013-07-09 19:35:14 -0700736 }
737
Suren Baghdasaryan1ffa2462018-03-20 13:53:17 -0700738 ret = TEMP_FAILURE_RETRY(write(fd, s, len));
Todd Poynor3948f802013-07-09 19:35:14 -0700739 if (ret < 0) {
740 ALOGE("Error writing %s; errno=%d", path, errno);
741 } else if (ret < len) {
Suren Baghdasaryan1ffa2462018-03-20 13:53:17 -0700742 ALOGE("Short write on %s; length=%zd", path, ret);
Todd Poynor3948f802013-07-09 19:35:14 -0700743 }
744
745 close(fd);
Suren Baghdasaryan1ffa2462018-03-20 13:53:17 -0700746 return true;
Todd Poynor3948f802013-07-09 19:35:14 -0700747}
748
Suren Baghdasaryan314a5052018-07-24 17:13:06 -0700749static inline long get_time_diff_ms(struct timespec *from,
750 struct timespec *to) {
751 return (to->tv_sec - from->tv_sec) * (long)MS_PER_SEC +
752 (to->tv_nsec - from->tv_nsec) / (long)NS_PER_MS;
753}
754
Suren Baghdasaryan0082ef12019-07-02 15:52:07 -0700755static int proc_get_tgid(int pid) {
756 char path[PATH_MAX];
757 char buf[PAGE_SIZE];
758 int fd;
759 ssize_t size;
760 char *pos;
761 int64_t tgid = -1;
762
763 snprintf(path, PATH_MAX, "/proc/%d/status", pid);
764 fd = open(path, O_RDONLY | O_CLOEXEC);
765 if (fd < 0) {
766 return -1;
767 }
768
769 size = read_all(fd, buf, sizeof(buf) - 1);
770 if (size < 0) {
771 goto out;
772 }
773 buf[size] = 0;
774
775 pos = buf;
776 while (true) {
777 pos = strstr(pos, PROC_STATUS_TGID_FIELD);
778 /* Stop if TGID tag not found or found at the line beginning */
779 if (pos == NULL || pos == buf || pos[-1] == '\n') {
780 break;
781 }
782 pos++;
783 }
784
785 if (pos == NULL) {
786 goto out;
787 }
788
789 pos += strlen(PROC_STATUS_TGID_FIELD);
790 while (*pos == ' ') pos++;
791 parse_int64(pos, &tgid);
792
793out:
794 close(fd);
795 return (int)tgid;
796}
797
Suren Baghdasaryanb72c6652019-09-04 19:12:29 -0700798static int proc_get_size(int pid) {
799 char path[PATH_MAX];
800 char line[LINE_MAX];
801 int fd;
802 int rss = 0;
803 int total;
804 ssize_t ret;
805
806 /* gid containing AID_READPROC required */
807 snprintf(path, PATH_MAX, "/proc/%d/statm", pid);
808 fd = open(path, O_RDONLY | O_CLOEXEC);
809 if (fd == -1)
810 return -1;
811
812 ret = read_all(fd, line, sizeof(line) - 1);
813 if (ret < 0) {
814 close(fd);
815 return -1;
816 }
Suren Baghdasaryanca0790d2019-10-04 16:06:55 -0700817 line[ret] = '\0';
Suren Baghdasaryanb72c6652019-09-04 19:12:29 -0700818
819 sscanf(line, "%d %d ", &total, &rss);
820 close(fd);
821 return rss;
822}
823
Suren Baghdasaryanca0790d2019-10-04 16:06:55 -0700824static char *proc_get_name(int pid, char *buf, size_t buf_size) {
Suren Baghdasaryanb72c6652019-09-04 19:12:29 -0700825 char path[PATH_MAX];
Suren Baghdasaryanb72c6652019-09-04 19:12:29 -0700826 int fd;
827 char *cp;
828 ssize_t ret;
829
830 /* gid containing AID_READPROC required */
831 snprintf(path, PATH_MAX, "/proc/%d/cmdline", pid);
832 fd = open(path, O_RDONLY | O_CLOEXEC);
833 if (fd == -1) {
834 return NULL;
835 }
Suren Baghdasaryanca0790d2019-10-04 16:06:55 -0700836 ret = read_all(fd, buf, buf_size - 1);
Suren Baghdasaryanb72c6652019-09-04 19:12:29 -0700837 close(fd);
838 if (ret < 0) {
839 return NULL;
840 }
Suren Baghdasaryanca0790d2019-10-04 16:06:55 -0700841 buf[ret] = '\0';
Suren Baghdasaryanb72c6652019-09-04 19:12:29 -0700842
Suren Baghdasaryanca0790d2019-10-04 16:06:55 -0700843 cp = strchr(buf, ' ');
Suren Baghdasaryanb72c6652019-09-04 19:12:29 -0700844 if (cp) {
845 *cp = '\0';
Suren Baghdasaryanb72c6652019-09-04 19:12:29 -0700846 }
847
Suren Baghdasaryanca0790d2019-10-04 16:06:55 -0700848 return buf;
Suren Baghdasaryanb72c6652019-09-04 19:12:29 -0700849}
850
Suren Baghdasaryan12ab1872019-10-18 11:16:52 -0700851static bool claim_record(struct proc *procp, pid_t pid) {
852 if (procp->reg_pid == pid) {
853 /* Record already belongs to the registrant */
854 return true;
855 }
856 if (procp->reg_pid == 0) {
857 /* Old registrant is gone, claim the record */
858 procp->reg_pid = pid;
859 return true;
860 }
861 /* The record is owned by another registrant */
862 return false;
863}
864
865static void remove_claims(pid_t pid) {
866 int i;
867
868 for (i = 0; i < PIDHASH_SZ; i++) {
869 struct proc *procp = pidhash[i];
870 while (procp) {
871 if (procp->reg_pid == pid) {
872 procp->reg_pid = 0;
873 }
874 procp = procp->pidhash_next;
875 }
876 }
877}
878
Suren Baghdasaryane353d862019-10-22 17:12:01 -0700879static void cmd_procprio(LMKD_CTRL_PACKET packet, int field_count, struct ucred *cred) {
Todd Poynor3948f802013-07-09 19:35:14 -0700880 struct proc *procp;
Suren Baghdasaryanca0790d2019-10-04 16:06:55 -0700881 char path[LINE_MAX];
Todd Poynor3948f802013-07-09 19:35:14 -0700882 char val[20];
Robert Benea673e2762017-06-01 16:32:31 -0700883 int soft_limit_mult;
Suren Baghdasaryan0f100512018-01-24 16:51:41 -0800884 struct lmk_procprio params;
Suren Baghdasaryan4311d1e2018-03-20 16:03:29 -0700885 bool is_system_server;
886 struct passwd *pwdrec;
Suren Baghdasaryan0082ef12019-07-02 15:52:07 -0700887 int tgid;
Todd Poynor3948f802013-07-09 19:35:14 -0700888
Suren Baghdasaryane353d862019-10-22 17:12:01 -0700889 lmkd_pack_get_procprio(packet, field_count, &params);
Suren Baghdasaryan0f100512018-01-24 16:51:41 -0800890
891 if (params.oomadj < OOM_SCORE_ADJ_MIN ||
892 params.oomadj > OOM_SCORE_ADJ_MAX) {
893 ALOGE("Invalid PROCPRIO oomadj argument %d", params.oomadj);
Todd Poynor3948f802013-07-09 19:35:14 -0700894 return;
895 }
896
Suren Baghdasaryane353d862019-10-22 17:12:01 -0700897 if (params.ptype < PROC_TYPE_FIRST || params.ptype >= PROC_TYPE_COUNT) {
898 ALOGE("Invalid PROCPRIO process type argument %d", params.ptype);
899 return;
900 }
901
Suren Baghdasaryan0082ef12019-07-02 15:52:07 -0700902 /* Check if registered process is a thread group leader */
903 tgid = proc_get_tgid(params.pid);
904 if (tgid >= 0 && tgid != params.pid) {
905 ALOGE("Attempt to register a task that is not a thread group leader (tid %d, tgid %d)",
906 params.pid, tgid);
907 return;
908 }
909
Mark Salyzyn64d97d82018-04-09 09:50:32 -0700910 /* gid containing AID_READPROC required */
911 /* CAP_SYS_RESOURCE required */
912 /* CAP_DAC_OVERRIDE required */
Suren Baghdasaryan0f100512018-01-24 16:51:41 -0800913 snprintf(path, sizeof(path), "/proc/%d/oom_score_adj", params.pid);
914 snprintf(val, sizeof(val), "%d", params.oomadj);
Suren Baghdasaryan1ffa2462018-03-20 13:53:17 -0700915 if (!writefilestring(path, val, false)) {
916 ALOGW("Failed to open %s; errno=%d: process %d might have been killed",
917 path, errno, params.pid);
918 /* If this file does not exist the process is dead. */
919 return;
920 }
Todd Poynor3948f802013-07-09 19:35:14 -0700921
Mark Salyzyn721d7c72018-03-21 12:24:58 -0700922 if (use_inkernel_interface) {
Suren Baghdasaryanca0790d2019-10-04 16:06:55 -0700923 stats_store_taskname(params.pid, proc_get_name(params.pid, path, sizeof(path)),
924 kpoll_info.poll_fd);
Todd Poynor3948f802013-07-09 19:35:14 -0700925 return;
Mark Salyzyn721d7c72018-03-21 12:24:58 -0700926 }
Todd Poynor3948f802013-07-09 19:35:14 -0700927
Suren Baghdasaryane353d862019-10-22 17:12:01 -0700928 /* lmkd should not change soft limits for services */
929 if (params.ptype == PROC_TYPE_APP && per_app_memcg) {
Suren Baghdasaryan20686f02018-05-18 14:42:00 -0700930 if (params.oomadj >= 900) {
931 soft_limit_mult = 0;
932 } else if (params.oomadj >= 800) {
933 soft_limit_mult = 0;
934 } else if (params.oomadj >= 700) {
935 soft_limit_mult = 0;
936 } else if (params.oomadj >= 600) {
937 // Launcher should be perceptible, don't kill it.
938 params.oomadj = 200;
939 soft_limit_mult = 1;
940 } else if (params.oomadj >= 500) {
941 soft_limit_mult = 0;
942 } else if (params.oomadj >= 400) {
943 soft_limit_mult = 0;
944 } else if (params.oomadj >= 300) {
945 soft_limit_mult = 1;
946 } else if (params.oomadj >= 200) {
Srinivas Paladugu3eb20bc2018-10-09 14:21:10 -0700947 soft_limit_mult = 8;
Suren Baghdasaryan20686f02018-05-18 14:42:00 -0700948 } else if (params.oomadj >= 100) {
949 soft_limit_mult = 10;
950 } else if (params.oomadj >= 0) {
951 soft_limit_mult = 20;
952 } else {
953 // Persistent processes will have a large
954 // soft limit 512MB.
955 soft_limit_mult = 64;
956 }
Robert Benea673e2762017-06-01 16:32:31 -0700957
Suren Baghdasaryan3862dd32018-05-21 19:48:47 -0700958 snprintf(path, sizeof(path), MEMCG_SYSFS_PATH
959 "apps/uid_%d/pid_%d/memory.soft_limit_in_bytes",
960 params.uid, params.pid);
Suren Baghdasaryan20686f02018-05-18 14:42:00 -0700961 snprintf(val, sizeof(val), "%d", soft_limit_mult * EIGHT_MEGA);
Suren Baghdasaryan3862dd32018-05-21 19:48:47 -0700962
963 /*
964 * system_server process has no memcg under /dev/memcg/apps but should be
965 * registered with lmkd. This is the best way so far to identify it.
966 */
967 is_system_server = (params.oomadj == SYSTEM_ADJ &&
968 (pwdrec = getpwnam("system")) != NULL &&
969 params.uid == pwdrec->pw_uid);
970 writefilestring(path, val, !is_system_server);
Robert Benea673e2762017-06-01 16:32:31 -0700971 }
972
Suren Baghdasaryan0f100512018-01-24 16:51:41 -0800973 procp = pid_lookup(params.pid);
Todd Poynor3948f802013-07-09 19:35:14 -0700974 if (!procp) {
Suren Baghdasaryan11dc7342019-07-19 10:55:39 -0700975 int pidfd = -1;
976
977 if (pidfd_supported) {
978 pidfd = TEMP_FAILURE_RETRY(sys_pidfd_open(params.pid, 0));
979 if (pidfd < 0) {
980 ALOGE("pidfd_open for pid %d failed; errno=%d", params.pid, errno);
Todd Poynor3948f802013-07-09 19:35:14 -0700981 return;
982 }
Suren Baghdasaryan11dc7342019-07-19 10:55:39 -0700983 }
Todd Poynor3948f802013-07-09 19:35:14 -0700984
Suren Baghdasaryan11dc7342019-07-19 10:55:39 -0700985 procp = calloc(1, sizeof(struct proc));
986 if (!procp) {
987 // Oh, the irony. May need to rebuild our state.
988 return;
989 }
990
991 procp->pid = params.pid;
992 procp->pidfd = pidfd;
993 procp->uid = params.uid;
Suren Baghdasaryan12ab1872019-10-18 11:16:52 -0700994 procp->reg_pid = cred->pid;
Suren Baghdasaryan11dc7342019-07-19 10:55:39 -0700995 procp->oomadj = params.oomadj;
996 proc_insert(procp);
Todd Poynor3948f802013-07-09 19:35:14 -0700997 } else {
Suren Baghdasaryan12ab1872019-10-18 11:16:52 -0700998 if (!claim_record(procp, cred->pid)) {
999 char buf[LINE_MAX];
1000 /* Only registrant of the record can remove it */
1001 ALOGE("%s (%d, %d) attempts to modify a process registered by another client",
1002 proc_get_name(cred->pid, buf, sizeof(buf)), cred->uid, cred->pid);
1003 return;
1004 }
Todd Poynor3948f802013-07-09 19:35:14 -07001005 proc_unslot(procp);
Suren Baghdasaryan0f100512018-01-24 16:51:41 -08001006 procp->oomadj = params.oomadj;
Todd Poynor3948f802013-07-09 19:35:14 -07001007 proc_slot(procp);
1008 }
1009}
1010
Suren Baghdasaryan12ab1872019-10-18 11:16:52 -07001011static void cmd_procremove(LMKD_CTRL_PACKET packet, struct ucred *cred) {
Suren Baghdasaryan0f100512018-01-24 16:51:41 -08001012 struct lmk_procremove params;
Suren Baghdasaryan12ab1872019-10-18 11:16:52 -07001013 struct proc *procp;
Suren Baghdasaryan0f100512018-01-24 16:51:41 -08001014
George Burgess IVc73e0652019-10-02 11:22:55 -07001015 lmkd_pack_get_procremove(packet, &params);
Suren Baghdasaryan12ab1872019-10-18 11:16:52 -07001016
Mark Salyzyn721d7c72018-03-21 12:24:58 -07001017 if (use_inkernel_interface) {
Suren Baghdasaryanb72c6652019-09-04 19:12:29 -07001018 stats_remove_taskname(params.pid, kpoll_info.poll_fd);
Todd Poynor3948f802013-07-09 19:35:14 -07001019 return;
Mark Salyzyn721d7c72018-03-21 12:24:58 -07001020 }
Todd Poynor3948f802013-07-09 19:35:14 -07001021
Suren Baghdasaryan12ab1872019-10-18 11:16:52 -07001022 procp = pid_lookup(params.pid);
1023 if (!procp) {
1024 return;
1025 }
1026
1027 if (!claim_record(procp, cred->pid)) {
1028 char buf[LINE_MAX];
1029 /* Only registrant of the record can remove it */
1030 ALOGE("%s (%d, %d) attempts to unregister a process registered by another client",
1031 proc_get_name(cred->pid, buf, sizeof(buf)), cred->uid, cred->pid);
1032 return;
1033 }
1034
Suren Baghdasaryan01063272018-10-12 11:28:33 -07001035 /*
1036 * WARNING: After pid_remove() procp is freed and can't be used!
1037 * Therefore placed at the end of the function.
1038 */
Suren Baghdasaryan0f100512018-01-24 16:51:41 -08001039 pid_remove(params.pid);
Todd Poynor3948f802013-07-09 19:35:14 -07001040}
1041
Suren Baghdasaryan12ab1872019-10-18 11:16:52 -07001042static void cmd_procpurge(struct ucred *cred) {
Suren Baghdasaryane3b60472018-10-10 14:17:17 -07001043 int i;
1044 struct proc *procp;
1045 struct proc *next;
1046
1047 if (use_inkernel_interface) {
Jim Blacklerd2da8142019-09-10 15:30:05 +01001048 stats_purge_tasknames();
Suren Baghdasaryane3b60472018-10-10 14:17:17 -07001049 return;
1050 }
1051
Suren Baghdasaryane3b60472018-10-10 14:17:17 -07001052 for (i = 0; i < PIDHASH_SZ; i++) {
1053 procp = pidhash[i];
1054 while (procp) {
1055 next = procp->pidhash_next;
Suren Baghdasaryan12ab1872019-10-18 11:16:52 -07001056 /* Purge only records created by the requestor */
1057 if (claim_record(procp, cred->pid)) {
1058 pid_remove(procp->pid);
1059 }
Suren Baghdasaryane3b60472018-10-10 14:17:17 -07001060 procp = next;
1061 }
1062 }
Suren Baghdasaryane3b60472018-10-10 14:17:17 -07001063}
1064
Suren Baghdasaryand4a29902018-10-12 11:07:40 -07001065static void inc_killcnt(int oomadj) {
1066 int slot = ADJTOSLOT(oomadj);
1067 uint8_t idx = killcnt_idx[slot];
1068
1069 if (idx == KILLCNT_INVALID_IDX) {
1070 /* index is not assigned for this oomadj */
1071 if (killcnt_free_idx < MAX_DISTINCT_OOM_ADJ) {
1072 killcnt_idx[slot] = killcnt_free_idx;
1073 killcnt[killcnt_free_idx] = 1;
1074 killcnt_free_idx++;
1075 } else {
1076 ALOGW("Number of distinct oomadj levels exceeds %d",
1077 MAX_DISTINCT_OOM_ADJ);
1078 }
1079 } else {
1080 /*
1081 * wraparound is highly unlikely and is detectable using total
1082 * counter because it has to be equal to the sum of all counters
1083 */
1084 killcnt[idx]++;
1085 }
1086 /* increment total kill counter */
1087 killcnt_total++;
1088}
1089
1090static int get_killcnt(int min_oomadj, int max_oomadj) {
1091 int slot;
1092 int count = 0;
1093
1094 if (min_oomadj > max_oomadj)
1095 return 0;
1096
1097 /* special case to get total kill count */
1098 if (min_oomadj > OOM_SCORE_ADJ_MAX)
1099 return killcnt_total;
1100
1101 while (min_oomadj <= max_oomadj &&
1102 (slot = ADJTOSLOT(min_oomadj)) < ADJTOSLOT_COUNT) {
1103 uint8_t idx = killcnt_idx[slot];
1104 if (idx != KILLCNT_INVALID_IDX) {
1105 count += killcnt[idx];
1106 }
1107 min_oomadj++;
1108 }
1109
1110 return count;
1111}
1112
1113static int cmd_getkillcnt(LMKD_CTRL_PACKET packet) {
1114 struct lmk_getkillcnt params;
1115
1116 if (use_inkernel_interface) {
1117 /* kernel driver does not expose this information */
1118 return 0;
1119 }
1120
1121 lmkd_pack_get_getkillcnt(packet, &params);
1122
1123 return get_killcnt(params.min_oomadj, params.max_oomadj);
1124}
1125
Suren Baghdasaryan0f100512018-01-24 16:51:41 -08001126static void cmd_target(int ntargets, LMKD_CTRL_PACKET packet) {
Todd Poynor3948f802013-07-09 19:35:14 -07001127 int i;
Suren Baghdasaryan0f100512018-01-24 16:51:41 -08001128 struct lmk_target target;
Suren Baghdasaryan314a5052018-07-24 17:13:06 -07001129 char minfree_str[PROPERTY_VALUE_MAX];
1130 char *pstr = minfree_str;
1131 char *pend = minfree_str + sizeof(minfree_str);
1132 static struct timespec last_req_tm;
1133 struct timespec curr_tm;
Todd Poynor3948f802013-07-09 19:35:14 -07001134
Suren Baghdasaryan314a5052018-07-24 17:13:06 -07001135 if (ntargets < 1 || ntargets > (int)ARRAY_SIZE(lowmem_adj))
Todd Poynor3948f802013-07-09 19:35:14 -07001136 return;
1137
Suren Baghdasaryan314a5052018-07-24 17:13:06 -07001138 /*
1139 * Ratelimit minfree updates to once per TARGET_UPDATE_MIN_INTERVAL_MS
1140 * to prevent DoS attacks
1141 */
1142 if (clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm) != 0) {
1143 ALOGE("Failed to get current time");
1144 return;
1145 }
1146
1147 if (get_time_diff_ms(&last_req_tm, &curr_tm) <
1148 TARGET_UPDATE_MIN_INTERVAL_MS) {
1149 ALOGE("Ignoring frequent updated to lmkd limits");
1150 return;
1151 }
1152
1153 last_req_tm = curr_tm;
1154
Todd Poynor3948f802013-07-09 19:35:14 -07001155 for (i = 0; i < ntargets; i++) {
Suren Baghdasaryan0f100512018-01-24 16:51:41 -08001156 lmkd_pack_get_target(packet, i, &target);
1157 lowmem_minfree[i] = target.minfree;
1158 lowmem_adj[i] = target.oom_adj_score;
Suren Baghdasaryan314a5052018-07-24 17:13:06 -07001159
1160 pstr += snprintf(pstr, pend - pstr, "%d:%d,", target.minfree,
1161 target.oom_adj_score);
1162 if (pstr >= pend) {
1163 /* if no more space in the buffer then terminate the loop */
1164 pstr = pend;
1165 break;
1166 }
Todd Poynor3948f802013-07-09 19:35:14 -07001167 }
1168
1169 lowmem_targets_size = ntargets;
1170
Suren Baghdasaryan314a5052018-07-24 17:13:06 -07001171 /* Override the last extra comma */
1172 pstr[-1] = '\0';
1173 property_set("sys.lmk.minfree_levels", minfree_str);
1174
Robert Benea164baeb2017-09-11 16:53:28 -07001175 if (has_inkernel_module) {
Todd Poynor3948f802013-07-09 19:35:14 -07001176 char minfreestr[128];
1177 char killpriostr[128];
1178
1179 minfreestr[0] = '\0';
1180 killpriostr[0] = '\0';
1181
1182 for (i = 0; i < lowmem_targets_size; i++) {
1183 char val[40];
1184
1185 if (i) {
1186 strlcat(minfreestr, ",", sizeof(minfreestr));
1187 strlcat(killpriostr, ",", sizeof(killpriostr));
1188 }
1189
Robert Benea164baeb2017-09-11 16:53:28 -07001190 snprintf(val, sizeof(val), "%d", use_inkernel_interface ? lowmem_minfree[i] : 0);
Todd Poynor3948f802013-07-09 19:35:14 -07001191 strlcat(minfreestr, val, sizeof(minfreestr));
Robert Benea164baeb2017-09-11 16:53:28 -07001192 snprintf(val, sizeof(val), "%d", use_inkernel_interface ? lowmem_adj[i] : 0);
Todd Poynor3948f802013-07-09 19:35:14 -07001193 strlcat(killpriostr, val, sizeof(killpriostr));
1194 }
1195
Suren Baghdasaryan1ffa2462018-03-20 13:53:17 -07001196 writefilestring(INKERNEL_MINFREE_PATH, minfreestr, true);
1197 writefilestring(INKERNEL_ADJ_PATH, killpriostr, true);
Todd Poynor3948f802013-07-09 19:35:14 -07001198 }
1199}
1200
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08001201static void ctrl_data_close(int dsock_idx) {
1202 struct epoll_event epev;
1203
1204 ALOGI("closing lmkd data connection");
1205 if (epoll_ctl(epollfd, EPOLL_CTL_DEL, data_sock[dsock_idx].sock, &epev) == -1) {
1206 // Log a warning and keep going
1207 ALOGW("epoll_ctl for data connection socket failed; errno=%d", errno);
1208 }
Todd Poynor3948f802013-07-09 19:35:14 -07001209 maxevents--;
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08001210
1211 close(data_sock[dsock_idx].sock);
1212 data_sock[dsock_idx].sock = -1;
Suren Baghdasaryan12ab1872019-10-18 11:16:52 -07001213
1214 /* Mark all records of the old registrant as unclaimed */
1215 remove_claims(data_sock[dsock_idx].pid);
Todd Poynor3948f802013-07-09 19:35:14 -07001216}
1217
Suren Baghdasaryan12ab1872019-10-18 11:16:52 -07001218static ssize_t ctrl_data_read(int dsock_idx, char *buf, size_t bufsz, struct ucred *sender_cred) {
1219 struct iovec iov = { buf, bufsz };
1220 char control[CMSG_SPACE(sizeof(struct ucred))];
1221 struct msghdr hdr = {
1222 NULL, 0, &iov, 1, control, sizeof(control), 0,
1223 };
1224 ssize_t ret;
Todd Poynor3948f802013-07-09 19:35:14 -07001225
Suren Baghdasaryan12ab1872019-10-18 11:16:52 -07001226 ret = TEMP_FAILURE_RETRY(recvmsg(data_sock[dsock_idx].sock, &hdr, 0));
Todd Poynor3948f802013-07-09 19:35:14 -07001227 if (ret == -1) {
Suren Baghdasaryan12ab1872019-10-18 11:16:52 -07001228 ALOGE("control data socket read failed; %s", strerror(errno));
1229 return -1;
Todd Poynor3948f802013-07-09 19:35:14 -07001230 }
Suren Baghdasaryan12ab1872019-10-18 11:16:52 -07001231 if (ret == 0) {
1232 ALOGE("Got EOF on control data socket");
1233 return -1;
1234 }
1235
1236 struct ucred* cred = NULL;
1237 struct cmsghdr* cmsg = CMSG_FIRSTHDR(&hdr);
1238 while (cmsg != NULL) {
1239 if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_CREDENTIALS) {
1240 cred = (struct ucred*)CMSG_DATA(cmsg);
1241 break;
1242 }
1243 cmsg = CMSG_NXTHDR(&hdr, cmsg);
1244 }
1245
1246 if (cred == NULL) {
1247 ALOGE("Failed to retrieve sender credentials");
1248 /* Close the connection */
1249 ctrl_data_close(dsock_idx);
1250 return -1;
1251 }
1252
1253 memcpy(sender_cred, cred, sizeof(struct ucred));
1254
1255 /* Store PID of the peer */
1256 data_sock[dsock_idx].pid = cred->pid;
Todd Poynor3948f802013-07-09 19:35:14 -07001257
1258 return ret;
1259}
1260
Suren Baghdasaryand4a29902018-10-12 11:07:40 -07001261static int ctrl_data_write(int dsock_idx, char *buf, size_t bufsz) {
1262 int ret = 0;
1263
1264 ret = TEMP_FAILURE_RETRY(write(data_sock[dsock_idx].sock, buf, bufsz));
1265
1266 if (ret == -1) {
1267 ALOGE("control data socket write failed; errno=%d", errno);
1268 } else if (ret == 0) {
1269 ALOGE("Got EOF on control data socket");
1270 ret = -1;
1271 }
1272
1273 return ret;
1274}
1275
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08001276static void ctrl_command_handler(int dsock_idx) {
Suren Baghdasaryan0f100512018-01-24 16:51:41 -08001277 LMKD_CTRL_PACKET packet;
Suren Baghdasaryan12ab1872019-10-18 11:16:52 -07001278 struct ucred cred;
Todd Poynor3948f802013-07-09 19:35:14 -07001279 int len;
Suren Baghdasaryan0f100512018-01-24 16:51:41 -08001280 enum lmk_cmd cmd;
Todd Poynor3948f802013-07-09 19:35:14 -07001281 int nargs;
1282 int targets;
Suren Baghdasaryand4a29902018-10-12 11:07:40 -07001283 int kill_cnt;
Todd Poynor3948f802013-07-09 19:35:14 -07001284
Suren Baghdasaryan12ab1872019-10-18 11:16:52 -07001285 len = ctrl_data_read(dsock_idx, (char *)packet, CTRL_PACKET_MAX_SIZE, &cred);
Todd Poynor3948f802013-07-09 19:35:14 -07001286 if (len <= 0)
1287 return;
1288
Suren Baghdasaryan0f100512018-01-24 16:51:41 -08001289 if (len < (int)sizeof(int)) {
1290 ALOGE("Wrong control socket read length len=%d", len);
1291 return;
1292 }
1293
1294 cmd = lmkd_pack_get_cmd(packet);
Todd Poynor3948f802013-07-09 19:35:14 -07001295 nargs = len / sizeof(int) - 1;
1296 if (nargs < 0)
1297 goto wronglen;
1298
Todd Poynor3948f802013-07-09 19:35:14 -07001299 switch(cmd) {
1300 case LMK_TARGET:
1301 targets = nargs / 2;
1302 if (nargs & 0x1 || targets > (int)ARRAY_SIZE(lowmem_adj))
1303 goto wronglen;
Suren Baghdasaryan0f100512018-01-24 16:51:41 -08001304 cmd_target(targets, packet);
Todd Poynor3948f802013-07-09 19:35:14 -07001305 break;
1306 case LMK_PROCPRIO:
Suren Baghdasaryane353d862019-10-22 17:12:01 -07001307 /* process type field is optional for backward compatibility */
1308 if (nargs < 3 || nargs > 4)
Todd Poynor3948f802013-07-09 19:35:14 -07001309 goto wronglen;
Suren Baghdasaryane353d862019-10-22 17:12:01 -07001310 cmd_procprio(packet, nargs, &cred);
Todd Poynor3948f802013-07-09 19:35:14 -07001311 break;
1312 case LMK_PROCREMOVE:
1313 if (nargs != 1)
1314 goto wronglen;
Suren Baghdasaryan12ab1872019-10-18 11:16:52 -07001315 cmd_procremove(packet, &cred);
Todd Poynor3948f802013-07-09 19:35:14 -07001316 break;
Suren Baghdasaryane3b60472018-10-10 14:17:17 -07001317 case LMK_PROCPURGE:
1318 if (nargs != 0)
1319 goto wronglen;
Suren Baghdasaryan12ab1872019-10-18 11:16:52 -07001320 cmd_procpurge(&cred);
Suren Baghdasaryane3b60472018-10-10 14:17:17 -07001321 break;
Suren Baghdasaryand4a29902018-10-12 11:07:40 -07001322 case LMK_GETKILLCNT:
1323 if (nargs != 2)
1324 goto wronglen;
1325 kill_cnt = cmd_getkillcnt(packet);
1326 len = lmkd_pack_set_getkillcnt_repl(packet, kill_cnt);
1327 if (ctrl_data_write(dsock_idx, (char *)packet, len) != len)
1328 return;
1329 break;
Todd Poynor3948f802013-07-09 19:35:14 -07001330 default:
1331 ALOGE("Received unknown command code %d", cmd);
1332 return;
1333 }
1334
1335 return;
1336
1337wronglen:
1338 ALOGE("Wrong control socket read length cmd=%d len=%d", cmd, len);
1339}
1340
Suren Baghdasaryanef3650f2019-07-15 14:50:49 -07001341static void ctrl_data_handler(int data, uint32_t events,
1342 struct polling_params *poll_params __unused) {
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08001343 if (events & EPOLLIN) {
1344 ctrl_command_handler(data);
Todd Poynor3948f802013-07-09 19:35:14 -07001345 }
1346}
1347
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08001348static int get_free_dsock() {
1349 for (int i = 0; i < MAX_DATA_CONN; i++) {
1350 if (data_sock[i].sock < 0) {
1351 return i;
1352 }
1353 }
1354 return -1;
1355}
Todd Poynor3948f802013-07-09 19:35:14 -07001356
Suren Baghdasaryanef3650f2019-07-15 14:50:49 -07001357static void ctrl_connect_handler(int data __unused, uint32_t events __unused,
1358 struct polling_params *poll_params __unused) {
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08001359 struct epoll_event epev;
1360 int free_dscock_idx = get_free_dsock();
1361
1362 if (free_dscock_idx < 0) {
1363 /*
1364 * Number of data connections exceeded max supported. This should not
1365 * happen but if it does we drop all existing connections and accept
1366 * the new one. This prevents inactive connections from monopolizing
1367 * data socket and if we drop ActivityManager connection it will
1368 * immediately reconnect.
1369 */
1370 for (int i = 0; i < MAX_DATA_CONN; i++) {
1371 ctrl_data_close(i);
1372 }
1373 free_dscock_idx = 0;
Todd Poynor3948f802013-07-09 19:35:14 -07001374 }
1375
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08001376 data_sock[free_dscock_idx].sock = accept(ctrl_sock.sock, NULL, NULL);
1377 if (data_sock[free_dscock_idx].sock < 0) {
Todd Poynor3948f802013-07-09 19:35:14 -07001378 ALOGE("lmkd control socket accept failed; errno=%d", errno);
1379 return;
1380 }
1381
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08001382 ALOGI("lmkd data connection established");
1383 /* use data to store data connection idx */
1384 data_sock[free_dscock_idx].handler_info.data = free_dscock_idx;
1385 data_sock[free_dscock_idx].handler_info.handler = ctrl_data_handler;
Todd Poynor3948f802013-07-09 19:35:14 -07001386 epev.events = EPOLLIN;
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08001387 epev.data.ptr = (void *)&(data_sock[free_dscock_idx].handler_info);
1388 if (epoll_ctl(epollfd, EPOLL_CTL_ADD, data_sock[free_dscock_idx].sock, &epev) == -1) {
Todd Poynor3948f802013-07-09 19:35:14 -07001389 ALOGE("epoll_ctl for data connection socket failed; errno=%d", errno);
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08001390 ctrl_data_close(free_dscock_idx);
Todd Poynor3948f802013-07-09 19:35:14 -07001391 return;
1392 }
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08001393 maxevents++;
Todd Poynor3948f802013-07-09 19:35:14 -07001394}
1395
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07001396/*
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07001397 * /proc/zoneinfo parsing routines
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07001398 * Expected file format is:
1399 *
1400 * Node <node_id>, zone <zone_name>
1401 * (
1402 * per-node stats
1403 * (<per-node field name> <value>)+
1404 * )?
1405 * (pages free <value>
1406 * (<per-zone field name> <value>)+
1407 * pagesets
1408 * (<unused fields>)*
1409 * )+
1410 * ...
1411 */
1412static void zoneinfo_parse_protection(char *buf, struct zoneinfo_zone *zone) {
1413 int zone_idx;
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001414 int64_t max = 0;
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001415 char *save_ptr;
1416
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07001417 for (buf = strtok_r(buf, "(), ", &save_ptr), zone_idx = 0;
1418 buf && zone_idx < MAX_NR_ZONES;
1419 buf = strtok_r(NULL, "), ", &save_ptr), zone_idx++) {
1420 long long zoneval = strtoll(buf, &buf, 0);
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001421 if (zoneval > max) {
1422 max = (zoneval > INT64_MAX) ? INT64_MAX : zoneval;
1423 }
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07001424 zone->protection[zone_idx] = zoneval;
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001425 }
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07001426 zone->max_protection = max;
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001427}
1428
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07001429static int zoneinfo_parse_zone(char **buf, struct zoneinfo_zone *zone) {
1430 for (char *line = strtok_r(NULL, "\n", buf); line;
1431 line = strtok_r(NULL, "\n", buf)) {
1432 char *cp;
1433 char *ap;
1434 char *save_ptr;
1435 int64_t val;
1436 int field_idx;
1437 enum field_match_result match_res;
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001438
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07001439 cp = strtok_r(line, " ", &save_ptr);
1440 if (!cp) {
1441 return false;
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001442 }
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07001443
1444 field_idx = find_field(cp, zoneinfo_zone_spec_field_names, ZI_ZONE_SPEC_FIELD_COUNT);
1445 if (field_idx >= 0) {
1446 /* special field */
1447 if (field_idx == ZI_ZONE_SPEC_PAGESETS) {
1448 /* no mode fields we are interested in */
1449 return true;
1450 }
1451
1452 /* protection field */
1453 ap = strtok_r(NULL, ")", &save_ptr);
1454 if (ap) {
1455 zoneinfo_parse_protection(ap, zone);
1456 }
1457 continue;
1458 }
1459
1460 ap = strtok_r(NULL, " ", &save_ptr);
1461 if (!ap) {
1462 continue;
1463 }
1464
1465 match_res = match_field(cp, ap, zoneinfo_zone_field_names, ZI_ZONE_FIELD_COUNT,
1466 &val, &field_idx);
1467 if (match_res == PARSE_FAIL) {
1468 return false;
1469 }
1470 if (match_res == PARSE_SUCCESS) {
1471 zone->fields.arr[field_idx] = val;
1472 }
1473 if (field_idx == ZI_ZONE_PRESENT && val == 0) {
1474 /* zone is not populated, stop parsing it */
1475 return true;
1476 }
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001477 }
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07001478 return false;
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001479}
1480
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07001481static int zoneinfo_parse_node(char **buf, struct zoneinfo_node *node) {
1482 int fields_to_match = ZI_NODE_FIELD_COUNT;
1483
1484 for (char *line = strtok_r(NULL, "\n", buf); line;
1485 line = strtok_r(NULL, "\n", buf)) {
1486 char *cp;
1487 char *ap;
1488 char *save_ptr;
1489 int64_t val;
1490 int field_idx;
1491 enum field_match_result match_res;
1492
1493 cp = strtok_r(line, " ", &save_ptr);
1494 if (!cp) {
1495 return false;
1496 }
1497
1498 ap = strtok_r(NULL, " ", &save_ptr);
1499 if (!ap) {
1500 return false;
1501 }
1502
1503 match_res = match_field(cp, ap, zoneinfo_node_field_names, ZI_NODE_FIELD_COUNT,
1504 &val, &field_idx);
1505 if (match_res == PARSE_FAIL) {
1506 return false;
1507 }
1508 if (match_res == PARSE_SUCCESS) {
1509 node->fields.arr[field_idx] = val;
1510 fields_to_match--;
1511 if (!fields_to_match) {
1512 return true;
1513 }
1514 }
1515 }
1516 return false;
1517}
1518
1519static int zoneinfo_parse(struct zoneinfo *zi) {
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001520 static struct reread_data file_data = {
1521 .filename = ZONEINFO_PATH,
1522 .fd = -1,
1523 };
Suren Baghdasaryana77b3272019-07-15 13:35:04 -07001524 char *buf;
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001525 char *save_ptr;
1526 char *line;
Greg Kaiser724a1612019-10-02 07:07:32 -07001527 char zone_name[LINE_MAX + 1];
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07001528 struct zoneinfo_node *node = NULL;
1529 int node_idx = 0;
1530 int zone_idx = 0;
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001531
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07001532 memset(zi, 0, sizeof(struct zoneinfo));
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001533
Suren Baghdasaryana77b3272019-07-15 13:35:04 -07001534 if ((buf = reread_file(&file_data)) == NULL) {
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001535 return -1;
1536 }
1537
1538 for (line = strtok_r(buf, "\n", &save_ptr); line;
1539 line = strtok_r(NULL, "\n", &save_ptr)) {
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07001540 int node_id;
1541 if (sscanf(line, "Node %d, zone %" STRINGIFY(LINE_MAX) "s", &node_id, zone_name) == 2) {
1542 if (!node || node->id != node_id) {
1543 /* new node is found */
1544 if (node) {
1545 node->zone_count = zone_idx + 1;
1546 node_idx++;
1547 if (node_idx == MAX_NR_NODES) {
1548 /* max node count exceeded */
1549 ALOGE("%s parse error", file_data.filename);
1550 return -1;
1551 }
1552 }
1553 node = &zi->nodes[node_idx];
1554 node->id = node_id;
1555 zone_idx = 0;
1556 if (!zoneinfo_parse_node(&save_ptr, node)) {
1557 ALOGE("%s parse error", file_data.filename);
1558 return -1;
1559 }
1560 } else {
1561 /* new zone is found */
1562 zone_idx++;
1563 }
1564 if (!zoneinfo_parse_zone(&save_ptr, &node->zones[zone_idx])) {
1565 ALOGE("%s parse error", file_data.filename);
1566 return -1;
1567 }
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001568 }
1569 }
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07001570 if (!node) {
1571 ALOGE("%s parse error", file_data.filename);
1572 return -1;
1573 }
1574 node->zone_count = zone_idx + 1;
1575 zi->node_count = node_idx + 1;
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001576
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07001577 /* calculate totals fields */
1578 for (node_idx = 0; node_idx < zi->node_count; node_idx++) {
1579 node = &zi->nodes[node_idx];
1580 for (zone_idx = 0; zone_idx < node->zone_count; zone_idx++) {
1581 struct zoneinfo_zone *zone = &zi->nodes[node_idx].zones[zone_idx];
1582 zi->totalreserve_pages += zone->max_protection + zone->fields.field.high;
1583 }
1584 zi->total_inactive_file += node->fields.field.nr_inactive_file;
1585 zi->total_active_file += node->fields.field.nr_active_file;
1586 zi->total_workingset_refault += node->fields.field.workingset_refault;
1587 }
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001588 return 0;
1589}
1590
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07001591/* /proc/meminfo parsing routines */
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001592static bool meminfo_parse_line(char *line, union meminfo *mi) {
1593 char *cp = line;
1594 char *ap;
1595 char *save_ptr;
1596 int64_t val;
1597 int field_idx;
1598 enum field_match_result match_res;
1599
1600 cp = strtok_r(line, " ", &save_ptr);
1601 if (!cp) {
1602 return false;
1603 }
1604
1605 ap = strtok_r(NULL, " ", &save_ptr);
1606 if (!ap) {
1607 return false;
1608 }
1609
1610 match_res = match_field(cp, ap, meminfo_field_names, MI_FIELD_COUNT,
1611 &val, &field_idx);
1612 if (match_res == PARSE_SUCCESS) {
1613 mi->arr[field_idx] = val / page_k;
1614 }
1615 return (match_res != PARSE_FAIL);
1616}
1617
1618static int meminfo_parse(union meminfo *mi) {
1619 static struct reread_data file_data = {
1620 .filename = MEMINFO_PATH,
1621 .fd = -1,
1622 };
Suren Baghdasaryana77b3272019-07-15 13:35:04 -07001623 char *buf;
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001624 char *save_ptr;
1625 char *line;
1626
1627 memset(mi, 0, sizeof(union meminfo));
1628
Suren Baghdasaryana77b3272019-07-15 13:35:04 -07001629 if ((buf = reread_file(&file_data)) == NULL) {
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001630 return -1;
1631 }
1632
1633 for (line = strtok_r(buf, "\n", &save_ptr); line;
1634 line = strtok_r(NULL, "\n", &save_ptr)) {
1635 if (!meminfo_parse_line(line, mi)) {
1636 ALOGE("%s parse error", file_data.filename);
1637 return -1;
1638 }
1639 }
1640 mi->field.nr_file_pages = mi->field.cached + mi->field.swap_cached +
1641 mi->field.buffers;
1642
1643 return 0;
1644}
1645
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07001646/* /proc/vmstat parsing routines */
1647static bool vmstat_parse_line(char *line, union vmstat *vs) {
1648 char *cp;
1649 char *ap;
1650 char *save_ptr;
1651 int64_t val;
1652 int field_idx;
1653 enum field_match_result match_res;
1654
1655 cp = strtok_r(line, " ", &save_ptr);
1656 if (!cp) {
1657 return false;
1658 }
1659
1660 ap = strtok_r(NULL, " ", &save_ptr);
1661 if (!ap) {
1662 return false;
1663 }
1664
1665 match_res = match_field(cp, ap, vmstat_field_names, VS_FIELD_COUNT,
1666 &val, &field_idx);
1667 if (match_res == PARSE_SUCCESS) {
1668 vs->arr[field_idx] = val;
1669 }
1670 return (match_res != PARSE_FAIL);
1671}
1672
1673static int vmstat_parse(union vmstat *vs) {
1674 static struct reread_data file_data = {
1675 .filename = VMSTAT_PATH,
1676 .fd = -1,
1677 };
1678 char *buf;
1679 char *save_ptr;
1680 char *line;
1681
1682 memset(vs, 0, sizeof(union vmstat));
1683
1684 if ((buf = reread_file(&file_data)) == NULL) {
1685 return -1;
1686 }
1687
1688 for (line = strtok_r(buf, "\n", &save_ptr); line;
1689 line = strtok_r(NULL, "\n", &save_ptr)) {
1690 if (!vmstat_parse_line(line, vs)) {
1691 ALOGE("%s parse error", file_data.filename);
1692 return -1;
1693 }
1694 }
1695
1696 return 0;
1697}
1698
Suren Baghdasaryana7ac5782019-09-16 12:06:30 -07001699static void killinfo_log(struct proc* procp, int min_oom_score, int tasksize,
1700 int kill_reason, union meminfo *mi) {
1701 /* log process information */
1702 android_log_write_int32(ctx, procp->pid);
1703 android_log_write_int32(ctx, procp->uid);
1704 android_log_write_int32(ctx, procp->oomadj);
1705 android_log_write_int32(ctx, min_oom_score);
1706 android_log_write_int32(ctx, (int32_t)min(tasksize * page_k, INT32_MAX));
1707 android_log_write_int32(ctx, kill_reason);
1708
1709 /* log meminfo fields */
Suren Baghdasaryan282ad1a2018-07-26 16:34:27 -07001710 for (int field_idx = 0; field_idx < MI_FIELD_COUNT; field_idx++) {
1711 android_log_write_int32(ctx, (int32_t)min(mi->arr[field_idx] * page_k, INT32_MAX));
1712 }
1713
1714 android_log_write_list(ctx, LOG_ID_EVENTS);
1715 android_log_reset(ctx);
1716}
1717
Todd Poynor3948f802013-07-09 19:35:14 -07001718static struct proc *proc_adj_lru(int oomadj) {
1719 return (struct proc *)adjslot_tail(&procadjslot_list[ADJTOSLOT(oomadj)]);
1720}
1721
Suren Baghdasaryan662492a2017-12-08 13:17:06 -08001722static struct proc *proc_get_heaviest(int oomadj) {
1723 struct adjslot_list *head = &procadjslot_list[ADJTOSLOT(oomadj)];
1724 struct adjslot_list *curr = head->next;
1725 struct proc *maxprocp = NULL;
1726 int maxsize = 0;
1727 while (curr != head) {
1728 int pid = ((struct proc *)curr)->pid;
1729 int tasksize = proc_get_size(pid);
1730 if (tasksize <= 0) {
1731 struct adjslot_list *next = curr->next;
1732 pid_remove(pid);
1733 curr = next;
1734 } else {
1735 if (tasksize > maxsize) {
1736 maxsize = tasksize;
1737 maxprocp = (struct proc *)curr;
1738 }
1739 curr = curr->next;
1740 }
1741 }
1742 return maxprocp;
1743}
1744
Wei Wang2d95c102018-11-21 00:11:44 -08001745static void set_process_group_and_prio(int pid, SchedPolicy sp, int prio) {
1746 DIR* d;
1747 char proc_path[PATH_MAX];
1748 struct dirent* de;
1749
1750 snprintf(proc_path, sizeof(proc_path), "/proc/%d/task", pid);
1751 if (!(d = opendir(proc_path))) {
1752 ALOGW("Failed to open %s; errno=%d: process pid(%d) might have died", proc_path, errno,
1753 pid);
1754 return;
1755 }
1756
1757 while ((de = readdir(d))) {
1758 int t_pid;
1759
1760 if (de->d_name[0] == '.') continue;
1761 t_pid = atoi(de->d_name);
1762
1763 if (!t_pid) {
1764 ALOGW("Failed to get t_pid for '%s' of pid(%d)", de->d_name, pid);
1765 continue;
1766 }
1767
1768 if (setpriority(PRIO_PROCESS, t_pid, prio) && errno != ESRCH) {
1769 ALOGW("Unable to raise priority of killing t_pid (%d): errno=%d", t_pid, errno);
1770 }
1771
1772 if (set_cpuset_policy(t_pid, sp)) {
1773 ALOGW("Failed to set_cpuset_policy on pid(%d) t_pid(%d) to %d", pid, t_pid, (int)sp);
1774 continue;
1775 }
1776 }
1777 closedir(d);
1778}
1779
Suren Baghdasaryanf2081a92019-06-26 17:56:01 -07001780static bool is_kill_pending(void) {
1781 char buf[24];
1782
1783 if (last_kill_pid_or_fd < 0) {
1784 return false;
1785 }
1786
1787 if (pidfd_supported) {
1788 return true;
1789 }
1790
1791 /* when pidfd is not supported base the decision on /proc/<pid> existence */
1792 snprintf(buf, sizeof(buf), "/proc/%d/", last_kill_pid_or_fd);
1793 if (access(buf, F_OK) == 0) {
1794 return true;
1795 }
1796
1797 return false;
1798}
1799
1800static bool is_waiting_for_kill(void) {
1801 return pidfd_supported && last_kill_pid_or_fd >= 0;
1802}
1803
1804static void stop_wait_for_proc_kill(bool finished) {
1805 struct epoll_event epev;
1806
1807 if (last_kill_pid_or_fd < 0) {
1808 return;
1809 }
1810
1811 if (debug_process_killing) {
1812 struct timespec curr_tm;
1813
1814 if (clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm) != 0) {
1815 /*
1816 * curr_tm is used here merely to report kill duration, so this failure is not fatal.
1817 * Log an error and continue.
1818 */
1819 ALOGE("Failed to get current time");
1820 }
1821
1822 if (finished) {
1823 ALOGI("Process got killed in %ldms",
1824 get_time_diff_ms(&last_kill_tm, &curr_tm));
1825 } else {
1826 ALOGI("Stop waiting for process kill after %ldms",
1827 get_time_diff_ms(&last_kill_tm, &curr_tm));
1828 }
1829 }
1830
1831 if (pidfd_supported) {
1832 /* unregister fd */
1833 if (epoll_ctl(epollfd, EPOLL_CTL_DEL, last_kill_pid_or_fd, &epev) != 0) {
1834 ALOGE("epoll_ctl for last killed process failed; errno=%d", errno);
1835 return;
1836 }
1837 maxevents--;
1838 close(last_kill_pid_or_fd);
1839 }
1840
1841 last_kill_pid_or_fd = -1;
1842}
1843
1844static void kill_done_handler(int data __unused, uint32_t events __unused,
1845 struct polling_params *poll_params) {
1846 stop_wait_for_proc_kill(true);
1847 poll_params->update = POLLING_RESUME;
1848}
1849
Suren Baghdasaryan11dc7342019-07-19 10:55:39 -07001850static void start_wait_for_proc_kill(int pid_or_fd) {
Suren Baghdasaryanf2081a92019-06-26 17:56:01 -07001851 static struct event_handler_info kill_done_hinfo = { 0, kill_done_handler };
1852 struct epoll_event epev;
1853
1854 if (last_kill_pid_or_fd >= 0) {
1855 /* Should not happen but if it does we should stop previous wait */
1856 ALOGE("Attempt to wait for a kill while another wait is in progress");
1857 stop_wait_for_proc_kill(false);
1858 }
1859
Suren Baghdasaryan11dc7342019-07-19 10:55:39 -07001860 last_kill_pid_or_fd = pid_or_fd;
Suren Baghdasaryanf2081a92019-06-26 17:56:01 -07001861
Suren Baghdasaryan11dc7342019-07-19 10:55:39 -07001862 if (!pidfd_supported) {
1863 /* If pidfd is not supported just store PID and exit */
Suren Baghdasaryanf2081a92019-06-26 17:56:01 -07001864 return;
1865 }
1866
1867 epev.events = EPOLLIN;
1868 epev.data.ptr = (void *)&kill_done_hinfo;
1869 if (epoll_ctl(epollfd, EPOLL_CTL_ADD, last_kill_pid_or_fd, &epev) != 0) {
1870 ALOGE("epoll_ctl for last kill failed; errno=%d", errno);
1871 close(last_kill_pid_or_fd);
1872 last_kill_pid_or_fd = -1;
1873 return;
1874 }
1875 maxevents++;
1876}
Tim Murraye7853f62018-10-25 17:05:41 -07001877
Colin Cross16b09462014-07-14 12:39:56 -07001878/* Kill one process specified by procp. Returns the size of the process killed */
Suren Baghdasaryana7ac5782019-09-16 12:06:30 -07001879static int kill_one_process(struct proc* procp, int min_oom_score, int kill_reason,
Suren Baghdasaryanf2081a92019-06-26 17:56:01 -07001880 const char *kill_desc, union meminfo *mi, struct timespec *tm) {
Colin Cross16b09462014-07-14 12:39:56 -07001881 int pid = procp->pid;
Suren Baghdasaryan11dc7342019-07-19 10:55:39 -07001882 int pidfd = procp->pidfd;
Colin Cross16b09462014-07-14 12:39:56 -07001883 uid_t uid = procp->uid;
Suren Baghdasaryan0082ef12019-07-02 15:52:07 -07001884 int tgid;
Colin Cross16b09462014-07-14 12:39:56 -07001885 char *taskname;
1886 int tasksize;
1887 int r;
Suren Baghdasaryan01063272018-10-12 11:28:33 -07001888 int result = -1;
Suren Baghdasaryanb72c6652019-09-04 19:12:29 -07001889 struct memory_stat *mem_st;
Suren Baghdasaryanca0790d2019-10-04 16:06:55 -07001890 char buf[LINE_MAX];
Rajeev Kumar70450032018-01-31 17:54:56 -08001891
Suren Baghdasaryan0082ef12019-07-02 15:52:07 -07001892 tgid = proc_get_tgid(pid);
1893 if (tgid >= 0 && tgid != pid) {
1894 ALOGE("Possible pid reuse detected (pid %d, tgid %d)!", pid, tgid);
1895 goto out;
1896 }
1897
Suren Baghdasaryanca0790d2019-10-04 16:06:55 -07001898 taskname = proc_get_name(pid, buf, sizeof(buf));
Colin Cross16b09462014-07-14 12:39:56 -07001899 if (!taskname) {
Suren Baghdasaryan01063272018-10-12 11:28:33 -07001900 goto out;
Colin Cross16b09462014-07-14 12:39:56 -07001901 }
1902
1903 tasksize = proc_get_size(pid);
1904 if (tasksize <= 0) {
Suren Baghdasaryan01063272018-10-12 11:28:33 -07001905 goto out;
Colin Cross16b09462014-07-14 12:39:56 -07001906 }
1907
Suren Baghdasaryanb72c6652019-09-04 19:12:29 -07001908 mem_st = stats_read_memory_stat(per_app_memcg, pid, uid);
Rajeev Kumar70450032018-01-31 17:54:56 -08001909
Suren Baghdasaryanc7135592018-01-04 10:43:58 -08001910 TRACE_KILL_START(pid);
1911
Mark Salyzyn64d97d82018-04-09 09:50:32 -07001912 /* CAP_KILL required */
Suren Baghdasaryan11dc7342019-07-19 10:55:39 -07001913 if (pidfd < 0) {
1914 start_wait_for_proc_kill(pid);
1915 r = kill(pid, SIGKILL);
1916 } else {
1917 start_wait_for_proc_kill(pidfd);
1918 r = sys_pidfd_send_signal(pidfd, SIGKILL, NULL, 0);
1919 }
Wei Wang2d95c102018-11-21 00:11:44 -08001920
Suren Baghdasaryance862df2019-09-04 16:44:47 -07001921 TRACE_KILL_END();
1922
1923 if (r) {
Suren Baghdasaryanf2081a92019-06-26 17:56:01 -07001924 stop_wait_for_proc_kill(false);
Suren Baghdasaryance862df2019-09-04 16:44:47 -07001925 ALOGE("kill(%d): errno=%d", pid, errno);
1926 /* Delete process record even when we fail to kill so that we don't get stuck on it */
1927 goto out;
1928 }
1929
Wei Wang2d95c102018-11-21 00:11:44 -08001930 set_process_group_and_prio(pid, SP_FOREGROUND, ANDROID_PRIORITY_HIGHEST);
1931
Suren Baghdasaryanf2081a92019-06-26 17:56:01 -07001932 last_kill_tm = *tm;
1933
Suren Baghdasaryand4a29902018-10-12 11:07:40 -07001934 inc_killcnt(procp->oomadj);
Suren Baghdasaryana7ac5782019-09-16 12:06:30 -07001935
1936 killinfo_log(procp, min_oom_score, tasksize, kill_reason, mi);
1937
1938 if (kill_desc) {
Suren Baghdasaryanfd7518f2019-07-15 15:50:17 -07001939 ALOGI("Kill '%s' (%d), uid %d, oom_adj %d to free %ldkB; reason: %s", taskname, pid,
Suren Baghdasaryana7ac5782019-09-16 12:06:30 -07001940 uid, procp->oomadj, tasksize * page_k, kill_desc);
Suren Baghdasaryanfd7518f2019-07-15 15:50:17 -07001941 } else {
1942 ALOGI("Kill '%s' (%d), uid %d, oom_adj %d to free %ldkB", taskname, pid,
1943 uid, procp->oomadj, tasksize * page_k);
1944 }
Colin Cross16b09462014-07-14 12:39:56 -07001945
Suren Baghdasaryanb72c6652019-09-04 19:12:29 -07001946 stats_write_lmk_kill_occurred(LMK_KILL_OCCURRED, uid, taskname,
1947 procp->oomadj, min_oom_score, tasksize, mem_st);
1948
Suren Baghdasaryance862df2019-09-04 16:44:47 -07001949 result = tasksize;
Mark Salyzyn919f5382018-02-04 15:27:23 -08001950
Suren Baghdasaryan01063272018-10-12 11:28:33 -07001951out:
1952 /*
1953 * WARNING: After pid_remove() procp is freed and can't be used!
1954 * Therefore placed at the end of the function.
1955 */
1956 pid_remove(pid);
1957 return result;
Colin Cross16b09462014-07-14 12:39:56 -07001958}
1959
1960/*
Suren Baghdasaryanf81b5f42018-10-26 11:32:15 -07001961 * Find one process to kill at or above the given oom_adj level.
1962 * Returns size of the killed process.
Colin Cross16b09462014-07-14 12:39:56 -07001963 */
Suren Baghdasaryana7ac5782019-09-16 12:06:30 -07001964static int find_and_kill_process(int min_score_adj, int kill_reason, const char *kill_desc,
Suren Baghdasaryanf2081a92019-06-26 17:56:01 -07001965 union meminfo *mi, struct timespec *tm) {
Colin Cross16b09462014-07-14 12:39:56 -07001966 int i;
Suren Baghdasaryanf81b5f42018-10-26 11:32:15 -07001967 int killed_size = 0;
Yang Lu5564f4e2018-05-15 04:59:44 +00001968 bool lmk_state_change_start = false;
Rajeev Kumar70450032018-01-31 17:54:56 -08001969
Chong Zhang0a4acdf2015-10-14 16:19:53 -07001970 for (i = OOM_SCORE_ADJ_MAX; i >= min_score_adj; i--) {
Colin Cross16b09462014-07-14 12:39:56 -07001971 struct proc *procp;
1972
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08001973 while (true) {
Suren Baghdasaryan818b59b2018-04-13 11:49:54 -07001974 procp = kill_heaviest_task ?
1975 proc_get_heaviest(i) : proc_adj_lru(i);
Colin Cross16b09462014-07-14 12:39:56 -07001976
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08001977 if (!procp)
1978 break;
1979
Suren Baghdasaryanf2081a92019-06-26 17:56:01 -07001980 killed_size = kill_one_process(procp, min_score_adj, kill_reason, kill_desc, mi, tm);
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08001981 if (killed_size >= 0) {
Suren Baghdasaryanb72c6652019-09-04 19:12:29 -07001982 if (!lmk_state_change_start) {
Yang Lu5564f4e2018-05-15 04:59:44 +00001983 lmk_state_change_start = true;
Suren Baghdasaryanb72c6652019-09-04 19:12:29 -07001984 stats_write_lmk_state_changed(LMK_STATE_CHANGED,
Yang Lu5564f4e2018-05-15 04:59:44 +00001985 LMK_STATE_CHANGE_START);
1986 }
Suren Baghdasaryanf81b5f42018-10-26 11:32:15 -07001987 break;
Colin Cross16b09462014-07-14 12:39:56 -07001988 }
1989 }
Suren Baghdasaryanf81b5f42018-10-26 11:32:15 -07001990 if (killed_size) {
1991 break;
1992 }
Colin Cross16b09462014-07-14 12:39:56 -07001993 }
1994
Suren Baghdasaryanb72c6652019-09-04 19:12:29 -07001995 if (lmk_state_change_start) {
1996 stats_write_lmk_state_changed(LMK_STATE_CHANGED, LMK_STATE_CHANGE_STOP);
Rajeev Kumar70450032018-01-31 17:54:56 -08001997 }
Rajeev Kumar70450032018-01-31 17:54:56 -08001998
Suren Baghdasaryanf81b5f42018-10-26 11:32:15 -07001999 return killed_size;
Colin Cross16b09462014-07-14 12:39:56 -07002000}
2001
Suren Baghdasaryan6499e5e2018-04-13 12:43:41 -07002002static int64_t get_memory_usage(struct reread_data *file_data) {
Robert Beneac47f2992017-08-21 15:18:31 -07002003 int ret;
2004 int64_t mem_usage;
Suren Baghdasaryana77b3272019-07-15 13:35:04 -07002005 char *buf;
Suren Baghdasaryan6499e5e2018-04-13 12:43:41 -07002006
Suren Baghdasaryana77b3272019-07-15 13:35:04 -07002007 if ((buf = reread_file(file_data)) == NULL) {
Robert Beneac47f2992017-08-21 15:18:31 -07002008 return -1;
2009 }
2010
Suren Baghdasaryan6499e5e2018-04-13 12:43:41 -07002011 if (!parse_int64(buf, &mem_usage)) {
2012 ALOGE("%s parse error", file_data->filename);
Robert Beneac47f2992017-08-21 15:18:31 -07002013 return -1;
2014 }
Robert Beneac47f2992017-08-21 15:18:31 -07002015 if (mem_usage == 0) {
2016 ALOGE("No memory!");
2017 return -1;
2018 }
2019 return mem_usage;
2020}
2021
Suren Baghdasaryan9926e572018-04-13 13:41:12 -07002022void record_low_pressure_levels(union meminfo *mi) {
2023 if (low_pressure_mem.min_nr_free_pages == -1 ||
2024 low_pressure_mem.min_nr_free_pages > mi->field.nr_free_pages) {
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08002025 if (debug_process_killing) {
Suren Baghdasaryan9926e572018-04-13 13:41:12 -07002026 ALOGI("Low pressure min memory update from %" PRId64 " to %" PRId64,
2027 low_pressure_mem.min_nr_free_pages, mi->field.nr_free_pages);
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08002028 }
Suren Baghdasaryan9926e572018-04-13 13:41:12 -07002029 low_pressure_mem.min_nr_free_pages = mi->field.nr_free_pages;
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08002030 }
2031 /*
2032 * Free memory at low vmpressure events occasionally gets spikes,
2033 * possibly a stale low vmpressure event with memory already
2034 * freed up (no memory pressure should have been reported).
Suren Baghdasaryan9926e572018-04-13 13:41:12 -07002035 * Ignore large jumps in max_nr_free_pages that would mess up our stats.
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08002036 */
Suren Baghdasaryan9926e572018-04-13 13:41:12 -07002037 if (low_pressure_mem.max_nr_free_pages == -1 ||
2038 (low_pressure_mem.max_nr_free_pages < mi->field.nr_free_pages &&
2039 mi->field.nr_free_pages - low_pressure_mem.max_nr_free_pages <
2040 low_pressure_mem.max_nr_free_pages * 0.1)) {
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08002041 if (debug_process_killing) {
Suren Baghdasaryan9926e572018-04-13 13:41:12 -07002042 ALOGI("Low pressure max memory update from %" PRId64 " to %" PRId64,
2043 low_pressure_mem.max_nr_free_pages, mi->field.nr_free_pages);
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08002044 }
Suren Baghdasaryan9926e572018-04-13 13:41:12 -07002045 low_pressure_mem.max_nr_free_pages = mi->field.nr_free_pages;
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08002046 }
2047}
2048
Suren Baghdasaryan96bf3a62017-12-08 12:58:52 -08002049enum vmpressure_level upgrade_level(enum vmpressure_level level) {
2050 return (enum vmpressure_level)((level < VMPRESS_LEVEL_CRITICAL) ?
2051 level + 1 : level);
2052}
2053
2054enum vmpressure_level downgrade_level(enum vmpressure_level level) {
2055 return (enum vmpressure_level)((level > VMPRESS_LEVEL_LOW) ?
2056 level - 1 : level);
2057}
2058
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002059enum zone_watermark {
2060 WMARK_MIN = 0,
2061 WMARK_LOW,
2062 WMARK_HIGH,
2063 WMARK_NONE
2064};
2065
Suren Baghdasaryan4787ab42019-08-14 09:48:35 -07002066struct zone_watermarks {
2067 long high_wmark;
2068 long low_wmark;
2069 long min_wmark;
2070};
2071
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002072/*
2073 * Returns lowest breached watermark or WMARK_NONE.
2074 */
Suren Baghdasaryan4787ab42019-08-14 09:48:35 -07002075static enum zone_watermark get_lowest_watermark(union meminfo *mi,
2076 struct zone_watermarks *watermarks)
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002077{
Suren Baghdasaryan4787ab42019-08-14 09:48:35 -07002078 int64_t nr_free_pages = mi->field.nr_free_pages - mi->field.cma_free;
2079
2080 if (nr_free_pages < watermarks->min_wmark) {
2081 return WMARK_MIN;
2082 }
2083 if (nr_free_pages < watermarks->low_wmark) {
2084 return WMARK_LOW;
2085 }
2086 if (nr_free_pages < watermarks->high_wmark) {
2087 return WMARK_HIGH;
2088 }
2089 return WMARK_NONE;
2090}
2091
2092void calc_zone_watermarks(struct zoneinfo *zi, struct zone_watermarks *watermarks) {
2093 memset(watermarks, 0, sizeof(struct zone_watermarks));
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002094
2095 for (int node_idx = 0; node_idx < zi->node_count; node_idx++) {
2096 struct zoneinfo_node *node = &zi->nodes[node_idx];
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002097 for (int zone_idx = 0; zone_idx < node->zone_count; zone_idx++) {
2098 struct zoneinfo_zone *zone = &node->zones[zone_idx];
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002099
2100 if (!zone->fields.field.present) {
2101 continue;
2102 }
2103
Suren Baghdasaryan4787ab42019-08-14 09:48:35 -07002104 watermarks->high_wmark += zone->max_protection + zone->fields.field.high;
2105 watermarks->low_wmark += zone->max_protection + zone->fields.field.low;
2106 watermarks->min_wmark += zone->max_protection + zone->fields.field.min;
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002107 }
2108 }
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002109}
2110
2111static void mp_event_psi(int data, uint32_t events, struct polling_params *poll_params) {
2112 enum kill_reasons {
2113 NONE = -1, /* To denote no kill condition */
2114 PRESSURE_AFTER_KILL = 0,
2115 NOT_RESPONDING,
2116 LOW_SWAP_AND_THRASHING,
2117 LOW_MEM_AND_SWAP,
2118 LOW_MEM_AND_THRASHING,
2119 DIRECT_RECL_AND_THRASHING,
2120 KILL_REASON_COUNT
2121 };
2122 enum reclaim_state {
2123 NO_RECLAIM = 0,
2124 KSWAPD_RECLAIM,
2125 DIRECT_RECLAIM,
2126 };
2127 static int64_t init_ws_refault;
2128 static int64_t base_file_lru;
2129 static int64_t init_pgscan_kswapd;
2130 static int64_t init_pgscan_direct;
2131 static int64_t swap_low_threshold;
2132 static bool killing;
2133 static int thrashing_limit;
2134 static bool in_reclaim;
Suren Baghdasaryan4787ab42019-08-14 09:48:35 -07002135 static struct zone_watermarks watermarks;
2136 static struct timespec wmark_update_tm;
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002137
2138 union meminfo mi;
2139 union vmstat vs;
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002140 struct timespec curr_tm;
2141 int64_t thrashing = 0;
2142 bool swap_is_low = false;
2143 enum vmpressure_level level = (enum vmpressure_level)data;
2144 enum kill_reasons kill_reason = NONE;
2145 bool cycle_after_kill = false;
2146 enum reclaim_state reclaim = NO_RECLAIM;
2147 enum zone_watermark wmark = WMARK_NONE;
Suren Baghdasaryanfd7518f2019-07-15 15:50:17 -07002148 char kill_desc[LINE_MAX];
Suren Baghdasaryan4b750882019-09-19 15:27:21 -07002149 bool cut_thrashing_limit = false;
2150 int min_score_adj = 0;
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002151
2152 /* Skip while still killing a process */
2153 if (is_kill_pending()) {
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002154 goto no_kill;
2155 }
Suren Baghdasaryanf2081a92019-06-26 17:56:01 -07002156 /*
2157 * Process is dead, stop waiting. This has no effect if pidfds are supported and
2158 * death notification already caused waiting to stop.
2159 */
2160 stop_wait_for_proc_kill(true);
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002161
2162 if (clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm) != 0) {
2163 ALOGE("Failed to get current time");
2164 return;
2165 }
2166
2167 if (vmstat_parse(&vs) < 0) {
2168 ALOGE("Failed to parse vmstat!");
2169 return;
2170 }
2171
2172 if (meminfo_parse(&mi) < 0) {
2173 ALOGE("Failed to parse meminfo!");
2174 return;
2175 }
2176
2177 /* Reset states after process got killed */
2178 if (killing) {
2179 killing = false;
2180 cycle_after_kill = true;
2181 /* Reset file-backed pagecache size and refault amounts after a kill */
2182 base_file_lru = vs.field.nr_inactive_file + vs.field.nr_active_file;
2183 init_ws_refault = vs.field.workingset_refault;
2184 }
2185
2186 /* Check free swap levels */
2187 if (swap_free_low_percentage) {
2188 if (!swap_low_threshold) {
2189 swap_low_threshold = mi.field.total_swap * swap_free_low_percentage / 100;
2190 }
2191 swap_is_low = mi.field.free_swap < swap_low_threshold;
2192 }
2193
2194 /* Identify reclaim state */
2195 if (vs.field.pgscan_direct > init_pgscan_direct) {
2196 init_pgscan_direct = vs.field.pgscan_direct;
2197 init_pgscan_kswapd = vs.field.pgscan_kswapd;
2198 reclaim = DIRECT_RECLAIM;
2199 } else if (vs.field.pgscan_kswapd > init_pgscan_kswapd) {
2200 init_pgscan_kswapd = vs.field.pgscan_kswapd;
2201 reclaim = KSWAPD_RECLAIM;
2202 } else {
2203 in_reclaim = false;
2204 /* Skip if system is not reclaiming */
2205 goto no_kill;
2206 }
2207
2208 if (!in_reclaim) {
2209 /* Record file-backed pagecache size when entering reclaim cycle */
2210 base_file_lru = vs.field.nr_inactive_file + vs.field.nr_active_file;
2211 init_ws_refault = vs.field.workingset_refault;
2212 thrashing_limit = thrashing_limit_pct;
2213 } else {
2214 /* Calculate what % of the file-backed pagecache refaulted so far */
2215 thrashing = (vs.field.workingset_refault - init_ws_refault) * 100 / base_file_lru;
2216 }
2217 in_reclaim = true;
2218
Suren Baghdasaryan4787ab42019-08-14 09:48:35 -07002219 /*
2220 * Refresh watermarks once per min in case user updated one of the margins.
2221 * TODO: b/140521024 replace this periodic update with an API for AMS to notify LMKD
2222 * that zone watermarks were changed by the system software.
2223 */
2224 if (watermarks.high_wmark == 0 || get_time_diff_ms(&wmark_update_tm, &curr_tm) > 60000) {
2225 struct zoneinfo zi;
2226
2227 if (zoneinfo_parse(&zi) < 0) {
2228 ALOGE("Failed to parse zoneinfo!");
2229 return;
2230 }
2231
2232 calc_zone_watermarks(&zi, &watermarks);
2233 wmark_update_tm = curr_tm;
2234 }
2235
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002236 /* Find out which watermark is breached if any */
Suren Baghdasaryan4787ab42019-08-14 09:48:35 -07002237 wmark = get_lowest_watermark(&mi, &watermarks);
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002238
2239 /*
2240 * TODO: move this logic into a separate function
2241 * Decide if killing a process is necessary and record the reason
2242 */
2243 if (cycle_after_kill && wmark < WMARK_LOW) {
2244 /*
2245 * Prevent kills not freeing enough memory which might lead to OOM kill.
2246 * This might happen when a process is consuming memory faster than reclaim can
2247 * free even after a kill. Mostly happens when running memory stress tests.
2248 */
2249 kill_reason = PRESSURE_AFTER_KILL;
Suren Baghdasaryanfd7518f2019-07-15 15:50:17 -07002250 strncpy(kill_desc, "min watermark is breached even after kill", sizeof(kill_desc));
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002251 } else if (level == VMPRESS_LEVEL_CRITICAL && events != 0) {
2252 /*
2253 * Device is too busy reclaiming memory which might lead to ANR.
2254 * Critical level is triggered when PSI complete stall (all tasks are blocked because
2255 * of the memory congestion) breaches the configured threshold.
2256 */
2257 kill_reason = NOT_RESPONDING;
Suren Baghdasaryanfd7518f2019-07-15 15:50:17 -07002258 strncpy(kill_desc, "device is not responding", sizeof(kill_desc));
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002259 } else if (swap_is_low && thrashing > thrashing_limit_pct) {
2260 /* Page cache is thrashing while swap is low */
2261 kill_reason = LOW_SWAP_AND_THRASHING;
Suren Baghdasaryanfd7518f2019-07-15 15:50:17 -07002262 snprintf(kill_desc, sizeof(kill_desc), "device is low on swap (%" PRId64
2263 "kB < %" PRId64 "kB) and thrashing (%" PRId64 "%%)",
2264 mi.field.free_swap * page_k, swap_low_threshold * page_k, thrashing);
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002265 } else if (swap_is_low && wmark < WMARK_HIGH) {
2266 /* Both free memory and swap are low */
2267 kill_reason = LOW_MEM_AND_SWAP;
Suren Baghdasaryanfd7518f2019-07-15 15:50:17 -07002268 snprintf(kill_desc, sizeof(kill_desc), "%s watermark is breached and swap is low (%"
2269 PRId64 "kB < %" PRId64 "kB)", wmark > WMARK_LOW ? "min" : "low",
2270 mi.field.free_swap * page_k, swap_low_threshold * page_k);
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002271 } else if (wmark < WMARK_HIGH && thrashing > thrashing_limit) {
2272 /* Page cache is thrashing while memory is low */
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002273 kill_reason = LOW_MEM_AND_THRASHING;
Suren Baghdasaryanfd7518f2019-07-15 15:50:17 -07002274 snprintf(kill_desc, sizeof(kill_desc), "%s watermark is breached and thrashing (%"
2275 PRId64 "%%)", wmark > WMARK_LOW ? "min" : "low", thrashing);
Suren Baghdasaryan4b750882019-09-19 15:27:21 -07002276 cut_thrashing_limit = true;
2277 /* Do not kill perceptible apps because of thrashing */
2278 min_score_adj = PERCEPTIBLE_APP_ADJ;
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002279 } else if (reclaim == DIRECT_RECLAIM && thrashing > thrashing_limit) {
2280 /* Page cache is thrashing while in direct reclaim (mostly happens on lowram devices) */
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002281 kill_reason = DIRECT_RECL_AND_THRASHING;
Suren Baghdasaryanfd7518f2019-07-15 15:50:17 -07002282 snprintf(kill_desc, sizeof(kill_desc), "device is in direct reclaim and thrashing (%"
2283 PRId64 "%%)", thrashing);
Suren Baghdasaryan4b750882019-09-19 15:27:21 -07002284 cut_thrashing_limit = true;
2285 /* Do not kill perceptible apps because of thrashing */
2286 min_score_adj = PERCEPTIBLE_APP_ADJ;
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002287 }
2288
2289 /* Kill a process if necessary */
2290 if (kill_reason != NONE) {
Suren Baghdasaryanf2081a92019-06-26 17:56:01 -07002291 int pages_freed = find_and_kill_process(min_score_adj, kill_reason, kill_desc, &mi,
2292 &curr_tm);
Suren Baghdasaryan4b750882019-09-19 15:27:21 -07002293 if (pages_freed > 0) {
2294 killing = true;
2295 if (cut_thrashing_limit) {
2296 /*
2297 * Cut thrasing limit by thrashing_limit_decay_pct percentage of the current
2298 * thrashing limit until the system stops thrashing.
2299 */
2300 thrashing_limit = (thrashing_limit * (100 - thrashing_limit_decay_pct)) / 100;
2301 }
2302 }
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002303 }
2304
2305no_kill:
Suren Baghdasaryanf2081a92019-06-26 17:56:01 -07002306 /* Do not poll if kernel supports pidfd waiting */
2307 if (is_waiting_for_kill()) {
2308 /* Pause polling if we are waiting for process death notification */
2309 poll_params->update = POLLING_PAUSE;
2310 return;
2311 }
2312
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002313 /*
2314 * Start polling after initial PSI event;
2315 * extend polling while device is in direct reclaim or process is being killed;
2316 * do not extend when kswapd reclaims because that might go on for a long time
2317 * without causing memory pressure
2318 */
2319 if (events || killing || reclaim == DIRECT_RECLAIM) {
2320 poll_params->update = POLLING_START;
2321 }
2322
2323 /* Decide the polling interval */
2324 if (swap_is_low || killing) {
2325 /* Fast polling during and after a kill or when swap is low */
2326 poll_params->polling_interval_ms = PSI_POLL_PERIOD_SHORT_MS;
2327 } else {
2328 /* By default use long intervals */
2329 poll_params->polling_interval_ms = PSI_POLL_PERIOD_LONG_MS;
2330 }
2331}
2332
Suren Baghdasaryanef3650f2019-07-15 14:50:49 -07002333static void mp_event_common(int data, uint32_t events, struct polling_params *poll_params) {
Todd Poynor3948f802013-07-09 19:35:14 -07002334 int ret;
2335 unsigned long long evcount;
Robert Beneac47f2992017-08-21 15:18:31 -07002336 int64_t mem_usage, memsw_usage;
Robert Benea6e8e7102017-09-13 15:20:30 -07002337 int64_t mem_pressure;
Suren Baghdasaryane82e15c2018-01-04 09:16:21 -08002338 enum vmpressure_level lvl;
Suren Baghdasaryan9926e572018-04-13 13:41:12 -07002339 union meminfo mi;
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07002340 struct zoneinfo zi;
Suren Baghdasaryan36934412018-09-05 15:46:32 -07002341 struct timespec curr_tm;
Suren Baghdasaryan314a5052018-07-24 17:13:06 -07002342 static unsigned long kill_skip_count = 0;
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08002343 enum vmpressure_level level = (enum vmpressure_level)data;
Suren Baghdasaryanffdc4dd2018-04-13 13:53:43 -07002344 long other_free = 0, other_file = 0;
2345 int min_score_adj;
Suren Baghdasaryanffdc4dd2018-04-13 13:53:43 -07002346 int minfree = 0;
Suren Baghdasaryan6499e5e2018-04-13 12:43:41 -07002347 static struct reread_data mem_usage_file_data = {
2348 .filename = MEMCG_MEMORY_USAGE,
2349 .fd = -1,
2350 };
2351 static struct reread_data memsw_usage_file_data = {
2352 .filename = MEMCG_MEMORYSW_USAGE,
2353 .fd = -1,
2354 };
Todd Poynor3948f802013-07-09 19:35:14 -07002355
Suren Baghdasaryan77122e52019-01-08 12:54:48 -08002356 if (debug_process_killing) {
2357 ALOGI("%s memory pressure event is triggered", level_name[level]);
2358 }
2359
2360 if (!use_psi_monitors) {
2361 /*
2362 * Check all event counters from low to critical
2363 * and upgrade to the highest priority one. By reading
2364 * eventfd we also reset the event counters.
2365 */
2366 for (lvl = VMPRESS_LEVEL_LOW; lvl < VMPRESS_LEVEL_COUNT; lvl++) {
2367 if (mpevfd[lvl] != -1 &&
2368 TEMP_FAILURE_RETRY(read(mpevfd[lvl],
2369 &evcount, sizeof(evcount))) > 0 &&
2370 evcount > 0 && lvl > level) {
2371 level = lvl;
2372 }
Suren Baghdasaryane82e15c2018-01-04 09:16:21 -08002373 }
2374 }
Todd Poynor3948f802013-07-09 19:35:14 -07002375
Suren Baghdasaryanef3650f2019-07-15 14:50:49 -07002376 /* Start polling after initial PSI event */
2377 if (use_psi_monitors && events) {
2378 /* Override polling params only if current event is more critical */
2379 if (!poll_params->poll_handler || data > poll_params->poll_handler->data) {
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002380 poll_params->polling_interval_ms = PSI_POLL_PERIOD_SHORT_MS;
Suren Baghdasaryanef3650f2019-07-15 14:50:49 -07002381 poll_params->update = POLLING_START;
2382 }
2383 }
2384
Suren Baghdasaryan36934412018-09-05 15:46:32 -07002385 if (clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm) != 0) {
2386 ALOGE("Failed to get current time");
2387 return;
2388 }
2389
Suren Baghdasaryanf2081a92019-06-26 17:56:01 -07002390 if (kill_timeout_ms && get_time_diff_ms(&last_kill_tm, &curr_tm) < kill_timeout_ms) {
2391 /*
2392 * If we're within the no-kill timeout, see if there's pending reclaim work
2393 * from the last killed process. If so, skip killing for now.
2394 */
2395 if (is_kill_pending()) {
Suren Baghdasaryan314a5052018-07-24 17:13:06 -07002396 kill_skip_count++;
Suren Baghdasaryancaa2dc52018-01-17 17:28:01 -08002397 return;
2398 }
Suren Baghdasaryanf2081a92019-06-26 17:56:01 -07002399 /*
2400 * Process is dead, stop waiting. This has no effect if pidfds are supported and
2401 * death notification already caused waiting to stop.
2402 */
2403 stop_wait_for_proc_kill(true);
2404 } else {
2405 /*
2406 * Killing took longer than no-kill timeout. Stop waiting for the last process
2407 * to die because we are ready to kill again.
2408 */
2409 stop_wait_for_proc_kill(false);
Suren Baghdasaryancaa2dc52018-01-17 17:28:01 -08002410 }
2411
Suren Baghdasaryan314a5052018-07-24 17:13:06 -07002412 if (kill_skip_count > 0) {
Suren Baghdasaryanda88b242018-05-10 16:10:56 -07002413 ALOGI("%lu memory pressure events were skipped after a kill!",
Suren Baghdasaryan314a5052018-07-24 17:13:06 -07002414 kill_skip_count);
2415 kill_skip_count = 0;
Suren Baghdasaryancaa2dc52018-01-17 17:28:01 -08002416 }
2417
Suren Baghdasaryanffdc4dd2018-04-13 13:53:43 -07002418 if (meminfo_parse(&mi) < 0 || zoneinfo_parse(&zi) < 0) {
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08002419 ALOGE("Failed to get free memory!");
2420 return;
2421 }
2422
Suren Baghdasaryanffdc4dd2018-04-13 13:53:43 -07002423 if (use_minfree_levels) {
2424 int i;
2425
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07002426 other_free = mi.field.nr_free_pages - zi.totalreserve_pages;
Suren Baghdasaryanffdc4dd2018-04-13 13:53:43 -07002427 if (mi.field.nr_file_pages > (mi.field.shmem + mi.field.unevictable + mi.field.swap_cached)) {
2428 other_file = (mi.field.nr_file_pages - mi.field.shmem -
2429 mi.field.unevictable - mi.field.swap_cached);
2430 } else {
2431 other_file = 0;
2432 }
2433
2434 min_score_adj = OOM_SCORE_ADJ_MAX + 1;
2435 for (i = 0; i < lowmem_targets_size; i++) {
2436 minfree = lowmem_minfree[i];
2437 if (other_free < minfree && other_file < minfree) {
2438 min_score_adj = lowmem_adj[i];
2439 break;
2440 }
2441 }
2442
Suren Baghdasaryan20686f02018-05-18 14:42:00 -07002443 if (min_score_adj == OOM_SCORE_ADJ_MAX + 1) {
2444 if (debug_process_killing) {
2445 ALOGI("Ignore %s memory pressure event "
2446 "(free memory=%ldkB, cache=%ldkB, limit=%ldkB)",
2447 level_name[level], other_free * page_k, other_file * page_k,
2448 (long)lowmem_minfree[lowmem_targets_size - 1] * page_k);
2449 }
Suren Baghdasaryanffdc4dd2018-04-13 13:53:43 -07002450 return;
Suren Baghdasaryan20686f02018-05-18 14:42:00 -07002451 }
Suren Baghdasaryanffdc4dd2018-04-13 13:53:43 -07002452
Suren Baghdasaryanffdc4dd2018-04-13 13:53:43 -07002453 goto do_kill;
2454 }
2455
Suren Baghdasaryan9926e572018-04-13 13:41:12 -07002456 if (level == VMPRESS_LEVEL_LOW) {
2457 record_low_pressure_levels(&mi);
2458 }
2459
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08002460 if (level_oomadj[level] > OOM_SCORE_ADJ_MAX) {
2461 /* Do not monitor this pressure level */
2462 return;
2463 }
2464
Suren Baghdasaryan6499e5e2018-04-13 12:43:41 -07002465 if ((mem_usage = get_memory_usage(&mem_usage_file_data)) < 0) {
2466 goto do_kill;
2467 }
2468 if ((memsw_usage = get_memory_usage(&memsw_usage_file_data)) < 0) {
Suren Baghdasaryan96bf3a62017-12-08 12:58:52 -08002469 goto do_kill;
Robert Benea6e8e7102017-09-13 15:20:30 -07002470 }
Robert Beneac47f2992017-08-21 15:18:31 -07002471
Robert Benea6e8e7102017-09-13 15:20:30 -07002472 // Calculate percent for swappinness.
2473 mem_pressure = (mem_usage * 100) / memsw_usage;
2474
Suren Baghdasaryan96bf3a62017-12-08 12:58:52 -08002475 if (enable_pressure_upgrade && level != VMPRESS_LEVEL_CRITICAL) {
Robert Benea6e8e7102017-09-13 15:20:30 -07002476 // We are swapping too much.
2477 if (mem_pressure < upgrade_pressure) {
Suren Baghdasaryan96bf3a62017-12-08 12:58:52 -08002478 level = upgrade_level(level);
2479 if (debug_process_killing) {
2480 ALOGI("Event upgraded to %s", level_name[level]);
2481 }
Robert Beneac47f2992017-08-21 15:18:31 -07002482 }
2483 }
2484
Vic Yang360a1132018-08-07 10:18:22 -07002485 // If we still have enough swap space available, check if we want to
2486 // ignore/downgrade pressure events.
2487 if (mi.field.free_swap >=
2488 mi.field.total_swap * swap_free_low_percentage / 100) {
2489 // If the pressure is larger than downgrade_pressure lmk will not
2490 // kill any process, since enough memory is available.
2491 if (mem_pressure > downgrade_pressure) {
2492 if (debug_process_killing) {
2493 ALOGI("Ignore %s memory pressure", level_name[level]);
2494 }
2495 return;
2496 } else if (level == VMPRESS_LEVEL_CRITICAL && mem_pressure > upgrade_pressure) {
2497 if (debug_process_killing) {
2498 ALOGI("Downgrade critical memory pressure");
2499 }
2500 // Downgrade event, since enough memory available.
2501 level = downgrade_level(level);
Robert Benea6e8e7102017-09-13 15:20:30 -07002502 }
Robert Benea6e8e7102017-09-13 15:20:30 -07002503 }
2504
Suren Baghdasaryan96bf3a62017-12-08 12:58:52 -08002505do_kill:
Suren Baghdasaryanff61afb2018-04-13 11:45:38 -07002506 if (low_ram_device) {
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08002507 /* For Go devices kill only one task */
Suren Baghdasaryanf2081a92019-06-26 17:56:01 -07002508 if (find_and_kill_process(level_oomadj[level], -1, NULL, &mi, &curr_tm) == 0) {
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08002509 if (debug_process_killing) {
2510 ALOGI("Nothing to kill");
2511 }
2512 }
2513 } else {
Suren Baghdasaryanffdc4dd2018-04-13 13:53:43 -07002514 int pages_freed;
Suren Baghdasaryan36934412018-09-05 15:46:32 -07002515 static struct timespec last_report_tm;
2516 static unsigned long report_skip_count = 0;
Suren Baghdasaryanffdc4dd2018-04-13 13:53:43 -07002517
2518 if (!use_minfree_levels) {
Suren Baghdasaryanffdc4dd2018-04-13 13:53:43 -07002519 /* Free up enough memory to downgrate the memory pressure to low level */
Suren Baghdasaryanf81b5f42018-10-26 11:32:15 -07002520 if (mi.field.nr_free_pages >= low_pressure_mem.max_nr_free_pages) {
Suren Baghdasaryanffdc4dd2018-04-13 13:53:43 -07002521 if (debug_process_killing) {
2522 ALOGI("Ignoring pressure since more memory is "
2523 "available (%" PRId64 ") than watermark (%" PRId64 ")",
2524 mi.field.nr_free_pages, low_pressure_mem.max_nr_free_pages);
2525 }
2526 return;
2527 }
2528 min_score_adj = level_oomadj[level];
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08002529 }
2530
Suren Baghdasaryanf2081a92019-06-26 17:56:01 -07002531 pages_freed = find_and_kill_process(min_score_adj, -1, NULL, &mi, &curr_tm);
Suren Baghdasaryanda88b242018-05-10 16:10:56 -07002532
Suren Baghdasaryan36934412018-09-05 15:46:32 -07002533 if (pages_freed == 0) {
2534 /* Rate limit kill reports when nothing was reclaimed */
2535 if (get_time_diff_ms(&last_report_tm, &curr_tm) < FAIL_REPORT_RLIMIT_MS) {
2536 report_skip_count++;
Suren Baghdasaryan314a5052018-07-24 17:13:06 -07002537 return;
2538 }
Robert Beneacaeaa652017-08-11 16:03:20 -07002539 }
Suren Baghdasaryan36934412018-09-05 15:46:32 -07002540
Suren Baghdasaryana7ac5782019-09-16 12:06:30 -07002541 /* Log whenever we kill or when report rate limit allows */
Suren Baghdasaryan36934412018-09-05 15:46:32 -07002542 if (use_minfree_levels) {
Suren Baghdasaryanf81b5f42018-10-26 11:32:15 -07002543 ALOGI("Reclaimed %ldkB, cache(%ldkB) and "
Suren Baghdasaryan36934412018-09-05 15:46:32 -07002544 "free(%" PRId64 "kB)-reserved(%" PRId64 "kB) below min(%ldkB) for oom_adj %d",
Suren Baghdasaryanf81b5f42018-10-26 11:32:15 -07002545 pages_freed * page_k,
Suren Baghdasaryan36934412018-09-05 15:46:32 -07002546 other_file * page_k, mi.field.nr_free_pages * page_k,
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07002547 zi.totalreserve_pages * page_k,
Suren Baghdasaryan36934412018-09-05 15:46:32 -07002548 minfree * page_k, min_score_adj);
2549 } else {
Suren Baghdasaryanf81b5f42018-10-26 11:32:15 -07002550 ALOGI("Reclaimed %ldkB at oom_adj %d",
2551 pages_freed * page_k, min_score_adj);
Suren Baghdasaryan36934412018-09-05 15:46:32 -07002552 }
2553
2554 if (report_skip_count > 0) {
2555 ALOGI("Suppressed %lu failed kill reports", report_skip_count);
2556 report_skip_count = 0;
2557 }
2558
2559 last_report_tm = curr_tm;
Colin Crossf8857cc2014-07-11 17:16:56 -07002560 }
Suren Baghdasaryanf2081a92019-06-26 17:56:01 -07002561 if (is_waiting_for_kill()) {
2562 /* pause polling if we are waiting for process death notification */
2563 poll_params->update = POLLING_PAUSE;
2564 }
Todd Poynor3948f802013-07-09 19:35:14 -07002565}
2566
Suren Baghdasaryan844f26b2019-07-15 15:42:09 -07002567static bool init_mp_psi(enum vmpressure_level level, bool use_new_strategy) {
2568 int fd;
2569
2570 /* Do not register a handler if threshold_ms is not set */
2571 if (!psi_thresholds[level].threshold_ms) {
2572 return true;
2573 }
2574
2575 fd = init_psi_monitor(psi_thresholds[level].stall_type,
Suren Baghdasaryan77122e52019-01-08 12:54:48 -08002576 psi_thresholds[level].threshold_ms * US_PER_MS,
2577 PSI_WINDOW_SIZE_MS * US_PER_MS);
2578
2579 if (fd < 0) {
2580 return false;
2581 }
2582
Suren Baghdasaryan844f26b2019-07-15 15:42:09 -07002583 vmpressure_hinfo[level].handler = use_new_strategy ? mp_event_psi : mp_event_common;
Suren Baghdasaryan77122e52019-01-08 12:54:48 -08002584 vmpressure_hinfo[level].data = level;
2585 if (register_psi_monitor(epollfd, fd, &vmpressure_hinfo[level]) < 0) {
2586 destroy_psi_monitor(fd);
2587 return false;
2588 }
2589 maxevents++;
2590 mpevfd[level] = fd;
2591
2592 return true;
2593}
2594
2595static void destroy_mp_psi(enum vmpressure_level level) {
2596 int fd = mpevfd[level];
2597
2598 if (unregister_psi_monitor(epollfd, fd) < 0) {
2599 ALOGE("Failed to unregister psi monitor for %s memory pressure; errno=%d",
2600 level_name[level], errno);
2601 }
2602 destroy_psi_monitor(fd);
2603 mpevfd[level] = -1;
2604}
2605
2606static bool init_psi_monitors() {
Suren Baghdasaryan844f26b2019-07-15 15:42:09 -07002607 /*
2608 * When PSI is used on low-ram devices or on high-end devices without memfree levels
2609 * use new kill strategy based on zone watermarks, free swap and thrashing stats
2610 */
2611 bool use_new_strategy =
2612 property_get_bool("ro.lmk.use_new_strategy", low_ram_device || !use_minfree_levels);
2613
2614 /* In default PSI mode override stall amounts using system properties */
2615 if (use_new_strategy) {
2616 /* Do not use low pressure level */
2617 psi_thresholds[VMPRESS_LEVEL_LOW].threshold_ms = 0;
2618 psi_thresholds[VMPRESS_LEVEL_MEDIUM].threshold_ms = psi_partial_stall_ms;
2619 psi_thresholds[VMPRESS_LEVEL_CRITICAL].threshold_ms = psi_complete_stall_ms;
2620 }
2621
2622 if (!init_mp_psi(VMPRESS_LEVEL_LOW, use_new_strategy)) {
Suren Baghdasaryan77122e52019-01-08 12:54:48 -08002623 return false;
2624 }
Suren Baghdasaryan844f26b2019-07-15 15:42:09 -07002625 if (!init_mp_psi(VMPRESS_LEVEL_MEDIUM, use_new_strategy)) {
Suren Baghdasaryan77122e52019-01-08 12:54:48 -08002626 destroy_mp_psi(VMPRESS_LEVEL_LOW);
2627 return false;
2628 }
Suren Baghdasaryan844f26b2019-07-15 15:42:09 -07002629 if (!init_mp_psi(VMPRESS_LEVEL_CRITICAL, use_new_strategy)) {
Suren Baghdasaryan77122e52019-01-08 12:54:48 -08002630 destroy_mp_psi(VMPRESS_LEVEL_MEDIUM);
2631 destroy_mp_psi(VMPRESS_LEVEL_LOW);
2632 return false;
2633 }
2634 return true;
2635}
2636
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08002637static bool init_mp_common(enum vmpressure_level level) {
Todd Poynor3948f802013-07-09 19:35:14 -07002638 int mpfd;
2639 int evfd;
2640 int evctlfd;
2641 char buf[256];
2642 struct epoll_event epev;
2643 int ret;
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08002644 int level_idx = (int)level;
2645 const char *levelstr = level_name[level_idx];
Suren Baghdasaryan96bf3a62017-12-08 12:58:52 -08002646
Mark Salyzyn64d97d82018-04-09 09:50:32 -07002647 /* gid containing AID_SYSTEM required */
Nick Kralevichc68c8862015-12-18 20:52:37 -08002648 mpfd = open(MEMCG_SYSFS_PATH "memory.pressure_level", O_RDONLY | O_CLOEXEC);
Todd Poynor3948f802013-07-09 19:35:14 -07002649 if (mpfd < 0) {
2650 ALOGI("No kernel memory.pressure_level support (errno=%d)", errno);
2651 goto err_open_mpfd;
2652 }
2653
Nick Kralevichc68c8862015-12-18 20:52:37 -08002654 evctlfd = open(MEMCG_SYSFS_PATH "cgroup.event_control", O_WRONLY | O_CLOEXEC);
Todd Poynor3948f802013-07-09 19:35:14 -07002655 if (evctlfd < 0) {
2656 ALOGI("No kernel memory cgroup event control (errno=%d)", errno);
2657 goto err_open_evctlfd;
2658 }
2659
Nick Kralevichc68c8862015-12-18 20:52:37 -08002660 evfd = eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC);
Todd Poynor3948f802013-07-09 19:35:14 -07002661 if (evfd < 0) {
2662 ALOGE("eventfd failed for level %s; errno=%d", levelstr, errno);
2663 goto err_eventfd;
2664 }
2665
2666 ret = snprintf(buf, sizeof(buf), "%d %d %s", evfd, mpfd, levelstr);
2667 if (ret >= (ssize_t)sizeof(buf)) {
2668 ALOGE("cgroup.event_control line overflow for level %s", levelstr);
2669 goto err;
2670 }
2671
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08002672 ret = TEMP_FAILURE_RETRY(write(evctlfd, buf, strlen(buf) + 1));
Todd Poynor3948f802013-07-09 19:35:14 -07002673 if (ret == -1) {
2674 ALOGE("cgroup.event_control write failed for level %s; errno=%d",
2675 levelstr, errno);
2676 goto err;
2677 }
2678
2679 epev.events = EPOLLIN;
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08002680 /* use data to store event level */
2681 vmpressure_hinfo[level_idx].data = level_idx;
2682 vmpressure_hinfo[level_idx].handler = mp_event_common;
2683 epev.data.ptr = (void *)&vmpressure_hinfo[level_idx];
Todd Poynor3948f802013-07-09 19:35:14 -07002684 ret = epoll_ctl(epollfd, EPOLL_CTL_ADD, evfd, &epev);
2685 if (ret == -1) {
2686 ALOGE("epoll_ctl for level %s failed; errno=%d", levelstr, errno);
2687 goto err;
2688 }
2689 maxevents++;
Suren Baghdasaryan96bf3a62017-12-08 12:58:52 -08002690 mpevfd[level] = evfd;
Suren Baghdasaryan1bd2fc42018-01-04 08:54:53 -08002691 close(evctlfd);
Suren Baghdasaryan96bf3a62017-12-08 12:58:52 -08002692 return true;
Todd Poynor3948f802013-07-09 19:35:14 -07002693
2694err:
2695 close(evfd);
2696err_eventfd:
2697 close(evctlfd);
2698err_open_evctlfd:
2699 close(mpfd);
2700err_open_mpfd:
Suren Baghdasaryan96bf3a62017-12-08 12:58:52 -08002701 return false;
Robert Benea673e2762017-06-01 16:32:31 -07002702}
2703
Suren Baghdasaryanb72c6652019-09-04 19:12:29 -07002704static void kernel_event_handler(int data __unused, uint32_t events __unused,
2705 struct polling_params *poll_params __unused) {
2706 kpoll_info.handler(kpoll_info.poll_fd);
Jim Blackler3947c932019-04-26 11:18:29 +01002707}
2708
Todd Poynor3948f802013-07-09 19:35:14 -07002709static int init(void) {
Suren Baghdasaryanb72c6652019-09-04 19:12:29 -07002710 static struct event_handler_info kernel_poll_hinfo = { 0, kernel_event_handler };
Suren Baghdasaryana77b3272019-07-15 13:35:04 -07002711 struct reread_data file_data = {
2712 .filename = ZONEINFO_PATH,
2713 .fd = -1,
2714 };
Todd Poynor3948f802013-07-09 19:35:14 -07002715 struct epoll_event epev;
Suren Baghdasaryanf2081a92019-06-26 17:56:01 -07002716 int pidfd;
Todd Poynor3948f802013-07-09 19:35:14 -07002717 int i;
2718 int ret;
2719
2720 page_k = sysconf(_SC_PAGESIZE);
2721 if (page_k == -1)
2722 page_k = PAGE_SIZE;
2723 page_k /= 1024;
2724
2725 epollfd = epoll_create(MAX_EPOLL_EVENTS);
2726 if (epollfd == -1) {
2727 ALOGE("epoll_create failed (errno=%d)", errno);
2728 return -1;
2729 }
2730
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08002731 // mark data connections as not connected
2732 for (int i = 0; i < MAX_DATA_CONN; i++) {
2733 data_sock[i].sock = -1;
2734 }
2735
2736 ctrl_sock.sock = android_get_control_socket("lmkd");
2737 if (ctrl_sock.sock < 0) {
Todd Poynor3948f802013-07-09 19:35:14 -07002738 ALOGE("get lmkd control socket failed");
2739 return -1;
2740 }
2741
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08002742 ret = listen(ctrl_sock.sock, MAX_DATA_CONN);
Todd Poynor3948f802013-07-09 19:35:14 -07002743 if (ret < 0) {
2744 ALOGE("lmkd control socket listen failed (errno=%d)", errno);
2745 return -1;
2746 }
2747
2748 epev.events = EPOLLIN;
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08002749 ctrl_sock.handler_info.handler = ctrl_connect_handler;
2750 epev.data.ptr = (void *)&(ctrl_sock.handler_info);
2751 if (epoll_ctl(epollfd, EPOLL_CTL_ADD, ctrl_sock.sock, &epev) == -1) {
Todd Poynor3948f802013-07-09 19:35:14 -07002752 ALOGE("epoll_ctl for lmkd control socket failed (errno=%d)", errno);
2753 return -1;
2754 }
2755 maxevents++;
2756
Robert Benea164baeb2017-09-11 16:53:28 -07002757 has_inkernel_module = !access(INKERNEL_MINFREE_PATH, W_OK);
Suren Baghdasaryan979591b2018-01-18 17:27:30 -08002758 use_inkernel_interface = has_inkernel_module;
Todd Poynor3948f802013-07-09 19:35:14 -07002759
2760 if (use_inkernel_interface) {
2761 ALOGI("Using in-kernel low memory killer interface");
Suren Baghdasaryanb72c6652019-09-04 19:12:29 -07002762 if (init_poll_kernel(&kpoll_info)) {
2763 epev.events = EPOLLIN;
2764 epev.data.ptr = (void*)&kernel_poll_hinfo;
2765 if (epoll_ctl(epollfd, EPOLL_CTL_ADD, kpoll_info.poll_fd, &epev) != 0) {
2766 ALOGE("epoll_ctl for lmk events failed (errno=%d)", errno);
2767 close(kpoll_info.poll_fd);
2768 kpoll_info.poll_fd = -1;
2769 } else {
2770 maxevents++;
2771 }
Jim Blackler3947c932019-04-26 11:18:29 +01002772 }
Todd Poynor3948f802013-07-09 19:35:14 -07002773 } else {
Suren Baghdasaryan77122e52019-01-08 12:54:48 -08002774 /* Try to use psi monitor first if kernel has it */
2775 use_psi_monitors = property_get_bool("ro.lmk.use_psi", true) &&
2776 init_psi_monitors();
2777 /* Fall back to vmpressure */
2778 if (!use_psi_monitors &&
2779 (!init_mp_common(VMPRESS_LEVEL_LOW) ||
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08002780 !init_mp_common(VMPRESS_LEVEL_MEDIUM) ||
Suren Baghdasaryan77122e52019-01-08 12:54:48 -08002781 !init_mp_common(VMPRESS_LEVEL_CRITICAL))) {
Todd Poynor3948f802013-07-09 19:35:14 -07002782 ALOGE("Kernel does not support memory pressure events or in-kernel low memory killer");
Suren Baghdasaryan96bf3a62017-12-08 12:58:52 -08002783 return -1;
2784 }
Suren Baghdasaryan77122e52019-01-08 12:54:48 -08002785 if (use_psi_monitors) {
2786 ALOGI("Using psi monitors for memory pressure detection");
2787 } else {
2788 ALOGI("Using vmpressure for memory pressure detection");
2789 }
Todd Poynor3948f802013-07-09 19:35:14 -07002790 }
2791
Chong Zhang0a4acdf2015-10-14 16:19:53 -07002792 for (i = 0; i <= ADJTOSLOT(OOM_SCORE_ADJ_MAX); i++) {
Todd Poynor3948f802013-07-09 19:35:14 -07002793 procadjslot_list[i].next = &procadjslot_list[i];
2794 procadjslot_list[i].prev = &procadjslot_list[i];
2795 }
2796
Suren Baghdasaryand4a29902018-10-12 11:07:40 -07002797 memset(killcnt_idx, KILLCNT_INVALID_IDX, sizeof(killcnt_idx));
2798
Suren Baghdasaryana77b3272019-07-15 13:35:04 -07002799 /*
2800 * Read zoneinfo as the biggest file we read to create and size the initial
2801 * read buffer and avoid memory re-allocations during memory pressure
2802 */
2803 if (reread_file(&file_data) == NULL) {
2804 ALOGE("Failed to read %s: %s", file_data.filename, strerror(errno));
2805 }
2806
Suren Baghdasaryanf2081a92019-06-26 17:56:01 -07002807 /* check if kernel supports pidfd_open syscall */
2808 pidfd = TEMP_FAILURE_RETRY(sys_pidfd_open(getpid(), 0));
2809 if (pidfd < 0) {
2810 pidfd_supported = (errno != ENOSYS);
2811 } else {
2812 pidfd_supported = true;
2813 close(pidfd);
2814 }
2815 ALOGI("Process polling is %s", pidfd_supported ? "supported" : "not supported" );
2816
Todd Poynor3948f802013-07-09 19:35:14 -07002817 return 0;
2818}
2819
Suren Baghdasaryanf2081a92019-06-26 17:56:01 -07002820static void call_handler(struct event_handler_info* handler_info,
2821 struct polling_params *poll_params, uint32_t events) {
2822 struct timespec curr_tm;
2823
2824 handler_info->handler(handler_info->data, events, poll_params);
2825 clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm);
2826 poll_params->last_poll_tm = curr_tm;
2827
2828 switch (poll_params->update) {
2829 case POLLING_START:
2830 /*
2831 * Poll for the duration of PSI_WINDOW_SIZE_MS after the
2832 * initial PSI event because psi events are rate-limited
2833 * at one per sec.
2834 */
2835 poll_params->poll_start_tm = curr_tm;
Greg Kaiser5670fab2019-10-10 06:52:23 -07002836 poll_params->poll_handler = handler_info;
Suren Baghdasaryanf2081a92019-06-26 17:56:01 -07002837 break;
2838 case POLLING_STOP:
2839 poll_params->poll_handler = NULL;
2840 break;
2841 case POLLING_PAUSE:
2842 poll_params->paused_handler = handler_info;
2843 poll_params->poll_handler = NULL;
2844 break;
2845 case POLLING_RESUME:
2846 poll_params->poll_start_tm = curr_tm;
2847 poll_params->poll_handler = poll_params->paused_handler;
2848 break;
2849 case POLLING_DO_NOT_CHANGE:
2850 if (get_time_diff_ms(&poll_params->poll_start_tm, &curr_tm) > PSI_WINDOW_SIZE_MS) {
2851 /* Polled for the duration of PSI window, time to stop */
2852 poll_params->poll_handler = NULL;
2853 }
2854 /* WARNING: skipping the rest of the function */
2855 return;
2856 }
2857 poll_params->update = POLLING_DO_NOT_CHANGE;
2858}
2859
Todd Poynor3948f802013-07-09 19:35:14 -07002860static void mainloop(void) {
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08002861 struct event_handler_info* handler_info;
Suren Baghdasaryanef3650f2019-07-15 14:50:49 -07002862 struct polling_params poll_params;
2863 struct timespec curr_tm;
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08002864 struct epoll_event *evt;
Suren Baghdasaryan77122e52019-01-08 12:54:48 -08002865 long delay = -1;
Suren Baghdasaryanef3650f2019-07-15 14:50:49 -07002866
2867 poll_params.poll_handler = NULL;
2868 poll_params.update = POLLING_DO_NOT_CHANGE;
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08002869
Todd Poynor3948f802013-07-09 19:35:14 -07002870 while (1) {
2871 struct epoll_event events[maxevents];
2872 int nevents;
2873 int i;
2874
Suren Baghdasaryanef3650f2019-07-15 14:50:49 -07002875 if (poll_params.poll_handler) {
Suren Baghdasaryanf2081a92019-06-26 17:56:01 -07002876 bool poll_now;
Suren Baghdasaryan77122e52019-01-08 12:54:48 -08002877
2878 clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm);
Suren Baghdasaryanf2081a92019-06-26 17:56:01 -07002879 if (poll_params.poll_handler == poll_params.paused_handler) {
2880 /*
2881 * Just transitioned into POLLING_RESUME. Reset paused_handler
2882 * and poll immediately
2883 */
2884 poll_params.paused_handler = NULL;
2885 poll_now = true;
2886 nevents = 0;
2887 } else {
2888 /* Calculate next timeout */
2889 delay = get_time_diff_ms(&poll_params.last_poll_tm, &curr_tm);
2890 delay = (delay < poll_params.polling_interval_ms) ?
2891 poll_params.polling_interval_ms - delay : poll_params.polling_interval_ms;
Suren Baghdasaryanef3650f2019-07-15 14:50:49 -07002892
Suren Baghdasaryanf2081a92019-06-26 17:56:01 -07002893 /* Wait for events until the next polling timeout */
2894 nevents = epoll_wait(epollfd, events, maxevents, delay);
2895
2896 /* Update current time after wait */
2897 clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm);
2898 poll_now = (get_time_diff_ms(&poll_params.last_poll_tm, &curr_tm) >=
2899 poll_params.polling_interval_ms);
2900 }
2901 if (poll_now) {
2902 call_handler(poll_params.poll_handler, &poll_params, 0);
Suren Baghdasaryan77122e52019-01-08 12:54:48 -08002903 }
2904 } else {
2905 /* Wait for events with no timeout */
2906 nevents = epoll_wait(epollfd, events, maxevents, -1);
2907 }
Todd Poynor3948f802013-07-09 19:35:14 -07002908
2909 if (nevents == -1) {
2910 if (errno == EINTR)
2911 continue;
2912 ALOGE("epoll_wait failed (errno=%d)", errno);
2913 continue;
2914 }
2915
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08002916 /*
2917 * First pass to see if any data socket connections were dropped.
2918 * Dropped connection should be handled before any other events
2919 * to deallocate data connection and correctly handle cases when
2920 * connection gets dropped and reestablished in the same epoll cycle.
2921 * In such cases it's essential to handle connection closures first.
2922 */
2923 for (i = 0, evt = &events[0]; i < nevents; ++i, evt++) {
2924 if ((evt->events & EPOLLHUP) && evt->data.ptr) {
2925 ALOGI("lmkd data connection dropped");
2926 handler_info = (struct event_handler_info*)evt->data.ptr;
2927 ctrl_data_close(handler_info->data);
2928 }
2929 }
2930
2931 /* Second pass to handle all other events */
2932 for (i = 0, evt = &events[0]; i < nevents; ++i, evt++) {
Suren Baghdasaryanef3650f2019-07-15 14:50:49 -07002933 if (evt->events & EPOLLERR) {
Todd Poynor3948f802013-07-09 19:35:14 -07002934 ALOGD("EPOLLERR on event #%d", i);
Suren Baghdasaryanef3650f2019-07-15 14:50:49 -07002935 }
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08002936 if (evt->events & EPOLLHUP) {
2937 /* This case was handled in the first pass */
2938 continue;
2939 }
2940 if (evt->data.ptr) {
2941 handler_info = (struct event_handler_info*)evt->data.ptr;
Suren Baghdasaryanf2081a92019-06-26 17:56:01 -07002942 call_handler(handler_info, &poll_params, evt->events);
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08002943 }
Todd Poynor3948f802013-07-09 19:35:14 -07002944 }
2945 }
2946}
2947
Mark Salyzyne6ed68b2014-04-30 13:36:35 -07002948int main(int argc __unused, char **argv __unused) {
Colin Cross1a0d9be2014-07-14 14:31:15 -07002949 struct sched_param param = {
2950 .sched_priority = 1,
2951 };
2952
Suren Baghdasaryan96bf3a62017-12-08 12:58:52 -08002953 /* By default disable low level vmpressure events */
2954 level_oomadj[VMPRESS_LEVEL_LOW] =
2955 property_get_int32("ro.lmk.low", OOM_SCORE_ADJ_MAX + 1);
2956 level_oomadj[VMPRESS_LEVEL_MEDIUM] =
2957 property_get_int32("ro.lmk.medium", 800);
2958 level_oomadj[VMPRESS_LEVEL_CRITICAL] =
2959 property_get_int32("ro.lmk.critical", 0);
Robert Beneacaeaa652017-08-11 16:03:20 -07002960 debug_process_killing = property_get_bool("ro.lmk.debug", false);
Suren Baghdasaryanad2fd912017-12-08 13:08:41 -08002961
2962 /* By default disable upgrade/downgrade logic */
2963 enable_pressure_upgrade =
2964 property_get_bool("ro.lmk.critical_upgrade", false);
2965 upgrade_pressure =
2966 (int64_t)property_get_int32("ro.lmk.upgrade_pressure", 100);
2967 downgrade_pressure =
2968 (int64_t)property_get_int32("ro.lmk.downgrade_pressure", 100);
Suren Baghdasaryan662492a2017-12-08 13:17:06 -08002969 kill_heaviest_task =
Suren Baghdasaryan818b59b2018-04-13 11:49:54 -07002970 property_get_bool("ro.lmk.kill_heaviest_task", false);
Suren Baghdasaryanff61afb2018-04-13 11:45:38 -07002971 low_ram_device = property_get_bool("ro.config.low_ram", false);
Suren Baghdasaryancaa2dc52018-01-17 17:28:01 -08002972 kill_timeout_ms =
2973 (unsigned long)property_get_int32("ro.lmk.kill_timeout_ms", 0);
Suren Baghdasaryanffdc4dd2018-04-13 13:53:43 -07002974 use_minfree_levels =
2975 property_get_bool("ro.lmk.use_minfree_levels", false);
Suren Baghdasaryance13cb52018-06-19 18:38:12 -07002976 per_app_memcg =
2977 property_get_bool("ro.config.per_app_memcg", low_ram_device);
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002978 swap_free_low_percentage = clamp(0, 100, property_get_int32("ro.lmk.swap_free_low_percentage",
2979 low_ram_device ? DEF_LOW_SWAP_LOWRAM : DEF_LOW_SWAP));
Suren Baghdasaryan844f26b2019-07-15 15:42:09 -07002980 psi_partial_stall_ms = property_get_int32("ro.lmk.psi_partial_stall_ms",
2981 low_ram_device ? DEF_PARTIAL_STALL_LOWRAM : DEF_PARTIAL_STALL);
2982 psi_complete_stall_ms = property_get_int32("ro.lmk.psi_complete_stall_ms",
2983 DEF_COMPLETE_STALL);
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002984 thrashing_limit_pct = max(0, property_get_int32("ro.lmk.thrashing_limit",
2985 low_ram_device ? DEF_THRASHING_LOWRAM : DEF_THRASHING));
2986 thrashing_limit_decay_pct = clamp(0, 100, property_get_int32("ro.lmk.thrashing_limit_decay",
2987 low_ram_device ? DEF_THRASHING_DECAY_LOWRAM : DEF_THRASHING_DECAY));
Robert Benea58891d52017-07-31 17:15:20 -07002988
Suren Baghdasaryana7ac5782019-09-16 12:06:30 -07002989 ctx = create_android_logger(KILLINFO_LOG_TAG);
Suren Baghdasaryan282ad1a2018-07-26 16:34:27 -07002990
Suren Baghdasaryanb72c6652019-09-04 19:12:29 -07002991 statslog_init();
Rajeev Kumar70450032018-01-31 17:54:56 -08002992
Mark Salyzyn721d7c72018-03-21 12:24:58 -07002993 if (!init()) {
2994 if (!use_inkernel_interface) {
2995 /*
2996 * MCL_ONFAULT pins pages as they fault instead of loading
2997 * everything immediately all at once. (Which would be bad,
2998 * because as of this writing, we have a lot of mapped pages we
2999 * never use.) Old kernels will see MCL_ONFAULT and fail with
3000 * EINVAL; we ignore this failure.
3001 *
3002 * N.B. read the man page for mlockall. MCL_CURRENT | MCL_ONFAULT
3003 * pins ⊆ MCL_CURRENT, converging to just MCL_CURRENT as we fault
3004 * in pages.
3005 */
Mark Salyzyn64d97d82018-04-09 09:50:32 -07003006 /* CAP_IPC_LOCK required */
Mark Salyzyn721d7c72018-03-21 12:24:58 -07003007 if (mlockall(MCL_CURRENT | MCL_FUTURE | MCL_ONFAULT) && (errno != EINVAL)) {
3008 ALOGW("mlockall failed %s", strerror(errno));
3009 }
Daniel Colascione4dd5d002018-01-03 12:01:02 -08003010
Mark Salyzyn64d97d82018-04-09 09:50:32 -07003011 /* CAP_NICE required */
3012 if (sched_setscheduler(0, SCHED_FIFO, &param)) {
3013 ALOGW("set SCHED_FIFO failed %s", strerror(errno));
3014 }
Mark Salyzyn721d7c72018-03-21 12:24:58 -07003015 }
3016
Todd Poynor3948f802013-07-09 19:35:14 -07003017 mainloop();
Mark Salyzyn721d7c72018-03-21 12:24:58 -07003018 }
Todd Poynor3948f802013-07-09 19:35:14 -07003019
Suren Baghdasaryanb72c6652019-09-04 19:12:29 -07003020 statslog_destroy();
Rajeev Kumar70450032018-01-31 17:54:56 -08003021
Suren Baghdasaryan282ad1a2018-07-26 16:34:27 -07003022 android_log_destroy(&ctx);
3023
Todd Poynor3948f802013-07-09 19:35:14 -07003024 ALOGI("exiting");
3025 return 0;
3026}