blob: 1edd77223e93f17e8fa90351483898b8b029c2f4 [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
879static void cmd_procprio(LMKD_CTRL_PACKET packet, 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 Baghdasaryan0f100512018-01-24 16:51:41 -0800889 lmkd_pack_get_procprio(packet, &params);
890
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 Baghdasaryan0082ef12019-07-02 15:52:07 -0700897 /* Check if registered process is a thread group leader */
898 tgid = proc_get_tgid(params.pid);
899 if (tgid >= 0 && tgid != params.pid) {
900 ALOGE("Attempt to register a task that is not a thread group leader (tid %d, tgid %d)",
901 params.pid, tgid);
902 return;
903 }
904
Mark Salyzyn64d97d82018-04-09 09:50:32 -0700905 /* gid containing AID_READPROC required */
906 /* CAP_SYS_RESOURCE required */
907 /* CAP_DAC_OVERRIDE required */
Suren Baghdasaryan0f100512018-01-24 16:51:41 -0800908 snprintf(path, sizeof(path), "/proc/%d/oom_score_adj", params.pid);
909 snprintf(val, sizeof(val), "%d", params.oomadj);
Suren Baghdasaryan1ffa2462018-03-20 13:53:17 -0700910 if (!writefilestring(path, val, false)) {
911 ALOGW("Failed to open %s; errno=%d: process %d might have been killed",
912 path, errno, params.pid);
913 /* If this file does not exist the process is dead. */
914 return;
915 }
Todd Poynor3948f802013-07-09 19:35:14 -0700916
Mark Salyzyn721d7c72018-03-21 12:24:58 -0700917 if (use_inkernel_interface) {
Suren Baghdasaryanca0790d2019-10-04 16:06:55 -0700918 stats_store_taskname(params.pid, proc_get_name(params.pid, path, sizeof(path)),
919 kpoll_info.poll_fd);
Todd Poynor3948f802013-07-09 19:35:14 -0700920 return;
Mark Salyzyn721d7c72018-03-21 12:24:58 -0700921 }
Todd Poynor3948f802013-07-09 19:35:14 -0700922
Suren Baghdasaryance13cb52018-06-19 18:38:12 -0700923 if (per_app_memcg) {
Suren Baghdasaryan20686f02018-05-18 14:42:00 -0700924 if (params.oomadj >= 900) {
925 soft_limit_mult = 0;
926 } else if (params.oomadj >= 800) {
927 soft_limit_mult = 0;
928 } else if (params.oomadj >= 700) {
929 soft_limit_mult = 0;
930 } else if (params.oomadj >= 600) {
931 // Launcher should be perceptible, don't kill it.
932 params.oomadj = 200;
933 soft_limit_mult = 1;
934 } else if (params.oomadj >= 500) {
935 soft_limit_mult = 0;
936 } else if (params.oomadj >= 400) {
937 soft_limit_mult = 0;
938 } else if (params.oomadj >= 300) {
939 soft_limit_mult = 1;
940 } else if (params.oomadj >= 200) {
Srinivas Paladugu3eb20bc2018-10-09 14:21:10 -0700941 soft_limit_mult = 8;
Suren Baghdasaryan20686f02018-05-18 14:42:00 -0700942 } else if (params.oomadj >= 100) {
943 soft_limit_mult = 10;
944 } else if (params.oomadj >= 0) {
945 soft_limit_mult = 20;
946 } else {
947 // Persistent processes will have a large
948 // soft limit 512MB.
949 soft_limit_mult = 64;
950 }
Robert Benea673e2762017-06-01 16:32:31 -0700951
Suren Baghdasaryan3862dd32018-05-21 19:48:47 -0700952 snprintf(path, sizeof(path), MEMCG_SYSFS_PATH
953 "apps/uid_%d/pid_%d/memory.soft_limit_in_bytes",
954 params.uid, params.pid);
Suren Baghdasaryan20686f02018-05-18 14:42:00 -0700955 snprintf(val, sizeof(val), "%d", soft_limit_mult * EIGHT_MEGA);
Suren Baghdasaryan3862dd32018-05-21 19:48:47 -0700956
957 /*
958 * system_server process has no memcg under /dev/memcg/apps but should be
959 * registered with lmkd. This is the best way so far to identify it.
960 */
961 is_system_server = (params.oomadj == SYSTEM_ADJ &&
962 (pwdrec = getpwnam("system")) != NULL &&
963 params.uid == pwdrec->pw_uid);
964 writefilestring(path, val, !is_system_server);
Robert Benea673e2762017-06-01 16:32:31 -0700965 }
966
Suren Baghdasaryan0f100512018-01-24 16:51:41 -0800967 procp = pid_lookup(params.pid);
Todd Poynor3948f802013-07-09 19:35:14 -0700968 if (!procp) {
Suren Baghdasaryan11dc7342019-07-19 10:55:39 -0700969 int pidfd = -1;
970
971 if (pidfd_supported) {
972 pidfd = TEMP_FAILURE_RETRY(sys_pidfd_open(params.pid, 0));
973 if (pidfd < 0) {
974 ALOGE("pidfd_open for pid %d failed; errno=%d", params.pid, errno);
Todd Poynor3948f802013-07-09 19:35:14 -0700975 return;
976 }
Suren Baghdasaryan11dc7342019-07-19 10:55:39 -0700977 }
Todd Poynor3948f802013-07-09 19:35:14 -0700978
Suren Baghdasaryan11dc7342019-07-19 10:55:39 -0700979 procp = calloc(1, sizeof(struct proc));
980 if (!procp) {
981 // Oh, the irony. May need to rebuild our state.
982 return;
983 }
984
985 procp->pid = params.pid;
986 procp->pidfd = pidfd;
987 procp->uid = params.uid;
Suren Baghdasaryan12ab1872019-10-18 11:16:52 -0700988 procp->reg_pid = cred->pid;
Suren Baghdasaryan11dc7342019-07-19 10:55:39 -0700989 procp->oomadj = params.oomadj;
990 proc_insert(procp);
Todd Poynor3948f802013-07-09 19:35:14 -0700991 } else {
Suren Baghdasaryan12ab1872019-10-18 11:16:52 -0700992 if (!claim_record(procp, cred->pid)) {
993 char buf[LINE_MAX];
994 /* Only registrant of the record can remove it */
995 ALOGE("%s (%d, %d) attempts to modify a process registered by another client",
996 proc_get_name(cred->pid, buf, sizeof(buf)), cred->uid, cred->pid);
997 return;
998 }
Todd Poynor3948f802013-07-09 19:35:14 -0700999 proc_unslot(procp);
Suren Baghdasaryan0f100512018-01-24 16:51:41 -08001000 procp->oomadj = params.oomadj;
Todd Poynor3948f802013-07-09 19:35:14 -07001001 proc_slot(procp);
1002 }
1003}
1004
Suren Baghdasaryan12ab1872019-10-18 11:16:52 -07001005static void cmd_procremove(LMKD_CTRL_PACKET packet, struct ucred *cred) {
Suren Baghdasaryan0f100512018-01-24 16:51:41 -08001006 struct lmk_procremove params;
Suren Baghdasaryan12ab1872019-10-18 11:16:52 -07001007 struct proc *procp;
Suren Baghdasaryan0f100512018-01-24 16:51:41 -08001008
George Burgess IVc73e0652019-10-02 11:22:55 -07001009 lmkd_pack_get_procremove(packet, &params);
Suren Baghdasaryan12ab1872019-10-18 11:16:52 -07001010
Mark Salyzyn721d7c72018-03-21 12:24:58 -07001011 if (use_inkernel_interface) {
Suren Baghdasaryanb72c6652019-09-04 19:12:29 -07001012 stats_remove_taskname(params.pid, kpoll_info.poll_fd);
Todd Poynor3948f802013-07-09 19:35:14 -07001013 return;
Mark Salyzyn721d7c72018-03-21 12:24:58 -07001014 }
Todd Poynor3948f802013-07-09 19:35:14 -07001015
Suren Baghdasaryan12ab1872019-10-18 11:16:52 -07001016 procp = pid_lookup(params.pid);
1017 if (!procp) {
1018 return;
1019 }
1020
1021 if (!claim_record(procp, cred->pid)) {
1022 char buf[LINE_MAX];
1023 /* Only registrant of the record can remove it */
1024 ALOGE("%s (%d, %d) attempts to unregister a process registered by another client",
1025 proc_get_name(cred->pid, buf, sizeof(buf)), cred->uid, cred->pid);
1026 return;
1027 }
1028
Suren Baghdasaryan01063272018-10-12 11:28:33 -07001029 /*
1030 * WARNING: After pid_remove() procp is freed and can't be used!
1031 * Therefore placed at the end of the function.
1032 */
Suren Baghdasaryan0f100512018-01-24 16:51:41 -08001033 pid_remove(params.pid);
Todd Poynor3948f802013-07-09 19:35:14 -07001034}
1035
Suren Baghdasaryan12ab1872019-10-18 11:16:52 -07001036static void cmd_procpurge(struct ucred *cred) {
Suren Baghdasaryane3b60472018-10-10 14:17:17 -07001037 int i;
1038 struct proc *procp;
1039 struct proc *next;
1040
1041 if (use_inkernel_interface) {
Jim Blacklerd2da8142019-09-10 15:30:05 +01001042 stats_purge_tasknames();
Suren Baghdasaryane3b60472018-10-10 14:17:17 -07001043 return;
1044 }
1045
Suren Baghdasaryane3b60472018-10-10 14:17:17 -07001046 for (i = 0; i < PIDHASH_SZ; i++) {
1047 procp = pidhash[i];
1048 while (procp) {
1049 next = procp->pidhash_next;
Suren Baghdasaryan12ab1872019-10-18 11:16:52 -07001050 /* Purge only records created by the requestor */
1051 if (claim_record(procp, cred->pid)) {
1052 pid_remove(procp->pid);
1053 }
Suren Baghdasaryane3b60472018-10-10 14:17:17 -07001054 procp = next;
1055 }
1056 }
Suren Baghdasaryane3b60472018-10-10 14:17:17 -07001057}
1058
Suren Baghdasaryand4a29902018-10-12 11:07:40 -07001059static void inc_killcnt(int oomadj) {
1060 int slot = ADJTOSLOT(oomadj);
1061 uint8_t idx = killcnt_idx[slot];
1062
1063 if (idx == KILLCNT_INVALID_IDX) {
1064 /* index is not assigned for this oomadj */
1065 if (killcnt_free_idx < MAX_DISTINCT_OOM_ADJ) {
1066 killcnt_idx[slot] = killcnt_free_idx;
1067 killcnt[killcnt_free_idx] = 1;
1068 killcnt_free_idx++;
1069 } else {
1070 ALOGW("Number of distinct oomadj levels exceeds %d",
1071 MAX_DISTINCT_OOM_ADJ);
1072 }
1073 } else {
1074 /*
1075 * wraparound is highly unlikely and is detectable using total
1076 * counter because it has to be equal to the sum of all counters
1077 */
1078 killcnt[idx]++;
1079 }
1080 /* increment total kill counter */
1081 killcnt_total++;
1082}
1083
1084static int get_killcnt(int min_oomadj, int max_oomadj) {
1085 int slot;
1086 int count = 0;
1087
1088 if (min_oomadj > max_oomadj)
1089 return 0;
1090
1091 /* special case to get total kill count */
1092 if (min_oomadj > OOM_SCORE_ADJ_MAX)
1093 return killcnt_total;
1094
1095 while (min_oomadj <= max_oomadj &&
1096 (slot = ADJTOSLOT(min_oomadj)) < ADJTOSLOT_COUNT) {
1097 uint8_t idx = killcnt_idx[slot];
1098 if (idx != KILLCNT_INVALID_IDX) {
1099 count += killcnt[idx];
1100 }
1101 min_oomadj++;
1102 }
1103
1104 return count;
1105}
1106
1107static int cmd_getkillcnt(LMKD_CTRL_PACKET packet) {
1108 struct lmk_getkillcnt params;
1109
1110 if (use_inkernel_interface) {
1111 /* kernel driver does not expose this information */
1112 return 0;
1113 }
1114
1115 lmkd_pack_get_getkillcnt(packet, &params);
1116
1117 return get_killcnt(params.min_oomadj, params.max_oomadj);
1118}
1119
Suren Baghdasaryan0f100512018-01-24 16:51:41 -08001120static void cmd_target(int ntargets, LMKD_CTRL_PACKET packet) {
Todd Poynor3948f802013-07-09 19:35:14 -07001121 int i;
Suren Baghdasaryan0f100512018-01-24 16:51:41 -08001122 struct lmk_target target;
Suren Baghdasaryan314a5052018-07-24 17:13:06 -07001123 char minfree_str[PROPERTY_VALUE_MAX];
1124 char *pstr = minfree_str;
1125 char *pend = minfree_str + sizeof(minfree_str);
1126 static struct timespec last_req_tm;
1127 struct timespec curr_tm;
Todd Poynor3948f802013-07-09 19:35:14 -07001128
Suren Baghdasaryan314a5052018-07-24 17:13:06 -07001129 if (ntargets < 1 || ntargets > (int)ARRAY_SIZE(lowmem_adj))
Todd Poynor3948f802013-07-09 19:35:14 -07001130 return;
1131
Suren Baghdasaryan314a5052018-07-24 17:13:06 -07001132 /*
1133 * Ratelimit minfree updates to once per TARGET_UPDATE_MIN_INTERVAL_MS
1134 * to prevent DoS attacks
1135 */
1136 if (clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm) != 0) {
1137 ALOGE("Failed to get current time");
1138 return;
1139 }
1140
1141 if (get_time_diff_ms(&last_req_tm, &curr_tm) <
1142 TARGET_UPDATE_MIN_INTERVAL_MS) {
1143 ALOGE("Ignoring frequent updated to lmkd limits");
1144 return;
1145 }
1146
1147 last_req_tm = curr_tm;
1148
Todd Poynor3948f802013-07-09 19:35:14 -07001149 for (i = 0; i < ntargets; i++) {
Suren Baghdasaryan0f100512018-01-24 16:51:41 -08001150 lmkd_pack_get_target(packet, i, &target);
1151 lowmem_minfree[i] = target.minfree;
1152 lowmem_adj[i] = target.oom_adj_score;
Suren Baghdasaryan314a5052018-07-24 17:13:06 -07001153
1154 pstr += snprintf(pstr, pend - pstr, "%d:%d,", target.minfree,
1155 target.oom_adj_score);
1156 if (pstr >= pend) {
1157 /* if no more space in the buffer then terminate the loop */
1158 pstr = pend;
1159 break;
1160 }
Todd Poynor3948f802013-07-09 19:35:14 -07001161 }
1162
1163 lowmem_targets_size = ntargets;
1164
Suren Baghdasaryan314a5052018-07-24 17:13:06 -07001165 /* Override the last extra comma */
1166 pstr[-1] = '\0';
1167 property_set("sys.lmk.minfree_levels", minfree_str);
1168
Robert Benea164baeb2017-09-11 16:53:28 -07001169 if (has_inkernel_module) {
Todd Poynor3948f802013-07-09 19:35:14 -07001170 char minfreestr[128];
1171 char killpriostr[128];
1172
1173 minfreestr[0] = '\0';
1174 killpriostr[0] = '\0';
1175
1176 for (i = 0; i < lowmem_targets_size; i++) {
1177 char val[40];
1178
1179 if (i) {
1180 strlcat(minfreestr, ",", sizeof(minfreestr));
1181 strlcat(killpriostr, ",", sizeof(killpriostr));
1182 }
1183
Robert Benea164baeb2017-09-11 16:53:28 -07001184 snprintf(val, sizeof(val), "%d", use_inkernel_interface ? lowmem_minfree[i] : 0);
Todd Poynor3948f802013-07-09 19:35:14 -07001185 strlcat(minfreestr, val, sizeof(minfreestr));
Robert Benea164baeb2017-09-11 16:53:28 -07001186 snprintf(val, sizeof(val), "%d", use_inkernel_interface ? lowmem_adj[i] : 0);
Todd Poynor3948f802013-07-09 19:35:14 -07001187 strlcat(killpriostr, val, sizeof(killpriostr));
1188 }
1189
Suren Baghdasaryan1ffa2462018-03-20 13:53:17 -07001190 writefilestring(INKERNEL_MINFREE_PATH, minfreestr, true);
1191 writefilestring(INKERNEL_ADJ_PATH, killpriostr, true);
Todd Poynor3948f802013-07-09 19:35:14 -07001192 }
1193}
1194
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08001195static void ctrl_data_close(int dsock_idx) {
1196 struct epoll_event epev;
1197
1198 ALOGI("closing lmkd data connection");
1199 if (epoll_ctl(epollfd, EPOLL_CTL_DEL, data_sock[dsock_idx].sock, &epev) == -1) {
1200 // Log a warning and keep going
1201 ALOGW("epoll_ctl for data connection socket failed; errno=%d", errno);
1202 }
Todd Poynor3948f802013-07-09 19:35:14 -07001203 maxevents--;
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08001204
1205 close(data_sock[dsock_idx].sock);
1206 data_sock[dsock_idx].sock = -1;
Suren Baghdasaryan12ab1872019-10-18 11:16:52 -07001207
1208 /* Mark all records of the old registrant as unclaimed */
1209 remove_claims(data_sock[dsock_idx].pid);
Todd Poynor3948f802013-07-09 19:35:14 -07001210}
1211
Suren Baghdasaryan12ab1872019-10-18 11:16:52 -07001212static ssize_t ctrl_data_read(int dsock_idx, char *buf, size_t bufsz, struct ucred *sender_cred) {
1213 struct iovec iov = { buf, bufsz };
1214 char control[CMSG_SPACE(sizeof(struct ucred))];
1215 struct msghdr hdr = {
1216 NULL, 0, &iov, 1, control, sizeof(control), 0,
1217 };
1218 ssize_t ret;
Todd Poynor3948f802013-07-09 19:35:14 -07001219
Suren Baghdasaryan12ab1872019-10-18 11:16:52 -07001220 ret = TEMP_FAILURE_RETRY(recvmsg(data_sock[dsock_idx].sock, &hdr, 0));
Todd Poynor3948f802013-07-09 19:35:14 -07001221 if (ret == -1) {
Suren Baghdasaryan12ab1872019-10-18 11:16:52 -07001222 ALOGE("control data socket read failed; %s", strerror(errno));
1223 return -1;
Todd Poynor3948f802013-07-09 19:35:14 -07001224 }
Suren Baghdasaryan12ab1872019-10-18 11:16:52 -07001225 if (ret == 0) {
1226 ALOGE("Got EOF on control data socket");
1227 return -1;
1228 }
1229
1230 struct ucred* cred = NULL;
1231 struct cmsghdr* cmsg = CMSG_FIRSTHDR(&hdr);
1232 while (cmsg != NULL) {
1233 if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_CREDENTIALS) {
1234 cred = (struct ucred*)CMSG_DATA(cmsg);
1235 break;
1236 }
1237 cmsg = CMSG_NXTHDR(&hdr, cmsg);
1238 }
1239
1240 if (cred == NULL) {
1241 ALOGE("Failed to retrieve sender credentials");
1242 /* Close the connection */
1243 ctrl_data_close(dsock_idx);
1244 return -1;
1245 }
1246
1247 memcpy(sender_cred, cred, sizeof(struct ucred));
1248
1249 /* Store PID of the peer */
1250 data_sock[dsock_idx].pid = cred->pid;
Todd Poynor3948f802013-07-09 19:35:14 -07001251
1252 return ret;
1253}
1254
Suren Baghdasaryand4a29902018-10-12 11:07:40 -07001255static int ctrl_data_write(int dsock_idx, char *buf, size_t bufsz) {
1256 int ret = 0;
1257
1258 ret = TEMP_FAILURE_RETRY(write(data_sock[dsock_idx].sock, buf, bufsz));
1259
1260 if (ret == -1) {
1261 ALOGE("control data socket write failed; errno=%d", errno);
1262 } else if (ret == 0) {
1263 ALOGE("Got EOF on control data socket");
1264 ret = -1;
1265 }
1266
1267 return ret;
1268}
1269
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08001270static void ctrl_command_handler(int dsock_idx) {
Suren Baghdasaryan0f100512018-01-24 16:51:41 -08001271 LMKD_CTRL_PACKET packet;
Suren Baghdasaryan12ab1872019-10-18 11:16:52 -07001272 struct ucred cred;
Todd Poynor3948f802013-07-09 19:35:14 -07001273 int len;
Suren Baghdasaryan0f100512018-01-24 16:51:41 -08001274 enum lmk_cmd cmd;
Todd Poynor3948f802013-07-09 19:35:14 -07001275 int nargs;
1276 int targets;
Suren Baghdasaryand4a29902018-10-12 11:07:40 -07001277 int kill_cnt;
Todd Poynor3948f802013-07-09 19:35:14 -07001278
Suren Baghdasaryan12ab1872019-10-18 11:16:52 -07001279 len = ctrl_data_read(dsock_idx, (char *)packet, CTRL_PACKET_MAX_SIZE, &cred);
Todd Poynor3948f802013-07-09 19:35:14 -07001280 if (len <= 0)
1281 return;
1282
Suren Baghdasaryan0f100512018-01-24 16:51:41 -08001283 if (len < (int)sizeof(int)) {
1284 ALOGE("Wrong control socket read length len=%d", len);
1285 return;
1286 }
1287
1288 cmd = lmkd_pack_get_cmd(packet);
Todd Poynor3948f802013-07-09 19:35:14 -07001289 nargs = len / sizeof(int) - 1;
1290 if (nargs < 0)
1291 goto wronglen;
1292
Todd Poynor3948f802013-07-09 19:35:14 -07001293 switch(cmd) {
1294 case LMK_TARGET:
1295 targets = nargs / 2;
1296 if (nargs & 0x1 || targets > (int)ARRAY_SIZE(lowmem_adj))
1297 goto wronglen;
Suren Baghdasaryan0f100512018-01-24 16:51:41 -08001298 cmd_target(targets, packet);
Todd Poynor3948f802013-07-09 19:35:14 -07001299 break;
1300 case LMK_PROCPRIO:
Colin Crossfbb78c62014-06-13 14:52:43 -07001301 if (nargs != 3)
Todd Poynor3948f802013-07-09 19:35:14 -07001302 goto wronglen;
Suren Baghdasaryan12ab1872019-10-18 11:16:52 -07001303 cmd_procprio(packet, &cred);
Todd Poynor3948f802013-07-09 19:35:14 -07001304 break;
1305 case LMK_PROCREMOVE:
1306 if (nargs != 1)
1307 goto wronglen;
Suren Baghdasaryan12ab1872019-10-18 11:16:52 -07001308 cmd_procremove(packet, &cred);
Todd Poynor3948f802013-07-09 19:35:14 -07001309 break;
Suren Baghdasaryane3b60472018-10-10 14:17:17 -07001310 case LMK_PROCPURGE:
1311 if (nargs != 0)
1312 goto wronglen;
Suren Baghdasaryan12ab1872019-10-18 11:16:52 -07001313 cmd_procpurge(&cred);
Suren Baghdasaryane3b60472018-10-10 14:17:17 -07001314 break;
Suren Baghdasaryand4a29902018-10-12 11:07:40 -07001315 case LMK_GETKILLCNT:
1316 if (nargs != 2)
1317 goto wronglen;
1318 kill_cnt = cmd_getkillcnt(packet);
1319 len = lmkd_pack_set_getkillcnt_repl(packet, kill_cnt);
1320 if (ctrl_data_write(dsock_idx, (char *)packet, len) != len)
1321 return;
1322 break;
Todd Poynor3948f802013-07-09 19:35:14 -07001323 default:
1324 ALOGE("Received unknown command code %d", cmd);
1325 return;
1326 }
1327
1328 return;
1329
1330wronglen:
1331 ALOGE("Wrong control socket read length cmd=%d len=%d", cmd, len);
1332}
1333
Suren Baghdasaryanef3650f2019-07-15 14:50:49 -07001334static void ctrl_data_handler(int data, uint32_t events,
1335 struct polling_params *poll_params __unused) {
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08001336 if (events & EPOLLIN) {
1337 ctrl_command_handler(data);
Todd Poynor3948f802013-07-09 19:35:14 -07001338 }
1339}
1340
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08001341static int get_free_dsock() {
1342 for (int i = 0; i < MAX_DATA_CONN; i++) {
1343 if (data_sock[i].sock < 0) {
1344 return i;
1345 }
1346 }
1347 return -1;
1348}
Todd Poynor3948f802013-07-09 19:35:14 -07001349
Suren Baghdasaryanef3650f2019-07-15 14:50:49 -07001350static void ctrl_connect_handler(int data __unused, uint32_t events __unused,
1351 struct polling_params *poll_params __unused) {
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08001352 struct epoll_event epev;
1353 int free_dscock_idx = get_free_dsock();
1354
1355 if (free_dscock_idx < 0) {
1356 /*
1357 * Number of data connections exceeded max supported. This should not
1358 * happen but if it does we drop all existing connections and accept
1359 * the new one. This prevents inactive connections from monopolizing
1360 * data socket and if we drop ActivityManager connection it will
1361 * immediately reconnect.
1362 */
1363 for (int i = 0; i < MAX_DATA_CONN; i++) {
1364 ctrl_data_close(i);
1365 }
1366 free_dscock_idx = 0;
Todd Poynor3948f802013-07-09 19:35:14 -07001367 }
1368
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08001369 data_sock[free_dscock_idx].sock = accept(ctrl_sock.sock, NULL, NULL);
1370 if (data_sock[free_dscock_idx].sock < 0) {
Todd Poynor3948f802013-07-09 19:35:14 -07001371 ALOGE("lmkd control socket accept failed; errno=%d", errno);
1372 return;
1373 }
1374
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08001375 ALOGI("lmkd data connection established");
1376 /* use data to store data connection idx */
1377 data_sock[free_dscock_idx].handler_info.data = free_dscock_idx;
1378 data_sock[free_dscock_idx].handler_info.handler = ctrl_data_handler;
Todd Poynor3948f802013-07-09 19:35:14 -07001379 epev.events = EPOLLIN;
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08001380 epev.data.ptr = (void *)&(data_sock[free_dscock_idx].handler_info);
1381 if (epoll_ctl(epollfd, EPOLL_CTL_ADD, data_sock[free_dscock_idx].sock, &epev) == -1) {
Todd Poynor3948f802013-07-09 19:35:14 -07001382 ALOGE("epoll_ctl for data connection socket failed; errno=%d", errno);
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08001383 ctrl_data_close(free_dscock_idx);
Todd Poynor3948f802013-07-09 19:35:14 -07001384 return;
1385 }
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08001386 maxevents++;
Todd Poynor3948f802013-07-09 19:35:14 -07001387}
1388
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07001389/*
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07001390 * /proc/zoneinfo parsing routines
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07001391 * Expected file format is:
1392 *
1393 * Node <node_id>, zone <zone_name>
1394 * (
1395 * per-node stats
1396 * (<per-node field name> <value>)+
1397 * )?
1398 * (pages free <value>
1399 * (<per-zone field name> <value>)+
1400 * pagesets
1401 * (<unused fields>)*
1402 * )+
1403 * ...
1404 */
1405static void zoneinfo_parse_protection(char *buf, struct zoneinfo_zone *zone) {
1406 int zone_idx;
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001407 int64_t max = 0;
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001408 char *save_ptr;
1409
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07001410 for (buf = strtok_r(buf, "(), ", &save_ptr), zone_idx = 0;
1411 buf && zone_idx < MAX_NR_ZONES;
1412 buf = strtok_r(NULL, "), ", &save_ptr), zone_idx++) {
1413 long long zoneval = strtoll(buf, &buf, 0);
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001414 if (zoneval > max) {
1415 max = (zoneval > INT64_MAX) ? INT64_MAX : zoneval;
1416 }
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07001417 zone->protection[zone_idx] = zoneval;
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001418 }
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07001419 zone->max_protection = max;
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001420}
1421
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07001422static int zoneinfo_parse_zone(char **buf, struct zoneinfo_zone *zone) {
1423 for (char *line = strtok_r(NULL, "\n", buf); line;
1424 line = strtok_r(NULL, "\n", buf)) {
1425 char *cp;
1426 char *ap;
1427 char *save_ptr;
1428 int64_t val;
1429 int field_idx;
1430 enum field_match_result match_res;
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001431
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07001432 cp = strtok_r(line, " ", &save_ptr);
1433 if (!cp) {
1434 return false;
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001435 }
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07001436
1437 field_idx = find_field(cp, zoneinfo_zone_spec_field_names, ZI_ZONE_SPEC_FIELD_COUNT);
1438 if (field_idx >= 0) {
1439 /* special field */
1440 if (field_idx == ZI_ZONE_SPEC_PAGESETS) {
1441 /* no mode fields we are interested in */
1442 return true;
1443 }
1444
1445 /* protection field */
1446 ap = strtok_r(NULL, ")", &save_ptr);
1447 if (ap) {
1448 zoneinfo_parse_protection(ap, zone);
1449 }
1450 continue;
1451 }
1452
1453 ap = strtok_r(NULL, " ", &save_ptr);
1454 if (!ap) {
1455 continue;
1456 }
1457
1458 match_res = match_field(cp, ap, zoneinfo_zone_field_names, ZI_ZONE_FIELD_COUNT,
1459 &val, &field_idx);
1460 if (match_res == PARSE_FAIL) {
1461 return false;
1462 }
1463 if (match_res == PARSE_SUCCESS) {
1464 zone->fields.arr[field_idx] = val;
1465 }
1466 if (field_idx == ZI_ZONE_PRESENT && val == 0) {
1467 /* zone is not populated, stop parsing it */
1468 return true;
1469 }
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001470 }
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07001471 return false;
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001472}
1473
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07001474static int zoneinfo_parse_node(char **buf, struct zoneinfo_node *node) {
1475 int fields_to_match = ZI_NODE_FIELD_COUNT;
1476
1477 for (char *line = strtok_r(NULL, "\n", buf); line;
1478 line = strtok_r(NULL, "\n", buf)) {
1479 char *cp;
1480 char *ap;
1481 char *save_ptr;
1482 int64_t val;
1483 int field_idx;
1484 enum field_match_result match_res;
1485
1486 cp = strtok_r(line, " ", &save_ptr);
1487 if (!cp) {
1488 return false;
1489 }
1490
1491 ap = strtok_r(NULL, " ", &save_ptr);
1492 if (!ap) {
1493 return false;
1494 }
1495
1496 match_res = match_field(cp, ap, zoneinfo_node_field_names, ZI_NODE_FIELD_COUNT,
1497 &val, &field_idx);
1498 if (match_res == PARSE_FAIL) {
1499 return false;
1500 }
1501 if (match_res == PARSE_SUCCESS) {
1502 node->fields.arr[field_idx] = val;
1503 fields_to_match--;
1504 if (!fields_to_match) {
1505 return true;
1506 }
1507 }
1508 }
1509 return false;
1510}
1511
1512static int zoneinfo_parse(struct zoneinfo *zi) {
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001513 static struct reread_data file_data = {
1514 .filename = ZONEINFO_PATH,
1515 .fd = -1,
1516 };
Suren Baghdasaryana77b3272019-07-15 13:35:04 -07001517 char *buf;
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001518 char *save_ptr;
1519 char *line;
Greg Kaiser724a1612019-10-02 07:07:32 -07001520 char zone_name[LINE_MAX + 1];
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07001521 struct zoneinfo_node *node = NULL;
1522 int node_idx = 0;
1523 int zone_idx = 0;
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001524
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07001525 memset(zi, 0, sizeof(struct zoneinfo));
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001526
Suren Baghdasaryana77b3272019-07-15 13:35:04 -07001527 if ((buf = reread_file(&file_data)) == NULL) {
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001528 return -1;
1529 }
1530
1531 for (line = strtok_r(buf, "\n", &save_ptr); line;
1532 line = strtok_r(NULL, "\n", &save_ptr)) {
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07001533 int node_id;
1534 if (sscanf(line, "Node %d, zone %" STRINGIFY(LINE_MAX) "s", &node_id, zone_name) == 2) {
1535 if (!node || node->id != node_id) {
1536 /* new node is found */
1537 if (node) {
1538 node->zone_count = zone_idx + 1;
1539 node_idx++;
1540 if (node_idx == MAX_NR_NODES) {
1541 /* max node count exceeded */
1542 ALOGE("%s parse error", file_data.filename);
1543 return -1;
1544 }
1545 }
1546 node = &zi->nodes[node_idx];
1547 node->id = node_id;
1548 zone_idx = 0;
1549 if (!zoneinfo_parse_node(&save_ptr, node)) {
1550 ALOGE("%s parse error", file_data.filename);
1551 return -1;
1552 }
1553 } else {
1554 /* new zone is found */
1555 zone_idx++;
1556 }
1557 if (!zoneinfo_parse_zone(&save_ptr, &node->zones[zone_idx])) {
1558 ALOGE("%s parse error", file_data.filename);
1559 return -1;
1560 }
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001561 }
1562 }
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07001563 if (!node) {
1564 ALOGE("%s parse error", file_data.filename);
1565 return -1;
1566 }
1567 node->zone_count = zone_idx + 1;
1568 zi->node_count = node_idx + 1;
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001569
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07001570 /* calculate totals fields */
1571 for (node_idx = 0; node_idx < zi->node_count; node_idx++) {
1572 node = &zi->nodes[node_idx];
1573 for (zone_idx = 0; zone_idx < node->zone_count; zone_idx++) {
1574 struct zoneinfo_zone *zone = &zi->nodes[node_idx].zones[zone_idx];
1575 zi->totalreserve_pages += zone->max_protection + zone->fields.field.high;
1576 }
1577 zi->total_inactive_file += node->fields.field.nr_inactive_file;
1578 zi->total_active_file += node->fields.field.nr_active_file;
1579 zi->total_workingset_refault += node->fields.field.workingset_refault;
1580 }
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001581 return 0;
1582}
1583
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07001584/* /proc/meminfo parsing routines */
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001585static bool meminfo_parse_line(char *line, union meminfo *mi) {
1586 char *cp = line;
1587 char *ap;
1588 char *save_ptr;
1589 int64_t val;
1590 int field_idx;
1591 enum field_match_result match_res;
1592
1593 cp = strtok_r(line, " ", &save_ptr);
1594 if (!cp) {
1595 return false;
1596 }
1597
1598 ap = strtok_r(NULL, " ", &save_ptr);
1599 if (!ap) {
1600 return false;
1601 }
1602
1603 match_res = match_field(cp, ap, meminfo_field_names, MI_FIELD_COUNT,
1604 &val, &field_idx);
1605 if (match_res == PARSE_SUCCESS) {
1606 mi->arr[field_idx] = val / page_k;
1607 }
1608 return (match_res != PARSE_FAIL);
1609}
1610
1611static int meminfo_parse(union meminfo *mi) {
1612 static struct reread_data file_data = {
1613 .filename = MEMINFO_PATH,
1614 .fd = -1,
1615 };
Suren Baghdasaryana77b3272019-07-15 13:35:04 -07001616 char *buf;
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001617 char *save_ptr;
1618 char *line;
1619
1620 memset(mi, 0, sizeof(union meminfo));
1621
Suren Baghdasaryana77b3272019-07-15 13:35:04 -07001622 if ((buf = reread_file(&file_data)) == NULL) {
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001623 return -1;
1624 }
1625
1626 for (line = strtok_r(buf, "\n", &save_ptr); line;
1627 line = strtok_r(NULL, "\n", &save_ptr)) {
1628 if (!meminfo_parse_line(line, mi)) {
1629 ALOGE("%s parse error", file_data.filename);
1630 return -1;
1631 }
1632 }
1633 mi->field.nr_file_pages = mi->field.cached + mi->field.swap_cached +
1634 mi->field.buffers;
1635
1636 return 0;
1637}
1638
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07001639/* /proc/vmstat parsing routines */
1640static bool vmstat_parse_line(char *line, union vmstat *vs) {
1641 char *cp;
1642 char *ap;
1643 char *save_ptr;
1644 int64_t val;
1645 int field_idx;
1646 enum field_match_result match_res;
1647
1648 cp = strtok_r(line, " ", &save_ptr);
1649 if (!cp) {
1650 return false;
1651 }
1652
1653 ap = strtok_r(NULL, " ", &save_ptr);
1654 if (!ap) {
1655 return false;
1656 }
1657
1658 match_res = match_field(cp, ap, vmstat_field_names, VS_FIELD_COUNT,
1659 &val, &field_idx);
1660 if (match_res == PARSE_SUCCESS) {
1661 vs->arr[field_idx] = val;
1662 }
1663 return (match_res != PARSE_FAIL);
1664}
1665
1666static int vmstat_parse(union vmstat *vs) {
1667 static struct reread_data file_data = {
1668 .filename = VMSTAT_PATH,
1669 .fd = -1,
1670 };
1671 char *buf;
1672 char *save_ptr;
1673 char *line;
1674
1675 memset(vs, 0, sizeof(union vmstat));
1676
1677 if ((buf = reread_file(&file_data)) == NULL) {
1678 return -1;
1679 }
1680
1681 for (line = strtok_r(buf, "\n", &save_ptr); line;
1682 line = strtok_r(NULL, "\n", &save_ptr)) {
1683 if (!vmstat_parse_line(line, vs)) {
1684 ALOGE("%s parse error", file_data.filename);
1685 return -1;
1686 }
1687 }
1688
1689 return 0;
1690}
1691
Suren Baghdasaryana7ac5782019-09-16 12:06:30 -07001692static void killinfo_log(struct proc* procp, int min_oom_score, int tasksize,
1693 int kill_reason, union meminfo *mi) {
1694 /* log process information */
1695 android_log_write_int32(ctx, procp->pid);
1696 android_log_write_int32(ctx, procp->uid);
1697 android_log_write_int32(ctx, procp->oomadj);
1698 android_log_write_int32(ctx, min_oom_score);
1699 android_log_write_int32(ctx, (int32_t)min(tasksize * page_k, INT32_MAX));
1700 android_log_write_int32(ctx, kill_reason);
1701
1702 /* log meminfo fields */
Suren Baghdasaryan282ad1a2018-07-26 16:34:27 -07001703 for (int field_idx = 0; field_idx < MI_FIELD_COUNT; field_idx++) {
1704 android_log_write_int32(ctx, (int32_t)min(mi->arr[field_idx] * page_k, INT32_MAX));
1705 }
1706
1707 android_log_write_list(ctx, LOG_ID_EVENTS);
1708 android_log_reset(ctx);
1709}
1710
Todd Poynor3948f802013-07-09 19:35:14 -07001711static struct proc *proc_adj_lru(int oomadj) {
1712 return (struct proc *)adjslot_tail(&procadjslot_list[ADJTOSLOT(oomadj)]);
1713}
1714
Suren Baghdasaryan662492a2017-12-08 13:17:06 -08001715static struct proc *proc_get_heaviest(int oomadj) {
1716 struct adjslot_list *head = &procadjslot_list[ADJTOSLOT(oomadj)];
1717 struct adjslot_list *curr = head->next;
1718 struct proc *maxprocp = NULL;
1719 int maxsize = 0;
1720 while (curr != head) {
1721 int pid = ((struct proc *)curr)->pid;
1722 int tasksize = proc_get_size(pid);
1723 if (tasksize <= 0) {
1724 struct adjslot_list *next = curr->next;
1725 pid_remove(pid);
1726 curr = next;
1727 } else {
1728 if (tasksize > maxsize) {
1729 maxsize = tasksize;
1730 maxprocp = (struct proc *)curr;
1731 }
1732 curr = curr->next;
1733 }
1734 }
1735 return maxprocp;
1736}
1737
Wei Wang2d95c102018-11-21 00:11:44 -08001738static void set_process_group_and_prio(int pid, SchedPolicy sp, int prio) {
1739 DIR* d;
1740 char proc_path[PATH_MAX];
1741 struct dirent* de;
1742
1743 snprintf(proc_path, sizeof(proc_path), "/proc/%d/task", pid);
1744 if (!(d = opendir(proc_path))) {
1745 ALOGW("Failed to open %s; errno=%d: process pid(%d) might have died", proc_path, errno,
1746 pid);
1747 return;
1748 }
1749
1750 while ((de = readdir(d))) {
1751 int t_pid;
1752
1753 if (de->d_name[0] == '.') continue;
1754 t_pid = atoi(de->d_name);
1755
1756 if (!t_pid) {
1757 ALOGW("Failed to get t_pid for '%s' of pid(%d)", de->d_name, pid);
1758 continue;
1759 }
1760
1761 if (setpriority(PRIO_PROCESS, t_pid, prio) && errno != ESRCH) {
1762 ALOGW("Unable to raise priority of killing t_pid (%d): errno=%d", t_pid, errno);
1763 }
1764
1765 if (set_cpuset_policy(t_pid, sp)) {
1766 ALOGW("Failed to set_cpuset_policy on pid(%d) t_pid(%d) to %d", pid, t_pid, (int)sp);
1767 continue;
1768 }
1769 }
1770 closedir(d);
1771}
1772
Suren Baghdasaryanf2081a92019-06-26 17:56:01 -07001773static bool is_kill_pending(void) {
1774 char buf[24];
1775
1776 if (last_kill_pid_or_fd < 0) {
1777 return false;
1778 }
1779
1780 if (pidfd_supported) {
1781 return true;
1782 }
1783
1784 /* when pidfd is not supported base the decision on /proc/<pid> existence */
1785 snprintf(buf, sizeof(buf), "/proc/%d/", last_kill_pid_or_fd);
1786 if (access(buf, F_OK) == 0) {
1787 return true;
1788 }
1789
1790 return false;
1791}
1792
1793static bool is_waiting_for_kill(void) {
1794 return pidfd_supported && last_kill_pid_or_fd >= 0;
1795}
1796
1797static void stop_wait_for_proc_kill(bool finished) {
1798 struct epoll_event epev;
1799
1800 if (last_kill_pid_or_fd < 0) {
1801 return;
1802 }
1803
1804 if (debug_process_killing) {
1805 struct timespec curr_tm;
1806
1807 if (clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm) != 0) {
1808 /*
1809 * curr_tm is used here merely to report kill duration, so this failure is not fatal.
1810 * Log an error and continue.
1811 */
1812 ALOGE("Failed to get current time");
1813 }
1814
1815 if (finished) {
1816 ALOGI("Process got killed in %ldms",
1817 get_time_diff_ms(&last_kill_tm, &curr_tm));
1818 } else {
1819 ALOGI("Stop waiting for process kill after %ldms",
1820 get_time_diff_ms(&last_kill_tm, &curr_tm));
1821 }
1822 }
1823
1824 if (pidfd_supported) {
1825 /* unregister fd */
1826 if (epoll_ctl(epollfd, EPOLL_CTL_DEL, last_kill_pid_or_fd, &epev) != 0) {
1827 ALOGE("epoll_ctl for last killed process failed; errno=%d", errno);
1828 return;
1829 }
1830 maxevents--;
1831 close(last_kill_pid_or_fd);
1832 }
1833
1834 last_kill_pid_or_fd = -1;
1835}
1836
1837static void kill_done_handler(int data __unused, uint32_t events __unused,
1838 struct polling_params *poll_params) {
1839 stop_wait_for_proc_kill(true);
1840 poll_params->update = POLLING_RESUME;
1841}
1842
Suren Baghdasaryan11dc7342019-07-19 10:55:39 -07001843static void start_wait_for_proc_kill(int pid_or_fd) {
Suren Baghdasaryanf2081a92019-06-26 17:56:01 -07001844 static struct event_handler_info kill_done_hinfo = { 0, kill_done_handler };
1845 struct epoll_event epev;
1846
1847 if (last_kill_pid_or_fd >= 0) {
1848 /* Should not happen but if it does we should stop previous wait */
1849 ALOGE("Attempt to wait for a kill while another wait is in progress");
1850 stop_wait_for_proc_kill(false);
1851 }
1852
Suren Baghdasaryan11dc7342019-07-19 10:55:39 -07001853 last_kill_pid_or_fd = pid_or_fd;
Suren Baghdasaryanf2081a92019-06-26 17:56:01 -07001854
Suren Baghdasaryan11dc7342019-07-19 10:55:39 -07001855 if (!pidfd_supported) {
1856 /* If pidfd is not supported just store PID and exit */
Suren Baghdasaryanf2081a92019-06-26 17:56:01 -07001857 return;
1858 }
1859
1860 epev.events = EPOLLIN;
1861 epev.data.ptr = (void *)&kill_done_hinfo;
1862 if (epoll_ctl(epollfd, EPOLL_CTL_ADD, last_kill_pid_or_fd, &epev) != 0) {
1863 ALOGE("epoll_ctl for last kill failed; errno=%d", errno);
1864 close(last_kill_pid_or_fd);
1865 last_kill_pid_or_fd = -1;
1866 return;
1867 }
1868 maxevents++;
1869}
Tim Murraye7853f62018-10-25 17:05:41 -07001870
Colin Cross16b09462014-07-14 12:39:56 -07001871/* Kill one process specified by procp. Returns the size of the process killed */
Suren Baghdasaryana7ac5782019-09-16 12:06:30 -07001872static int kill_one_process(struct proc* procp, int min_oom_score, int kill_reason,
Suren Baghdasaryanf2081a92019-06-26 17:56:01 -07001873 const char *kill_desc, union meminfo *mi, struct timespec *tm) {
Colin Cross16b09462014-07-14 12:39:56 -07001874 int pid = procp->pid;
Suren Baghdasaryan11dc7342019-07-19 10:55:39 -07001875 int pidfd = procp->pidfd;
Colin Cross16b09462014-07-14 12:39:56 -07001876 uid_t uid = procp->uid;
Suren Baghdasaryan0082ef12019-07-02 15:52:07 -07001877 int tgid;
Colin Cross16b09462014-07-14 12:39:56 -07001878 char *taskname;
1879 int tasksize;
1880 int r;
Suren Baghdasaryan01063272018-10-12 11:28:33 -07001881 int result = -1;
Suren Baghdasaryanb72c6652019-09-04 19:12:29 -07001882 struct memory_stat *mem_st;
Suren Baghdasaryanca0790d2019-10-04 16:06:55 -07001883 char buf[LINE_MAX];
Rajeev Kumar70450032018-01-31 17:54:56 -08001884
Suren Baghdasaryan0082ef12019-07-02 15:52:07 -07001885 tgid = proc_get_tgid(pid);
1886 if (tgid >= 0 && tgid != pid) {
1887 ALOGE("Possible pid reuse detected (pid %d, tgid %d)!", pid, tgid);
1888 goto out;
1889 }
1890
Suren Baghdasaryanca0790d2019-10-04 16:06:55 -07001891 taskname = proc_get_name(pid, buf, sizeof(buf));
Colin Cross16b09462014-07-14 12:39:56 -07001892 if (!taskname) {
Suren Baghdasaryan01063272018-10-12 11:28:33 -07001893 goto out;
Colin Cross16b09462014-07-14 12:39:56 -07001894 }
1895
1896 tasksize = proc_get_size(pid);
1897 if (tasksize <= 0) {
Suren Baghdasaryan01063272018-10-12 11:28:33 -07001898 goto out;
Colin Cross16b09462014-07-14 12:39:56 -07001899 }
1900
Suren Baghdasaryanb72c6652019-09-04 19:12:29 -07001901 mem_st = stats_read_memory_stat(per_app_memcg, pid, uid);
Rajeev Kumar70450032018-01-31 17:54:56 -08001902
Suren Baghdasaryanc7135592018-01-04 10:43:58 -08001903 TRACE_KILL_START(pid);
1904
Mark Salyzyn64d97d82018-04-09 09:50:32 -07001905 /* CAP_KILL required */
Suren Baghdasaryan11dc7342019-07-19 10:55:39 -07001906 if (pidfd < 0) {
1907 start_wait_for_proc_kill(pid);
1908 r = kill(pid, SIGKILL);
1909 } else {
1910 start_wait_for_proc_kill(pidfd);
1911 r = sys_pidfd_send_signal(pidfd, SIGKILL, NULL, 0);
1912 }
Wei Wang2d95c102018-11-21 00:11:44 -08001913
Suren Baghdasaryance862df2019-09-04 16:44:47 -07001914 TRACE_KILL_END();
1915
1916 if (r) {
Suren Baghdasaryanf2081a92019-06-26 17:56:01 -07001917 stop_wait_for_proc_kill(false);
Suren Baghdasaryance862df2019-09-04 16:44:47 -07001918 ALOGE("kill(%d): errno=%d", pid, errno);
1919 /* Delete process record even when we fail to kill so that we don't get stuck on it */
1920 goto out;
1921 }
1922
Wei Wang2d95c102018-11-21 00:11:44 -08001923 set_process_group_and_prio(pid, SP_FOREGROUND, ANDROID_PRIORITY_HIGHEST);
1924
Suren Baghdasaryanf2081a92019-06-26 17:56:01 -07001925 last_kill_tm = *tm;
1926
Suren Baghdasaryand4a29902018-10-12 11:07:40 -07001927 inc_killcnt(procp->oomadj);
Suren Baghdasaryana7ac5782019-09-16 12:06:30 -07001928
1929 killinfo_log(procp, min_oom_score, tasksize, kill_reason, mi);
1930
1931 if (kill_desc) {
Suren Baghdasaryanfd7518f2019-07-15 15:50:17 -07001932 ALOGI("Kill '%s' (%d), uid %d, oom_adj %d to free %ldkB; reason: %s", taskname, pid,
Suren Baghdasaryana7ac5782019-09-16 12:06:30 -07001933 uid, procp->oomadj, tasksize * page_k, kill_desc);
Suren Baghdasaryanfd7518f2019-07-15 15:50:17 -07001934 } else {
1935 ALOGI("Kill '%s' (%d), uid %d, oom_adj %d to free %ldkB", taskname, pid,
1936 uid, procp->oomadj, tasksize * page_k);
1937 }
Colin Cross16b09462014-07-14 12:39:56 -07001938
Suren Baghdasaryanb72c6652019-09-04 19:12:29 -07001939 stats_write_lmk_kill_occurred(LMK_KILL_OCCURRED, uid, taskname,
1940 procp->oomadj, min_oom_score, tasksize, mem_st);
1941
Suren Baghdasaryance862df2019-09-04 16:44:47 -07001942 result = tasksize;
Mark Salyzyn919f5382018-02-04 15:27:23 -08001943
Suren Baghdasaryan01063272018-10-12 11:28:33 -07001944out:
1945 /*
1946 * WARNING: After pid_remove() procp is freed and can't be used!
1947 * Therefore placed at the end of the function.
1948 */
1949 pid_remove(pid);
1950 return result;
Colin Cross16b09462014-07-14 12:39:56 -07001951}
1952
1953/*
Suren Baghdasaryanf81b5f42018-10-26 11:32:15 -07001954 * Find one process to kill at or above the given oom_adj level.
1955 * Returns size of the killed process.
Colin Cross16b09462014-07-14 12:39:56 -07001956 */
Suren Baghdasaryana7ac5782019-09-16 12:06:30 -07001957static int find_and_kill_process(int min_score_adj, int kill_reason, const char *kill_desc,
Suren Baghdasaryanf2081a92019-06-26 17:56:01 -07001958 union meminfo *mi, struct timespec *tm) {
Colin Cross16b09462014-07-14 12:39:56 -07001959 int i;
Suren Baghdasaryanf81b5f42018-10-26 11:32:15 -07001960 int killed_size = 0;
Yang Lu5564f4e2018-05-15 04:59:44 +00001961 bool lmk_state_change_start = false;
Rajeev Kumar70450032018-01-31 17:54:56 -08001962
Chong Zhang0a4acdf2015-10-14 16:19:53 -07001963 for (i = OOM_SCORE_ADJ_MAX; i >= min_score_adj; i--) {
Colin Cross16b09462014-07-14 12:39:56 -07001964 struct proc *procp;
1965
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08001966 while (true) {
Suren Baghdasaryan818b59b2018-04-13 11:49:54 -07001967 procp = kill_heaviest_task ?
1968 proc_get_heaviest(i) : proc_adj_lru(i);
Colin Cross16b09462014-07-14 12:39:56 -07001969
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08001970 if (!procp)
1971 break;
1972
Suren Baghdasaryanf2081a92019-06-26 17:56:01 -07001973 killed_size = kill_one_process(procp, min_score_adj, kill_reason, kill_desc, mi, tm);
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08001974 if (killed_size >= 0) {
Suren Baghdasaryanb72c6652019-09-04 19:12:29 -07001975 if (!lmk_state_change_start) {
Yang Lu5564f4e2018-05-15 04:59:44 +00001976 lmk_state_change_start = true;
Suren Baghdasaryanb72c6652019-09-04 19:12:29 -07001977 stats_write_lmk_state_changed(LMK_STATE_CHANGED,
Yang Lu5564f4e2018-05-15 04:59:44 +00001978 LMK_STATE_CHANGE_START);
1979 }
Suren Baghdasaryanf81b5f42018-10-26 11:32:15 -07001980 break;
Colin Cross16b09462014-07-14 12:39:56 -07001981 }
1982 }
Suren Baghdasaryanf81b5f42018-10-26 11:32:15 -07001983 if (killed_size) {
1984 break;
1985 }
Colin Cross16b09462014-07-14 12:39:56 -07001986 }
1987
Suren Baghdasaryanb72c6652019-09-04 19:12:29 -07001988 if (lmk_state_change_start) {
1989 stats_write_lmk_state_changed(LMK_STATE_CHANGED, LMK_STATE_CHANGE_STOP);
Rajeev Kumar70450032018-01-31 17:54:56 -08001990 }
Rajeev Kumar70450032018-01-31 17:54:56 -08001991
Suren Baghdasaryanf81b5f42018-10-26 11:32:15 -07001992 return killed_size;
Colin Cross16b09462014-07-14 12:39:56 -07001993}
1994
Suren Baghdasaryan6499e5e2018-04-13 12:43:41 -07001995static int64_t get_memory_usage(struct reread_data *file_data) {
Robert Beneac47f2992017-08-21 15:18:31 -07001996 int ret;
1997 int64_t mem_usage;
Suren Baghdasaryana77b3272019-07-15 13:35:04 -07001998 char *buf;
Suren Baghdasaryan6499e5e2018-04-13 12:43:41 -07001999
Suren Baghdasaryana77b3272019-07-15 13:35:04 -07002000 if ((buf = reread_file(file_data)) == NULL) {
Robert Beneac47f2992017-08-21 15:18:31 -07002001 return -1;
2002 }
2003
Suren Baghdasaryan6499e5e2018-04-13 12:43:41 -07002004 if (!parse_int64(buf, &mem_usage)) {
2005 ALOGE("%s parse error", file_data->filename);
Robert Beneac47f2992017-08-21 15:18:31 -07002006 return -1;
2007 }
Robert Beneac47f2992017-08-21 15:18:31 -07002008 if (mem_usage == 0) {
2009 ALOGE("No memory!");
2010 return -1;
2011 }
2012 return mem_usage;
2013}
2014
Suren Baghdasaryan9926e572018-04-13 13:41:12 -07002015void record_low_pressure_levels(union meminfo *mi) {
2016 if (low_pressure_mem.min_nr_free_pages == -1 ||
2017 low_pressure_mem.min_nr_free_pages > mi->field.nr_free_pages) {
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08002018 if (debug_process_killing) {
Suren Baghdasaryan9926e572018-04-13 13:41:12 -07002019 ALOGI("Low pressure min memory update from %" PRId64 " to %" PRId64,
2020 low_pressure_mem.min_nr_free_pages, mi->field.nr_free_pages);
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08002021 }
Suren Baghdasaryan9926e572018-04-13 13:41:12 -07002022 low_pressure_mem.min_nr_free_pages = mi->field.nr_free_pages;
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08002023 }
2024 /*
2025 * Free memory at low vmpressure events occasionally gets spikes,
2026 * possibly a stale low vmpressure event with memory already
2027 * freed up (no memory pressure should have been reported).
Suren Baghdasaryan9926e572018-04-13 13:41:12 -07002028 * Ignore large jumps in max_nr_free_pages that would mess up our stats.
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08002029 */
Suren Baghdasaryan9926e572018-04-13 13:41:12 -07002030 if (low_pressure_mem.max_nr_free_pages == -1 ||
2031 (low_pressure_mem.max_nr_free_pages < mi->field.nr_free_pages &&
2032 mi->field.nr_free_pages - low_pressure_mem.max_nr_free_pages <
2033 low_pressure_mem.max_nr_free_pages * 0.1)) {
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08002034 if (debug_process_killing) {
Suren Baghdasaryan9926e572018-04-13 13:41:12 -07002035 ALOGI("Low pressure max memory update from %" PRId64 " to %" PRId64,
2036 low_pressure_mem.max_nr_free_pages, mi->field.nr_free_pages);
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08002037 }
Suren Baghdasaryan9926e572018-04-13 13:41:12 -07002038 low_pressure_mem.max_nr_free_pages = mi->field.nr_free_pages;
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08002039 }
2040}
2041
Suren Baghdasaryan96bf3a62017-12-08 12:58:52 -08002042enum vmpressure_level upgrade_level(enum vmpressure_level level) {
2043 return (enum vmpressure_level)((level < VMPRESS_LEVEL_CRITICAL) ?
2044 level + 1 : level);
2045}
2046
2047enum vmpressure_level downgrade_level(enum vmpressure_level level) {
2048 return (enum vmpressure_level)((level > VMPRESS_LEVEL_LOW) ?
2049 level - 1 : level);
2050}
2051
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002052enum zone_watermark {
2053 WMARK_MIN = 0,
2054 WMARK_LOW,
2055 WMARK_HIGH,
2056 WMARK_NONE
2057};
2058
Suren Baghdasaryan4787ab42019-08-14 09:48:35 -07002059struct zone_watermarks {
2060 long high_wmark;
2061 long low_wmark;
2062 long min_wmark;
2063};
2064
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002065/*
2066 * Returns lowest breached watermark or WMARK_NONE.
2067 */
Suren Baghdasaryan4787ab42019-08-14 09:48:35 -07002068static enum zone_watermark get_lowest_watermark(union meminfo *mi,
2069 struct zone_watermarks *watermarks)
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002070{
Suren Baghdasaryan4787ab42019-08-14 09:48:35 -07002071 int64_t nr_free_pages = mi->field.nr_free_pages - mi->field.cma_free;
2072
2073 if (nr_free_pages < watermarks->min_wmark) {
2074 return WMARK_MIN;
2075 }
2076 if (nr_free_pages < watermarks->low_wmark) {
2077 return WMARK_LOW;
2078 }
2079 if (nr_free_pages < watermarks->high_wmark) {
2080 return WMARK_HIGH;
2081 }
2082 return WMARK_NONE;
2083}
2084
2085void calc_zone_watermarks(struct zoneinfo *zi, struct zone_watermarks *watermarks) {
2086 memset(watermarks, 0, sizeof(struct zone_watermarks));
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002087
2088 for (int node_idx = 0; node_idx < zi->node_count; node_idx++) {
2089 struct zoneinfo_node *node = &zi->nodes[node_idx];
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002090 for (int zone_idx = 0; zone_idx < node->zone_count; zone_idx++) {
2091 struct zoneinfo_zone *zone = &node->zones[zone_idx];
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002092
2093 if (!zone->fields.field.present) {
2094 continue;
2095 }
2096
Suren Baghdasaryan4787ab42019-08-14 09:48:35 -07002097 watermarks->high_wmark += zone->max_protection + zone->fields.field.high;
2098 watermarks->low_wmark += zone->max_protection + zone->fields.field.low;
2099 watermarks->min_wmark += zone->max_protection + zone->fields.field.min;
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002100 }
2101 }
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002102}
2103
2104static void mp_event_psi(int data, uint32_t events, struct polling_params *poll_params) {
2105 enum kill_reasons {
2106 NONE = -1, /* To denote no kill condition */
2107 PRESSURE_AFTER_KILL = 0,
2108 NOT_RESPONDING,
2109 LOW_SWAP_AND_THRASHING,
2110 LOW_MEM_AND_SWAP,
2111 LOW_MEM_AND_THRASHING,
2112 DIRECT_RECL_AND_THRASHING,
2113 KILL_REASON_COUNT
2114 };
2115 enum reclaim_state {
2116 NO_RECLAIM = 0,
2117 KSWAPD_RECLAIM,
2118 DIRECT_RECLAIM,
2119 };
2120 static int64_t init_ws_refault;
2121 static int64_t base_file_lru;
2122 static int64_t init_pgscan_kswapd;
2123 static int64_t init_pgscan_direct;
2124 static int64_t swap_low_threshold;
2125 static bool killing;
2126 static int thrashing_limit;
2127 static bool in_reclaim;
Suren Baghdasaryan4787ab42019-08-14 09:48:35 -07002128 static struct zone_watermarks watermarks;
2129 static struct timespec wmark_update_tm;
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002130
2131 union meminfo mi;
2132 union vmstat vs;
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002133 struct timespec curr_tm;
2134 int64_t thrashing = 0;
2135 bool swap_is_low = false;
2136 enum vmpressure_level level = (enum vmpressure_level)data;
2137 enum kill_reasons kill_reason = NONE;
2138 bool cycle_after_kill = false;
2139 enum reclaim_state reclaim = NO_RECLAIM;
2140 enum zone_watermark wmark = WMARK_NONE;
Suren Baghdasaryanfd7518f2019-07-15 15:50:17 -07002141 char kill_desc[LINE_MAX];
Suren Baghdasaryan4b750882019-09-19 15:27:21 -07002142 bool cut_thrashing_limit = false;
2143 int min_score_adj = 0;
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002144
2145 /* Skip while still killing a process */
2146 if (is_kill_pending()) {
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002147 goto no_kill;
2148 }
Suren Baghdasaryanf2081a92019-06-26 17:56:01 -07002149 /*
2150 * Process is dead, stop waiting. This has no effect if pidfds are supported and
2151 * death notification already caused waiting to stop.
2152 */
2153 stop_wait_for_proc_kill(true);
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002154
2155 if (clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm) != 0) {
2156 ALOGE("Failed to get current time");
2157 return;
2158 }
2159
2160 if (vmstat_parse(&vs) < 0) {
2161 ALOGE("Failed to parse vmstat!");
2162 return;
2163 }
2164
2165 if (meminfo_parse(&mi) < 0) {
2166 ALOGE("Failed to parse meminfo!");
2167 return;
2168 }
2169
2170 /* Reset states after process got killed */
2171 if (killing) {
2172 killing = false;
2173 cycle_after_kill = true;
2174 /* Reset file-backed pagecache size and refault amounts after a kill */
2175 base_file_lru = vs.field.nr_inactive_file + vs.field.nr_active_file;
2176 init_ws_refault = vs.field.workingset_refault;
2177 }
2178
2179 /* Check free swap levels */
2180 if (swap_free_low_percentage) {
2181 if (!swap_low_threshold) {
2182 swap_low_threshold = mi.field.total_swap * swap_free_low_percentage / 100;
2183 }
2184 swap_is_low = mi.field.free_swap < swap_low_threshold;
2185 }
2186
2187 /* Identify reclaim state */
2188 if (vs.field.pgscan_direct > init_pgscan_direct) {
2189 init_pgscan_direct = vs.field.pgscan_direct;
2190 init_pgscan_kswapd = vs.field.pgscan_kswapd;
2191 reclaim = DIRECT_RECLAIM;
2192 } else if (vs.field.pgscan_kswapd > init_pgscan_kswapd) {
2193 init_pgscan_kswapd = vs.field.pgscan_kswapd;
2194 reclaim = KSWAPD_RECLAIM;
2195 } else {
2196 in_reclaim = false;
2197 /* Skip if system is not reclaiming */
2198 goto no_kill;
2199 }
2200
2201 if (!in_reclaim) {
2202 /* Record file-backed pagecache size when entering reclaim cycle */
2203 base_file_lru = vs.field.nr_inactive_file + vs.field.nr_active_file;
2204 init_ws_refault = vs.field.workingset_refault;
2205 thrashing_limit = thrashing_limit_pct;
2206 } else {
2207 /* Calculate what % of the file-backed pagecache refaulted so far */
2208 thrashing = (vs.field.workingset_refault - init_ws_refault) * 100 / base_file_lru;
2209 }
2210 in_reclaim = true;
2211
Suren Baghdasaryan4787ab42019-08-14 09:48:35 -07002212 /*
2213 * Refresh watermarks once per min in case user updated one of the margins.
2214 * TODO: b/140521024 replace this periodic update with an API for AMS to notify LMKD
2215 * that zone watermarks were changed by the system software.
2216 */
2217 if (watermarks.high_wmark == 0 || get_time_diff_ms(&wmark_update_tm, &curr_tm) > 60000) {
2218 struct zoneinfo zi;
2219
2220 if (zoneinfo_parse(&zi) < 0) {
2221 ALOGE("Failed to parse zoneinfo!");
2222 return;
2223 }
2224
2225 calc_zone_watermarks(&zi, &watermarks);
2226 wmark_update_tm = curr_tm;
2227 }
2228
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002229 /* Find out which watermark is breached if any */
Suren Baghdasaryan4787ab42019-08-14 09:48:35 -07002230 wmark = get_lowest_watermark(&mi, &watermarks);
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002231
2232 /*
2233 * TODO: move this logic into a separate function
2234 * Decide if killing a process is necessary and record the reason
2235 */
2236 if (cycle_after_kill && wmark < WMARK_LOW) {
2237 /*
2238 * Prevent kills not freeing enough memory which might lead to OOM kill.
2239 * This might happen when a process is consuming memory faster than reclaim can
2240 * free even after a kill. Mostly happens when running memory stress tests.
2241 */
2242 kill_reason = PRESSURE_AFTER_KILL;
Suren Baghdasaryanfd7518f2019-07-15 15:50:17 -07002243 strncpy(kill_desc, "min watermark is breached even after kill", sizeof(kill_desc));
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002244 } else if (level == VMPRESS_LEVEL_CRITICAL && events != 0) {
2245 /*
2246 * Device is too busy reclaiming memory which might lead to ANR.
2247 * Critical level is triggered when PSI complete stall (all tasks are blocked because
2248 * of the memory congestion) breaches the configured threshold.
2249 */
2250 kill_reason = NOT_RESPONDING;
Suren Baghdasaryanfd7518f2019-07-15 15:50:17 -07002251 strncpy(kill_desc, "device is not responding", sizeof(kill_desc));
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002252 } else if (swap_is_low && thrashing > thrashing_limit_pct) {
2253 /* Page cache is thrashing while swap is low */
2254 kill_reason = LOW_SWAP_AND_THRASHING;
Suren Baghdasaryanfd7518f2019-07-15 15:50:17 -07002255 snprintf(kill_desc, sizeof(kill_desc), "device is low on swap (%" PRId64
2256 "kB < %" PRId64 "kB) and thrashing (%" PRId64 "%%)",
2257 mi.field.free_swap * page_k, swap_low_threshold * page_k, thrashing);
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002258 } else if (swap_is_low && wmark < WMARK_HIGH) {
2259 /* Both free memory and swap are low */
2260 kill_reason = LOW_MEM_AND_SWAP;
Suren Baghdasaryanfd7518f2019-07-15 15:50:17 -07002261 snprintf(kill_desc, sizeof(kill_desc), "%s watermark is breached and swap is low (%"
2262 PRId64 "kB < %" PRId64 "kB)", wmark > WMARK_LOW ? "min" : "low",
2263 mi.field.free_swap * page_k, swap_low_threshold * page_k);
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002264 } else if (wmark < WMARK_HIGH && thrashing > thrashing_limit) {
2265 /* Page cache is thrashing while memory is low */
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002266 kill_reason = LOW_MEM_AND_THRASHING;
Suren Baghdasaryanfd7518f2019-07-15 15:50:17 -07002267 snprintf(kill_desc, sizeof(kill_desc), "%s watermark is breached and thrashing (%"
2268 PRId64 "%%)", wmark > WMARK_LOW ? "min" : "low", thrashing);
Suren Baghdasaryan4b750882019-09-19 15:27:21 -07002269 cut_thrashing_limit = true;
2270 /* Do not kill perceptible apps because of thrashing */
2271 min_score_adj = PERCEPTIBLE_APP_ADJ;
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002272 } else if (reclaim == DIRECT_RECLAIM && thrashing > thrashing_limit) {
2273 /* Page cache is thrashing while in direct reclaim (mostly happens on lowram devices) */
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002274 kill_reason = DIRECT_RECL_AND_THRASHING;
Suren Baghdasaryanfd7518f2019-07-15 15:50:17 -07002275 snprintf(kill_desc, sizeof(kill_desc), "device is in direct reclaim and thrashing (%"
2276 PRId64 "%%)", thrashing);
Suren Baghdasaryan4b750882019-09-19 15:27:21 -07002277 cut_thrashing_limit = true;
2278 /* Do not kill perceptible apps because of thrashing */
2279 min_score_adj = PERCEPTIBLE_APP_ADJ;
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002280 }
2281
2282 /* Kill a process if necessary */
2283 if (kill_reason != NONE) {
Suren Baghdasaryanf2081a92019-06-26 17:56:01 -07002284 int pages_freed = find_and_kill_process(min_score_adj, kill_reason, kill_desc, &mi,
2285 &curr_tm);
Suren Baghdasaryan4b750882019-09-19 15:27:21 -07002286 if (pages_freed > 0) {
2287 killing = true;
2288 if (cut_thrashing_limit) {
2289 /*
2290 * Cut thrasing limit by thrashing_limit_decay_pct percentage of the current
2291 * thrashing limit until the system stops thrashing.
2292 */
2293 thrashing_limit = (thrashing_limit * (100 - thrashing_limit_decay_pct)) / 100;
2294 }
2295 }
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002296 }
2297
2298no_kill:
Suren Baghdasaryanf2081a92019-06-26 17:56:01 -07002299 /* Do not poll if kernel supports pidfd waiting */
2300 if (is_waiting_for_kill()) {
2301 /* Pause polling if we are waiting for process death notification */
2302 poll_params->update = POLLING_PAUSE;
2303 return;
2304 }
2305
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002306 /*
2307 * Start polling after initial PSI event;
2308 * extend polling while device is in direct reclaim or process is being killed;
2309 * do not extend when kswapd reclaims because that might go on for a long time
2310 * without causing memory pressure
2311 */
2312 if (events || killing || reclaim == DIRECT_RECLAIM) {
2313 poll_params->update = POLLING_START;
2314 }
2315
2316 /* Decide the polling interval */
2317 if (swap_is_low || killing) {
2318 /* Fast polling during and after a kill or when swap is low */
2319 poll_params->polling_interval_ms = PSI_POLL_PERIOD_SHORT_MS;
2320 } else {
2321 /* By default use long intervals */
2322 poll_params->polling_interval_ms = PSI_POLL_PERIOD_LONG_MS;
2323 }
2324}
2325
Suren Baghdasaryanef3650f2019-07-15 14:50:49 -07002326static void mp_event_common(int data, uint32_t events, struct polling_params *poll_params) {
Todd Poynor3948f802013-07-09 19:35:14 -07002327 int ret;
2328 unsigned long long evcount;
Robert Beneac47f2992017-08-21 15:18:31 -07002329 int64_t mem_usage, memsw_usage;
Robert Benea6e8e7102017-09-13 15:20:30 -07002330 int64_t mem_pressure;
Suren Baghdasaryane82e15c2018-01-04 09:16:21 -08002331 enum vmpressure_level lvl;
Suren Baghdasaryan9926e572018-04-13 13:41:12 -07002332 union meminfo mi;
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07002333 struct zoneinfo zi;
Suren Baghdasaryan36934412018-09-05 15:46:32 -07002334 struct timespec curr_tm;
Suren Baghdasaryan314a5052018-07-24 17:13:06 -07002335 static unsigned long kill_skip_count = 0;
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08002336 enum vmpressure_level level = (enum vmpressure_level)data;
Suren Baghdasaryanffdc4dd2018-04-13 13:53:43 -07002337 long other_free = 0, other_file = 0;
2338 int min_score_adj;
Suren Baghdasaryanffdc4dd2018-04-13 13:53:43 -07002339 int minfree = 0;
Suren Baghdasaryan6499e5e2018-04-13 12:43:41 -07002340 static struct reread_data mem_usage_file_data = {
2341 .filename = MEMCG_MEMORY_USAGE,
2342 .fd = -1,
2343 };
2344 static struct reread_data memsw_usage_file_data = {
2345 .filename = MEMCG_MEMORYSW_USAGE,
2346 .fd = -1,
2347 };
Todd Poynor3948f802013-07-09 19:35:14 -07002348
Suren Baghdasaryan77122e52019-01-08 12:54:48 -08002349 if (debug_process_killing) {
2350 ALOGI("%s memory pressure event is triggered", level_name[level]);
2351 }
2352
2353 if (!use_psi_monitors) {
2354 /*
2355 * Check all event counters from low to critical
2356 * and upgrade to the highest priority one. By reading
2357 * eventfd we also reset the event counters.
2358 */
2359 for (lvl = VMPRESS_LEVEL_LOW; lvl < VMPRESS_LEVEL_COUNT; lvl++) {
2360 if (mpevfd[lvl] != -1 &&
2361 TEMP_FAILURE_RETRY(read(mpevfd[lvl],
2362 &evcount, sizeof(evcount))) > 0 &&
2363 evcount > 0 && lvl > level) {
2364 level = lvl;
2365 }
Suren Baghdasaryane82e15c2018-01-04 09:16:21 -08002366 }
2367 }
Todd Poynor3948f802013-07-09 19:35:14 -07002368
Suren Baghdasaryanef3650f2019-07-15 14:50:49 -07002369 /* Start polling after initial PSI event */
2370 if (use_psi_monitors && events) {
2371 /* Override polling params only if current event is more critical */
2372 if (!poll_params->poll_handler || data > poll_params->poll_handler->data) {
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002373 poll_params->polling_interval_ms = PSI_POLL_PERIOD_SHORT_MS;
Suren Baghdasaryanef3650f2019-07-15 14:50:49 -07002374 poll_params->update = POLLING_START;
2375 }
2376 }
2377
Suren Baghdasaryan36934412018-09-05 15:46:32 -07002378 if (clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm) != 0) {
2379 ALOGE("Failed to get current time");
2380 return;
2381 }
2382
Suren Baghdasaryanf2081a92019-06-26 17:56:01 -07002383 if (kill_timeout_ms && get_time_diff_ms(&last_kill_tm, &curr_tm) < kill_timeout_ms) {
2384 /*
2385 * If we're within the no-kill timeout, see if there's pending reclaim work
2386 * from the last killed process. If so, skip killing for now.
2387 */
2388 if (is_kill_pending()) {
Suren Baghdasaryan314a5052018-07-24 17:13:06 -07002389 kill_skip_count++;
Suren Baghdasaryancaa2dc52018-01-17 17:28:01 -08002390 return;
2391 }
Suren Baghdasaryanf2081a92019-06-26 17:56:01 -07002392 /*
2393 * Process is dead, stop waiting. This has no effect if pidfds are supported and
2394 * death notification already caused waiting to stop.
2395 */
2396 stop_wait_for_proc_kill(true);
2397 } else {
2398 /*
2399 * Killing took longer than no-kill timeout. Stop waiting for the last process
2400 * to die because we are ready to kill again.
2401 */
2402 stop_wait_for_proc_kill(false);
Suren Baghdasaryancaa2dc52018-01-17 17:28:01 -08002403 }
2404
Suren Baghdasaryan314a5052018-07-24 17:13:06 -07002405 if (kill_skip_count > 0) {
Suren Baghdasaryanda88b242018-05-10 16:10:56 -07002406 ALOGI("%lu memory pressure events were skipped after a kill!",
Suren Baghdasaryan314a5052018-07-24 17:13:06 -07002407 kill_skip_count);
2408 kill_skip_count = 0;
Suren Baghdasaryancaa2dc52018-01-17 17:28:01 -08002409 }
2410
Suren Baghdasaryanffdc4dd2018-04-13 13:53:43 -07002411 if (meminfo_parse(&mi) < 0 || zoneinfo_parse(&zi) < 0) {
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08002412 ALOGE("Failed to get free memory!");
2413 return;
2414 }
2415
Suren Baghdasaryanffdc4dd2018-04-13 13:53:43 -07002416 if (use_minfree_levels) {
2417 int i;
2418
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07002419 other_free = mi.field.nr_free_pages - zi.totalreserve_pages;
Suren Baghdasaryanffdc4dd2018-04-13 13:53:43 -07002420 if (mi.field.nr_file_pages > (mi.field.shmem + mi.field.unevictable + mi.field.swap_cached)) {
2421 other_file = (mi.field.nr_file_pages - mi.field.shmem -
2422 mi.field.unevictable - mi.field.swap_cached);
2423 } else {
2424 other_file = 0;
2425 }
2426
2427 min_score_adj = OOM_SCORE_ADJ_MAX + 1;
2428 for (i = 0; i < lowmem_targets_size; i++) {
2429 minfree = lowmem_minfree[i];
2430 if (other_free < minfree && other_file < minfree) {
2431 min_score_adj = lowmem_adj[i];
2432 break;
2433 }
2434 }
2435
Suren Baghdasaryan20686f02018-05-18 14:42:00 -07002436 if (min_score_adj == OOM_SCORE_ADJ_MAX + 1) {
2437 if (debug_process_killing) {
2438 ALOGI("Ignore %s memory pressure event "
2439 "(free memory=%ldkB, cache=%ldkB, limit=%ldkB)",
2440 level_name[level], other_free * page_k, other_file * page_k,
2441 (long)lowmem_minfree[lowmem_targets_size - 1] * page_k);
2442 }
Suren Baghdasaryanffdc4dd2018-04-13 13:53:43 -07002443 return;
Suren Baghdasaryan20686f02018-05-18 14:42:00 -07002444 }
Suren Baghdasaryanffdc4dd2018-04-13 13:53:43 -07002445
Suren Baghdasaryanffdc4dd2018-04-13 13:53:43 -07002446 goto do_kill;
2447 }
2448
Suren Baghdasaryan9926e572018-04-13 13:41:12 -07002449 if (level == VMPRESS_LEVEL_LOW) {
2450 record_low_pressure_levels(&mi);
2451 }
2452
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08002453 if (level_oomadj[level] > OOM_SCORE_ADJ_MAX) {
2454 /* Do not monitor this pressure level */
2455 return;
2456 }
2457
Suren Baghdasaryan6499e5e2018-04-13 12:43:41 -07002458 if ((mem_usage = get_memory_usage(&mem_usage_file_data)) < 0) {
2459 goto do_kill;
2460 }
2461 if ((memsw_usage = get_memory_usage(&memsw_usage_file_data)) < 0) {
Suren Baghdasaryan96bf3a62017-12-08 12:58:52 -08002462 goto do_kill;
Robert Benea6e8e7102017-09-13 15:20:30 -07002463 }
Robert Beneac47f2992017-08-21 15:18:31 -07002464
Robert Benea6e8e7102017-09-13 15:20:30 -07002465 // Calculate percent for swappinness.
2466 mem_pressure = (mem_usage * 100) / memsw_usage;
2467
Suren Baghdasaryan96bf3a62017-12-08 12:58:52 -08002468 if (enable_pressure_upgrade && level != VMPRESS_LEVEL_CRITICAL) {
Robert Benea6e8e7102017-09-13 15:20:30 -07002469 // We are swapping too much.
2470 if (mem_pressure < upgrade_pressure) {
Suren Baghdasaryan96bf3a62017-12-08 12:58:52 -08002471 level = upgrade_level(level);
2472 if (debug_process_killing) {
2473 ALOGI("Event upgraded to %s", level_name[level]);
2474 }
Robert Beneac47f2992017-08-21 15:18:31 -07002475 }
2476 }
2477
Vic Yang360a1132018-08-07 10:18:22 -07002478 // If we still have enough swap space available, check if we want to
2479 // ignore/downgrade pressure events.
2480 if (mi.field.free_swap >=
2481 mi.field.total_swap * swap_free_low_percentage / 100) {
2482 // If the pressure is larger than downgrade_pressure lmk will not
2483 // kill any process, since enough memory is available.
2484 if (mem_pressure > downgrade_pressure) {
2485 if (debug_process_killing) {
2486 ALOGI("Ignore %s memory pressure", level_name[level]);
2487 }
2488 return;
2489 } else if (level == VMPRESS_LEVEL_CRITICAL && mem_pressure > upgrade_pressure) {
2490 if (debug_process_killing) {
2491 ALOGI("Downgrade critical memory pressure");
2492 }
2493 // Downgrade event, since enough memory available.
2494 level = downgrade_level(level);
Robert Benea6e8e7102017-09-13 15:20:30 -07002495 }
Robert Benea6e8e7102017-09-13 15:20:30 -07002496 }
2497
Suren Baghdasaryan96bf3a62017-12-08 12:58:52 -08002498do_kill:
Suren Baghdasaryanff61afb2018-04-13 11:45:38 -07002499 if (low_ram_device) {
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08002500 /* For Go devices kill only one task */
Suren Baghdasaryanf2081a92019-06-26 17:56:01 -07002501 if (find_and_kill_process(level_oomadj[level], -1, NULL, &mi, &curr_tm) == 0) {
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08002502 if (debug_process_killing) {
2503 ALOGI("Nothing to kill");
2504 }
2505 }
2506 } else {
Suren Baghdasaryanffdc4dd2018-04-13 13:53:43 -07002507 int pages_freed;
Suren Baghdasaryan36934412018-09-05 15:46:32 -07002508 static struct timespec last_report_tm;
2509 static unsigned long report_skip_count = 0;
Suren Baghdasaryanffdc4dd2018-04-13 13:53:43 -07002510
2511 if (!use_minfree_levels) {
Suren Baghdasaryanffdc4dd2018-04-13 13:53:43 -07002512 /* Free up enough memory to downgrate the memory pressure to low level */
Suren Baghdasaryanf81b5f42018-10-26 11:32:15 -07002513 if (mi.field.nr_free_pages >= low_pressure_mem.max_nr_free_pages) {
Suren Baghdasaryanffdc4dd2018-04-13 13:53:43 -07002514 if (debug_process_killing) {
2515 ALOGI("Ignoring pressure since more memory is "
2516 "available (%" PRId64 ") than watermark (%" PRId64 ")",
2517 mi.field.nr_free_pages, low_pressure_mem.max_nr_free_pages);
2518 }
2519 return;
2520 }
2521 min_score_adj = level_oomadj[level];
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08002522 }
2523
Suren Baghdasaryanf2081a92019-06-26 17:56:01 -07002524 pages_freed = find_and_kill_process(min_score_adj, -1, NULL, &mi, &curr_tm);
Suren Baghdasaryanda88b242018-05-10 16:10:56 -07002525
Suren Baghdasaryan36934412018-09-05 15:46:32 -07002526 if (pages_freed == 0) {
2527 /* Rate limit kill reports when nothing was reclaimed */
2528 if (get_time_diff_ms(&last_report_tm, &curr_tm) < FAIL_REPORT_RLIMIT_MS) {
2529 report_skip_count++;
Suren Baghdasaryan314a5052018-07-24 17:13:06 -07002530 return;
2531 }
Robert Beneacaeaa652017-08-11 16:03:20 -07002532 }
Suren Baghdasaryan36934412018-09-05 15:46:32 -07002533
Suren Baghdasaryana7ac5782019-09-16 12:06:30 -07002534 /* Log whenever we kill or when report rate limit allows */
Suren Baghdasaryan36934412018-09-05 15:46:32 -07002535 if (use_minfree_levels) {
Suren Baghdasaryanf81b5f42018-10-26 11:32:15 -07002536 ALOGI("Reclaimed %ldkB, cache(%ldkB) and "
Suren Baghdasaryan36934412018-09-05 15:46:32 -07002537 "free(%" PRId64 "kB)-reserved(%" PRId64 "kB) below min(%ldkB) for oom_adj %d",
Suren Baghdasaryanf81b5f42018-10-26 11:32:15 -07002538 pages_freed * page_k,
Suren Baghdasaryan36934412018-09-05 15:46:32 -07002539 other_file * page_k, mi.field.nr_free_pages * page_k,
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07002540 zi.totalreserve_pages * page_k,
Suren Baghdasaryan36934412018-09-05 15:46:32 -07002541 minfree * page_k, min_score_adj);
2542 } else {
Suren Baghdasaryanf81b5f42018-10-26 11:32:15 -07002543 ALOGI("Reclaimed %ldkB at oom_adj %d",
2544 pages_freed * page_k, min_score_adj);
Suren Baghdasaryan36934412018-09-05 15:46:32 -07002545 }
2546
2547 if (report_skip_count > 0) {
2548 ALOGI("Suppressed %lu failed kill reports", report_skip_count);
2549 report_skip_count = 0;
2550 }
2551
2552 last_report_tm = curr_tm;
Colin Crossf8857cc2014-07-11 17:16:56 -07002553 }
Suren Baghdasaryanf2081a92019-06-26 17:56:01 -07002554 if (is_waiting_for_kill()) {
2555 /* pause polling if we are waiting for process death notification */
2556 poll_params->update = POLLING_PAUSE;
2557 }
Todd Poynor3948f802013-07-09 19:35:14 -07002558}
2559
Suren Baghdasaryan844f26b2019-07-15 15:42:09 -07002560static bool init_mp_psi(enum vmpressure_level level, bool use_new_strategy) {
2561 int fd;
2562
2563 /* Do not register a handler if threshold_ms is not set */
2564 if (!psi_thresholds[level].threshold_ms) {
2565 return true;
2566 }
2567
2568 fd = init_psi_monitor(psi_thresholds[level].stall_type,
Suren Baghdasaryan77122e52019-01-08 12:54:48 -08002569 psi_thresholds[level].threshold_ms * US_PER_MS,
2570 PSI_WINDOW_SIZE_MS * US_PER_MS);
2571
2572 if (fd < 0) {
2573 return false;
2574 }
2575
Suren Baghdasaryan844f26b2019-07-15 15:42:09 -07002576 vmpressure_hinfo[level].handler = use_new_strategy ? mp_event_psi : mp_event_common;
Suren Baghdasaryan77122e52019-01-08 12:54:48 -08002577 vmpressure_hinfo[level].data = level;
2578 if (register_psi_monitor(epollfd, fd, &vmpressure_hinfo[level]) < 0) {
2579 destroy_psi_monitor(fd);
2580 return false;
2581 }
2582 maxevents++;
2583 mpevfd[level] = fd;
2584
2585 return true;
2586}
2587
2588static void destroy_mp_psi(enum vmpressure_level level) {
2589 int fd = mpevfd[level];
2590
2591 if (unregister_psi_monitor(epollfd, fd) < 0) {
2592 ALOGE("Failed to unregister psi monitor for %s memory pressure; errno=%d",
2593 level_name[level], errno);
2594 }
2595 destroy_psi_monitor(fd);
2596 mpevfd[level] = -1;
2597}
2598
2599static bool init_psi_monitors() {
Suren Baghdasaryan844f26b2019-07-15 15:42:09 -07002600 /*
2601 * When PSI is used on low-ram devices or on high-end devices without memfree levels
2602 * use new kill strategy based on zone watermarks, free swap and thrashing stats
2603 */
2604 bool use_new_strategy =
2605 property_get_bool("ro.lmk.use_new_strategy", low_ram_device || !use_minfree_levels);
2606
2607 /* In default PSI mode override stall amounts using system properties */
2608 if (use_new_strategy) {
2609 /* Do not use low pressure level */
2610 psi_thresholds[VMPRESS_LEVEL_LOW].threshold_ms = 0;
2611 psi_thresholds[VMPRESS_LEVEL_MEDIUM].threshold_ms = psi_partial_stall_ms;
2612 psi_thresholds[VMPRESS_LEVEL_CRITICAL].threshold_ms = psi_complete_stall_ms;
2613 }
2614
2615 if (!init_mp_psi(VMPRESS_LEVEL_LOW, use_new_strategy)) {
Suren Baghdasaryan77122e52019-01-08 12:54:48 -08002616 return false;
2617 }
Suren Baghdasaryan844f26b2019-07-15 15:42:09 -07002618 if (!init_mp_psi(VMPRESS_LEVEL_MEDIUM, use_new_strategy)) {
Suren Baghdasaryan77122e52019-01-08 12:54:48 -08002619 destroy_mp_psi(VMPRESS_LEVEL_LOW);
2620 return false;
2621 }
Suren Baghdasaryan844f26b2019-07-15 15:42:09 -07002622 if (!init_mp_psi(VMPRESS_LEVEL_CRITICAL, use_new_strategy)) {
Suren Baghdasaryan77122e52019-01-08 12:54:48 -08002623 destroy_mp_psi(VMPRESS_LEVEL_MEDIUM);
2624 destroy_mp_psi(VMPRESS_LEVEL_LOW);
2625 return false;
2626 }
2627 return true;
2628}
2629
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08002630static bool init_mp_common(enum vmpressure_level level) {
Todd Poynor3948f802013-07-09 19:35:14 -07002631 int mpfd;
2632 int evfd;
2633 int evctlfd;
2634 char buf[256];
2635 struct epoll_event epev;
2636 int ret;
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08002637 int level_idx = (int)level;
2638 const char *levelstr = level_name[level_idx];
Suren Baghdasaryan96bf3a62017-12-08 12:58:52 -08002639
Mark Salyzyn64d97d82018-04-09 09:50:32 -07002640 /* gid containing AID_SYSTEM required */
Nick Kralevichc68c8862015-12-18 20:52:37 -08002641 mpfd = open(MEMCG_SYSFS_PATH "memory.pressure_level", O_RDONLY | O_CLOEXEC);
Todd Poynor3948f802013-07-09 19:35:14 -07002642 if (mpfd < 0) {
2643 ALOGI("No kernel memory.pressure_level support (errno=%d)", errno);
2644 goto err_open_mpfd;
2645 }
2646
Nick Kralevichc68c8862015-12-18 20:52:37 -08002647 evctlfd = open(MEMCG_SYSFS_PATH "cgroup.event_control", O_WRONLY | O_CLOEXEC);
Todd Poynor3948f802013-07-09 19:35:14 -07002648 if (evctlfd < 0) {
2649 ALOGI("No kernel memory cgroup event control (errno=%d)", errno);
2650 goto err_open_evctlfd;
2651 }
2652
Nick Kralevichc68c8862015-12-18 20:52:37 -08002653 evfd = eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC);
Todd Poynor3948f802013-07-09 19:35:14 -07002654 if (evfd < 0) {
2655 ALOGE("eventfd failed for level %s; errno=%d", levelstr, errno);
2656 goto err_eventfd;
2657 }
2658
2659 ret = snprintf(buf, sizeof(buf), "%d %d %s", evfd, mpfd, levelstr);
2660 if (ret >= (ssize_t)sizeof(buf)) {
2661 ALOGE("cgroup.event_control line overflow for level %s", levelstr);
2662 goto err;
2663 }
2664
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08002665 ret = TEMP_FAILURE_RETRY(write(evctlfd, buf, strlen(buf) + 1));
Todd Poynor3948f802013-07-09 19:35:14 -07002666 if (ret == -1) {
2667 ALOGE("cgroup.event_control write failed for level %s; errno=%d",
2668 levelstr, errno);
2669 goto err;
2670 }
2671
2672 epev.events = EPOLLIN;
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08002673 /* use data to store event level */
2674 vmpressure_hinfo[level_idx].data = level_idx;
2675 vmpressure_hinfo[level_idx].handler = mp_event_common;
2676 epev.data.ptr = (void *)&vmpressure_hinfo[level_idx];
Todd Poynor3948f802013-07-09 19:35:14 -07002677 ret = epoll_ctl(epollfd, EPOLL_CTL_ADD, evfd, &epev);
2678 if (ret == -1) {
2679 ALOGE("epoll_ctl for level %s failed; errno=%d", levelstr, errno);
2680 goto err;
2681 }
2682 maxevents++;
Suren Baghdasaryan96bf3a62017-12-08 12:58:52 -08002683 mpevfd[level] = evfd;
Suren Baghdasaryan1bd2fc42018-01-04 08:54:53 -08002684 close(evctlfd);
Suren Baghdasaryan96bf3a62017-12-08 12:58:52 -08002685 return true;
Todd Poynor3948f802013-07-09 19:35:14 -07002686
2687err:
2688 close(evfd);
2689err_eventfd:
2690 close(evctlfd);
2691err_open_evctlfd:
2692 close(mpfd);
2693err_open_mpfd:
Suren Baghdasaryan96bf3a62017-12-08 12:58:52 -08002694 return false;
Robert Benea673e2762017-06-01 16:32:31 -07002695}
2696
Suren Baghdasaryanb72c6652019-09-04 19:12:29 -07002697static void kernel_event_handler(int data __unused, uint32_t events __unused,
2698 struct polling_params *poll_params __unused) {
2699 kpoll_info.handler(kpoll_info.poll_fd);
Jim Blackler3947c932019-04-26 11:18:29 +01002700}
2701
Todd Poynor3948f802013-07-09 19:35:14 -07002702static int init(void) {
Suren Baghdasaryanb72c6652019-09-04 19:12:29 -07002703 static struct event_handler_info kernel_poll_hinfo = { 0, kernel_event_handler };
Suren Baghdasaryana77b3272019-07-15 13:35:04 -07002704 struct reread_data file_data = {
2705 .filename = ZONEINFO_PATH,
2706 .fd = -1,
2707 };
Todd Poynor3948f802013-07-09 19:35:14 -07002708 struct epoll_event epev;
Suren Baghdasaryanf2081a92019-06-26 17:56:01 -07002709 int pidfd;
Todd Poynor3948f802013-07-09 19:35:14 -07002710 int i;
2711 int ret;
2712
2713 page_k = sysconf(_SC_PAGESIZE);
2714 if (page_k == -1)
2715 page_k = PAGE_SIZE;
2716 page_k /= 1024;
2717
2718 epollfd = epoll_create(MAX_EPOLL_EVENTS);
2719 if (epollfd == -1) {
2720 ALOGE("epoll_create failed (errno=%d)", errno);
2721 return -1;
2722 }
2723
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08002724 // mark data connections as not connected
2725 for (int i = 0; i < MAX_DATA_CONN; i++) {
2726 data_sock[i].sock = -1;
2727 }
2728
2729 ctrl_sock.sock = android_get_control_socket("lmkd");
2730 if (ctrl_sock.sock < 0) {
Todd Poynor3948f802013-07-09 19:35:14 -07002731 ALOGE("get lmkd control socket failed");
2732 return -1;
2733 }
2734
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08002735 ret = listen(ctrl_sock.sock, MAX_DATA_CONN);
Todd Poynor3948f802013-07-09 19:35:14 -07002736 if (ret < 0) {
2737 ALOGE("lmkd control socket listen failed (errno=%d)", errno);
2738 return -1;
2739 }
2740
2741 epev.events = EPOLLIN;
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08002742 ctrl_sock.handler_info.handler = ctrl_connect_handler;
2743 epev.data.ptr = (void *)&(ctrl_sock.handler_info);
2744 if (epoll_ctl(epollfd, EPOLL_CTL_ADD, ctrl_sock.sock, &epev) == -1) {
Todd Poynor3948f802013-07-09 19:35:14 -07002745 ALOGE("epoll_ctl for lmkd control socket failed (errno=%d)", errno);
2746 return -1;
2747 }
2748 maxevents++;
2749
Robert Benea164baeb2017-09-11 16:53:28 -07002750 has_inkernel_module = !access(INKERNEL_MINFREE_PATH, W_OK);
Suren Baghdasaryan979591b2018-01-18 17:27:30 -08002751 use_inkernel_interface = has_inkernel_module;
Todd Poynor3948f802013-07-09 19:35:14 -07002752
2753 if (use_inkernel_interface) {
2754 ALOGI("Using in-kernel low memory killer interface");
Suren Baghdasaryanb72c6652019-09-04 19:12:29 -07002755 if (init_poll_kernel(&kpoll_info)) {
2756 epev.events = EPOLLIN;
2757 epev.data.ptr = (void*)&kernel_poll_hinfo;
2758 if (epoll_ctl(epollfd, EPOLL_CTL_ADD, kpoll_info.poll_fd, &epev) != 0) {
2759 ALOGE("epoll_ctl for lmk events failed (errno=%d)", errno);
2760 close(kpoll_info.poll_fd);
2761 kpoll_info.poll_fd = -1;
2762 } else {
2763 maxevents++;
2764 }
Jim Blackler3947c932019-04-26 11:18:29 +01002765 }
Todd Poynor3948f802013-07-09 19:35:14 -07002766 } else {
Suren Baghdasaryan77122e52019-01-08 12:54:48 -08002767 /* Try to use psi monitor first if kernel has it */
2768 use_psi_monitors = property_get_bool("ro.lmk.use_psi", true) &&
2769 init_psi_monitors();
2770 /* Fall back to vmpressure */
2771 if (!use_psi_monitors &&
2772 (!init_mp_common(VMPRESS_LEVEL_LOW) ||
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08002773 !init_mp_common(VMPRESS_LEVEL_MEDIUM) ||
Suren Baghdasaryan77122e52019-01-08 12:54:48 -08002774 !init_mp_common(VMPRESS_LEVEL_CRITICAL))) {
Todd Poynor3948f802013-07-09 19:35:14 -07002775 ALOGE("Kernel does not support memory pressure events or in-kernel low memory killer");
Suren Baghdasaryan96bf3a62017-12-08 12:58:52 -08002776 return -1;
2777 }
Suren Baghdasaryan77122e52019-01-08 12:54:48 -08002778 if (use_psi_monitors) {
2779 ALOGI("Using psi monitors for memory pressure detection");
2780 } else {
2781 ALOGI("Using vmpressure for memory pressure detection");
2782 }
Todd Poynor3948f802013-07-09 19:35:14 -07002783 }
2784
Chong Zhang0a4acdf2015-10-14 16:19:53 -07002785 for (i = 0; i <= ADJTOSLOT(OOM_SCORE_ADJ_MAX); i++) {
Todd Poynor3948f802013-07-09 19:35:14 -07002786 procadjslot_list[i].next = &procadjslot_list[i];
2787 procadjslot_list[i].prev = &procadjslot_list[i];
2788 }
2789
Suren Baghdasaryand4a29902018-10-12 11:07:40 -07002790 memset(killcnt_idx, KILLCNT_INVALID_IDX, sizeof(killcnt_idx));
2791
Suren Baghdasaryana77b3272019-07-15 13:35:04 -07002792 /*
2793 * Read zoneinfo as the biggest file we read to create and size the initial
2794 * read buffer and avoid memory re-allocations during memory pressure
2795 */
2796 if (reread_file(&file_data) == NULL) {
2797 ALOGE("Failed to read %s: %s", file_data.filename, strerror(errno));
2798 }
2799
Suren Baghdasaryanf2081a92019-06-26 17:56:01 -07002800 /* check if kernel supports pidfd_open syscall */
2801 pidfd = TEMP_FAILURE_RETRY(sys_pidfd_open(getpid(), 0));
2802 if (pidfd < 0) {
2803 pidfd_supported = (errno != ENOSYS);
2804 } else {
2805 pidfd_supported = true;
2806 close(pidfd);
2807 }
2808 ALOGI("Process polling is %s", pidfd_supported ? "supported" : "not supported" );
2809
Todd Poynor3948f802013-07-09 19:35:14 -07002810 return 0;
2811}
2812
Suren Baghdasaryanf2081a92019-06-26 17:56:01 -07002813static void call_handler(struct event_handler_info* handler_info,
2814 struct polling_params *poll_params, uint32_t events) {
2815 struct timespec curr_tm;
2816
2817 handler_info->handler(handler_info->data, events, poll_params);
2818 clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm);
2819 poll_params->last_poll_tm = curr_tm;
2820
2821 switch (poll_params->update) {
2822 case POLLING_START:
2823 /*
2824 * Poll for the duration of PSI_WINDOW_SIZE_MS after the
2825 * initial PSI event because psi events are rate-limited
2826 * at one per sec.
2827 */
2828 poll_params->poll_start_tm = curr_tm;
Greg Kaiser5670fab2019-10-10 06:52:23 -07002829 poll_params->poll_handler = handler_info;
Suren Baghdasaryanf2081a92019-06-26 17:56:01 -07002830 break;
2831 case POLLING_STOP:
2832 poll_params->poll_handler = NULL;
2833 break;
2834 case POLLING_PAUSE:
2835 poll_params->paused_handler = handler_info;
2836 poll_params->poll_handler = NULL;
2837 break;
2838 case POLLING_RESUME:
2839 poll_params->poll_start_tm = curr_tm;
2840 poll_params->poll_handler = poll_params->paused_handler;
2841 break;
2842 case POLLING_DO_NOT_CHANGE:
2843 if (get_time_diff_ms(&poll_params->poll_start_tm, &curr_tm) > PSI_WINDOW_SIZE_MS) {
2844 /* Polled for the duration of PSI window, time to stop */
2845 poll_params->poll_handler = NULL;
2846 }
2847 /* WARNING: skipping the rest of the function */
2848 return;
2849 }
2850 poll_params->update = POLLING_DO_NOT_CHANGE;
2851}
2852
Todd Poynor3948f802013-07-09 19:35:14 -07002853static void mainloop(void) {
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08002854 struct event_handler_info* handler_info;
Suren Baghdasaryanef3650f2019-07-15 14:50:49 -07002855 struct polling_params poll_params;
2856 struct timespec curr_tm;
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08002857 struct epoll_event *evt;
Suren Baghdasaryan77122e52019-01-08 12:54:48 -08002858 long delay = -1;
Suren Baghdasaryanef3650f2019-07-15 14:50:49 -07002859
2860 poll_params.poll_handler = NULL;
2861 poll_params.update = POLLING_DO_NOT_CHANGE;
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08002862
Todd Poynor3948f802013-07-09 19:35:14 -07002863 while (1) {
2864 struct epoll_event events[maxevents];
2865 int nevents;
2866 int i;
2867
Suren Baghdasaryanef3650f2019-07-15 14:50:49 -07002868 if (poll_params.poll_handler) {
Suren Baghdasaryanf2081a92019-06-26 17:56:01 -07002869 bool poll_now;
Suren Baghdasaryan77122e52019-01-08 12:54:48 -08002870
2871 clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm);
Suren Baghdasaryanf2081a92019-06-26 17:56:01 -07002872 if (poll_params.poll_handler == poll_params.paused_handler) {
2873 /*
2874 * Just transitioned into POLLING_RESUME. Reset paused_handler
2875 * and poll immediately
2876 */
2877 poll_params.paused_handler = NULL;
2878 poll_now = true;
2879 nevents = 0;
2880 } else {
2881 /* Calculate next timeout */
2882 delay = get_time_diff_ms(&poll_params.last_poll_tm, &curr_tm);
2883 delay = (delay < poll_params.polling_interval_ms) ?
2884 poll_params.polling_interval_ms - delay : poll_params.polling_interval_ms;
Suren Baghdasaryanef3650f2019-07-15 14:50:49 -07002885
Suren Baghdasaryanf2081a92019-06-26 17:56:01 -07002886 /* Wait for events until the next polling timeout */
2887 nevents = epoll_wait(epollfd, events, maxevents, delay);
2888
2889 /* Update current time after wait */
2890 clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm);
2891 poll_now = (get_time_diff_ms(&poll_params.last_poll_tm, &curr_tm) >=
2892 poll_params.polling_interval_ms);
2893 }
2894 if (poll_now) {
2895 call_handler(poll_params.poll_handler, &poll_params, 0);
Suren Baghdasaryan77122e52019-01-08 12:54:48 -08002896 }
2897 } else {
2898 /* Wait for events with no timeout */
2899 nevents = epoll_wait(epollfd, events, maxevents, -1);
2900 }
Todd Poynor3948f802013-07-09 19:35:14 -07002901
2902 if (nevents == -1) {
2903 if (errno == EINTR)
2904 continue;
2905 ALOGE("epoll_wait failed (errno=%d)", errno);
2906 continue;
2907 }
2908
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08002909 /*
2910 * First pass to see if any data socket connections were dropped.
2911 * Dropped connection should be handled before any other events
2912 * to deallocate data connection and correctly handle cases when
2913 * connection gets dropped and reestablished in the same epoll cycle.
2914 * In such cases it's essential to handle connection closures first.
2915 */
2916 for (i = 0, evt = &events[0]; i < nevents; ++i, evt++) {
2917 if ((evt->events & EPOLLHUP) && evt->data.ptr) {
2918 ALOGI("lmkd data connection dropped");
2919 handler_info = (struct event_handler_info*)evt->data.ptr;
2920 ctrl_data_close(handler_info->data);
2921 }
2922 }
2923
2924 /* Second pass to handle all other events */
2925 for (i = 0, evt = &events[0]; i < nevents; ++i, evt++) {
Suren Baghdasaryanef3650f2019-07-15 14:50:49 -07002926 if (evt->events & EPOLLERR) {
Todd Poynor3948f802013-07-09 19:35:14 -07002927 ALOGD("EPOLLERR on event #%d", i);
Suren Baghdasaryanef3650f2019-07-15 14:50:49 -07002928 }
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08002929 if (evt->events & EPOLLHUP) {
2930 /* This case was handled in the first pass */
2931 continue;
2932 }
2933 if (evt->data.ptr) {
2934 handler_info = (struct event_handler_info*)evt->data.ptr;
Suren Baghdasaryanf2081a92019-06-26 17:56:01 -07002935 call_handler(handler_info, &poll_params, evt->events);
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08002936 }
Todd Poynor3948f802013-07-09 19:35:14 -07002937 }
2938 }
2939}
2940
Mark Salyzyne6ed68b2014-04-30 13:36:35 -07002941int main(int argc __unused, char **argv __unused) {
Colin Cross1a0d9be2014-07-14 14:31:15 -07002942 struct sched_param param = {
2943 .sched_priority = 1,
2944 };
2945
Suren Baghdasaryan96bf3a62017-12-08 12:58:52 -08002946 /* By default disable low level vmpressure events */
2947 level_oomadj[VMPRESS_LEVEL_LOW] =
2948 property_get_int32("ro.lmk.low", OOM_SCORE_ADJ_MAX + 1);
2949 level_oomadj[VMPRESS_LEVEL_MEDIUM] =
2950 property_get_int32("ro.lmk.medium", 800);
2951 level_oomadj[VMPRESS_LEVEL_CRITICAL] =
2952 property_get_int32("ro.lmk.critical", 0);
Robert Beneacaeaa652017-08-11 16:03:20 -07002953 debug_process_killing = property_get_bool("ro.lmk.debug", false);
Suren Baghdasaryanad2fd912017-12-08 13:08:41 -08002954
2955 /* By default disable upgrade/downgrade logic */
2956 enable_pressure_upgrade =
2957 property_get_bool("ro.lmk.critical_upgrade", false);
2958 upgrade_pressure =
2959 (int64_t)property_get_int32("ro.lmk.upgrade_pressure", 100);
2960 downgrade_pressure =
2961 (int64_t)property_get_int32("ro.lmk.downgrade_pressure", 100);
Suren Baghdasaryan662492a2017-12-08 13:17:06 -08002962 kill_heaviest_task =
Suren Baghdasaryan818b59b2018-04-13 11:49:54 -07002963 property_get_bool("ro.lmk.kill_heaviest_task", false);
Suren Baghdasaryanff61afb2018-04-13 11:45:38 -07002964 low_ram_device = property_get_bool("ro.config.low_ram", false);
Suren Baghdasaryancaa2dc52018-01-17 17:28:01 -08002965 kill_timeout_ms =
2966 (unsigned long)property_get_int32("ro.lmk.kill_timeout_ms", 0);
Suren Baghdasaryanffdc4dd2018-04-13 13:53:43 -07002967 use_minfree_levels =
2968 property_get_bool("ro.lmk.use_minfree_levels", false);
Suren Baghdasaryance13cb52018-06-19 18:38:12 -07002969 per_app_memcg =
2970 property_get_bool("ro.config.per_app_memcg", low_ram_device);
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002971 swap_free_low_percentage = clamp(0, 100, property_get_int32("ro.lmk.swap_free_low_percentage",
2972 low_ram_device ? DEF_LOW_SWAP_LOWRAM : DEF_LOW_SWAP));
Suren Baghdasaryan844f26b2019-07-15 15:42:09 -07002973 psi_partial_stall_ms = property_get_int32("ro.lmk.psi_partial_stall_ms",
2974 low_ram_device ? DEF_PARTIAL_STALL_LOWRAM : DEF_PARTIAL_STALL);
2975 psi_complete_stall_ms = property_get_int32("ro.lmk.psi_complete_stall_ms",
2976 DEF_COMPLETE_STALL);
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002977 thrashing_limit_pct = max(0, property_get_int32("ro.lmk.thrashing_limit",
2978 low_ram_device ? DEF_THRASHING_LOWRAM : DEF_THRASHING));
2979 thrashing_limit_decay_pct = clamp(0, 100, property_get_int32("ro.lmk.thrashing_limit_decay",
2980 low_ram_device ? DEF_THRASHING_DECAY_LOWRAM : DEF_THRASHING_DECAY));
Robert Benea58891d52017-07-31 17:15:20 -07002981
Suren Baghdasaryana7ac5782019-09-16 12:06:30 -07002982 ctx = create_android_logger(KILLINFO_LOG_TAG);
Suren Baghdasaryan282ad1a2018-07-26 16:34:27 -07002983
Suren Baghdasaryanb72c6652019-09-04 19:12:29 -07002984 statslog_init();
Rajeev Kumar70450032018-01-31 17:54:56 -08002985
Mark Salyzyn721d7c72018-03-21 12:24:58 -07002986 if (!init()) {
2987 if (!use_inkernel_interface) {
2988 /*
2989 * MCL_ONFAULT pins pages as they fault instead of loading
2990 * everything immediately all at once. (Which would be bad,
2991 * because as of this writing, we have a lot of mapped pages we
2992 * never use.) Old kernels will see MCL_ONFAULT and fail with
2993 * EINVAL; we ignore this failure.
2994 *
2995 * N.B. read the man page for mlockall. MCL_CURRENT | MCL_ONFAULT
2996 * pins ⊆ MCL_CURRENT, converging to just MCL_CURRENT as we fault
2997 * in pages.
2998 */
Mark Salyzyn64d97d82018-04-09 09:50:32 -07002999 /* CAP_IPC_LOCK required */
Mark Salyzyn721d7c72018-03-21 12:24:58 -07003000 if (mlockall(MCL_CURRENT | MCL_FUTURE | MCL_ONFAULT) && (errno != EINVAL)) {
3001 ALOGW("mlockall failed %s", strerror(errno));
3002 }
Daniel Colascione4dd5d002018-01-03 12:01:02 -08003003
Mark Salyzyn64d97d82018-04-09 09:50:32 -07003004 /* CAP_NICE required */
3005 if (sched_setscheduler(0, SCHED_FIFO, &param)) {
3006 ALOGW("set SCHED_FIFO failed %s", strerror(errno));
3007 }
Mark Salyzyn721d7c72018-03-21 12:24:58 -07003008 }
3009
Todd Poynor3948f802013-07-09 19:35:14 -07003010 mainloop();
Mark Salyzyn721d7c72018-03-21 12:24:58 -07003011 }
Todd Poynor3948f802013-07-09 19:35:14 -07003012
Suren Baghdasaryanb72c6652019-09-04 19:12:29 -07003013 statslog_destroy();
Rajeev Kumar70450032018-01-31 17:54:56 -08003014
Suren Baghdasaryan282ad1a2018-07-26 16:34:27 -07003015 android_log_destroy(&ctx);
3016
Todd Poynor3948f802013-07-09 19:35:14 -07003017 ALOGI("exiting");
3018 return 0;
3019}