blob: b9a7366f316f650625e023f313466436cfb3a517 [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 Baghdasaryan65f54a22018-01-17 17:17:44 -080034#include <sys/sysinfo.h>
Wei Wang2d95c102018-11-21 00:11:44 -080035#include <sys/time.h>
Mark Salyzyn721d7c72018-03-21 12:24:58 -070036#include <sys/types.h>
Suren Baghdasaryan314a5052018-07-24 17:13:06 -070037#include <time.h>
Mark Salyzyne6ed68b2014-04-30 13:36:35 -070038#include <unistd.h>
39
Robert Benea58891d52017-07-31 17:15:20 -070040#include <cutils/properties.h>
Wei Wang2d95c102018-11-21 00:11:44 -080041#include <cutils/sched_policy.h>
Todd Poynor3948f802013-07-09 19:35:14 -070042#include <cutils/sockets.h>
Suren Baghdasaryan0f100512018-01-24 16:51:41 -080043#include <lmkd.h>
Mark Salyzyn30f991f2017-01-10 13:19:54 -080044#include <log/log.h>
Suren Baghdasaryan282ad1a2018-07-26 16:34:27 -070045#include <log/log_event_list.h>
Suren Baghdasaryan314a5052018-07-24 17:13:06 -070046#include <log/log_time.h>
Suren Baghdasaryan77122e52019-01-08 12:54:48 -080047#include <psi/psi.h>
Wei Wang2d95c102018-11-21 00:11:44 -080048#include <system/thread_defs.h>
Mark Salyzyne6ed68b2014-04-30 13:36:35 -070049
Rajeev Kumar70450032018-01-31 17:54:56 -080050#ifdef LMKD_LOG_STATS
Yao Chen389aee12018-05-02 11:19:27 -070051#include "statslog.h"
Rajeev Kumar70450032018-01-31 17:54:56 -080052#endif
53
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 Baghdasaryan282ad1a2018-07-26 16:34:27 -070086/* Android Logger event logtags (see event.logtags) */
87#define MEMINFO_LOG_TAG 10195355
88
Mark Salyzyn64d97d82018-04-09 09:50:32 -070089/* gid containing AID_SYSTEM required */
Todd Poynor3948f802013-07-09 19:35:14 -070090#define INKERNEL_MINFREE_PATH "/sys/module/lowmemorykiller/parameters/minfree"
91#define INKERNEL_ADJ_PATH "/sys/module/lowmemorykiller/parameters/adj"
92
93#define ARRAY_SIZE(x) (sizeof(x) / sizeof(*(x)))
Robert Benea673e2762017-06-01 16:32:31 -070094#define EIGHT_MEGA (1 << 23)
Todd Poynor3948f802013-07-09 19:35:14 -070095
Suren Baghdasaryan314a5052018-07-24 17:13:06 -070096#define TARGET_UPDATE_MIN_INTERVAL_MS 1000
97
98#define NS_PER_MS (NS_PER_SEC / MS_PER_SEC)
Suren Baghdasaryan77122e52019-01-08 12:54:48 -080099#define US_PER_MS (US_PER_SEC / MS_PER_SEC)
Suren Baghdasaryan314a5052018-07-24 17:13:06 -0700100
Suren Baghdasaryan4311d1e2018-03-20 16:03:29 -0700101/* Defined as ProcessList.SYSTEM_ADJ in ProcessList.java */
102#define SYSTEM_ADJ (-900)
103
Greg Kaiserf0da9b02018-03-23 14:16:12 -0700104#define STRINGIFY(x) STRINGIFY_INTERNAL(x)
105#define STRINGIFY_INTERNAL(x) #x
106
Suren Baghdasaryan77122e52019-01-08 12:54:48 -0800107/*
108 * PSI monitor tracking window size.
109 * PSI monitor generates events at most once per window,
110 * therefore we poll memory state for the duration of
111 * PSI_WINDOW_SIZE_MS after the event happens.
112 */
113#define PSI_WINDOW_SIZE_MS 1000
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -0700114/* Polling period after PSI signal when pressure is high */
115#define PSI_POLL_PERIOD_SHORT_MS 10
116/* Polling period after PSI signal when pressure is low */
117#define PSI_POLL_PERIOD_LONG_MS 100
Suren Baghdasaryan77122e52019-01-08 12:54:48 -0800118
Suren Baghdasaryan282ad1a2018-07-26 16:34:27 -0700119#define min(a, b) (((a) < (b)) ? (a) : (b))
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -0700120#define max(a, b) (((a) > (b)) ? (a) : (b))
Suren Baghdasaryan282ad1a2018-07-26 16:34:27 -0700121
Suren Baghdasaryan36934412018-09-05 15:46:32 -0700122#define FAIL_REPORT_RLIMIT_MS 1000
123
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -0700124/*
125 * System property defaults
126 */
127/* ro.lmk.swap_free_low_percentage property defaults */
128#define DEF_LOW_SWAP_LOWRAM 10
129#define DEF_LOW_SWAP 20
130/* ro.lmk.thrashing_limit property defaults */
131#define DEF_THRASHING_LOWRAM 30
132#define DEF_THRASHING 100
133/* ro.lmk.thrashing_limit_decay property defaults */
134#define DEF_THRASHING_DECAY_LOWRAM 50
135#define DEF_THRASHING_DECAY 10
Suren Baghdasaryan844f26b2019-07-15 15:42:09 -0700136/* ro.lmk.psi_partial_stall_ms property defaults */
137#define DEF_PARTIAL_STALL_LOWRAM 200
138#define DEF_PARTIAL_STALL 70
139/* ro.lmk.psi_complete_stall_ms property defaults */
140#define DEF_COMPLETE_STALL 700
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -0700141
Todd Poynor3948f802013-07-09 19:35:14 -0700142/* default to old in-kernel interface if no memory pressure events */
Mark Salyzyn721d7c72018-03-21 12:24:58 -0700143static bool use_inkernel_interface = true;
Robert Benea164baeb2017-09-11 16:53:28 -0700144static bool has_inkernel_module;
Todd Poynor3948f802013-07-09 19:35:14 -0700145
Suren Baghdasaryan96bf3a62017-12-08 12:58:52 -0800146/* memory pressure levels */
147enum vmpressure_level {
148 VMPRESS_LEVEL_LOW = 0,
149 VMPRESS_LEVEL_MEDIUM,
150 VMPRESS_LEVEL_CRITICAL,
151 VMPRESS_LEVEL_COUNT
152};
Todd Poynor3948f802013-07-09 19:35:14 -0700153
Suren Baghdasaryan96bf3a62017-12-08 12:58:52 -0800154static const char *level_name[] = {
155 "low",
156 "medium",
157 "critical"
158};
159
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -0800160struct {
Suren Baghdasaryan9926e572018-04-13 13:41:12 -0700161 int64_t min_nr_free_pages; /* recorded but not used yet */
162 int64_t max_nr_free_pages;
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -0800163} low_pressure_mem = { -1, -1 };
164
Suren Baghdasaryan77122e52019-01-08 12:54:48 -0800165struct psi_threshold {
166 enum psi_stall_type stall_type;
167 int threshold_ms;
168};
169
Suren Baghdasaryan96bf3a62017-12-08 12:58:52 -0800170static int level_oomadj[VMPRESS_LEVEL_COUNT];
Suren Baghdasaryane82e15c2018-01-04 09:16:21 -0800171static int mpevfd[VMPRESS_LEVEL_COUNT] = { -1, -1, -1 };
Robert Beneac47f2992017-08-21 15:18:31 -0700172static bool debug_process_killing;
173static bool enable_pressure_upgrade;
174static int64_t upgrade_pressure;
Robert Benea6e8e7102017-09-13 15:20:30 -0700175static int64_t downgrade_pressure;
Suren Baghdasaryanff61afb2018-04-13 11:45:38 -0700176static bool low_ram_device;
Suren Baghdasaryan662492a2017-12-08 13:17:06 -0800177static bool kill_heaviest_task;
Suren Baghdasaryancaa2dc52018-01-17 17:28:01 -0800178static unsigned long kill_timeout_ms;
Suren Baghdasaryanffdc4dd2018-04-13 13:53:43 -0700179static bool use_minfree_levels;
Suren Baghdasaryance13cb52018-06-19 18:38:12 -0700180static bool per_app_memcg;
Vic Yang360a1132018-08-07 10:18:22 -0700181static int swap_free_low_percentage;
Suren Baghdasaryan844f26b2019-07-15 15:42:09 -0700182static int psi_partial_stall_ms;
183static int psi_complete_stall_ms;
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -0700184static int thrashing_limit_pct;
185static int thrashing_limit_decay_pct;
Suren Baghdasaryan77122e52019-01-08 12:54:48 -0800186static bool use_psi_monitors = false;
187static struct psi_threshold psi_thresholds[VMPRESS_LEVEL_COUNT] = {
188 { PSI_SOME, 70 }, /* 70ms out of 1sec for partial stall */
189 { PSI_SOME, 100 }, /* 100ms out of 1sec for partial stall */
190 { PSI_FULL, 70 }, /* 70ms out of 1sec for complete stall */
191};
Robert Benea58891d52017-07-31 17:15:20 -0700192
Suren Baghdasaryan282ad1a2018-07-26 16:34:27 -0700193static android_log_context ctx;
194
Suren Baghdasaryanef3650f2019-07-15 14:50:49 -0700195enum polling_update {
196 POLLING_DO_NOT_CHANGE,
197 POLLING_START,
198 POLLING_STOP,
199};
200
201/*
202 * Data used for periodic polling for the memory state of the device.
203 * Note that when system is not polling poll_handler is set to NULL,
204 * when polling starts poll_handler gets set and is reset back to
205 * NULL when polling stops.
206 */
207struct polling_params {
208 struct event_handler_info* poll_handler;
209 struct timespec poll_start_tm;
210 struct timespec last_poll_tm;
211 int polling_interval_ms;
212 enum polling_update update;
213};
214
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -0800215/* data required to handle events */
216struct event_handler_info {
217 int data;
Suren Baghdasaryanef3650f2019-07-15 14:50:49 -0700218 void (*handler)(int data, uint32_t events, struct polling_params *poll_params);
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -0800219};
Todd Poynor3948f802013-07-09 19:35:14 -0700220
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -0800221/* data required to handle socket events */
222struct sock_event_handler_info {
223 int sock;
224 struct event_handler_info handler_info;
225};
226
227/* max supported number of data connections */
228#define MAX_DATA_CONN 2
229
230/* socket event handler data */
231static struct sock_event_handler_info ctrl_sock;
232static struct sock_event_handler_info data_sock[MAX_DATA_CONN];
233
234/* vmpressure event handler data */
235static struct event_handler_info vmpressure_hinfo[VMPRESS_LEVEL_COUNT];
236
Jim Blackler3947c932019-04-26 11:18:29 +0100237/* 3 memory pressure levels, 1 ctrl listen socket, 2 ctrl data socket, 1 lmk events */
238#define MAX_EPOLL_EVENTS (2 + MAX_DATA_CONN + VMPRESS_LEVEL_COUNT)
Todd Poynor3948f802013-07-09 19:35:14 -0700239static int epollfd;
240static int maxevents;
241
Chong Zhang0a4acdf2015-10-14 16:19:53 -0700242/* OOM score values used by both kernel and framework */
Todd Poynor16b60992013-09-16 19:26:47 -0700243#define OOM_SCORE_ADJ_MIN (-1000)
244#define OOM_SCORE_ADJ_MAX 1000
245
Todd Poynor3948f802013-07-09 19:35:14 -0700246static int lowmem_adj[MAX_TARGETS];
247static int lowmem_minfree[MAX_TARGETS];
248static int lowmem_targets_size;
249
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -0700250/* Fields to parse in /proc/zoneinfo */
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -0700251/* zoneinfo per-zone fields */
252enum zoneinfo_zone_field {
253 ZI_ZONE_NR_FREE_PAGES = 0,
254 ZI_ZONE_MIN,
255 ZI_ZONE_LOW,
256 ZI_ZONE_HIGH,
257 ZI_ZONE_PRESENT,
258 ZI_ZONE_NR_FREE_CMA,
259 ZI_ZONE_FIELD_COUNT
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -0700260};
261
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -0700262static const char* const zoneinfo_zone_field_names[ZI_ZONE_FIELD_COUNT] = {
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -0700263 "nr_free_pages",
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -0700264 "min",
265 "low",
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -0700266 "high",
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -0700267 "present",
268 "nr_free_cma",
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -0700269};
270
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -0700271/* zoneinfo per-zone special fields */
272enum zoneinfo_zone_spec_field {
273 ZI_ZONE_SPEC_PROTECTION = 0,
274 ZI_ZONE_SPEC_PAGESETS,
275 ZI_ZONE_SPEC_FIELD_COUNT,
276};
277
278static const char* const zoneinfo_zone_spec_field_names[ZI_ZONE_SPEC_FIELD_COUNT] = {
279 "protection:",
280 "pagesets",
281};
282
283/* see __MAX_NR_ZONES definition in kernel mmzone.h */
284#define MAX_NR_ZONES 6
285
286union zoneinfo_zone_fields {
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -0700287 struct {
288 int64_t nr_free_pages;
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -0700289 int64_t min;
290 int64_t low;
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -0700291 int64_t high;
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -0700292 int64_t present;
293 int64_t nr_free_cma;
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -0700294 } field;
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -0700295 int64_t arr[ZI_ZONE_FIELD_COUNT];
296};
297
298struct zoneinfo_zone {
299 union zoneinfo_zone_fields fields;
300 int64_t protection[MAX_NR_ZONES];
301 int64_t max_protection;
302};
303
304/* zoneinfo per-node fields */
305enum zoneinfo_node_field {
306 ZI_NODE_NR_INACTIVE_FILE = 0,
307 ZI_NODE_NR_ACTIVE_FILE,
308 ZI_NODE_WORKINGSET_REFAULT,
309 ZI_NODE_FIELD_COUNT
310};
311
312static const char* const zoneinfo_node_field_names[ZI_NODE_FIELD_COUNT] = {
313 "nr_inactive_file",
314 "nr_active_file",
315 "workingset_refault",
316};
317
318union zoneinfo_node_fields {
319 struct {
320 int64_t nr_inactive_file;
321 int64_t nr_active_file;
322 int64_t workingset_refault;
323 } field;
324 int64_t arr[ZI_NODE_FIELD_COUNT];
325};
326
327struct zoneinfo_node {
328 int id;
329 int zone_count;
330 struct zoneinfo_zone zones[MAX_NR_ZONES];
331 union zoneinfo_node_fields fields;
332};
333
334/* for now two memory nodes is more than enough */
335#define MAX_NR_NODES 2
336
337struct zoneinfo {
338 int node_count;
339 struct zoneinfo_node nodes[MAX_NR_NODES];
340 int64_t totalreserve_pages;
341 int64_t total_inactive_file;
342 int64_t total_active_file;
343 int64_t total_workingset_refault;
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -0700344};
345
346/* Fields to parse in /proc/meminfo */
347enum meminfo_field {
348 MI_NR_FREE_PAGES = 0,
349 MI_CACHED,
350 MI_SWAP_CACHED,
351 MI_BUFFERS,
352 MI_SHMEM,
353 MI_UNEVICTABLE,
Vic Yang360a1132018-08-07 10:18:22 -0700354 MI_TOTAL_SWAP,
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -0700355 MI_FREE_SWAP,
Suren Baghdasaryan282ad1a2018-07-26 16:34:27 -0700356 MI_ACTIVE_ANON,
357 MI_INACTIVE_ANON,
358 MI_ACTIVE_FILE,
359 MI_INACTIVE_FILE,
360 MI_SRECLAIMABLE,
361 MI_SUNRECLAIM,
362 MI_KERNEL_STACK,
363 MI_PAGE_TABLES,
364 MI_ION_HELP,
365 MI_ION_HELP_POOL,
366 MI_CMA_FREE,
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -0700367 MI_FIELD_COUNT
368};
369
370static const char* const meminfo_field_names[MI_FIELD_COUNT] = {
371 "MemFree:",
372 "Cached:",
373 "SwapCached:",
374 "Buffers:",
375 "Shmem:",
376 "Unevictable:",
Vic Yang360a1132018-08-07 10:18:22 -0700377 "SwapTotal:",
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -0700378 "SwapFree:",
Suren Baghdasaryan282ad1a2018-07-26 16:34:27 -0700379 "Active(anon):",
380 "Inactive(anon):",
381 "Active(file):",
382 "Inactive(file):",
383 "SReclaimable:",
384 "SUnreclaim:",
385 "KernelStack:",
386 "PageTables:",
387 "ION_heap:",
388 "ION_heap_pool:",
389 "CmaFree:",
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -0700390};
391
392union meminfo {
393 struct {
394 int64_t nr_free_pages;
395 int64_t cached;
396 int64_t swap_cached;
397 int64_t buffers;
398 int64_t shmem;
399 int64_t unevictable;
Vic Yang360a1132018-08-07 10:18:22 -0700400 int64_t total_swap;
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -0700401 int64_t free_swap;
Suren Baghdasaryan282ad1a2018-07-26 16:34:27 -0700402 int64_t active_anon;
403 int64_t inactive_anon;
404 int64_t active_file;
405 int64_t inactive_file;
406 int64_t sreclaimable;
407 int64_t sunreclaimable;
408 int64_t kernel_stack;
409 int64_t page_tables;
410 int64_t ion_heap;
411 int64_t ion_heap_pool;
412 int64_t cma_free;
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -0700413 /* fields below are calculated rather than read from the file */
414 int64_t nr_file_pages;
415 } field;
416 int64_t arr[MI_FIELD_COUNT];
417};
418
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -0700419/* Fields to parse in /proc/vmstat */
420enum vmstat_field {
421 VS_FREE_PAGES,
422 VS_INACTIVE_FILE,
423 VS_ACTIVE_FILE,
424 VS_WORKINGSET_REFAULT,
425 VS_PGSCAN_KSWAPD,
426 VS_PGSCAN_DIRECT,
427 VS_PGSCAN_DIRECT_THROTTLE,
428 VS_FIELD_COUNT
429};
430
431static const char* const vmstat_field_names[MI_FIELD_COUNT] = {
432 "nr_free_pages",
433 "nr_inactive_file",
434 "nr_active_file",
435 "workingset_refault",
436 "pgscan_kswapd",
437 "pgscan_direct",
438 "pgscan_direct_throttle",
439};
440
441union vmstat {
442 struct {
443 int64_t nr_free_pages;
444 int64_t nr_inactive_file;
445 int64_t nr_active_file;
446 int64_t workingset_refault;
447 int64_t pgscan_kswapd;
448 int64_t pgscan_direct;
449 int64_t pgscan_direct_throttle;
450 } field;
451 int64_t arr[VS_FIELD_COUNT];
452};
453
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -0700454enum field_match_result {
455 NO_MATCH,
456 PARSE_FAIL,
457 PARSE_SUCCESS
458};
459
Todd Poynor3948f802013-07-09 19:35:14 -0700460struct adjslot_list {
461 struct adjslot_list *next;
462 struct adjslot_list *prev;
463};
464
465struct proc {
466 struct adjslot_list asl;
467 int pid;
Colin Crossfbb78c62014-06-13 14:52:43 -0700468 uid_t uid;
Todd Poynor3948f802013-07-09 19:35:14 -0700469 int oomadj;
470 struct proc *pidhash_next;
471};
472
Suren Baghdasaryan6499e5e2018-04-13 12:43:41 -0700473struct reread_data {
474 const char* const filename;
475 int fd;
476};
477
Rajeev Kumar70450032018-01-31 17:54:56 -0800478#ifdef LMKD_LOG_STATS
Rajeev Kumar70450032018-01-31 17:54:56 -0800479static bool enable_stats_log;
480static android_log_context log_ctx;
481#endif
482
Todd Poynor3948f802013-07-09 19:35:14 -0700483#define PIDHASH_SZ 1024
484static struct proc *pidhash[PIDHASH_SZ];
485#define pid_hashfn(x) ((((x) >> 8) ^ (x)) & (PIDHASH_SZ - 1))
486
Chih-Hung Hsiehdaa13ea2016-05-19 16:02:22 -0700487#define ADJTOSLOT(adj) ((adj) + -OOM_SCORE_ADJ_MIN)
Suren Baghdasaryand4a29902018-10-12 11:07:40 -0700488#define ADJTOSLOT_COUNT (ADJTOSLOT(OOM_SCORE_ADJ_MAX) + 1)
489static struct adjslot_list procadjslot_list[ADJTOSLOT_COUNT];
490
491#define MAX_DISTINCT_OOM_ADJ 32
492#define KILLCNT_INVALID_IDX 0xFF
493/*
494 * Because killcnt array is sparse a two-level indirection is used
495 * to keep the size small. killcnt_idx stores index of the element in
496 * killcnt array. Index KILLCNT_INVALID_IDX indicates an unused slot.
497 */
498static uint8_t killcnt_idx[ADJTOSLOT_COUNT];
499static uint16_t killcnt[MAX_DISTINCT_OOM_ADJ];
500static int killcnt_free_idx = 0;
501static uint32_t killcnt_total = 0;
Todd Poynor3948f802013-07-09 19:35:14 -0700502
Todd Poynor3948f802013-07-09 19:35:14 -0700503/* PAGE_SIZE / 1024 */
504static long page_k;
505
Jim Blacklerd2da8142019-09-10 15:30:05 +0100506static char* proc_get_name(int pid);
507static void poll_kernel();
508
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -0700509static int clamp(int low, int high, int value) {
510 return max(min(value, high), low);
511}
512
Suren Baghdasaryan6499e5e2018-04-13 12:43:41 -0700513static bool parse_int64(const char* str, int64_t* ret) {
514 char* endptr;
515 long long val = strtoll(str, &endptr, 10);
516 if (str == endptr || val > INT64_MAX) {
517 return false;
518 }
519 *ret = (int64_t)val;
520 return true;
521}
522
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -0700523static int find_field(const char* name, const char* const field_names[], int field_count) {
524 for (int i = 0; i < field_count; i++) {
525 if (!strcmp(name, field_names[i])) {
526 return i;
527 }
528 }
529 return -1;
530}
531
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -0700532static enum field_match_result match_field(const char* cp, const char* ap,
533 const char* const field_names[],
534 int field_count, int64_t* field,
535 int *field_idx) {
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -0700536 int i = find_field(cp, field_names, field_count);
537 if (i < 0) {
538 return NO_MATCH;
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -0700539 }
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -0700540 *field_idx = i;
541 return parse_int64(ap, field) ? PARSE_SUCCESS : PARSE_FAIL;
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -0700542}
543
Suren Baghdasaryan6499e5e2018-04-13 12:43:41 -0700544/*
545 * Read file content from the beginning up to max_len bytes or EOF
546 * whichever happens first.
547 */
Colin Crossce85d952014-07-11 17:53:27 -0700548static ssize_t read_all(int fd, char *buf, size_t max_len)
549{
550 ssize_t ret = 0;
Suren Baghdasaryan6499e5e2018-04-13 12:43:41 -0700551 off_t offset = 0;
Colin Crossce85d952014-07-11 17:53:27 -0700552
553 while (max_len > 0) {
Suren Baghdasaryan6499e5e2018-04-13 12:43:41 -0700554 ssize_t r = TEMP_FAILURE_RETRY(pread(fd, buf, max_len, offset));
Colin Crossce85d952014-07-11 17:53:27 -0700555 if (r == 0) {
556 break;
557 }
558 if (r == -1) {
559 return -1;
560 }
561 ret += r;
562 buf += r;
Suren Baghdasaryan6499e5e2018-04-13 12:43:41 -0700563 offset += r;
Colin Crossce85d952014-07-11 17:53:27 -0700564 max_len -= r;
565 }
566
567 return ret;
568}
569
Suren Baghdasaryan6499e5e2018-04-13 12:43:41 -0700570/*
571 * Read a new or already opened file from the beginning.
572 * If the file has not been opened yet data->fd should be set to -1.
573 * To be used with files which are read often and possibly during high
574 * memory pressure to minimize file opening which by itself requires kernel
575 * memory allocation and might result in a stall on memory stressed system.
576 */
Suren Baghdasaryana77b3272019-07-15 13:35:04 -0700577static char *reread_file(struct reread_data *data) {
578 /* start with page-size buffer and increase if needed */
579 static ssize_t buf_size = PAGE_SIZE;
580 static char *new_buf, *buf = NULL;
Suren Baghdasaryan6499e5e2018-04-13 12:43:41 -0700581 ssize_t size;
582
583 if (data->fd == -1) {
Suren Baghdasaryana77b3272019-07-15 13:35:04 -0700584 /* First-time buffer initialization */
585 if (!buf && (buf = malloc(buf_size)) == NULL) {
586 return NULL;
587 }
588
589 data->fd = TEMP_FAILURE_RETRY(open(data->filename, O_RDONLY | O_CLOEXEC));
590 if (data->fd < 0) {
Suren Baghdasaryan6499e5e2018-04-13 12:43:41 -0700591 ALOGE("%s open: %s", data->filename, strerror(errno));
Suren Baghdasaryana77b3272019-07-15 13:35:04 -0700592 return NULL;
Suren Baghdasaryan6499e5e2018-04-13 12:43:41 -0700593 }
594 }
595
Suren Baghdasaryana77b3272019-07-15 13:35:04 -0700596 while (true) {
597 size = read_all(data->fd, buf, buf_size - 1);
598 if (size < 0) {
599 ALOGE("%s read: %s", data->filename, strerror(errno));
600 close(data->fd);
601 data->fd = -1;
602 return NULL;
603 }
604 if (size < buf_size - 1) {
605 break;
606 }
607 /*
608 * Since we are reading /proc files we can't use fstat to find out
609 * the real size of the file. Double the buffer size and keep retrying.
610 */
611 if ((new_buf = realloc(buf, buf_size * 2)) == NULL) {
612 errno = ENOMEM;
613 return NULL;
614 }
615 buf = new_buf;
616 buf_size *= 2;
Suren Baghdasaryan6499e5e2018-04-13 12:43:41 -0700617 }
Suren Baghdasaryan6499e5e2018-04-13 12:43:41 -0700618 buf[size] = 0;
619
Suren Baghdasaryana77b3272019-07-15 13:35:04 -0700620 return buf;
Suren Baghdasaryan6499e5e2018-04-13 12:43:41 -0700621}
622
Todd Poynor3948f802013-07-09 19:35:14 -0700623static struct proc *pid_lookup(int pid) {
624 struct proc *procp;
625
626 for (procp = pidhash[pid_hashfn(pid)]; procp && procp->pid != pid;
627 procp = procp->pidhash_next)
628 ;
629
630 return procp;
631}
632
633static void adjslot_insert(struct adjslot_list *head, struct adjslot_list *new)
634{
635 struct adjslot_list *next = head->next;
636 new->prev = head;
637 new->next = next;
638 next->prev = new;
639 head->next = new;
640}
641
642static void adjslot_remove(struct adjslot_list *old)
643{
644 struct adjslot_list *prev = old->prev;
645 struct adjslot_list *next = old->next;
646 next->prev = prev;
647 prev->next = next;
648}
649
650static struct adjslot_list *adjslot_tail(struct adjslot_list *head) {
651 struct adjslot_list *asl = head->prev;
652
653 return asl == head ? NULL : asl;
654}
655
656static void proc_slot(struct proc *procp) {
657 int adjslot = ADJTOSLOT(procp->oomadj);
658
659 adjslot_insert(&procadjslot_list[adjslot], &procp->asl);
660}
661
662static void proc_unslot(struct proc *procp) {
663 adjslot_remove(&procp->asl);
664}
665
666static void proc_insert(struct proc *procp) {
667 int hval = pid_hashfn(procp->pid);
668
669 procp->pidhash_next = pidhash[hval];
670 pidhash[hval] = procp;
671 proc_slot(procp);
672}
673
674static int pid_remove(int pid) {
675 int hval = pid_hashfn(pid);
676 struct proc *procp;
677 struct proc *prevp;
678
679 for (procp = pidhash[hval], prevp = NULL; procp && procp->pid != pid;
680 procp = procp->pidhash_next)
681 prevp = procp;
682
683 if (!procp)
684 return -1;
685
686 if (!prevp)
687 pidhash[hval] = procp->pidhash_next;
688 else
689 prevp->pidhash_next = procp->pidhash_next;
690
691 proc_unslot(procp);
692 free(procp);
693 return 0;
694}
695
Suren Baghdasaryan1ffa2462018-03-20 13:53:17 -0700696/*
697 * Write a string to a file.
698 * Returns false if the file does not exist.
699 */
700static bool writefilestring(const char *path, const char *s,
701 bool err_if_missing) {
Nick Kralevichc68c8862015-12-18 20:52:37 -0800702 int fd = open(path, O_WRONLY | O_CLOEXEC);
Suren Baghdasaryan1ffa2462018-03-20 13:53:17 -0700703 ssize_t len = strlen(s);
704 ssize_t ret;
Todd Poynor3948f802013-07-09 19:35:14 -0700705
706 if (fd < 0) {
Suren Baghdasaryan1ffa2462018-03-20 13:53:17 -0700707 if (err_if_missing) {
708 ALOGE("Error opening %s; errno=%d", path, errno);
709 }
710 return false;
Todd Poynor3948f802013-07-09 19:35:14 -0700711 }
712
Suren Baghdasaryan1ffa2462018-03-20 13:53:17 -0700713 ret = TEMP_FAILURE_RETRY(write(fd, s, len));
Todd Poynor3948f802013-07-09 19:35:14 -0700714 if (ret < 0) {
715 ALOGE("Error writing %s; errno=%d", path, errno);
716 } else if (ret < len) {
Suren Baghdasaryan1ffa2462018-03-20 13:53:17 -0700717 ALOGE("Short write on %s; length=%zd", path, ret);
Todd Poynor3948f802013-07-09 19:35:14 -0700718 }
719
720 close(fd);
Suren Baghdasaryan1ffa2462018-03-20 13:53:17 -0700721 return true;
Todd Poynor3948f802013-07-09 19:35:14 -0700722}
723
Suren Baghdasaryan314a5052018-07-24 17:13:06 -0700724static inline long get_time_diff_ms(struct timespec *from,
725 struct timespec *to) {
726 return (to->tv_sec - from->tv_sec) * (long)MS_PER_SEC +
727 (to->tv_nsec - from->tv_nsec) / (long)NS_PER_MS;
728}
729
Suren Baghdasaryan0082ef12019-07-02 15:52:07 -0700730static int proc_get_tgid(int pid) {
731 char path[PATH_MAX];
732 char buf[PAGE_SIZE];
733 int fd;
734 ssize_t size;
735 char *pos;
736 int64_t tgid = -1;
737
738 snprintf(path, PATH_MAX, "/proc/%d/status", pid);
739 fd = open(path, O_RDONLY | O_CLOEXEC);
740 if (fd < 0) {
741 return -1;
742 }
743
744 size = read_all(fd, buf, sizeof(buf) - 1);
745 if (size < 0) {
746 goto out;
747 }
748 buf[size] = 0;
749
750 pos = buf;
751 while (true) {
752 pos = strstr(pos, PROC_STATUS_TGID_FIELD);
753 /* Stop if TGID tag not found or found at the line beginning */
754 if (pos == NULL || pos == buf || pos[-1] == '\n') {
755 break;
756 }
757 pos++;
758 }
759
760 if (pos == NULL) {
761 goto out;
762 }
763
764 pos += strlen(PROC_STATUS_TGID_FIELD);
765 while (*pos == ' ') pos++;
766 parse_int64(pos, &tgid);
767
768out:
769 close(fd);
770 return (int)tgid;
771}
772
Suren Baghdasaryan0f100512018-01-24 16:51:41 -0800773static void cmd_procprio(LMKD_CTRL_PACKET packet) {
Todd Poynor3948f802013-07-09 19:35:14 -0700774 struct proc *procp;
775 char path[80];
776 char val[20];
Robert Benea673e2762017-06-01 16:32:31 -0700777 int soft_limit_mult;
Suren Baghdasaryan0f100512018-01-24 16:51:41 -0800778 struct lmk_procprio params;
Suren Baghdasaryan4311d1e2018-03-20 16:03:29 -0700779 bool is_system_server;
780 struct passwd *pwdrec;
Suren Baghdasaryan0082ef12019-07-02 15:52:07 -0700781 int tgid;
Todd Poynor3948f802013-07-09 19:35:14 -0700782
Suren Baghdasaryan0f100512018-01-24 16:51:41 -0800783 lmkd_pack_get_procprio(packet, &params);
784
785 if (params.oomadj < OOM_SCORE_ADJ_MIN ||
786 params.oomadj > OOM_SCORE_ADJ_MAX) {
787 ALOGE("Invalid PROCPRIO oomadj argument %d", params.oomadj);
Todd Poynor3948f802013-07-09 19:35:14 -0700788 return;
789 }
790
Suren Baghdasaryan0082ef12019-07-02 15:52:07 -0700791 /* Check if registered process is a thread group leader */
792 tgid = proc_get_tgid(params.pid);
793 if (tgid >= 0 && tgid != params.pid) {
794 ALOGE("Attempt to register a task that is not a thread group leader (tid %d, tgid %d)",
795 params.pid, tgid);
796 return;
797 }
798
Mark Salyzyn64d97d82018-04-09 09:50:32 -0700799 /* gid containing AID_READPROC required */
800 /* CAP_SYS_RESOURCE required */
801 /* CAP_DAC_OVERRIDE required */
Suren Baghdasaryan0f100512018-01-24 16:51:41 -0800802 snprintf(path, sizeof(path), "/proc/%d/oom_score_adj", params.pid);
803 snprintf(val, sizeof(val), "%d", params.oomadj);
Suren Baghdasaryan1ffa2462018-03-20 13:53:17 -0700804 if (!writefilestring(path, val, false)) {
805 ALOGW("Failed to open %s; errno=%d: process %d might have been killed",
806 path, errno, params.pid);
807 /* If this file does not exist the process is dead. */
808 return;
809 }
Todd Poynor3948f802013-07-09 19:35:14 -0700810
Mark Salyzyn721d7c72018-03-21 12:24:58 -0700811 if (use_inkernel_interface) {
Jim Blacklerd2da8142019-09-10 15:30:05 +0100812#ifdef LMKD_LOG_STATS
813 stats_store_taskname(params.pid, proc_get_name(params.pid));
814#endif
Todd Poynor3948f802013-07-09 19:35:14 -0700815 return;
Mark Salyzyn721d7c72018-03-21 12:24:58 -0700816 }
Todd Poynor3948f802013-07-09 19:35:14 -0700817
Suren Baghdasaryance13cb52018-06-19 18:38:12 -0700818 if (per_app_memcg) {
Suren Baghdasaryan20686f02018-05-18 14:42:00 -0700819 if (params.oomadj >= 900) {
820 soft_limit_mult = 0;
821 } else if (params.oomadj >= 800) {
822 soft_limit_mult = 0;
823 } else if (params.oomadj >= 700) {
824 soft_limit_mult = 0;
825 } else if (params.oomadj >= 600) {
826 // Launcher should be perceptible, don't kill it.
827 params.oomadj = 200;
828 soft_limit_mult = 1;
829 } else if (params.oomadj >= 500) {
830 soft_limit_mult = 0;
831 } else if (params.oomadj >= 400) {
832 soft_limit_mult = 0;
833 } else if (params.oomadj >= 300) {
834 soft_limit_mult = 1;
835 } else if (params.oomadj >= 200) {
Srinivas Paladugu3eb20bc2018-10-09 14:21:10 -0700836 soft_limit_mult = 8;
Suren Baghdasaryan20686f02018-05-18 14:42:00 -0700837 } else if (params.oomadj >= 100) {
838 soft_limit_mult = 10;
839 } else if (params.oomadj >= 0) {
840 soft_limit_mult = 20;
841 } else {
842 // Persistent processes will have a large
843 // soft limit 512MB.
844 soft_limit_mult = 64;
845 }
Robert Benea673e2762017-06-01 16:32:31 -0700846
Suren Baghdasaryan3862dd32018-05-21 19:48:47 -0700847 snprintf(path, sizeof(path), MEMCG_SYSFS_PATH
848 "apps/uid_%d/pid_%d/memory.soft_limit_in_bytes",
849 params.uid, params.pid);
Suren Baghdasaryan20686f02018-05-18 14:42:00 -0700850 snprintf(val, sizeof(val), "%d", soft_limit_mult * EIGHT_MEGA);
Suren Baghdasaryan3862dd32018-05-21 19:48:47 -0700851
852 /*
853 * system_server process has no memcg under /dev/memcg/apps but should be
854 * registered with lmkd. This is the best way so far to identify it.
855 */
856 is_system_server = (params.oomadj == SYSTEM_ADJ &&
857 (pwdrec = getpwnam("system")) != NULL &&
858 params.uid == pwdrec->pw_uid);
859 writefilestring(path, val, !is_system_server);
Robert Benea673e2762017-06-01 16:32:31 -0700860 }
861
Suren Baghdasaryan0f100512018-01-24 16:51:41 -0800862 procp = pid_lookup(params.pid);
Todd Poynor3948f802013-07-09 19:35:14 -0700863 if (!procp) {
864 procp = malloc(sizeof(struct proc));
865 if (!procp) {
866 // Oh, the irony. May need to rebuild our state.
867 return;
868 }
869
Suren Baghdasaryan0f100512018-01-24 16:51:41 -0800870 procp->pid = params.pid;
871 procp->uid = params.uid;
872 procp->oomadj = params.oomadj;
Todd Poynor3948f802013-07-09 19:35:14 -0700873 proc_insert(procp);
874 } else {
875 proc_unslot(procp);
Suren Baghdasaryan0f100512018-01-24 16:51:41 -0800876 procp->oomadj = params.oomadj;
Todd Poynor3948f802013-07-09 19:35:14 -0700877 proc_slot(procp);
878 }
879}
880
Suren Baghdasaryan0f100512018-01-24 16:51:41 -0800881static void cmd_procremove(LMKD_CTRL_PACKET packet) {
882 struct lmk_procremove params;
883
Mark Salyzyn721d7c72018-03-21 12:24:58 -0700884 if (use_inkernel_interface) {
Jim Blacklerd2da8142019-09-10 15:30:05 +0100885#ifdef LMKD_LOG_STATS
886 /* Perform an extra check before the pid is removed, after which it
887 * will be impossible for poll_kernel to get the taskname. poll_kernel()
888 * is potentially a long-running blocking function; however this method
889 * handles AMS requests but does not block AMS.*/
890 if (enable_stats_log) {
891 poll_kernel();
892 }
893 stats_remove_taskname(params.pid);
894#endif
Todd Poynor3948f802013-07-09 19:35:14 -0700895 return;
Mark Salyzyn721d7c72018-03-21 12:24:58 -0700896 }
Todd Poynor3948f802013-07-09 19:35:14 -0700897
Suren Baghdasaryan0f100512018-01-24 16:51:41 -0800898 lmkd_pack_get_procremove(packet, &params);
Suren Baghdasaryan01063272018-10-12 11:28:33 -0700899 /*
900 * WARNING: After pid_remove() procp is freed and can't be used!
901 * Therefore placed at the end of the function.
902 */
Suren Baghdasaryan0f100512018-01-24 16:51:41 -0800903 pid_remove(params.pid);
Todd Poynor3948f802013-07-09 19:35:14 -0700904}
905
Suren Baghdasaryane3b60472018-10-10 14:17:17 -0700906static void cmd_procpurge() {
907 int i;
908 struct proc *procp;
909 struct proc *next;
910
911 if (use_inkernel_interface) {
Jim Blacklerd2da8142019-09-10 15:30:05 +0100912#ifdef LMKD_LOG_STATS
913 stats_purge_tasknames();
914#endif
Suren Baghdasaryane3b60472018-10-10 14:17:17 -0700915 return;
916 }
917
918 for (i = 0; i <= ADJTOSLOT(OOM_SCORE_ADJ_MAX); i++) {
919 procadjslot_list[i].next = &procadjslot_list[i];
920 procadjslot_list[i].prev = &procadjslot_list[i];
921 }
922
923 for (i = 0; i < PIDHASH_SZ; i++) {
924 procp = pidhash[i];
925 while (procp) {
926 next = procp->pidhash_next;
927 free(procp);
928 procp = next;
929 }
930 }
931 memset(&pidhash[0], 0, sizeof(pidhash));
932}
933
Suren Baghdasaryand4a29902018-10-12 11:07:40 -0700934static void inc_killcnt(int oomadj) {
935 int slot = ADJTOSLOT(oomadj);
936 uint8_t idx = killcnt_idx[slot];
937
938 if (idx == KILLCNT_INVALID_IDX) {
939 /* index is not assigned for this oomadj */
940 if (killcnt_free_idx < MAX_DISTINCT_OOM_ADJ) {
941 killcnt_idx[slot] = killcnt_free_idx;
942 killcnt[killcnt_free_idx] = 1;
943 killcnt_free_idx++;
944 } else {
945 ALOGW("Number of distinct oomadj levels exceeds %d",
946 MAX_DISTINCT_OOM_ADJ);
947 }
948 } else {
949 /*
950 * wraparound is highly unlikely and is detectable using total
951 * counter because it has to be equal to the sum of all counters
952 */
953 killcnt[idx]++;
954 }
955 /* increment total kill counter */
956 killcnt_total++;
957}
958
959static int get_killcnt(int min_oomadj, int max_oomadj) {
960 int slot;
961 int count = 0;
962
963 if (min_oomadj > max_oomadj)
964 return 0;
965
966 /* special case to get total kill count */
967 if (min_oomadj > OOM_SCORE_ADJ_MAX)
968 return killcnt_total;
969
970 while (min_oomadj <= max_oomadj &&
971 (slot = ADJTOSLOT(min_oomadj)) < ADJTOSLOT_COUNT) {
972 uint8_t idx = killcnt_idx[slot];
973 if (idx != KILLCNT_INVALID_IDX) {
974 count += killcnt[idx];
975 }
976 min_oomadj++;
977 }
978
979 return count;
980}
981
982static int cmd_getkillcnt(LMKD_CTRL_PACKET packet) {
983 struct lmk_getkillcnt params;
984
985 if (use_inkernel_interface) {
986 /* kernel driver does not expose this information */
987 return 0;
988 }
989
990 lmkd_pack_get_getkillcnt(packet, &params);
991
992 return get_killcnt(params.min_oomadj, params.max_oomadj);
993}
994
Suren Baghdasaryan0f100512018-01-24 16:51:41 -0800995static void cmd_target(int ntargets, LMKD_CTRL_PACKET packet) {
Todd Poynor3948f802013-07-09 19:35:14 -0700996 int i;
Suren Baghdasaryan0f100512018-01-24 16:51:41 -0800997 struct lmk_target target;
Suren Baghdasaryan314a5052018-07-24 17:13:06 -0700998 char minfree_str[PROPERTY_VALUE_MAX];
999 char *pstr = minfree_str;
1000 char *pend = minfree_str + sizeof(minfree_str);
1001 static struct timespec last_req_tm;
1002 struct timespec curr_tm;
Todd Poynor3948f802013-07-09 19:35:14 -07001003
Suren Baghdasaryan314a5052018-07-24 17:13:06 -07001004 if (ntargets < 1 || ntargets > (int)ARRAY_SIZE(lowmem_adj))
Todd Poynor3948f802013-07-09 19:35:14 -07001005 return;
1006
Suren Baghdasaryan314a5052018-07-24 17:13:06 -07001007 /*
1008 * Ratelimit minfree updates to once per TARGET_UPDATE_MIN_INTERVAL_MS
1009 * to prevent DoS attacks
1010 */
1011 if (clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm) != 0) {
1012 ALOGE("Failed to get current time");
1013 return;
1014 }
1015
1016 if (get_time_diff_ms(&last_req_tm, &curr_tm) <
1017 TARGET_UPDATE_MIN_INTERVAL_MS) {
1018 ALOGE("Ignoring frequent updated to lmkd limits");
1019 return;
1020 }
1021
1022 last_req_tm = curr_tm;
1023
Todd Poynor3948f802013-07-09 19:35:14 -07001024 for (i = 0; i < ntargets; i++) {
Suren Baghdasaryan0f100512018-01-24 16:51:41 -08001025 lmkd_pack_get_target(packet, i, &target);
1026 lowmem_minfree[i] = target.minfree;
1027 lowmem_adj[i] = target.oom_adj_score;
Suren Baghdasaryan314a5052018-07-24 17:13:06 -07001028
1029 pstr += snprintf(pstr, pend - pstr, "%d:%d,", target.minfree,
1030 target.oom_adj_score);
1031 if (pstr >= pend) {
1032 /* if no more space in the buffer then terminate the loop */
1033 pstr = pend;
1034 break;
1035 }
Todd Poynor3948f802013-07-09 19:35:14 -07001036 }
1037
1038 lowmem_targets_size = ntargets;
1039
Suren Baghdasaryan314a5052018-07-24 17:13:06 -07001040 /* Override the last extra comma */
1041 pstr[-1] = '\0';
1042 property_set("sys.lmk.minfree_levels", minfree_str);
1043
Robert Benea164baeb2017-09-11 16:53:28 -07001044 if (has_inkernel_module) {
Todd Poynor3948f802013-07-09 19:35:14 -07001045 char minfreestr[128];
1046 char killpriostr[128];
1047
1048 minfreestr[0] = '\0';
1049 killpriostr[0] = '\0';
1050
1051 for (i = 0; i < lowmem_targets_size; i++) {
1052 char val[40];
1053
1054 if (i) {
1055 strlcat(minfreestr, ",", sizeof(minfreestr));
1056 strlcat(killpriostr, ",", sizeof(killpriostr));
1057 }
1058
Robert Benea164baeb2017-09-11 16:53:28 -07001059 snprintf(val, sizeof(val), "%d", use_inkernel_interface ? lowmem_minfree[i] : 0);
Todd Poynor3948f802013-07-09 19:35:14 -07001060 strlcat(minfreestr, val, sizeof(minfreestr));
Robert Benea164baeb2017-09-11 16:53:28 -07001061 snprintf(val, sizeof(val), "%d", use_inkernel_interface ? lowmem_adj[i] : 0);
Todd Poynor3948f802013-07-09 19:35:14 -07001062 strlcat(killpriostr, val, sizeof(killpriostr));
1063 }
1064
Suren Baghdasaryan1ffa2462018-03-20 13:53:17 -07001065 writefilestring(INKERNEL_MINFREE_PATH, minfreestr, true);
1066 writefilestring(INKERNEL_ADJ_PATH, killpriostr, true);
Todd Poynor3948f802013-07-09 19:35:14 -07001067 }
1068}
1069
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08001070static void ctrl_data_close(int dsock_idx) {
1071 struct epoll_event epev;
1072
1073 ALOGI("closing lmkd data connection");
1074 if (epoll_ctl(epollfd, EPOLL_CTL_DEL, data_sock[dsock_idx].sock, &epev) == -1) {
1075 // Log a warning and keep going
1076 ALOGW("epoll_ctl for data connection socket failed; errno=%d", errno);
1077 }
Todd Poynor3948f802013-07-09 19:35:14 -07001078 maxevents--;
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08001079
1080 close(data_sock[dsock_idx].sock);
1081 data_sock[dsock_idx].sock = -1;
Todd Poynor3948f802013-07-09 19:35:14 -07001082}
1083
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08001084static int ctrl_data_read(int dsock_idx, char *buf, size_t bufsz) {
Todd Poynor3948f802013-07-09 19:35:14 -07001085 int ret = 0;
1086
Suren Baghdasaryan6499e5e2018-04-13 12:43:41 -07001087 ret = TEMP_FAILURE_RETRY(read(data_sock[dsock_idx].sock, buf, bufsz));
Todd Poynor3948f802013-07-09 19:35:14 -07001088
1089 if (ret == -1) {
1090 ALOGE("control data socket read failed; errno=%d", errno);
1091 } else if (ret == 0) {
1092 ALOGE("Got EOF on control data socket");
1093 ret = -1;
1094 }
1095
1096 return ret;
1097}
1098
Suren Baghdasaryand4a29902018-10-12 11:07:40 -07001099static int ctrl_data_write(int dsock_idx, char *buf, size_t bufsz) {
1100 int ret = 0;
1101
1102 ret = TEMP_FAILURE_RETRY(write(data_sock[dsock_idx].sock, buf, bufsz));
1103
1104 if (ret == -1) {
1105 ALOGE("control data socket write failed; errno=%d", errno);
1106 } else if (ret == 0) {
1107 ALOGE("Got EOF on control data socket");
1108 ret = -1;
1109 }
1110
1111 return ret;
1112}
1113
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08001114static void ctrl_command_handler(int dsock_idx) {
Suren Baghdasaryan0f100512018-01-24 16:51:41 -08001115 LMKD_CTRL_PACKET packet;
Todd Poynor3948f802013-07-09 19:35:14 -07001116 int len;
Suren Baghdasaryan0f100512018-01-24 16:51:41 -08001117 enum lmk_cmd cmd;
Todd Poynor3948f802013-07-09 19:35:14 -07001118 int nargs;
1119 int targets;
Suren Baghdasaryand4a29902018-10-12 11:07:40 -07001120 int kill_cnt;
Todd Poynor3948f802013-07-09 19:35:14 -07001121
Suren Baghdasaryan0f100512018-01-24 16:51:41 -08001122 len = ctrl_data_read(dsock_idx, (char *)packet, CTRL_PACKET_MAX_SIZE);
Todd Poynor3948f802013-07-09 19:35:14 -07001123 if (len <= 0)
1124 return;
1125
Suren Baghdasaryan0f100512018-01-24 16:51:41 -08001126 if (len < (int)sizeof(int)) {
1127 ALOGE("Wrong control socket read length len=%d", len);
1128 return;
1129 }
1130
1131 cmd = lmkd_pack_get_cmd(packet);
Todd Poynor3948f802013-07-09 19:35:14 -07001132 nargs = len / sizeof(int) - 1;
1133 if (nargs < 0)
1134 goto wronglen;
1135
Todd Poynor3948f802013-07-09 19:35:14 -07001136 switch(cmd) {
1137 case LMK_TARGET:
1138 targets = nargs / 2;
1139 if (nargs & 0x1 || targets > (int)ARRAY_SIZE(lowmem_adj))
1140 goto wronglen;
Suren Baghdasaryan0f100512018-01-24 16:51:41 -08001141 cmd_target(targets, packet);
Todd Poynor3948f802013-07-09 19:35:14 -07001142 break;
1143 case LMK_PROCPRIO:
Colin Crossfbb78c62014-06-13 14:52:43 -07001144 if (nargs != 3)
Todd Poynor3948f802013-07-09 19:35:14 -07001145 goto wronglen;
Suren Baghdasaryan0f100512018-01-24 16:51:41 -08001146 cmd_procprio(packet);
Todd Poynor3948f802013-07-09 19:35:14 -07001147 break;
1148 case LMK_PROCREMOVE:
1149 if (nargs != 1)
1150 goto wronglen;
Suren Baghdasaryan0f100512018-01-24 16:51:41 -08001151 cmd_procremove(packet);
Todd Poynor3948f802013-07-09 19:35:14 -07001152 break;
Suren Baghdasaryane3b60472018-10-10 14:17:17 -07001153 case LMK_PROCPURGE:
1154 if (nargs != 0)
1155 goto wronglen;
1156 cmd_procpurge();
1157 break;
Suren Baghdasaryand4a29902018-10-12 11:07:40 -07001158 case LMK_GETKILLCNT:
1159 if (nargs != 2)
1160 goto wronglen;
1161 kill_cnt = cmd_getkillcnt(packet);
1162 len = lmkd_pack_set_getkillcnt_repl(packet, kill_cnt);
1163 if (ctrl_data_write(dsock_idx, (char *)packet, len) != len)
1164 return;
1165 break;
Todd Poynor3948f802013-07-09 19:35:14 -07001166 default:
1167 ALOGE("Received unknown command code %d", cmd);
1168 return;
1169 }
1170
1171 return;
1172
1173wronglen:
1174 ALOGE("Wrong control socket read length cmd=%d len=%d", cmd, len);
1175}
1176
Suren Baghdasaryanef3650f2019-07-15 14:50:49 -07001177static void ctrl_data_handler(int data, uint32_t events,
1178 struct polling_params *poll_params __unused) {
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08001179 if (events & EPOLLIN) {
1180 ctrl_command_handler(data);
Todd Poynor3948f802013-07-09 19:35:14 -07001181 }
1182}
1183
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08001184static int get_free_dsock() {
1185 for (int i = 0; i < MAX_DATA_CONN; i++) {
1186 if (data_sock[i].sock < 0) {
1187 return i;
1188 }
1189 }
1190 return -1;
1191}
Todd Poynor3948f802013-07-09 19:35:14 -07001192
Suren Baghdasaryanef3650f2019-07-15 14:50:49 -07001193static void ctrl_connect_handler(int data __unused, uint32_t events __unused,
1194 struct polling_params *poll_params __unused) {
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08001195 struct epoll_event epev;
1196 int free_dscock_idx = get_free_dsock();
1197
1198 if (free_dscock_idx < 0) {
1199 /*
1200 * Number of data connections exceeded max supported. This should not
1201 * happen but if it does we drop all existing connections and accept
1202 * the new one. This prevents inactive connections from monopolizing
1203 * data socket and if we drop ActivityManager connection it will
1204 * immediately reconnect.
1205 */
1206 for (int i = 0; i < MAX_DATA_CONN; i++) {
1207 ctrl_data_close(i);
1208 }
1209 free_dscock_idx = 0;
Todd Poynor3948f802013-07-09 19:35:14 -07001210 }
1211
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08001212 data_sock[free_dscock_idx].sock = accept(ctrl_sock.sock, NULL, NULL);
1213 if (data_sock[free_dscock_idx].sock < 0) {
Todd Poynor3948f802013-07-09 19:35:14 -07001214 ALOGE("lmkd control socket accept failed; errno=%d", errno);
1215 return;
1216 }
1217
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08001218 ALOGI("lmkd data connection established");
1219 /* use data to store data connection idx */
1220 data_sock[free_dscock_idx].handler_info.data = free_dscock_idx;
1221 data_sock[free_dscock_idx].handler_info.handler = ctrl_data_handler;
Todd Poynor3948f802013-07-09 19:35:14 -07001222 epev.events = EPOLLIN;
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08001223 epev.data.ptr = (void *)&(data_sock[free_dscock_idx].handler_info);
1224 if (epoll_ctl(epollfd, EPOLL_CTL_ADD, data_sock[free_dscock_idx].sock, &epev) == -1) {
Todd Poynor3948f802013-07-09 19:35:14 -07001225 ALOGE("epoll_ctl for data connection socket failed; errno=%d", errno);
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08001226 ctrl_data_close(free_dscock_idx);
Todd Poynor3948f802013-07-09 19:35:14 -07001227 return;
1228 }
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08001229 maxevents++;
Todd Poynor3948f802013-07-09 19:35:14 -07001230}
1231
Rajeev Kumar70450032018-01-31 17:54:56 -08001232#ifdef LMKD_LOG_STATS
Rajeev Kumar4dbc24d2018-10-05 12:34:59 -07001233static void memory_stat_parse_line(char* line, struct memory_stat* mem_st) {
Greg Kaiserf0da9b02018-03-23 14:16:12 -07001234 char key[LINE_MAX + 1];
Rajeev Kumar70450032018-01-31 17:54:56 -08001235 int64_t value;
1236
Greg Kaiserf0da9b02018-03-23 14:16:12 -07001237 sscanf(line, "%" STRINGIFY(LINE_MAX) "s %" SCNd64 "", key, &value);
Rajeev Kumar70450032018-01-31 17:54:56 -08001238
1239 if (strcmp(key, "total_") < 0) {
1240 return;
1241 }
1242
1243 if (!strcmp(key, "total_pgfault"))
1244 mem_st->pgfault = value;
1245 else if (!strcmp(key, "total_pgmajfault"))
1246 mem_st->pgmajfault = value;
1247 else if (!strcmp(key, "total_rss"))
1248 mem_st->rss_in_bytes = value;
1249 else if (!strcmp(key, "total_cache"))
1250 mem_st->cache_in_bytes = value;
1251 else if (!strcmp(key, "total_swap"))
1252 mem_st->swap_in_bytes = value;
1253}
1254
Rajeev Kumar4dbc24d2018-10-05 12:34:59 -07001255static int memory_stat_from_cgroup(struct memory_stat* mem_st, int pid, uid_t uid) {
Suren Baghdasaryan1d1c0022018-06-19 18:38:12 -07001256 FILE *fp;
1257 char buf[PATH_MAX];
Rajeev Kumar70450032018-01-31 17:54:56 -08001258
Suren Baghdasaryan1d1c0022018-06-19 18:38:12 -07001259 snprintf(buf, sizeof(buf), MEMCG_PROCESS_MEMORY_STAT_PATH, uid, pid);
Rajeev Kumar70450032018-01-31 17:54:56 -08001260
Suren Baghdasaryan1d1c0022018-06-19 18:38:12 -07001261 fp = fopen(buf, "r");
Rajeev Kumar70450032018-01-31 17:54:56 -08001262
Suren Baghdasaryan1d1c0022018-06-19 18:38:12 -07001263 if (fp == NULL) {
1264 ALOGE("%s open failed: %s", buf, strerror(errno));
1265 return -1;
1266 }
Rajeev Kumar70450032018-01-31 17:54:56 -08001267
Rajeev Kumar4dbc24d2018-10-05 12:34:59 -07001268 while (fgets(buf, PAGE_SIZE, fp) != NULL) {
Suren Baghdasaryan1d1c0022018-06-19 18:38:12 -07001269 memory_stat_parse_line(buf, mem_st);
1270 }
1271 fclose(fp);
1272
1273 return 0;
Rajeev Kumar70450032018-01-31 17:54:56 -08001274}
Rajeev Kumar4dbc24d2018-10-05 12:34:59 -07001275
1276static int memory_stat_from_procfs(struct memory_stat* mem_st, int pid) {
1277 char path[PATH_MAX];
1278 char buffer[PROC_STAT_BUFFER_SIZE];
1279 int fd, ret;
1280
1281 snprintf(path, sizeof(path), PROC_STAT_FILE_PATH, pid);
1282 if ((fd = open(path, O_RDONLY | O_CLOEXEC)) < 0) {
1283 ALOGE("%s open failed: %s", path, strerror(errno));
1284 return -1;
1285 }
1286
1287 ret = read(fd, buffer, sizeof(buffer));
1288 if (ret < 0) {
1289 ALOGE("%s read failed: %s", path, strerror(errno));
1290 close(fd);
1291 return -1;
1292 }
1293 close(fd);
1294
1295 // field 10 is pgfault
1296 // field 12 is pgmajfault
Jim Blackler1417cdb2018-11-21 16:22:36 +00001297 // field 22 is starttime
Rajeev Kumar4dbc24d2018-10-05 12:34:59 -07001298 // field 24 is rss_in_pages
Jim Blackler1417cdb2018-11-21 16:22:36 +00001299 int64_t pgfault = 0, pgmajfault = 0, starttime = 0, rss_in_pages = 0;
Rajeev Kumar4dbc24d2018-10-05 12:34:59 -07001300 if (sscanf(buffer,
1301 "%*u %*s %*s %*d %*d %*d %*d %*d %*d %" SCNd64 " %*d "
1302 "%" SCNd64 " %*d %*u %*u %*d %*d %*d %*d %*d %*d "
Jim Blackler1417cdb2018-11-21 16:22:36 +00001303 "%" SCNd64 " %*d %" SCNd64 "",
1304 &pgfault, &pgmajfault, &starttime, &rss_in_pages) != 4) {
Rajeev Kumar4dbc24d2018-10-05 12:34:59 -07001305 return -1;
1306 }
1307 mem_st->pgfault = pgfault;
1308 mem_st->pgmajfault = pgmajfault;
1309 mem_st->rss_in_bytes = (rss_in_pages * PAGE_SIZE);
Jim Blackler1417cdb2018-11-21 16:22:36 +00001310 mem_st->process_start_time_ns = starttime * (NS_PER_SEC / sysconf(_SC_CLK_TCK));
Rajeev Kumar4dbc24d2018-10-05 12:34:59 -07001311 return 0;
1312}
Rajeev Kumar70450032018-01-31 17:54:56 -08001313#endif
1314
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07001315/*
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07001316 * /proc/zoneinfo parsing routines
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07001317 * Expected file format is:
1318 *
1319 * Node <node_id>, zone <zone_name>
1320 * (
1321 * per-node stats
1322 * (<per-node field name> <value>)+
1323 * )?
1324 * (pages free <value>
1325 * (<per-zone field name> <value>)+
1326 * pagesets
1327 * (<unused fields>)*
1328 * )+
1329 * ...
1330 */
1331static void zoneinfo_parse_protection(char *buf, struct zoneinfo_zone *zone) {
1332 int zone_idx;
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001333 int64_t max = 0;
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001334 char *save_ptr;
1335
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07001336 for (buf = strtok_r(buf, "(), ", &save_ptr), zone_idx = 0;
1337 buf && zone_idx < MAX_NR_ZONES;
1338 buf = strtok_r(NULL, "), ", &save_ptr), zone_idx++) {
1339 long long zoneval = strtoll(buf, &buf, 0);
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001340 if (zoneval > max) {
1341 max = (zoneval > INT64_MAX) ? INT64_MAX : zoneval;
1342 }
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07001343 zone->protection[zone_idx] = zoneval;
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001344 }
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07001345 zone->max_protection = max;
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001346}
1347
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07001348static int zoneinfo_parse_zone(char **buf, struct zoneinfo_zone *zone) {
1349 for (char *line = strtok_r(NULL, "\n", buf); line;
1350 line = strtok_r(NULL, "\n", buf)) {
1351 char *cp;
1352 char *ap;
1353 char *save_ptr;
1354 int64_t val;
1355 int field_idx;
1356 enum field_match_result match_res;
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001357
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07001358 cp = strtok_r(line, " ", &save_ptr);
1359 if (!cp) {
1360 return false;
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001361 }
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07001362
1363 field_idx = find_field(cp, zoneinfo_zone_spec_field_names, ZI_ZONE_SPEC_FIELD_COUNT);
1364 if (field_idx >= 0) {
1365 /* special field */
1366 if (field_idx == ZI_ZONE_SPEC_PAGESETS) {
1367 /* no mode fields we are interested in */
1368 return true;
1369 }
1370
1371 /* protection field */
1372 ap = strtok_r(NULL, ")", &save_ptr);
1373 if (ap) {
1374 zoneinfo_parse_protection(ap, zone);
1375 }
1376 continue;
1377 }
1378
1379 ap = strtok_r(NULL, " ", &save_ptr);
1380 if (!ap) {
1381 continue;
1382 }
1383
1384 match_res = match_field(cp, ap, zoneinfo_zone_field_names, ZI_ZONE_FIELD_COUNT,
1385 &val, &field_idx);
1386 if (match_res == PARSE_FAIL) {
1387 return false;
1388 }
1389 if (match_res == PARSE_SUCCESS) {
1390 zone->fields.arr[field_idx] = val;
1391 }
1392 if (field_idx == ZI_ZONE_PRESENT && val == 0) {
1393 /* zone is not populated, stop parsing it */
1394 return true;
1395 }
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001396 }
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07001397 return false;
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001398}
1399
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07001400static int zoneinfo_parse_node(char **buf, struct zoneinfo_node *node) {
1401 int fields_to_match = ZI_NODE_FIELD_COUNT;
1402
1403 for (char *line = strtok_r(NULL, "\n", buf); line;
1404 line = strtok_r(NULL, "\n", buf)) {
1405 char *cp;
1406 char *ap;
1407 char *save_ptr;
1408 int64_t val;
1409 int field_idx;
1410 enum field_match_result match_res;
1411
1412 cp = strtok_r(line, " ", &save_ptr);
1413 if (!cp) {
1414 return false;
1415 }
1416
1417 ap = strtok_r(NULL, " ", &save_ptr);
1418 if (!ap) {
1419 return false;
1420 }
1421
1422 match_res = match_field(cp, ap, zoneinfo_node_field_names, ZI_NODE_FIELD_COUNT,
1423 &val, &field_idx);
1424 if (match_res == PARSE_FAIL) {
1425 return false;
1426 }
1427 if (match_res == PARSE_SUCCESS) {
1428 node->fields.arr[field_idx] = val;
1429 fields_to_match--;
1430 if (!fields_to_match) {
1431 return true;
1432 }
1433 }
1434 }
1435 return false;
1436}
1437
1438static int zoneinfo_parse(struct zoneinfo *zi) {
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001439 static struct reread_data file_data = {
1440 .filename = ZONEINFO_PATH,
1441 .fd = -1,
1442 };
Suren Baghdasaryana77b3272019-07-15 13:35:04 -07001443 char *buf;
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001444 char *save_ptr;
1445 char *line;
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07001446 char zone_name[LINE_MAX];
1447 struct zoneinfo_node *node = NULL;
1448 int node_idx = 0;
1449 int zone_idx = 0;
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001450
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07001451 memset(zi, 0, sizeof(struct zoneinfo));
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001452
Suren Baghdasaryana77b3272019-07-15 13:35:04 -07001453 if ((buf = reread_file(&file_data)) == NULL) {
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001454 return -1;
1455 }
1456
1457 for (line = strtok_r(buf, "\n", &save_ptr); line;
1458 line = strtok_r(NULL, "\n", &save_ptr)) {
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07001459 int node_id;
1460 if (sscanf(line, "Node %d, zone %" STRINGIFY(LINE_MAX) "s", &node_id, zone_name) == 2) {
1461 if (!node || node->id != node_id) {
1462 /* new node is found */
1463 if (node) {
1464 node->zone_count = zone_idx + 1;
1465 node_idx++;
1466 if (node_idx == MAX_NR_NODES) {
1467 /* max node count exceeded */
1468 ALOGE("%s parse error", file_data.filename);
1469 return -1;
1470 }
1471 }
1472 node = &zi->nodes[node_idx];
1473 node->id = node_id;
1474 zone_idx = 0;
1475 if (!zoneinfo_parse_node(&save_ptr, node)) {
1476 ALOGE("%s parse error", file_data.filename);
1477 return -1;
1478 }
1479 } else {
1480 /* new zone is found */
1481 zone_idx++;
1482 }
1483 if (!zoneinfo_parse_zone(&save_ptr, &node->zones[zone_idx])) {
1484 ALOGE("%s parse error", file_data.filename);
1485 return -1;
1486 }
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001487 }
1488 }
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07001489 if (!node) {
1490 ALOGE("%s parse error", file_data.filename);
1491 return -1;
1492 }
1493 node->zone_count = zone_idx + 1;
1494 zi->node_count = node_idx + 1;
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001495
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07001496 /* calculate totals fields */
1497 for (node_idx = 0; node_idx < zi->node_count; node_idx++) {
1498 node = &zi->nodes[node_idx];
1499 for (zone_idx = 0; zone_idx < node->zone_count; zone_idx++) {
1500 struct zoneinfo_zone *zone = &zi->nodes[node_idx].zones[zone_idx];
1501 zi->totalreserve_pages += zone->max_protection + zone->fields.field.high;
1502 }
1503 zi->total_inactive_file += node->fields.field.nr_inactive_file;
1504 zi->total_active_file += node->fields.field.nr_active_file;
1505 zi->total_workingset_refault += node->fields.field.workingset_refault;
1506 }
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001507 return 0;
1508}
1509
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07001510/* /proc/meminfo parsing routines */
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001511static bool meminfo_parse_line(char *line, union meminfo *mi) {
1512 char *cp = line;
1513 char *ap;
1514 char *save_ptr;
1515 int64_t val;
1516 int field_idx;
1517 enum field_match_result match_res;
1518
1519 cp = strtok_r(line, " ", &save_ptr);
1520 if (!cp) {
1521 return false;
1522 }
1523
1524 ap = strtok_r(NULL, " ", &save_ptr);
1525 if (!ap) {
1526 return false;
1527 }
1528
1529 match_res = match_field(cp, ap, meminfo_field_names, MI_FIELD_COUNT,
1530 &val, &field_idx);
1531 if (match_res == PARSE_SUCCESS) {
1532 mi->arr[field_idx] = val / page_k;
1533 }
1534 return (match_res != PARSE_FAIL);
1535}
1536
1537static int meminfo_parse(union meminfo *mi) {
1538 static struct reread_data file_data = {
1539 .filename = MEMINFO_PATH,
1540 .fd = -1,
1541 };
Suren Baghdasaryana77b3272019-07-15 13:35:04 -07001542 char *buf;
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001543 char *save_ptr;
1544 char *line;
1545
1546 memset(mi, 0, sizeof(union meminfo));
1547
Suren Baghdasaryana77b3272019-07-15 13:35:04 -07001548 if ((buf = reread_file(&file_data)) == NULL) {
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001549 return -1;
1550 }
1551
1552 for (line = strtok_r(buf, "\n", &save_ptr); line;
1553 line = strtok_r(NULL, "\n", &save_ptr)) {
1554 if (!meminfo_parse_line(line, mi)) {
1555 ALOGE("%s parse error", file_data.filename);
1556 return -1;
1557 }
1558 }
1559 mi->field.nr_file_pages = mi->field.cached + mi->field.swap_cached +
1560 mi->field.buffers;
1561
1562 return 0;
1563}
1564
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07001565/* /proc/vmstat parsing routines */
1566static bool vmstat_parse_line(char *line, union vmstat *vs) {
1567 char *cp;
1568 char *ap;
1569 char *save_ptr;
1570 int64_t val;
1571 int field_idx;
1572 enum field_match_result match_res;
1573
1574 cp = strtok_r(line, " ", &save_ptr);
1575 if (!cp) {
1576 return false;
1577 }
1578
1579 ap = strtok_r(NULL, " ", &save_ptr);
1580 if (!ap) {
1581 return false;
1582 }
1583
1584 match_res = match_field(cp, ap, vmstat_field_names, VS_FIELD_COUNT,
1585 &val, &field_idx);
1586 if (match_res == PARSE_SUCCESS) {
1587 vs->arr[field_idx] = val;
1588 }
1589 return (match_res != PARSE_FAIL);
1590}
1591
1592static int vmstat_parse(union vmstat *vs) {
1593 static struct reread_data file_data = {
1594 .filename = VMSTAT_PATH,
1595 .fd = -1,
1596 };
1597 char *buf;
1598 char *save_ptr;
1599 char *line;
1600
1601 memset(vs, 0, sizeof(union vmstat));
1602
1603 if ((buf = reread_file(&file_data)) == NULL) {
1604 return -1;
1605 }
1606
1607 for (line = strtok_r(buf, "\n", &save_ptr); line;
1608 line = strtok_r(NULL, "\n", &save_ptr)) {
1609 if (!vmstat_parse_line(line, vs)) {
1610 ALOGE("%s parse error", file_data.filename);
1611 return -1;
1612 }
1613 }
1614
1615 return 0;
1616}
1617
Suren Baghdasaryan282ad1a2018-07-26 16:34:27 -07001618static void meminfo_log(union meminfo *mi) {
1619 for (int field_idx = 0; field_idx < MI_FIELD_COUNT; field_idx++) {
1620 android_log_write_int32(ctx, (int32_t)min(mi->arr[field_idx] * page_k, INT32_MAX));
1621 }
1622
1623 android_log_write_list(ctx, LOG_ID_EVENTS);
1624 android_log_reset(ctx);
1625}
1626
Todd Poynor3948f802013-07-09 19:35:14 -07001627static int proc_get_size(int pid) {
1628 char path[PATH_MAX];
1629 char line[LINE_MAX];
Colin Crossce85d952014-07-11 17:53:27 -07001630 int fd;
Todd Poynor3948f802013-07-09 19:35:14 -07001631 int rss = 0;
1632 int total;
Colin Crossce85d952014-07-11 17:53:27 -07001633 ssize_t ret;
Todd Poynor3948f802013-07-09 19:35:14 -07001634
Mark Salyzyn64d97d82018-04-09 09:50:32 -07001635 /* gid containing AID_READPROC required */
Todd Poynor3948f802013-07-09 19:35:14 -07001636 snprintf(path, PATH_MAX, "/proc/%d/statm", pid);
Nick Kralevichc68c8862015-12-18 20:52:37 -08001637 fd = open(path, O_RDONLY | O_CLOEXEC);
Colin Crossce85d952014-07-11 17:53:27 -07001638 if (fd == -1)
Todd Poynor3948f802013-07-09 19:35:14 -07001639 return -1;
Colin Crossce85d952014-07-11 17:53:27 -07001640
1641 ret = read_all(fd, line, sizeof(line) - 1);
1642 if (ret < 0) {
1643 close(fd);
Todd Poynor3948f802013-07-09 19:35:14 -07001644 return -1;
1645 }
1646
1647 sscanf(line, "%d %d ", &total, &rss);
Colin Crossce85d952014-07-11 17:53:27 -07001648 close(fd);
Todd Poynor3948f802013-07-09 19:35:14 -07001649 return rss;
1650}
1651
1652static char *proc_get_name(int pid) {
1653 char path[PATH_MAX];
1654 static char line[LINE_MAX];
Colin Crossce85d952014-07-11 17:53:27 -07001655 int fd;
Todd Poynor3948f802013-07-09 19:35:14 -07001656 char *cp;
Colin Crossce85d952014-07-11 17:53:27 -07001657 ssize_t ret;
Todd Poynor3948f802013-07-09 19:35:14 -07001658
Mark Salyzyn64d97d82018-04-09 09:50:32 -07001659 /* gid containing AID_READPROC required */
Todd Poynor3948f802013-07-09 19:35:14 -07001660 snprintf(path, PATH_MAX, "/proc/%d/cmdline", pid);
Nick Kralevichc68c8862015-12-18 20:52:37 -08001661 fd = open(path, O_RDONLY | O_CLOEXEC);
Suren Baghdasaryan9e359db2019-09-27 16:56:50 -07001662 if (fd == -1) {
Todd Poynor3948f802013-07-09 19:35:14 -07001663 return NULL;
Suren Baghdasaryan9e359db2019-09-27 16:56:50 -07001664 }
Colin Crossce85d952014-07-11 17:53:27 -07001665 ret = read_all(fd, line, sizeof(line) - 1);
1666 close(fd);
1667 if (ret < 0) {
Todd Poynor3948f802013-07-09 19:35:14 -07001668 return NULL;
1669 }
1670
1671 cp = strchr(line, ' ');
Suren Baghdasaryan9e359db2019-09-27 16:56:50 -07001672 if (cp) {
Todd Poynor3948f802013-07-09 19:35:14 -07001673 *cp = '\0';
Suren Baghdasaryan9e359db2019-09-27 16:56:50 -07001674 } else {
1675 line[ret] = '\0';
1676 }
Todd Poynor3948f802013-07-09 19:35:14 -07001677
1678 return line;
1679}
1680
1681static struct proc *proc_adj_lru(int oomadj) {
1682 return (struct proc *)adjslot_tail(&procadjslot_list[ADJTOSLOT(oomadj)]);
1683}
1684
Suren Baghdasaryan662492a2017-12-08 13:17:06 -08001685static struct proc *proc_get_heaviest(int oomadj) {
1686 struct adjslot_list *head = &procadjslot_list[ADJTOSLOT(oomadj)];
1687 struct adjslot_list *curr = head->next;
1688 struct proc *maxprocp = NULL;
1689 int maxsize = 0;
1690 while (curr != head) {
1691 int pid = ((struct proc *)curr)->pid;
1692 int tasksize = proc_get_size(pid);
1693 if (tasksize <= 0) {
1694 struct adjslot_list *next = curr->next;
1695 pid_remove(pid);
1696 curr = next;
1697 } else {
1698 if (tasksize > maxsize) {
1699 maxsize = tasksize;
1700 maxprocp = (struct proc *)curr;
1701 }
1702 curr = curr->next;
1703 }
1704 }
1705 return maxprocp;
1706}
1707
Wei Wang2d95c102018-11-21 00:11:44 -08001708static void set_process_group_and_prio(int pid, SchedPolicy sp, int prio) {
1709 DIR* d;
1710 char proc_path[PATH_MAX];
1711 struct dirent* de;
1712
1713 snprintf(proc_path, sizeof(proc_path), "/proc/%d/task", pid);
1714 if (!(d = opendir(proc_path))) {
1715 ALOGW("Failed to open %s; errno=%d: process pid(%d) might have died", proc_path, errno,
1716 pid);
1717 return;
1718 }
1719
1720 while ((de = readdir(d))) {
1721 int t_pid;
1722
1723 if (de->d_name[0] == '.') continue;
1724 t_pid = atoi(de->d_name);
1725
1726 if (!t_pid) {
1727 ALOGW("Failed to get t_pid for '%s' of pid(%d)", de->d_name, pid);
1728 continue;
1729 }
1730
1731 if (setpriority(PRIO_PROCESS, t_pid, prio) && errno != ESRCH) {
1732 ALOGW("Unable to raise priority of killing t_pid (%d): errno=%d", t_pid, errno);
1733 }
1734
1735 if (set_cpuset_policy(t_pid, sp)) {
1736 ALOGW("Failed to set_cpuset_policy on pid(%d) t_pid(%d) to %d", pid, t_pid, (int)sp);
1737 continue;
1738 }
1739 }
1740 closedir(d);
1741}
1742
Tim Murraye7853f62018-10-25 17:05:41 -07001743static int last_killed_pid = -1;
1744
Colin Cross16b09462014-07-14 12:39:56 -07001745/* Kill one process specified by procp. Returns the size of the process killed */
Suren Baghdasaryanfd7518f2019-07-15 15:50:17 -07001746static int kill_one_process(struct proc* procp, int min_oom_score, const char *reason) {
Colin Cross16b09462014-07-14 12:39:56 -07001747 int pid = procp->pid;
1748 uid_t uid = procp->uid;
Suren Baghdasaryan0082ef12019-07-02 15:52:07 -07001749 int tgid;
Colin Cross16b09462014-07-14 12:39:56 -07001750 char *taskname;
1751 int tasksize;
1752 int r;
Suren Baghdasaryan01063272018-10-12 11:28:33 -07001753 int result = -1;
Colin Cross16b09462014-07-14 12:39:56 -07001754
Rajeev Kumar70450032018-01-31 17:54:56 -08001755#ifdef LMKD_LOG_STATS
Rajeev Kumar92b659b2018-02-21 19:08:15 -08001756 struct memory_stat mem_st = {};
Rajeev Kumar70450032018-01-31 17:54:56 -08001757 int memory_stat_parse_result = -1;
Suren Baghdasaryanec5e4c62019-03-04 11:07:39 -08001758#else
1759 /* To prevent unused parameter warning */
1760 (void)(min_oom_score);
Rajeev Kumar70450032018-01-31 17:54:56 -08001761#endif
1762
Suren Baghdasaryan0082ef12019-07-02 15:52:07 -07001763 tgid = proc_get_tgid(pid);
1764 if (tgid >= 0 && tgid != pid) {
1765 ALOGE("Possible pid reuse detected (pid %d, tgid %d)!", pid, tgid);
1766 goto out;
1767 }
1768
Colin Cross16b09462014-07-14 12:39:56 -07001769 taskname = proc_get_name(pid);
1770 if (!taskname) {
Suren Baghdasaryan01063272018-10-12 11:28:33 -07001771 goto out;
Colin Cross16b09462014-07-14 12:39:56 -07001772 }
1773
1774 tasksize = proc_get_size(pid);
1775 if (tasksize <= 0) {
Suren Baghdasaryan01063272018-10-12 11:28:33 -07001776 goto out;
Colin Cross16b09462014-07-14 12:39:56 -07001777 }
1778
Rajeev Kumar70450032018-01-31 17:54:56 -08001779#ifdef LMKD_LOG_STATS
1780 if (enable_stats_log) {
Rajeev Kumar4dbc24d2018-10-05 12:34:59 -07001781 if (per_app_memcg) {
1782 memory_stat_parse_result = memory_stat_from_cgroup(&mem_st, pid, uid);
1783 } else {
1784 memory_stat_parse_result = memory_stat_from_procfs(&mem_st, pid);
1785 }
Rajeev Kumar70450032018-01-31 17:54:56 -08001786 }
1787#endif
1788
Suren Baghdasaryanc7135592018-01-04 10:43:58 -08001789 TRACE_KILL_START(pid);
1790
Mark Salyzyn64d97d82018-04-09 09:50:32 -07001791 /* CAP_KILL required */
Suren Baghdasaryan96bf3a62017-12-08 12:58:52 -08001792 r = kill(pid, SIGKILL);
Wei Wang2d95c102018-11-21 00:11:44 -08001793
1794 set_process_group_and_prio(pid, SP_FOREGROUND, ANDROID_PRIORITY_HIGHEST);
1795
Suren Baghdasaryand4a29902018-10-12 11:07:40 -07001796 inc_killcnt(procp->oomadj);
Suren Baghdasaryanfd7518f2019-07-15 15:50:17 -07001797 if (reason) {
1798 ALOGI("Kill '%s' (%d), uid %d, oom_adj %d to free %ldkB; reason: %s", taskname, pid,
1799 uid, procp->oomadj, tasksize * page_k, reason);
1800 } else {
1801 ALOGI("Kill '%s' (%d), uid %d, oom_adj %d to free %ldkB", taskname, pid,
1802 uid, procp->oomadj, tasksize * page_k);
1803 }
Colin Cross16b09462014-07-14 12:39:56 -07001804
Suren Baghdasaryanc7135592018-01-04 10:43:58 -08001805 TRACE_KILL_END();
1806
Tim Murraye7853f62018-10-25 17:05:41 -07001807 last_killed_pid = pid;
1808
Colin Cross16b09462014-07-14 12:39:56 -07001809 if (r) {
Mark Salyzyn919f5382018-02-04 15:27:23 -08001810 ALOGE("kill(%d): errno=%d", pid, errno);
Suren Baghdasaryan01063272018-10-12 11:28:33 -07001811 goto out;
Rajeev Kumar70450032018-01-31 17:54:56 -08001812 } else {
1813#ifdef LMKD_LOG_STATS
1814 if (memory_stat_parse_result == 0) {
1815 stats_write_lmk_kill_occurred(log_ctx, LMK_KILL_OCCURRED, uid, taskname,
1816 procp->oomadj, mem_st.pgfault, mem_st.pgmajfault, mem_st.rss_in_bytes,
Suren Baghdasaryanec5e4c62019-03-04 11:07:39 -08001817 mem_st.cache_in_bytes, mem_st.swap_in_bytes, mem_st.process_start_time_ns,
1818 min_oom_score);
Rajeev Kumar4dbc24d2018-10-05 12:34:59 -07001819 } else if (enable_stats_log) {
1820 stats_write_lmk_kill_occurred(log_ctx, LMK_KILL_OCCURRED, uid, taskname, procp->oomadj,
Suren Baghdasaryanec5e4c62019-03-04 11:07:39 -08001821 -1, -1, tasksize * BYTES_IN_KILOBYTE, -1, -1, -1,
1822 min_oom_score);
Rajeev Kumar70450032018-01-31 17:54:56 -08001823 }
1824#endif
Suren Baghdasaryan01063272018-10-12 11:28:33 -07001825 result = tasksize;
Colin Cross16b09462014-07-14 12:39:56 -07001826 }
Mark Salyzyn919f5382018-02-04 15:27:23 -08001827
Suren Baghdasaryan01063272018-10-12 11:28:33 -07001828out:
1829 /*
1830 * WARNING: After pid_remove() procp is freed and can't be used!
1831 * Therefore placed at the end of the function.
1832 */
1833 pid_remove(pid);
1834 return result;
Colin Cross16b09462014-07-14 12:39:56 -07001835}
1836
1837/*
Suren Baghdasaryanf81b5f42018-10-26 11:32:15 -07001838 * Find one process to kill at or above the given oom_adj level.
1839 * Returns size of the killed process.
Colin Cross16b09462014-07-14 12:39:56 -07001840 */
Suren Baghdasaryanfd7518f2019-07-15 15:50:17 -07001841static int find_and_kill_process(int min_score_adj, const char *reason) {
Colin Cross16b09462014-07-14 12:39:56 -07001842 int i;
Suren Baghdasaryanf81b5f42018-10-26 11:32:15 -07001843 int killed_size = 0;
Colin Cross16b09462014-07-14 12:39:56 -07001844
Rajeev Kumar70450032018-01-31 17:54:56 -08001845#ifdef LMKD_LOG_STATS
Yang Lu5564f4e2018-05-15 04:59:44 +00001846 bool lmk_state_change_start = false;
Rajeev Kumar70450032018-01-31 17:54:56 -08001847#endif
1848
Chong Zhang0a4acdf2015-10-14 16:19:53 -07001849 for (i = OOM_SCORE_ADJ_MAX; i >= min_score_adj; i--) {
Colin Cross16b09462014-07-14 12:39:56 -07001850 struct proc *procp;
1851
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08001852 while (true) {
Suren Baghdasaryan818b59b2018-04-13 11:49:54 -07001853 procp = kill_heaviest_task ?
1854 proc_get_heaviest(i) : proc_adj_lru(i);
Colin Cross16b09462014-07-14 12:39:56 -07001855
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08001856 if (!procp)
1857 break;
1858
Suren Baghdasaryanfd7518f2019-07-15 15:50:17 -07001859 killed_size = kill_one_process(procp, min_score_adj, reason);
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08001860 if (killed_size >= 0) {
Yang Lu5564f4e2018-05-15 04:59:44 +00001861#ifdef LMKD_LOG_STATS
1862 if (enable_stats_log && !lmk_state_change_start) {
1863 lmk_state_change_start = true;
1864 stats_write_lmk_state_changed(log_ctx, LMK_STATE_CHANGED,
1865 LMK_STATE_CHANGE_START);
1866 }
1867#endif
Suren Baghdasaryanf81b5f42018-10-26 11:32:15 -07001868 break;
Colin Cross16b09462014-07-14 12:39:56 -07001869 }
1870 }
Suren Baghdasaryanf81b5f42018-10-26 11:32:15 -07001871 if (killed_size) {
1872 break;
1873 }
Colin Cross16b09462014-07-14 12:39:56 -07001874 }
1875
Rajeev Kumar70450032018-01-31 17:54:56 -08001876#ifdef LMKD_LOG_STATS
Yang Lu5564f4e2018-05-15 04:59:44 +00001877 if (enable_stats_log && lmk_state_change_start) {
Rajeev Kumar70450032018-01-31 17:54:56 -08001878 stats_write_lmk_state_changed(log_ctx, LMK_STATE_CHANGED, LMK_STATE_CHANGE_STOP);
1879 }
1880#endif
1881
Suren Baghdasaryanf81b5f42018-10-26 11:32:15 -07001882 return killed_size;
Colin Cross16b09462014-07-14 12:39:56 -07001883}
1884
Suren Baghdasaryan6499e5e2018-04-13 12:43:41 -07001885static int64_t get_memory_usage(struct reread_data *file_data) {
Robert Beneac47f2992017-08-21 15:18:31 -07001886 int ret;
1887 int64_t mem_usage;
Suren Baghdasaryana77b3272019-07-15 13:35:04 -07001888 char *buf;
Suren Baghdasaryan6499e5e2018-04-13 12:43:41 -07001889
Suren Baghdasaryana77b3272019-07-15 13:35:04 -07001890 if ((buf = reread_file(file_data)) == NULL) {
Robert Beneac47f2992017-08-21 15:18:31 -07001891 return -1;
1892 }
1893
Suren Baghdasaryan6499e5e2018-04-13 12:43:41 -07001894 if (!parse_int64(buf, &mem_usage)) {
1895 ALOGE("%s parse error", file_data->filename);
Robert Beneac47f2992017-08-21 15:18:31 -07001896 return -1;
1897 }
Robert Beneac47f2992017-08-21 15:18:31 -07001898 if (mem_usage == 0) {
1899 ALOGE("No memory!");
1900 return -1;
1901 }
1902 return mem_usage;
1903}
1904
Suren Baghdasaryan9926e572018-04-13 13:41:12 -07001905void record_low_pressure_levels(union meminfo *mi) {
1906 if (low_pressure_mem.min_nr_free_pages == -1 ||
1907 low_pressure_mem.min_nr_free_pages > mi->field.nr_free_pages) {
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08001908 if (debug_process_killing) {
Suren Baghdasaryan9926e572018-04-13 13:41:12 -07001909 ALOGI("Low pressure min memory update from %" PRId64 " to %" PRId64,
1910 low_pressure_mem.min_nr_free_pages, mi->field.nr_free_pages);
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08001911 }
Suren Baghdasaryan9926e572018-04-13 13:41:12 -07001912 low_pressure_mem.min_nr_free_pages = mi->field.nr_free_pages;
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08001913 }
1914 /*
1915 * Free memory at low vmpressure events occasionally gets spikes,
1916 * possibly a stale low vmpressure event with memory already
1917 * freed up (no memory pressure should have been reported).
Suren Baghdasaryan9926e572018-04-13 13:41:12 -07001918 * Ignore large jumps in max_nr_free_pages that would mess up our stats.
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08001919 */
Suren Baghdasaryan9926e572018-04-13 13:41:12 -07001920 if (low_pressure_mem.max_nr_free_pages == -1 ||
1921 (low_pressure_mem.max_nr_free_pages < mi->field.nr_free_pages &&
1922 mi->field.nr_free_pages - low_pressure_mem.max_nr_free_pages <
1923 low_pressure_mem.max_nr_free_pages * 0.1)) {
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08001924 if (debug_process_killing) {
Suren Baghdasaryan9926e572018-04-13 13:41:12 -07001925 ALOGI("Low pressure max memory update from %" PRId64 " to %" PRId64,
1926 low_pressure_mem.max_nr_free_pages, mi->field.nr_free_pages);
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08001927 }
Suren Baghdasaryan9926e572018-04-13 13:41:12 -07001928 low_pressure_mem.max_nr_free_pages = mi->field.nr_free_pages;
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08001929 }
1930}
1931
Suren Baghdasaryan96bf3a62017-12-08 12:58:52 -08001932enum vmpressure_level upgrade_level(enum vmpressure_level level) {
1933 return (enum vmpressure_level)((level < VMPRESS_LEVEL_CRITICAL) ?
1934 level + 1 : level);
1935}
1936
1937enum vmpressure_level downgrade_level(enum vmpressure_level level) {
1938 return (enum vmpressure_level)((level > VMPRESS_LEVEL_LOW) ?
1939 level - 1 : level);
1940}
1941
Tim Murraye7853f62018-10-25 17:05:41 -07001942static bool is_kill_pending(void) {
1943 char buf[24];
1944
1945 if (last_killed_pid < 0) {
1946 return false;
1947 }
1948
1949 snprintf(buf, sizeof(buf), "/proc/%d/", last_killed_pid);
1950 if (access(buf, F_OK) == 0) {
1951 return true;
1952 }
1953
1954 // reset last killed PID because there's nothing pending
1955 last_killed_pid = -1;
1956 return false;
1957}
1958
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07001959enum zone_watermark {
1960 WMARK_MIN = 0,
1961 WMARK_LOW,
1962 WMARK_HIGH,
1963 WMARK_NONE
1964};
1965
Suren Baghdasaryan4787ab42019-08-14 09:48:35 -07001966struct zone_watermarks {
1967 long high_wmark;
1968 long low_wmark;
1969 long min_wmark;
1970};
1971
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07001972/*
1973 * Returns lowest breached watermark or WMARK_NONE.
1974 */
Suren Baghdasaryan4787ab42019-08-14 09:48:35 -07001975static enum zone_watermark get_lowest_watermark(union meminfo *mi,
1976 struct zone_watermarks *watermarks)
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07001977{
Suren Baghdasaryan4787ab42019-08-14 09:48:35 -07001978 int64_t nr_free_pages = mi->field.nr_free_pages - mi->field.cma_free;
1979
1980 if (nr_free_pages < watermarks->min_wmark) {
1981 return WMARK_MIN;
1982 }
1983 if (nr_free_pages < watermarks->low_wmark) {
1984 return WMARK_LOW;
1985 }
1986 if (nr_free_pages < watermarks->high_wmark) {
1987 return WMARK_HIGH;
1988 }
1989 return WMARK_NONE;
1990}
1991
1992void calc_zone_watermarks(struct zoneinfo *zi, struct zone_watermarks *watermarks) {
1993 memset(watermarks, 0, sizeof(struct zone_watermarks));
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07001994
1995 for (int node_idx = 0; node_idx < zi->node_count; node_idx++) {
1996 struct zoneinfo_node *node = &zi->nodes[node_idx];
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07001997 for (int zone_idx = 0; zone_idx < node->zone_count; zone_idx++) {
1998 struct zoneinfo_zone *zone = &node->zones[zone_idx];
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07001999
2000 if (!zone->fields.field.present) {
2001 continue;
2002 }
2003
Suren Baghdasaryan4787ab42019-08-14 09:48:35 -07002004 watermarks->high_wmark += zone->max_protection + zone->fields.field.high;
2005 watermarks->low_wmark += zone->max_protection + zone->fields.field.low;
2006 watermarks->min_wmark += zone->max_protection + zone->fields.field.min;
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002007 }
2008 }
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002009}
2010
2011static void mp_event_psi(int data, uint32_t events, struct polling_params *poll_params) {
2012 enum kill_reasons {
2013 NONE = -1, /* To denote no kill condition */
2014 PRESSURE_AFTER_KILL = 0,
2015 NOT_RESPONDING,
2016 LOW_SWAP_AND_THRASHING,
2017 LOW_MEM_AND_SWAP,
2018 LOW_MEM_AND_THRASHING,
2019 DIRECT_RECL_AND_THRASHING,
2020 KILL_REASON_COUNT
2021 };
2022 enum reclaim_state {
2023 NO_RECLAIM = 0,
2024 KSWAPD_RECLAIM,
2025 DIRECT_RECLAIM,
2026 };
2027 static int64_t init_ws_refault;
2028 static int64_t base_file_lru;
2029 static int64_t init_pgscan_kswapd;
2030 static int64_t init_pgscan_direct;
2031 static int64_t swap_low_threshold;
2032 static bool killing;
2033 static int thrashing_limit;
2034 static bool in_reclaim;
Suren Baghdasaryan4787ab42019-08-14 09:48:35 -07002035 static struct zone_watermarks watermarks;
2036 static struct timespec wmark_update_tm;
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002037
2038 union meminfo mi;
2039 union vmstat vs;
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002040 struct timespec curr_tm;
2041 int64_t thrashing = 0;
2042 bool swap_is_low = false;
2043 enum vmpressure_level level = (enum vmpressure_level)data;
2044 enum kill_reasons kill_reason = NONE;
2045 bool cycle_after_kill = false;
2046 enum reclaim_state reclaim = NO_RECLAIM;
2047 enum zone_watermark wmark = WMARK_NONE;
Suren Baghdasaryanfd7518f2019-07-15 15:50:17 -07002048 char kill_desc[LINE_MAX];
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002049
2050 /* Skip while still killing a process */
2051 if (is_kill_pending()) {
2052 /* TODO: replace this quick polling with pidfd polling if kernel supports */
2053 goto no_kill;
2054 }
2055
2056 if (clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm) != 0) {
2057 ALOGE("Failed to get current time");
2058 return;
2059 }
2060
2061 if (vmstat_parse(&vs) < 0) {
2062 ALOGE("Failed to parse vmstat!");
2063 return;
2064 }
2065
2066 if (meminfo_parse(&mi) < 0) {
2067 ALOGE("Failed to parse meminfo!");
2068 return;
2069 }
2070
2071 /* Reset states after process got killed */
2072 if (killing) {
2073 killing = false;
2074 cycle_after_kill = true;
2075 /* Reset file-backed pagecache size and refault amounts after a kill */
2076 base_file_lru = vs.field.nr_inactive_file + vs.field.nr_active_file;
2077 init_ws_refault = vs.field.workingset_refault;
2078 }
2079
2080 /* Check free swap levels */
2081 if (swap_free_low_percentage) {
2082 if (!swap_low_threshold) {
2083 swap_low_threshold = mi.field.total_swap * swap_free_low_percentage / 100;
2084 }
2085 swap_is_low = mi.field.free_swap < swap_low_threshold;
2086 }
2087
2088 /* Identify reclaim state */
2089 if (vs.field.pgscan_direct > init_pgscan_direct) {
2090 init_pgscan_direct = vs.field.pgscan_direct;
2091 init_pgscan_kswapd = vs.field.pgscan_kswapd;
2092 reclaim = DIRECT_RECLAIM;
2093 } else if (vs.field.pgscan_kswapd > init_pgscan_kswapd) {
2094 init_pgscan_kswapd = vs.field.pgscan_kswapd;
2095 reclaim = KSWAPD_RECLAIM;
2096 } else {
2097 in_reclaim = false;
2098 /* Skip if system is not reclaiming */
2099 goto no_kill;
2100 }
2101
2102 if (!in_reclaim) {
2103 /* Record file-backed pagecache size when entering reclaim cycle */
2104 base_file_lru = vs.field.nr_inactive_file + vs.field.nr_active_file;
2105 init_ws_refault = vs.field.workingset_refault;
2106 thrashing_limit = thrashing_limit_pct;
2107 } else {
2108 /* Calculate what % of the file-backed pagecache refaulted so far */
2109 thrashing = (vs.field.workingset_refault - init_ws_refault) * 100 / base_file_lru;
2110 }
2111 in_reclaim = true;
2112
Suren Baghdasaryan4787ab42019-08-14 09:48:35 -07002113 /*
2114 * Refresh watermarks once per min in case user updated one of the margins.
2115 * TODO: b/140521024 replace this periodic update with an API for AMS to notify LMKD
2116 * that zone watermarks were changed by the system software.
2117 */
2118 if (watermarks.high_wmark == 0 || get_time_diff_ms(&wmark_update_tm, &curr_tm) > 60000) {
2119 struct zoneinfo zi;
2120
2121 if (zoneinfo_parse(&zi) < 0) {
2122 ALOGE("Failed to parse zoneinfo!");
2123 return;
2124 }
2125
2126 calc_zone_watermarks(&zi, &watermarks);
2127 wmark_update_tm = curr_tm;
2128 }
2129
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002130 /* Find out which watermark is breached if any */
Suren Baghdasaryan4787ab42019-08-14 09:48:35 -07002131 wmark = get_lowest_watermark(&mi, &watermarks);
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002132
2133 /*
2134 * TODO: move this logic into a separate function
2135 * Decide if killing a process is necessary and record the reason
2136 */
2137 if (cycle_after_kill && wmark < WMARK_LOW) {
2138 /*
2139 * Prevent kills not freeing enough memory which might lead to OOM kill.
2140 * This might happen when a process is consuming memory faster than reclaim can
2141 * free even after a kill. Mostly happens when running memory stress tests.
2142 */
2143 kill_reason = PRESSURE_AFTER_KILL;
Suren Baghdasaryanfd7518f2019-07-15 15:50:17 -07002144 strncpy(kill_desc, "min watermark is breached even after kill", sizeof(kill_desc));
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002145 } else if (level == VMPRESS_LEVEL_CRITICAL && events != 0) {
2146 /*
2147 * Device is too busy reclaiming memory which might lead to ANR.
2148 * Critical level is triggered when PSI complete stall (all tasks are blocked because
2149 * of the memory congestion) breaches the configured threshold.
2150 */
2151 kill_reason = NOT_RESPONDING;
Suren Baghdasaryanfd7518f2019-07-15 15:50:17 -07002152 strncpy(kill_desc, "device is not responding", sizeof(kill_desc));
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002153 } else if (swap_is_low && thrashing > thrashing_limit_pct) {
2154 /* Page cache is thrashing while swap is low */
2155 kill_reason = LOW_SWAP_AND_THRASHING;
Suren Baghdasaryanfd7518f2019-07-15 15:50:17 -07002156 snprintf(kill_desc, sizeof(kill_desc), "device is low on swap (%" PRId64
2157 "kB < %" PRId64 "kB) and thrashing (%" PRId64 "%%)",
2158 mi.field.free_swap * page_k, swap_low_threshold * page_k, thrashing);
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002159 } else if (swap_is_low && wmark < WMARK_HIGH) {
2160 /* Both free memory and swap are low */
2161 kill_reason = LOW_MEM_AND_SWAP;
Suren Baghdasaryanfd7518f2019-07-15 15:50:17 -07002162 snprintf(kill_desc, sizeof(kill_desc), "%s watermark is breached and swap is low (%"
2163 PRId64 "kB < %" PRId64 "kB)", wmark > WMARK_LOW ? "min" : "low",
2164 mi.field.free_swap * page_k, swap_low_threshold * page_k);
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002165 } else if (wmark < WMARK_HIGH && thrashing > thrashing_limit) {
2166 /* Page cache is thrashing while memory is low */
2167 thrashing_limit = (thrashing_limit * (100 - thrashing_limit_decay_pct)) / 100;
2168 kill_reason = LOW_MEM_AND_THRASHING;
Suren Baghdasaryanfd7518f2019-07-15 15:50:17 -07002169 snprintf(kill_desc, sizeof(kill_desc), "%s watermark is breached and thrashing (%"
2170 PRId64 "%%)", wmark > WMARK_LOW ? "min" : "low", thrashing);
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002171 } else if (reclaim == DIRECT_RECLAIM && thrashing > thrashing_limit) {
2172 /* Page cache is thrashing while in direct reclaim (mostly happens on lowram devices) */
2173 thrashing_limit = (thrashing_limit * (100 - thrashing_limit_decay_pct)) / 100;
2174 kill_reason = DIRECT_RECL_AND_THRASHING;
Suren Baghdasaryanfd7518f2019-07-15 15:50:17 -07002175 snprintf(kill_desc, sizeof(kill_desc), "device is in direct reclaim and thrashing (%"
2176 PRId64 "%%)", thrashing);
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002177 }
2178
2179 /* Kill a process if necessary */
2180 if (kill_reason != NONE) {
Suren Baghdasaryanfd7518f2019-07-15 15:50:17 -07002181 int pages_freed = find_and_kill_process(0, kill_desc);
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002182 killing = (pages_freed > 0);
2183 meminfo_log(&mi);
2184 }
2185
2186no_kill:
2187 /*
2188 * Start polling after initial PSI event;
2189 * extend polling while device is in direct reclaim or process is being killed;
2190 * do not extend when kswapd reclaims because that might go on for a long time
2191 * without causing memory pressure
2192 */
2193 if (events || killing || reclaim == DIRECT_RECLAIM) {
2194 poll_params->update = POLLING_START;
2195 }
2196
2197 /* Decide the polling interval */
2198 if (swap_is_low || killing) {
2199 /* Fast polling during and after a kill or when swap is low */
2200 poll_params->polling_interval_ms = PSI_POLL_PERIOD_SHORT_MS;
2201 } else {
2202 /* By default use long intervals */
2203 poll_params->polling_interval_ms = PSI_POLL_PERIOD_LONG_MS;
2204 }
2205}
2206
Suren Baghdasaryanef3650f2019-07-15 14:50:49 -07002207static void mp_event_common(int data, uint32_t events, struct polling_params *poll_params) {
Todd Poynor3948f802013-07-09 19:35:14 -07002208 int ret;
2209 unsigned long long evcount;
Robert Beneac47f2992017-08-21 15:18:31 -07002210 int64_t mem_usage, memsw_usage;
Robert Benea6e8e7102017-09-13 15:20:30 -07002211 int64_t mem_pressure;
Suren Baghdasaryane82e15c2018-01-04 09:16:21 -08002212 enum vmpressure_level lvl;
Suren Baghdasaryan9926e572018-04-13 13:41:12 -07002213 union meminfo mi;
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07002214 struct zoneinfo zi;
Suren Baghdasaryan36934412018-09-05 15:46:32 -07002215 struct timespec curr_tm;
Suren Baghdasaryan314a5052018-07-24 17:13:06 -07002216 static struct timespec last_kill_tm;
2217 static unsigned long kill_skip_count = 0;
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08002218 enum vmpressure_level level = (enum vmpressure_level)data;
Suren Baghdasaryanffdc4dd2018-04-13 13:53:43 -07002219 long other_free = 0, other_file = 0;
2220 int min_score_adj;
Suren Baghdasaryanffdc4dd2018-04-13 13:53:43 -07002221 int minfree = 0;
Suren Baghdasaryan6499e5e2018-04-13 12:43:41 -07002222 static struct reread_data mem_usage_file_data = {
2223 .filename = MEMCG_MEMORY_USAGE,
2224 .fd = -1,
2225 };
2226 static struct reread_data memsw_usage_file_data = {
2227 .filename = MEMCG_MEMORYSW_USAGE,
2228 .fd = -1,
2229 };
Todd Poynor3948f802013-07-09 19:35:14 -07002230
Suren Baghdasaryan77122e52019-01-08 12:54:48 -08002231 if (debug_process_killing) {
2232 ALOGI("%s memory pressure event is triggered", level_name[level]);
2233 }
2234
2235 if (!use_psi_monitors) {
2236 /*
2237 * Check all event counters from low to critical
2238 * and upgrade to the highest priority one. By reading
2239 * eventfd we also reset the event counters.
2240 */
2241 for (lvl = VMPRESS_LEVEL_LOW; lvl < VMPRESS_LEVEL_COUNT; lvl++) {
2242 if (mpevfd[lvl] != -1 &&
2243 TEMP_FAILURE_RETRY(read(mpevfd[lvl],
2244 &evcount, sizeof(evcount))) > 0 &&
2245 evcount > 0 && lvl > level) {
2246 level = lvl;
2247 }
Suren Baghdasaryane82e15c2018-01-04 09:16:21 -08002248 }
2249 }
Todd Poynor3948f802013-07-09 19:35:14 -07002250
Suren Baghdasaryanef3650f2019-07-15 14:50:49 -07002251 /* Start polling after initial PSI event */
2252 if (use_psi_monitors && events) {
2253 /* Override polling params only if current event is more critical */
2254 if (!poll_params->poll_handler || data > poll_params->poll_handler->data) {
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002255 poll_params->polling_interval_ms = PSI_POLL_PERIOD_SHORT_MS;
Suren Baghdasaryanef3650f2019-07-15 14:50:49 -07002256 poll_params->update = POLLING_START;
2257 }
2258 }
2259
Suren Baghdasaryan36934412018-09-05 15:46:32 -07002260 if (clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm) != 0) {
2261 ALOGE("Failed to get current time");
2262 return;
2263 }
2264
Suren Baghdasaryancaa2dc52018-01-17 17:28:01 -08002265 if (kill_timeout_ms) {
Tim Murraye7853f62018-10-25 17:05:41 -07002266 // If we're within the timeout, see if there's pending reclaim work
2267 // from the last killed process. If there is (as evidenced by
2268 // /proc/<pid> continuing to exist), skip killing for now.
2269 if ((get_time_diff_ms(&last_kill_tm, &curr_tm) < kill_timeout_ms) &&
2270 (low_ram_device || is_kill_pending())) {
Suren Baghdasaryan314a5052018-07-24 17:13:06 -07002271 kill_skip_count++;
Suren Baghdasaryancaa2dc52018-01-17 17:28:01 -08002272 return;
2273 }
2274 }
2275
Suren Baghdasaryan314a5052018-07-24 17:13:06 -07002276 if (kill_skip_count > 0) {
Suren Baghdasaryanda88b242018-05-10 16:10:56 -07002277 ALOGI("%lu memory pressure events were skipped after a kill!",
Suren Baghdasaryan314a5052018-07-24 17:13:06 -07002278 kill_skip_count);
2279 kill_skip_count = 0;
Suren Baghdasaryancaa2dc52018-01-17 17:28:01 -08002280 }
2281
Suren Baghdasaryanffdc4dd2018-04-13 13:53:43 -07002282 if (meminfo_parse(&mi) < 0 || zoneinfo_parse(&zi) < 0) {
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08002283 ALOGE("Failed to get free memory!");
2284 return;
2285 }
2286
Suren Baghdasaryanffdc4dd2018-04-13 13:53:43 -07002287 if (use_minfree_levels) {
2288 int i;
2289
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07002290 other_free = mi.field.nr_free_pages - zi.totalreserve_pages;
Suren Baghdasaryanffdc4dd2018-04-13 13:53:43 -07002291 if (mi.field.nr_file_pages > (mi.field.shmem + mi.field.unevictable + mi.field.swap_cached)) {
2292 other_file = (mi.field.nr_file_pages - mi.field.shmem -
2293 mi.field.unevictable - mi.field.swap_cached);
2294 } else {
2295 other_file = 0;
2296 }
2297
2298 min_score_adj = OOM_SCORE_ADJ_MAX + 1;
2299 for (i = 0; i < lowmem_targets_size; i++) {
2300 minfree = lowmem_minfree[i];
2301 if (other_free < minfree && other_file < minfree) {
2302 min_score_adj = lowmem_adj[i];
2303 break;
2304 }
2305 }
2306
Suren Baghdasaryan20686f02018-05-18 14:42:00 -07002307 if (min_score_adj == OOM_SCORE_ADJ_MAX + 1) {
2308 if (debug_process_killing) {
2309 ALOGI("Ignore %s memory pressure event "
2310 "(free memory=%ldkB, cache=%ldkB, limit=%ldkB)",
2311 level_name[level], other_free * page_k, other_file * page_k,
2312 (long)lowmem_minfree[lowmem_targets_size - 1] * page_k);
2313 }
Suren Baghdasaryanffdc4dd2018-04-13 13:53:43 -07002314 return;
Suren Baghdasaryan20686f02018-05-18 14:42:00 -07002315 }
Suren Baghdasaryanffdc4dd2018-04-13 13:53:43 -07002316
Suren Baghdasaryanffdc4dd2018-04-13 13:53:43 -07002317 goto do_kill;
2318 }
2319
Suren Baghdasaryan9926e572018-04-13 13:41:12 -07002320 if (level == VMPRESS_LEVEL_LOW) {
2321 record_low_pressure_levels(&mi);
2322 }
2323
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08002324 if (level_oomadj[level] > OOM_SCORE_ADJ_MAX) {
2325 /* Do not monitor this pressure level */
2326 return;
2327 }
2328
Suren Baghdasaryan6499e5e2018-04-13 12:43:41 -07002329 if ((mem_usage = get_memory_usage(&mem_usage_file_data)) < 0) {
2330 goto do_kill;
2331 }
2332 if ((memsw_usage = get_memory_usage(&memsw_usage_file_data)) < 0) {
Suren Baghdasaryan96bf3a62017-12-08 12:58:52 -08002333 goto do_kill;
Robert Benea6e8e7102017-09-13 15:20:30 -07002334 }
Robert Beneac47f2992017-08-21 15:18:31 -07002335
Robert Benea6e8e7102017-09-13 15:20:30 -07002336 // Calculate percent for swappinness.
2337 mem_pressure = (mem_usage * 100) / memsw_usage;
2338
Suren Baghdasaryan96bf3a62017-12-08 12:58:52 -08002339 if (enable_pressure_upgrade && level != VMPRESS_LEVEL_CRITICAL) {
Robert Benea6e8e7102017-09-13 15:20:30 -07002340 // We are swapping too much.
2341 if (mem_pressure < upgrade_pressure) {
Suren Baghdasaryan96bf3a62017-12-08 12:58:52 -08002342 level = upgrade_level(level);
2343 if (debug_process_killing) {
2344 ALOGI("Event upgraded to %s", level_name[level]);
2345 }
Robert Beneac47f2992017-08-21 15:18:31 -07002346 }
2347 }
2348
Vic Yang360a1132018-08-07 10:18:22 -07002349 // If we still have enough swap space available, check if we want to
2350 // ignore/downgrade pressure events.
2351 if (mi.field.free_swap >=
2352 mi.field.total_swap * swap_free_low_percentage / 100) {
2353 // If the pressure is larger than downgrade_pressure lmk will not
2354 // kill any process, since enough memory is available.
2355 if (mem_pressure > downgrade_pressure) {
2356 if (debug_process_killing) {
2357 ALOGI("Ignore %s memory pressure", level_name[level]);
2358 }
2359 return;
2360 } else if (level == VMPRESS_LEVEL_CRITICAL && mem_pressure > upgrade_pressure) {
2361 if (debug_process_killing) {
2362 ALOGI("Downgrade critical memory pressure");
2363 }
2364 // Downgrade event, since enough memory available.
2365 level = downgrade_level(level);
Robert Benea6e8e7102017-09-13 15:20:30 -07002366 }
Robert Benea6e8e7102017-09-13 15:20:30 -07002367 }
2368
Suren Baghdasaryan96bf3a62017-12-08 12:58:52 -08002369do_kill:
Suren Baghdasaryanff61afb2018-04-13 11:45:38 -07002370 if (low_ram_device) {
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08002371 /* For Go devices kill only one task */
Suren Baghdasaryanfd7518f2019-07-15 15:50:17 -07002372 if (find_and_kill_process(level_oomadj[level], NULL) == 0) {
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08002373 if (debug_process_killing) {
2374 ALOGI("Nothing to kill");
2375 }
Suren Baghdasaryan282ad1a2018-07-26 16:34:27 -07002376 } else {
2377 meminfo_log(&mi);
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08002378 }
2379 } else {
Suren Baghdasaryanffdc4dd2018-04-13 13:53:43 -07002380 int pages_freed;
Suren Baghdasaryan36934412018-09-05 15:46:32 -07002381 static struct timespec last_report_tm;
2382 static unsigned long report_skip_count = 0;
Suren Baghdasaryanffdc4dd2018-04-13 13:53:43 -07002383
2384 if (!use_minfree_levels) {
Suren Baghdasaryanffdc4dd2018-04-13 13:53:43 -07002385 /* Free up enough memory to downgrate the memory pressure to low level */
Suren Baghdasaryanf81b5f42018-10-26 11:32:15 -07002386 if (mi.field.nr_free_pages >= low_pressure_mem.max_nr_free_pages) {
Suren Baghdasaryanffdc4dd2018-04-13 13:53:43 -07002387 if (debug_process_killing) {
2388 ALOGI("Ignoring pressure since more memory is "
2389 "available (%" PRId64 ") than watermark (%" PRId64 ")",
2390 mi.field.nr_free_pages, low_pressure_mem.max_nr_free_pages);
2391 }
2392 return;
2393 }
2394 min_score_adj = level_oomadj[level];
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08002395 }
2396
Suren Baghdasaryanfd7518f2019-07-15 15:50:17 -07002397 pages_freed = find_and_kill_process(min_score_adj, NULL);
Suren Baghdasaryanda88b242018-05-10 16:10:56 -07002398
Suren Baghdasaryan36934412018-09-05 15:46:32 -07002399 if (pages_freed == 0) {
2400 /* Rate limit kill reports when nothing was reclaimed */
2401 if (get_time_diff_ms(&last_report_tm, &curr_tm) < FAIL_REPORT_RLIMIT_MS) {
2402 report_skip_count++;
Suren Baghdasaryan314a5052018-07-24 17:13:06 -07002403 return;
2404 }
Tim Murraye7853f62018-10-25 17:05:41 -07002405 } else {
2406 /* If we killed anything, update the last killed timestamp. */
2407 last_kill_tm = curr_tm;
Robert Beneacaeaa652017-08-11 16:03:20 -07002408 }
Suren Baghdasaryan36934412018-09-05 15:46:32 -07002409
2410 /* Log meminfo whenever we kill or when report rate limit allows */
2411 meminfo_log(&mi);
Suren Baghdasaryan36934412018-09-05 15:46:32 -07002412
2413 if (use_minfree_levels) {
Suren Baghdasaryanf81b5f42018-10-26 11:32:15 -07002414 ALOGI("Reclaimed %ldkB, cache(%ldkB) and "
Suren Baghdasaryan36934412018-09-05 15:46:32 -07002415 "free(%" PRId64 "kB)-reserved(%" PRId64 "kB) below min(%ldkB) for oom_adj %d",
Suren Baghdasaryanf81b5f42018-10-26 11:32:15 -07002416 pages_freed * page_k,
Suren Baghdasaryan36934412018-09-05 15:46:32 -07002417 other_file * page_k, mi.field.nr_free_pages * page_k,
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07002418 zi.totalreserve_pages * page_k,
Suren Baghdasaryan36934412018-09-05 15:46:32 -07002419 minfree * page_k, min_score_adj);
2420 } else {
Suren Baghdasaryanf81b5f42018-10-26 11:32:15 -07002421 ALOGI("Reclaimed %ldkB at oom_adj %d",
2422 pages_freed * page_k, min_score_adj);
Suren Baghdasaryan36934412018-09-05 15:46:32 -07002423 }
2424
2425 if (report_skip_count > 0) {
2426 ALOGI("Suppressed %lu failed kill reports", report_skip_count);
2427 report_skip_count = 0;
2428 }
2429
2430 last_report_tm = curr_tm;
Colin Crossf8857cc2014-07-11 17:16:56 -07002431 }
Todd Poynor3948f802013-07-09 19:35:14 -07002432}
2433
Suren Baghdasaryan844f26b2019-07-15 15:42:09 -07002434static bool init_mp_psi(enum vmpressure_level level, bool use_new_strategy) {
2435 int fd;
2436
2437 /* Do not register a handler if threshold_ms is not set */
2438 if (!psi_thresholds[level].threshold_ms) {
2439 return true;
2440 }
2441
2442 fd = init_psi_monitor(psi_thresholds[level].stall_type,
Suren Baghdasaryan77122e52019-01-08 12:54:48 -08002443 psi_thresholds[level].threshold_ms * US_PER_MS,
2444 PSI_WINDOW_SIZE_MS * US_PER_MS);
2445
2446 if (fd < 0) {
2447 return false;
2448 }
2449
Suren Baghdasaryan844f26b2019-07-15 15:42:09 -07002450 vmpressure_hinfo[level].handler = use_new_strategy ? mp_event_psi : mp_event_common;
Suren Baghdasaryan77122e52019-01-08 12:54:48 -08002451 vmpressure_hinfo[level].data = level;
2452 if (register_psi_monitor(epollfd, fd, &vmpressure_hinfo[level]) < 0) {
2453 destroy_psi_monitor(fd);
2454 return false;
2455 }
2456 maxevents++;
2457 mpevfd[level] = fd;
2458
2459 return true;
2460}
2461
2462static void destroy_mp_psi(enum vmpressure_level level) {
2463 int fd = mpevfd[level];
2464
2465 if (unregister_psi_monitor(epollfd, fd) < 0) {
2466 ALOGE("Failed to unregister psi monitor for %s memory pressure; errno=%d",
2467 level_name[level], errno);
2468 }
2469 destroy_psi_monitor(fd);
2470 mpevfd[level] = -1;
2471}
2472
2473static bool init_psi_monitors() {
Suren Baghdasaryan844f26b2019-07-15 15:42:09 -07002474 /*
2475 * When PSI is used on low-ram devices or on high-end devices without memfree levels
2476 * use new kill strategy based on zone watermarks, free swap and thrashing stats
2477 */
2478 bool use_new_strategy =
2479 property_get_bool("ro.lmk.use_new_strategy", low_ram_device || !use_minfree_levels);
2480
2481 /* In default PSI mode override stall amounts using system properties */
2482 if (use_new_strategy) {
2483 /* Do not use low pressure level */
2484 psi_thresholds[VMPRESS_LEVEL_LOW].threshold_ms = 0;
2485 psi_thresholds[VMPRESS_LEVEL_MEDIUM].threshold_ms = psi_partial_stall_ms;
2486 psi_thresholds[VMPRESS_LEVEL_CRITICAL].threshold_ms = psi_complete_stall_ms;
2487 }
2488
2489 if (!init_mp_psi(VMPRESS_LEVEL_LOW, use_new_strategy)) {
Suren Baghdasaryan77122e52019-01-08 12:54:48 -08002490 return false;
2491 }
Suren Baghdasaryan844f26b2019-07-15 15:42:09 -07002492 if (!init_mp_psi(VMPRESS_LEVEL_MEDIUM, use_new_strategy)) {
Suren Baghdasaryan77122e52019-01-08 12:54:48 -08002493 destroy_mp_psi(VMPRESS_LEVEL_LOW);
2494 return false;
2495 }
Suren Baghdasaryan844f26b2019-07-15 15:42:09 -07002496 if (!init_mp_psi(VMPRESS_LEVEL_CRITICAL, use_new_strategy)) {
Suren Baghdasaryan77122e52019-01-08 12:54:48 -08002497 destroy_mp_psi(VMPRESS_LEVEL_MEDIUM);
2498 destroy_mp_psi(VMPRESS_LEVEL_LOW);
2499 return false;
2500 }
2501 return true;
2502}
2503
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08002504static bool init_mp_common(enum vmpressure_level level) {
Todd Poynor3948f802013-07-09 19:35:14 -07002505 int mpfd;
2506 int evfd;
2507 int evctlfd;
2508 char buf[256];
2509 struct epoll_event epev;
2510 int ret;
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08002511 int level_idx = (int)level;
2512 const char *levelstr = level_name[level_idx];
Suren Baghdasaryan96bf3a62017-12-08 12:58:52 -08002513
Mark Salyzyn64d97d82018-04-09 09:50:32 -07002514 /* gid containing AID_SYSTEM required */
Nick Kralevichc68c8862015-12-18 20:52:37 -08002515 mpfd = open(MEMCG_SYSFS_PATH "memory.pressure_level", O_RDONLY | O_CLOEXEC);
Todd Poynor3948f802013-07-09 19:35:14 -07002516 if (mpfd < 0) {
2517 ALOGI("No kernel memory.pressure_level support (errno=%d)", errno);
2518 goto err_open_mpfd;
2519 }
2520
Nick Kralevichc68c8862015-12-18 20:52:37 -08002521 evctlfd = open(MEMCG_SYSFS_PATH "cgroup.event_control", O_WRONLY | O_CLOEXEC);
Todd Poynor3948f802013-07-09 19:35:14 -07002522 if (evctlfd < 0) {
2523 ALOGI("No kernel memory cgroup event control (errno=%d)", errno);
2524 goto err_open_evctlfd;
2525 }
2526
Nick Kralevichc68c8862015-12-18 20:52:37 -08002527 evfd = eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC);
Todd Poynor3948f802013-07-09 19:35:14 -07002528 if (evfd < 0) {
2529 ALOGE("eventfd failed for level %s; errno=%d", levelstr, errno);
2530 goto err_eventfd;
2531 }
2532
2533 ret = snprintf(buf, sizeof(buf), "%d %d %s", evfd, mpfd, levelstr);
2534 if (ret >= (ssize_t)sizeof(buf)) {
2535 ALOGE("cgroup.event_control line overflow for level %s", levelstr);
2536 goto err;
2537 }
2538
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08002539 ret = TEMP_FAILURE_RETRY(write(evctlfd, buf, strlen(buf) + 1));
Todd Poynor3948f802013-07-09 19:35:14 -07002540 if (ret == -1) {
2541 ALOGE("cgroup.event_control write failed for level %s; errno=%d",
2542 levelstr, errno);
2543 goto err;
2544 }
2545
2546 epev.events = EPOLLIN;
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08002547 /* use data to store event level */
2548 vmpressure_hinfo[level_idx].data = level_idx;
2549 vmpressure_hinfo[level_idx].handler = mp_event_common;
2550 epev.data.ptr = (void *)&vmpressure_hinfo[level_idx];
Todd Poynor3948f802013-07-09 19:35:14 -07002551 ret = epoll_ctl(epollfd, EPOLL_CTL_ADD, evfd, &epev);
2552 if (ret == -1) {
2553 ALOGE("epoll_ctl for level %s failed; errno=%d", levelstr, errno);
2554 goto err;
2555 }
2556 maxevents++;
Suren Baghdasaryan96bf3a62017-12-08 12:58:52 -08002557 mpevfd[level] = evfd;
Suren Baghdasaryan1bd2fc42018-01-04 08:54:53 -08002558 close(evctlfd);
Suren Baghdasaryan96bf3a62017-12-08 12:58:52 -08002559 return true;
Todd Poynor3948f802013-07-09 19:35:14 -07002560
2561err:
2562 close(evfd);
2563err_eventfd:
2564 close(evctlfd);
2565err_open_evctlfd:
2566 close(mpfd);
2567err_open_mpfd:
Suren Baghdasaryan96bf3a62017-12-08 12:58:52 -08002568 return false;
Robert Benea673e2762017-06-01 16:32:31 -07002569}
2570
Jim Blackler3947c932019-04-26 11:18:29 +01002571#ifdef LMKD_LOG_STATS
2572static int kernel_poll_fd = -1;
Jim Blackler3947c932019-04-26 11:18:29 +01002573static void poll_kernel() {
2574 if (kernel_poll_fd == -1) {
2575 // not waiting
2576 return;
2577 }
2578
2579 while (1) {
2580 char rd_buf[256];
2581 int bytes_read =
2582 TEMP_FAILURE_RETRY(pread(kernel_poll_fd, (void*)rd_buf, sizeof(rd_buf), 0));
2583 if (bytes_read <= 0) break;
2584 rd_buf[bytes_read] = '\0';
2585
2586 int64_t pid;
2587 int64_t uid;
2588 int64_t group_leader_pid;
2589 int64_t min_flt;
2590 int64_t maj_flt;
2591 int64_t rss_in_pages;
2592 int16_t oom_score_adj;
2593 int16_t min_score_adj;
2594 int64_t starttime;
2595 char* taskname = 0;
2596 int fields_read = sscanf(rd_buf,
2597 "%" SCNd64 " %" SCNd64 " %" SCNd64 " %" SCNd64 " %" SCNd64
2598 " %" SCNd64 " %" SCNd16 " %" SCNd16 " %" SCNd64 "\n%m[^\n]",
2599 &pid, &uid, &group_leader_pid, &min_flt, &maj_flt, &rss_in_pages,
2600 &oom_score_adj, &min_score_adj, &starttime, &taskname);
2601
2602 /* only the death of the group leader process is logged */
2603 if (fields_read == 10 && group_leader_pid == pid) {
2604 int64_t process_start_time_ns = starttime * (NS_PER_SEC / sysconf(_SC_CLK_TCK));
Jim Blacklerd2da8142019-09-10 15:30:05 +01002605 stats_write_lmk_kill_occurred_pid(log_ctx, LMK_KILL_OCCURRED, uid, pid, oom_score_adj,
2606 min_flt, maj_flt, rss_in_pages * PAGE_SIZE, 0, 0,
2607 process_start_time_ns, min_score_adj);
Jim Blackler3947c932019-04-26 11:18:29 +01002608 }
2609
2610 free(taskname);
2611 }
2612}
2613
2614static struct event_handler_info kernel_poll_hinfo = {0, poll_kernel};
2615
2616static void init_poll_kernel() {
2617 struct epoll_event epev;
2618 kernel_poll_fd =
2619 TEMP_FAILURE_RETRY(open("/proc/lowmemorykiller", O_RDONLY | O_NONBLOCK | O_CLOEXEC));
2620
2621 if (kernel_poll_fd < 0) {
2622 ALOGE("kernel lmk event file could not be opened; errno=%d", kernel_poll_fd);
2623 return;
2624 }
2625
2626 epev.events = EPOLLIN;
2627 epev.data.ptr = (void*)&kernel_poll_hinfo;
2628 if (epoll_ctl(epollfd, EPOLL_CTL_ADD, kernel_poll_fd, &epev) != 0) {
2629 ALOGE("epoll_ctl for lmk events failed; errno=%d", errno);
2630 close(kernel_poll_fd);
2631 kernel_poll_fd = -1;
2632 } else {
2633 maxevents++;
2634 }
2635}
2636#endif
2637
Todd Poynor3948f802013-07-09 19:35:14 -07002638static int init(void) {
Suren Baghdasaryana77b3272019-07-15 13:35:04 -07002639 struct reread_data file_data = {
2640 .filename = ZONEINFO_PATH,
2641 .fd = -1,
2642 };
Todd Poynor3948f802013-07-09 19:35:14 -07002643 struct epoll_event epev;
2644 int i;
2645 int ret;
2646
2647 page_k = sysconf(_SC_PAGESIZE);
2648 if (page_k == -1)
2649 page_k = PAGE_SIZE;
2650 page_k /= 1024;
2651
2652 epollfd = epoll_create(MAX_EPOLL_EVENTS);
2653 if (epollfd == -1) {
2654 ALOGE("epoll_create failed (errno=%d)", errno);
2655 return -1;
2656 }
2657
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08002658 // mark data connections as not connected
2659 for (int i = 0; i < MAX_DATA_CONN; i++) {
2660 data_sock[i].sock = -1;
2661 }
2662
2663 ctrl_sock.sock = android_get_control_socket("lmkd");
2664 if (ctrl_sock.sock < 0) {
Todd Poynor3948f802013-07-09 19:35:14 -07002665 ALOGE("get lmkd control socket failed");
2666 return -1;
2667 }
2668
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08002669 ret = listen(ctrl_sock.sock, MAX_DATA_CONN);
Todd Poynor3948f802013-07-09 19:35:14 -07002670 if (ret < 0) {
2671 ALOGE("lmkd control socket listen failed (errno=%d)", errno);
2672 return -1;
2673 }
2674
2675 epev.events = EPOLLIN;
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08002676 ctrl_sock.handler_info.handler = ctrl_connect_handler;
2677 epev.data.ptr = (void *)&(ctrl_sock.handler_info);
2678 if (epoll_ctl(epollfd, EPOLL_CTL_ADD, ctrl_sock.sock, &epev) == -1) {
Todd Poynor3948f802013-07-09 19:35:14 -07002679 ALOGE("epoll_ctl for lmkd control socket failed (errno=%d)", errno);
2680 return -1;
2681 }
2682 maxevents++;
2683
Robert Benea164baeb2017-09-11 16:53:28 -07002684 has_inkernel_module = !access(INKERNEL_MINFREE_PATH, W_OK);
Suren Baghdasaryan979591b2018-01-18 17:27:30 -08002685 use_inkernel_interface = has_inkernel_module;
Todd Poynor3948f802013-07-09 19:35:14 -07002686
2687 if (use_inkernel_interface) {
2688 ALOGI("Using in-kernel low memory killer interface");
Jim Blackler3947c932019-04-26 11:18:29 +01002689#ifdef LMKD_LOG_STATS
2690 if (enable_stats_log) {
2691 init_poll_kernel();
2692 }
2693#endif
Todd Poynor3948f802013-07-09 19:35:14 -07002694 } else {
Suren Baghdasaryan77122e52019-01-08 12:54:48 -08002695 /* Try to use psi monitor first if kernel has it */
2696 use_psi_monitors = property_get_bool("ro.lmk.use_psi", true) &&
2697 init_psi_monitors();
2698 /* Fall back to vmpressure */
2699 if (!use_psi_monitors &&
2700 (!init_mp_common(VMPRESS_LEVEL_LOW) ||
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08002701 !init_mp_common(VMPRESS_LEVEL_MEDIUM) ||
Suren Baghdasaryan77122e52019-01-08 12:54:48 -08002702 !init_mp_common(VMPRESS_LEVEL_CRITICAL))) {
Todd Poynor3948f802013-07-09 19:35:14 -07002703 ALOGE("Kernel does not support memory pressure events or in-kernel low memory killer");
Suren Baghdasaryan96bf3a62017-12-08 12:58:52 -08002704 return -1;
2705 }
Suren Baghdasaryan77122e52019-01-08 12:54:48 -08002706 if (use_psi_monitors) {
2707 ALOGI("Using psi monitors for memory pressure detection");
2708 } else {
2709 ALOGI("Using vmpressure for memory pressure detection");
2710 }
Todd Poynor3948f802013-07-09 19:35:14 -07002711 }
2712
Chong Zhang0a4acdf2015-10-14 16:19:53 -07002713 for (i = 0; i <= ADJTOSLOT(OOM_SCORE_ADJ_MAX); i++) {
Todd Poynor3948f802013-07-09 19:35:14 -07002714 procadjslot_list[i].next = &procadjslot_list[i];
2715 procadjslot_list[i].prev = &procadjslot_list[i];
2716 }
2717
Suren Baghdasaryand4a29902018-10-12 11:07:40 -07002718 memset(killcnt_idx, KILLCNT_INVALID_IDX, sizeof(killcnt_idx));
2719
Suren Baghdasaryana77b3272019-07-15 13:35:04 -07002720 /*
2721 * Read zoneinfo as the biggest file we read to create and size the initial
2722 * read buffer and avoid memory re-allocations during memory pressure
2723 */
2724 if (reread_file(&file_data) == NULL) {
2725 ALOGE("Failed to read %s: %s", file_data.filename, strerror(errno));
2726 }
2727
Todd Poynor3948f802013-07-09 19:35:14 -07002728 return 0;
2729}
2730
2731static void mainloop(void) {
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08002732 struct event_handler_info* handler_info;
Suren Baghdasaryanef3650f2019-07-15 14:50:49 -07002733 struct polling_params poll_params;
2734 struct timespec curr_tm;
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08002735 struct epoll_event *evt;
Suren Baghdasaryan77122e52019-01-08 12:54:48 -08002736 long delay = -1;
Suren Baghdasaryanef3650f2019-07-15 14:50:49 -07002737
2738 poll_params.poll_handler = NULL;
2739 poll_params.update = POLLING_DO_NOT_CHANGE;
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08002740
Todd Poynor3948f802013-07-09 19:35:14 -07002741 while (1) {
2742 struct epoll_event events[maxevents];
2743 int nevents;
2744 int i;
2745
Suren Baghdasaryanef3650f2019-07-15 14:50:49 -07002746 if (poll_params.poll_handler) {
Suren Baghdasaryan77122e52019-01-08 12:54:48 -08002747 /* Calculate next timeout */
2748 clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm);
Suren Baghdasaryanef3650f2019-07-15 14:50:49 -07002749 delay = get_time_diff_ms(&poll_params.last_poll_tm, &curr_tm);
2750 delay = (delay < poll_params.polling_interval_ms) ?
2751 poll_params.polling_interval_ms - delay : poll_params.polling_interval_ms;
Suren Baghdasaryan77122e52019-01-08 12:54:48 -08002752
2753 /* Wait for events until the next polling timeout */
2754 nevents = epoll_wait(epollfd, events, maxevents, delay);
2755
2756 clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm);
Suren Baghdasaryanef3650f2019-07-15 14:50:49 -07002757 if (get_time_diff_ms(&poll_params.last_poll_tm, &curr_tm) >=
2758 poll_params.polling_interval_ms) {
2759 /* Set input params for the call */
2760 poll_params.poll_handler->handler(poll_params.poll_handler->data, 0, &poll_params);
2761 poll_params.last_poll_tm = curr_tm;
2762
2763 if (poll_params.update != POLLING_DO_NOT_CHANGE) {
2764 switch (poll_params.update) {
2765 case POLLING_START:
2766 poll_params.poll_start_tm = curr_tm;
2767 break;
2768 case POLLING_STOP:
2769 poll_params.poll_handler = NULL;
2770 break;
2771 default:
2772 break;
2773 }
2774 poll_params.update = POLLING_DO_NOT_CHANGE;
2775 } else {
2776 if (get_time_diff_ms(&poll_params.poll_start_tm, &curr_tm) >
2777 PSI_WINDOW_SIZE_MS) {
2778 /* Polled for the duration of PSI window, time to stop */
2779 poll_params.poll_handler = NULL;
2780 }
2781 }
Suren Baghdasaryan77122e52019-01-08 12:54:48 -08002782 }
2783 } else {
2784 /* Wait for events with no timeout */
2785 nevents = epoll_wait(epollfd, events, maxevents, -1);
2786 }
Todd Poynor3948f802013-07-09 19:35:14 -07002787
2788 if (nevents == -1) {
2789 if (errno == EINTR)
2790 continue;
2791 ALOGE("epoll_wait failed (errno=%d)", errno);
2792 continue;
2793 }
2794
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08002795 /*
2796 * First pass to see if any data socket connections were dropped.
2797 * Dropped connection should be handled before any other events
2798 * to deallocate data connection and correctly handle cases when
2799 * connection gets dropped and reestablished in the same epoll cycle.
2800 * In such cases it's essential to handle connection closures first.
2801 */
2802 for (i = 0, evt = &events[0]; i < nevents; ++i, evt++) {
2803 if ((evt->events & EPOLLHUP) && evt->data.ptr) {
2804 ALOGI("lmkd data connection dropped");
2805 handler_info = (struct event_handler_info*)evt->data.ptr;
2806 ctrl_data_close(handler_info->data);
2807 }
2808 }
2809
2810 /* Second pass to handle all other events */
2811 for (i = 0, evt = &events[0]; i < nevents; ++i, evt++) {
Suren Baghdasaryanef3650f2019-07-15 14:50:49 -07002812 if (evt->events & EPOLLERR) {
Todd Poynor3948f802013-07-09 19:35:14 -07002813 ALOGD("EPOLLERR on event #%d", i);
Suren Baghdasaryanef3650f2019-07-15 14:50:49 -07002814 }
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08002815 if (evt->events & EPOLLHUP) {
2816 /* This case was handled in the first pass */
2817 continue;
2818 }
2819 if (evt->data.ptr) {
2820 handler_info = (struct event_handler_info*)evt->data.ptr;
Suren Baghdasaryanef3650f2019-07-15 14:50:49 -07002821 /* Set input params for the call */
2822 handler_info->handler(handler_info->data, evt->events, &poll_params);
Suren Baghdasaryan77122e52019-01-08 12:54:48 -08002823
Suren Baghdasaryanef3650f2019-07-15 14:50:49 -07002824 if (poll_params.update != POLLING_DO_NOT_CHANGE) {
2825 switch (poll_params.update) {
2826 case POLLING_START:
2827 /*
2828 * Poll for the duration of PSI_WINDOW_SIZE_MS after the
2829 * initial PSI event because psi events are rate-limited
2830 * at one per sec.
2831 */
2832 clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm);
2833 poll_params.poll_start_tm = poll_params.last_poll_tm = curr_tm;
2834 poll_params.poll_handler = handler_info;
2835 break;
2836 case POLLING_STOP:
2837 poll_params.poll_handler = NULL;
2838 break;
2839 default:
2840 break;
2841 }
2842 poll_params.update = POLLING_DO_NOT_CHANGE;
Suren Baghdasaryan77122e52019-01-08 12:54:48 -08002843 }
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08002844 }
Todd Poynor3948f802013-07-09 19:35:14 -07002845 }
2846 }
2847}
2848
Mark Salyzyne6ed68b2014-04-30 13:36:35 -07002849int main(int argc __unused, char **argv __unused) {
Colin Cross1a0d9be2014-07-14 14:31:15 -07002850 struct sched_param param = {
2851 .sched_priority = 1,
2852 };
2853
Suren Baghdasaryan96bf3a62017-12-08 12:58:52 -08002854 /* By default disable low level vmpressure events */
2855 level_oomadj[VMPRESS_LEVEL_LOW] =
2856 property_get_int32("ro.lmk.low", OOM_SCORE_ADJ_MAX + 1);
2857 level_oomadj[VMPRESS_LEVEL_MEDIUM] =
2858 property_get_int32("ro.lmk.medium", 800);
2859 level_oomadj[VMPRESS_LEVEL_CRITICAL] =
2860 property_get_int32("ro.lmk.critical", 0);
Robert Beneacaeaa652017-08-11 16:03:20 -07002861 debug_process_killing = property_get_bool("ro.lmk.debug", false);
Suren Baghdasaryanad2fd912017-12-08 13:08:41 -08002862
2863 /* By default disable upgrade/downgrade logic */
2864 enable_pressure_upgrade =
2865 property_get_bool("ro.lmk.critical_upgrade", false);
2866 upgrade_pressure =
2867 (int64_t)property_get_int32("ro.lmk.upgrade_pressure", 100);
2868 downgrade_pressure =
2869 (int64_t)property_get_int32("ro.lmk.downgrade_pressure", 100);
Suren Baghdasaryan662492a2017-12-08 13:17:06 -08002870 kill_heaviest_task =
Suren Baghdasaryan818b59b2018-04-13 11:49:54 -07002871 property_get_bool("ro.lmk.kill_heaviest_task", false);
Suren Baghdasaryanff61afb2018-04-13 11:45:38 -07002872 low_ram_device = property_get_bool("ro.config.low_ram", false);
Suren Baghdasaryancaa2dc52018-01-17 17:28:01 -08002873 kill_timeout_ms =
2874 (unsigned long)property_get_int32("ro.lmk.kill_timeout_ms", 0);
Suren Baghdasaryanffdc4dd2018-04-13 13:53:43 -07002875 use_minfree_levels =
2876 property_get_bool("ro.lmk.use_minfree_levels", false);
Suren Baghdasaryance13cb52018-06-19 18:38:12 -07002877 per_app_memcg =
2878 property_get_bool("ro.config.per_app_memcg", low_ram_device);
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002879 swap_free_low_percentage = clamp(0, 100, property_get_int32("ro.lmk.swap_free_low_percentage",
2880 low_ram_device ? DEF_LOW_SWAP_LOWRAM : DEF_LOW_SWAP));
Suren Baghdasaryan844f26b2019-07-15 15:42:09 -07002881 psi_partial_stall_ms = property_get_int32("ro.lmk.psi_partial_stall_ms",
2882 low_ram_device ? DEF_PARTIAL_STALL_LOWRAM : DEF_PARTIAL_STALL);
2883 psi_complete_stall_ms = property_get_int32("ro.lmk.psi_complete_stall_ms",
2884 DEF_COMPLETE_STALL);
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002885 thrashing_limit_pct = max(0, property_get_int32("ro.lmk.thrashing_limit",
2886 low_ram_device ? DEF_THRASHING_LOWRAM : DEF_THRASHING));
2887 thrashing_limit_decay_pct = clamp(0, 100, property_get_int32("ro.lmk.thrashing_limit_decay",
2888 low_ram_device ? DEF_THRASHING_DECAY_LOWRAM : DEF_THRASHING_DECAY));
Robert Benea58891d52017-07-31 17:15:20 -07002889
Suren Baghdasaryan282ad1a2018-07-26 16:34:27 -07002890 ctx = create_android_logger(MEMINFO_LOG_TAG);
2891
Rajeev Kumar70450032018-01-31 17:54:56 -08002892#ifdef LMKD_LOG_STATS
Rajeev Kumar1c669f72018-03-09 15:20:56 -08002893 statslog_init(&log_ctx, &enable_stats_log);
Rajeev Kumar70450032018-01-31 17:54:56 -08002894#endif
2895
Mark Salyzyn721d7c72018-03-21 12:24:58 -07002896 if (!init()) {
2897 if (!use_inkernel_interface) {
2898 /*
2899 * MCL_ONFAULT pins pages as they fault instead of loading
2900 * everything immediately all at once. (Which would be bad,
2901 * because as of this writing, we have a lot of mapped pages we
2902 * never use.) Old kernels will see MCL_ONFAULT and fail with
2903 * EINVAL; we ignore this failure.
2904 *
2905 * N.B. read the man page for mlockall. MCL_CURRENT | MCL_ONFAULT
2906 * pins ⊆ MCL_CURRENT, converging to just MCL_CURRENT as we fault
2907 * in pages.
2908 */
Mark Salyzyn64d97d82018-04-09 09:50:32 -07002909 /* CAP_IPC_LOCK required */
Mark Salyzyn721d7c72018-03-21 12:24:58 -07002910 if (mlockall(MCL_CURRENT | MCL_FUTURE | MCL_ONFAULT) && (errno != EINVAL)) {
2911 ALOGW("mlockall failed %s", strerror(errno));
2912 }
Daniel Colascione4dd5d002018-01-03 12:01:02 -08002913
Mark Salyzyn64d97d82018-04-09 09:50:32 -07002914 /* CAP_NICE required */
2915 if (sched_setscheduler(0, SCHED_FIFO, &param)) {
2916 ALOGW("set SCHED_FIFO failed %s", strerror(errno));
2917 }
Mark Salyzyn721d7c72018-03-21 12:24:58 -07002918 }
2919
Todd Poynor3948f802013-07-09 19:35:14 -07002920 mainloop();
Mark Salyzyn721d7c72018-03-21 12:24:58 -07002921 }
Todd Poynor3948f802013-07-09 19:35:14 -07002922
Rajeev Kumar70450032018-01-31 17:54:56 -08002923#ifdef LMKD_LOG_STATS
Rajeev Kumar1c669f72018-03-09 15:20:56 -08002924 statslog_destroy(&log_ctx);
Rajeev Kumar70450032018-01-31 17:54:56 -08002925#endif
2926
Suren Baghdasaryan282ad1a2018-07-26 16:34:27 -07002927 android_log_destroy(&ctx);
2928
Todd Poynor3948f802013-07-09 19:35:14 -07002929 ALOGI("exiting");
2930 return 0;
2931}