blob: 661fd8b0c3d5833aae2de315ea1ed25ac782697c [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 Baghdasaryan4b750882019-09-19 15:27:21 -070086#define PERCEPTIBLE_APP_ADJ 200
87
Suren Baghdasaryan282ad1a2018-07-26 16:34:27 -070088/* Android Logger event logtags (see event.logtags) */
89#define MEMINFO_LOG_TAG 10195355
90
Mark Salyzyn64d97d82018-04-09 09:50:32 -070091/* gid containing AID_SYSTEM required */
Todd Poynor3948f802013-07-09 19:35:14 -070092#define INKERNEL_MINFREE_PATH "/sys/module/lowmemorykiller/parameters/minfree"
93#define INKERNEL_ADJ_PATH "/sys/module/lowmemorykiller/parameters/adj"
94
95#define ARRAY_SIZE(x) (sizeof(x) / sizeof(*(x)))
Robert Benea673e2762017-06-01 16:32:31 -070096#define EIGHT_MEGA (1 << 23)
Todd Poynor3948f802013-07-09 19:35:14 -070097
Suren Baghdasaryan314a5052018-07-24 17:13:06 -070098#define TARGET_UPDATE_MIN_INTERVAL_MS 1000
99
100#define NS_PER_MS (NS_PER_SEC / MS_PER_SEC)
Suren Baghdasaryan77122e52019-01-08 12:54:48 -0800101#define US_PER_MS (US_PER_SEC / MS_PER_SEC)
Suren Baghdasaryan314a5052018-07-24 17:13:06 -0700102
Suren Baghdasaryan4311d1e2018-03-20 16:03:29 -0700103/* Defined as ProcessList.SYSTEM_ADJ in ProcessList.java */
104#define SYSTEM_ADJ (-900)
105
Greg Kaiserf0da9b02018-03-23 14:16:12 -0700106#define STRINGIFY(x) STRINGIFY_INTERNAL(x)
107#define STRINGIFY_INTERNAL(x) #x
108
Suren Baghdasaryan77122e52019-01-08 12:54:48 -0800109/*
110 * PSI monitor tracking window size.
111 * PSI monitor generates events at most once per window,
112 * therefore we poll memory state for the duration of
113 * PSI_WINDOW_SIZE_MS after the event happens.
114 */
115#define PSI_WINDOW_SIZE_MS 1000
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -0700116/* Polling period after PSI signal when pressure is high */
117#define PSI_POLL_PERIOD_SHORT_MS 10
118/* Polling period after PSI signal when pressure is low */
119#define PSI_POLL_PERIOD_LONG_MS 100
Suren Baghdasaryan77122e52019-01-08 12:54:48 -0800120
Suren Baghdasaryan282ad1a2018-07-26 16:34:27 -0700121#define min(a, b) (((a) < (b)) ? (a) : (b))
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -0700122#define max(a, b) (((a) > (b)) ? (a) : (b))
Suren Baghdasaryan282ad1a2018-07-26 16:34:27 -0700123
Suren Baghdasaryan36934412018-09-05 15:46:32 -0700124#define FAIL_REPORT_RLIMIT_MS 1000
125
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -0700126/*
127 * System property defaults
128 */
129/* ro.lmk.swap_free_low_percentage property defaults */
130#define DEF_LOW_SWAP_LOWRAM 10
131#define DEF_LOW_SWAP 20
132/* ro.lmk.thrashing_limit property defaults */
133#define DEF_THRASHING_LOWRAM 30
134#define DEF_THRASHING 100
135/* ro.lmk.thrashing_limit_decay property defaults */
136#define DEF_THRASHING_DECAY_LOWRAM 50
137#define DEF_THRASHING_DECAY 10
Suren Baghdasaryan844f26b2019-07-15 15:42:09 -0700138/* ro.lmk.psi_partial_stall_ms property defaults */
139#define DEF_PARTIAL_STALL_LOWRAM 200
140#define DEF_PARTIAL_STALL 70
141/* ro.lmk.psi_complete_stall_ms property defaults */
142#define DEF_COMPLETE_STALL 700
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -0700143
Todd Poynor3948f802013-07-09 19:35:14 -0700144/* default to old in-kernel interface if no memory pressure events */
Mark Salyzyn721d7c72018-03-21 12:24:58 -0700145static bool use_inkernel_interface = true;
Robert Benea164baeb2017-09-11 16:53:28 -0700146static bool has_inkernel_module;
Todd Poynor3948f802013-07-09 19:35:14 -0700147
Suren Baghdasaryan96bf3a62017-12-08 12:58:52 -0800148/* memory pressure levels */
149enum vmpressure_level {
150 VMPRESS_LEVEL_LOW = 0,
151 VMPRESS_LEVEL_MEDIUM,
152 VMPRESS_LEVEL_CRITICAL,
153 VMPRESS_LEVEL_COUNT
154};
Todd Poynor3948f802013-07-09 19:35:14 -0700155
Suren Baghdasaryan96bf3a62017-12-08 12:58:52 -0800156static const char *level_name[] = {
157 "low",
158 "medium",
159 "critical"
160};
161
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -0800162struct {
Suren Baghdasaryan9926e572018-04-13 13:41:12 -0700163 int64_t min_nr_free_pages; /* recorded but not used yet */
164 int64_t max_nr_free_pages;
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -0800165} low_pressure_mem = { -1, -1 };
166
Suren Baghdasaryan77122e52019-01-08 12:54:48 -0800167struct psi_threshold {
168 enum psi_stall_type stall_type;
169 int threshold_ms;
170};
171
Suren Baghdasaryan96bf3a62017-12-08 12:58:52 -0800172static int level_oomadj[VMPRESS_LEVEL_COUNT];
Suren Baghdasaryane82e15c2018-01-04 09:16:21 -0800173static int mpevfd[VMPRESS_LEVEL_COUNT] = { -1, -1, -1 };
Robert Beneac47f2992017-08-21 15:18:31 -0700174static bool debug_process_killing;
175static bool enable_pressure_upgrade;
176static int64_t upgrade_pressure;
Robert Benea6e8e7102017-09-13 15:20:30 -0700177static int64_t downgrade_pressure;
Suren Baghdasaryanff61afb2018-04-13 11:45:38 -0700178static bool low_ram_device;
Suren Baghdasaryan662492a2017-12-08 13:17:06 -0800179static bool kill_heaviest_task;
Suren Baghdasaryancaa2dc52018-01-17 17:28:01 -0800180static unsigned long kill_timeout_ms;
Suren Baghdasaryanffdc4dd2018-04-13 13:53:43 -0700181static bool use_minfree_levels;
Suren Baghdasaryance13cb52018-06-19 18:38:12 -0700182static bool per_app_memcg;
Vic Yang360a1132018-08-07 10:18:22 -0700183static int swap_free_low_percentage;
Suren Baghdasaryan844f26b2019-07-15 15:42:09 -0700184static int psi_partial_stall_ms;
185static int psi_complete_stall_ms;
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -0700186static int thrashing_limit_pct;
187static int thrashing_limit_decay_pct;
Suren Baghdasaryan77122e52019-01-08 12:54:48 -0800188static bool use_psi_monitors = false;
189static struct psi_threshold psi_thresholds[VMPRESS_LEVEL_COUNT] = {
190 { PSI_SOME, 70 }, /* 70ms out of 1sec for partial stall */
191 { PSI_SOME, 100 }, /* 100ms out of 1sec for partial stall */
192 { PSI_FULL, 70 }, /* 70ms out of 1sec for complete stall */
193};
Robert Benea58891d52017-07-31 17:15:20 -0700194
Suren Baghdasaryan282ad1a2018-07-26 16:34:27 -0700195static android_log_context ctx;
196
Suren Baghdasaryanef3650f2019-07-15 14:50:49 -0700197enum polling_update {
198 POLLING_DO_NOT_CHANGE,
199 POLLING_START,
200 POLLING_STOP,
201};
202
203/*
204 * Data used for periodic polling for the memory state of the device.
205 * Note that when system is not polling poll_handler is set to NULL,
206 * when polling starts poll_handler gets set and is reset back to
207 * NULL when polling stops.
208 */
209struct polling_params {
210 struct event_handler_info* poll_handler;
211 struct timespec poll_start_tm;
212 struct timespec last_poll_tm;
213 int polling_interval_ms;
214 enum polling_update update;
215};
216
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -0800217/* data required to handle events */
218struct event_handler_info {
219 int data;
Suren Baghdasaryanef3650f2019-07-15 14:50:49 -0700220 void (*handler)(int data, uint32_t events, struct polling_params *poll_params);
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -0800221};
Todd Poynor3948f802013-07-09 19:35:14 -0700222
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -0800223/* data required to handle socket events */
224struct sock_event_handler_info {
225 int sock;
226 struct event_handler_info handler_info;
227};
228
229/* max supported number of data connections */
230#define MAX_DATA_CONN 2
231
232/* socket event handler data */
233static struct sock_event_handler_info ctrl_sock;
234static struct sock_event_handler_info data_sock[MAX_DATA_CONN];
235
236/* vmpressure event handler data */
237static struct event_handler_info vmpressure_hinfo[VMPRESS_LEVEL_COUNT];
238
Jim Blackler3947c932019-04-26 11:18:29 +0100239/* 3 memory pressure levels, 1 ctrl listen socket, 2 ctrl data socket, 1 lmk events */
240#define MAX_EPOLL_EVENTS (2 + MAX_DATA_CONN + VMPRESS_LEVEL_COUNT)
Todd Poynor3948f802013-07-09 19:35:14 -0700241static int epollfd;
242static int maxevents;
243
Chong Zhang0a4acdf2015-10-14 16:19:53 -0700244/* OOM score values used by both kernel and framework */
Todd Poynor16b60992013-09-16 19:26:47 -0700245#define OOM_SCORE_ADJ_MIN (-1000)
246#define OOM_SCORE_ADJ_MAX 1000
247
Todd Poynor3948f802013-07-09 19:35:14 -0700248static int lowmem_adj[MAX_TARGETS];
249static int lowmem_minfree[MAX_TARGETS];
250static int lowmem_targets_size;
251
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -0700252/* Fields to parse in /proc/zoneinfo */
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -0700253/* zoneinfo per-zone fields */
254enum zoneinfo_zone_field {
255 ZI_ZONE_NR_FREE_PAGES = 0,
256 ZI_ZONE_MIN,
257 ZI_ZONE_LOW,
258 ZI_ZONE_HIGH,
259 ZI_ZONE_PRESENT,
260 ZI_ZONE_NR_FREE_CMA,
261 ZI_ZONE_FIELD_COUNT
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -0700262};
263
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -0700264static const char* const zoneinfo_zone_field_names[ZI_ZONE_FIELD_COUNT] = {
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -0700265 "nr_free_pages",
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -0700266 "min",
267 "low",
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -0700268 "high",
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -0700269 "present",
270 "nr_free_cma",
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -0700271};
272
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -0700273/* zoneinfo per-zone special fields */
274enum zoneinfo_zone_spec_field {
275 ZI_ZONE_SPEC_PROTECTION = 0,
276 ZI_ZONE_SPEC_PAGESETS,
277 ZI_ZONE_SPEC_FIELD_COUNT,
278};
279
280static const char* const zoneinfo_zone_spec_field_names[ZI_ZONE_SPEC_FIELD_COUNT] = {
281 "protection:",
282 "pagesets",
283};
284
285/* see __MAX_NR_ZONES definition in kernel mmzone.h */
286#define MAX_NR_ZONES 6
287
288union zoneinfo_zone_fields {
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -0700289 struct {
290 int64_t nr_free_pages;
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -0700291 int64_t min;
292 int64_t low;
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -0700293 int64_t high;
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -0700294 int64_t present;
295 int64_t nr_free_cma;
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -0700296 } field;
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -0700297 int64_t arr[ZI_ZONE_FIELD_COUNT];
298};
299
300struct zoneinfo_zone {
301 union zoneinfo_zone_fields fields;
302 int64_t protection[MAX_NR_ZONES];
303 int64_t max_protection;
304};
305
306/* zoneinfo per-node fields */
307enum zoneinfo_node_field {
308 ZI_NODE_NR_INACTIVE_FILE = 0,
309 ZI_NODE_NR_ACTIVE_FILE,
310 ZI_NODE_WORKINGSET_REFAULT,
311 ZI_NODE_FIELD_COUNT
312};
313
314static const char* const zoneinfo_node_field_names[ZI_NODE_FIELD_COUNT] = {
315 "nr_inactive_file",
316 "nr_active_file",
317 "workingset_refault",
318};
319
320union zoneinfo_node_fields {
321 struct {
322 int64_t nr_inactive_file;
323 int64_t nr_active_file;
324 int64_t workingset_refault;
325 } field;
326 int64_t arr[ZI_NODE_FIELD_COUNT];
327};
328
329struct zoneinfo_node {
330 int id;
331 int zone_count;
332 struct zoneinfo_zone zones[MAX_NR_ZONES];
333 union zoneinfo_node_fields fields;
334};
335
336/* for now two memory nodes is more than enough */
337#define MAX_NR_NODES 2
338
339struct zoneinfo {
340 int node_count;
341 struct zoneinfo_node nodes[MAX_NR_NODES];
342 int64_t totalreserve_pages;
343 int64_t total_inactive_file;
344 int64_t total_active_file;
345 int64_t total_workingset_refault;
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -0700346};
347
348/* Fields to parse in /proc/meminfo */
349enum meminfo_field {
350 MI_NR_FREE_PAGES = 0,
351 MI_CACHED,
352 MI_SWAP_CACHED,
353 MI_BUFFERS,
354 MI_SHMEM,
355 MI_UNEVICTABLE,
Vic Yang360a1132018-08-07 10:18:22 -0700356 MI_TOTAL_SWAP,
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -0700357 MI_FREE_SWAP,
Suren Baghdasaryan282ad1a2018-07-26 16:34:27 -0700358 MI_ACTIVE_ANON,
359 MI_INACTIVE_ANON,
360 MI_ACTIVE_FILE,
361 MI_INACTIVE_FILE,
362 MI_SRECLAIMABLE,
363 MI_SUNRECLAIM,
364 MI_KERNEL_STACK,
365 MI_PAGE_TABLES,
366 MI_ION_HELP,
367 MI_ION_HELP_POOL,
368 MI_CMA_FREE,
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -0700369 MI_FIELD_COUNT
370};
371
372static const char* const meminfo_field_names[MI_FIELD_COUNT] = {
373 "MemFree:",
374 "Cached:",
375 "SwapCached:",
376 "Buffers:",
377 "Shmem:",
378 "Unevictable:",
Vic Yang360a1132018-08-07 10:18:22 -0700379 "SwapTotal:",
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -0700380 "SwapFree:",
Suren Baghdasaryan282ad1a2018-07-26 16:34:27 -0700381 "Active(anon):",
382 "Inactive(anon):",
383 "Active(file):",
384 "Inactive(file):",
385 "SReclaimable:",
386 "SUnreclaim:",
387 "KernelStack:",
388 "PageTables:",
389 "ION_heap:",
390 "ION_heap_pool:",
391 "CmaFree:",
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -0700392};
393
394union meminfo {
395 struct {
396 int64_t nr_free_pages;
397 int64_t cached;
398 int64_t swap_cached;
399 int64_t buffers;
400 int64_t shmem;
401 int64_t unevictable;
Vic Yang360a1132018-08-07 10:18:22 -0700402 int64_t total_swap;
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -0700403 int64_t free_swap;
Suren Baghdasaryan282ad1a2018-07-26 16:34:27 -0700404 int64_t active_anon;
405 int64_t inactive_anon;
406 int64_t active_file;
407 int64_t inactive_file;
408 int64_t sreclaimable;
409 int64_t sunreclaimable;
410 int64_t kernel_stack;
411 int64_t page_tables;
412 int64_t ion_heap;
413 int64_t ion_heap_pool;
414 int64_t cma_free;
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -0700415 /* fields below are calculated rather than read from the file */
416 int64_t nr_file_pages;
417 } field;
418 int64_t arr[MI_FIELD_COUNT];
419};
420
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -0700421/* Fields to parse in /proc/vmstat */
422enum vmstat_field {
423 VS_FREE_PAGES,
424 VS_INACTIVE_FILE,
425 VS_ACTIVE_FILE,
426 VS_WORKINGSET_REFAULT,
427 VS_PGSCAN_KSWAPD,
428 VS_PGSCAN_DIRECT,
429 VS_PGSCAN_DIRECT_THROTTLE,
430 VS_FIELD_COUNT
431};
432
433static const char* const vmstat_field_names[MI_FIELD_COUNT] = {
434 "nr_free_pages",
435 "nr_inactive_file",
436 "nr_active_file",
437 "workingset_refault",
438 "pgscan_kswapd",
439 "pgscan_direct",
440 "pgscan_direct_throttle",
441};
442
443union vmstat {
444 struct {
445 int64_t nr_free_pages;
446 int64_t nr_inactive_file;
447 int64_t nr_active_file;
448 int64_t workingset_refault;
449 int64_t pgscan_kswapd;
450 int64_t pgscan_direct;
451 int64_t pgscan_direct_throttle;
452 } field;
453 int64_t arr[VS_FIELD_COUNT];
454};
455
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -0700456enum field_match_result {
457 NO_MATCH,
458 PARSE_FAIL,
459 PARSE_SUCCESS
460};
461
Todd Poynor3948f802013-07-09 19:35:14 -0700462struct adjslot_list {
463 struct adjslot_list *next;
464 struct adjslot_list *prev;
465};
466
467struct proc {
468 struct adjslot_list asl;
469 int pid;
Colin Crossfbb78c62014-06-13 14:52:43 -0700470 uid_t uid;
Todd Poynor3948f802013-07-09 19:35:14 -0700471 int oomadj;
472 struct proc *pidhash_next;
473};
474
Suren Baghdasaryan6499e5e2018-04-13 12:43:41 -0700475struct reread_data {
476 const char* const filename;
477 int fd;
478};
479
Rajeev Kumar70450032018-01-31 17:54:56 -0800480#ifdef LMKD_LOG_STATS
Rajeev Kumar70450032018-01-31 17:54:56 -0800481static bool enable_stats_log;
482static android_log_context log_ctx;
483#endif
484
Todd Poynor3948f802013-07-09 19:35:14 -0700485#define PIDHASH_SZ 1024
486static struct proc *pidhash[PIDHASH_SZ];
487#define pid_hashfn(x) ((((x) >> 8) ^ (x)) & (PIDHASH_SZ - 1))
488
Chih-Hung Hsiehdaa13ea2016-05-19 16:02:22 -0700489#define ADJTOSLOT(adj) ((adj) + -OOM_SCORE_ADJ_MIN)
Suren Baghdasaryand4a29902018-10-12 11:07:40 -0700490#define ADJTOSLOT_COUNT (ADJTOSLOT(OOM_SCORE_ADJ_MAX) + 1)
491static struct adjslot_list procadjslot_list[ADJTOSLOT_COUNT];
492
493#define MAX_DISTINCT_OOM_ADJ 32
494#define KILLCNT_INVALID_IDX 0xFF
495/*
496 * Because killcnt array is sparse a two-level indirection is used
497 * to keep the size small. killcnt_idx stores index of the element in
498 * killcnt array. Index KILLCNT_INVALID_IDX indicates an unused slot.
499 */
500static uint8_t killcnt_idx[ADJTOSLOT_COUNT];
501static uint16_t killcnt[MAX_DISTINCT_OOM_ADJ];
502static int killcnt_free_idx = 0;
503static uint32_t killcnt_total = 0;
Todd Poynor3948f802013-07-09 19:35:14 -0700504
Todd Poynor3948f802013-07-09 19:35:14 -0700505/* PAGE_SIZE / 1024 */
506static long page_k;
507
Jim Blacklerd2da8142019-09-10 15:30:05 +0100508static char* proc_get_name(int pid);
509static void poll_kernel();
510
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -0700511static int clamp(int low, int high, int value) {
512 return max(min(value, high), low);
513}
514
Suren Baghdasaryan6499e5e2018-04-13 12:43:41 -0700515static bool parse_int64(const char* str, int64_t* ret) {
516 char* endptr;
517 long long val = strtoll(str, &endptr, 10);
518 if (str == endptr || val > INT64_MAX) {
519 return false;
520 }
521 *ret = (int64_t)val;
522 return true;
523}
524
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -0700525static int find_field(const char* name, const char* const field_names[], int field_count) {
526 for (int i = 0; i < field_count; i++) {
527 if (!strcmp(name, field_names[i])) {
528 return i;
529 }
530 }
531 return -1;
532}
533
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -0700534static enum field_match_result match_field(const char* cp, const char* ap,
535 const char* const field_names[],
536 int field_count, int64_t* field,
537 int *field_idx) {
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -0700538 int i = find_field(cp, field_names, field_count);
539 if (i < 0) {
540 return NO_MATCH;
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -0700541 }
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -0700542 *field_idx = i;
543 return parse_int64(ap, field) ? PARSE_SUCCESS : PARSE_FAIL;
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -0700544}
545
Suren Baghdasaryan6499e5e2018-04-13 12:43:41 -0700546/*
547 * Read file content from the beginning up to max_len bytes or EOF
548 * whichever happens first.
549 */
Colin Crossce85d952014-07-11 17:53:27 -0700550static ssize_t read_all(int fd, char *buf, size_t max_len)
551{
552 ssize_t ret = 0;
Suren Baghdasaryan6499e5e2018-04-13 12:43:41 -0700553 off_t offset = 0;
Colin Crossce85d952014-07-11 17:53:27 -0700554
555 while (max_len > 0) {
Suren Baghdasaryan6499e5e2018-04-13 12:43:41 -0700556 ssize_t r = TEMP_FAILURE_RETRY(pread(fd, buf, max_len, offset));
Colin Crossce85d952014-07-11 17:53:27 -0700557 if (r == 0) {
558 break;
559 }
560 if (r == -1) {
561 return -1;
562 }
563 ret += r;
564 buf += r;
Suren Baghdasaryan6499e5e2018-04-13 12:43:41 -0700565 offset += r;
Colin Crossce85d952014-07-11 17:53:27 -0700566 max_len -= r;
567 }
568
569 return ret;
570}
571
Suren Baghdasaryan6499e5e2018-04-13 12:43:41 -0700572/*
573 * Read a new or already opened file from the beginning.
574 * If the file has not been opened yet data->fd should be set to -1.
575 * To be used with files which are read often and possibly during high
576 * memory pressure to minimize file opening which by itself requires kernel
577 * memory allocation and might result in a stall on memory stressed system.
578 */
Suren Baghdasaryana77b3272019-07-15 13:35:04 -0700579static char *reread_file(struct reread_data *data) {
580 /* start with page-size buffer and increase if needed */
581 static ssize_t buf_size = PAGE_SIZE;
582 static char *new_buf, *buf = NULL;
Suren Baghdasaryan6499e5e2018-04-13 12:43:41 -0700583 ssize_t size;
584
585 if (data->fd == -1) {
Suren Baghdasaryana77b3272019-07-15 13:35:04 -0700586 /* First-time buffer initialization */
587 if (!buf && (buf = malloc(buf_size)) == NULL) {
588 return NULL;
589 }
590
591 data->fd = TEMP_FAILURE_RETRY(open(data->filename, O_RDONLY | O_CLOEXEC));
592 if (data->fd < 0) {
Suren Baghdasaryan6499e5e2018-04-13 12:43:41 -0700593 ALOGE("%s open: %s", data->filename, strerror(errno));
Suren Baghdasaryana77b3272019-07-15 13:35:04 -0700594 return NULL;
Suren Baghdasaryan6499e5e2018-04-13 12:43:41 -0700595 }
596 }
597
Suren Baghdasaryana77b3272019-07-15 13:35:04 -0700598 while (true) {
599 size = read_all(data->fd, buf, buf_size - 1);
600 if (size < 0) {
601 ALOGE("%s read: %s", data->filename, strerror(errno));
602 close(data->fd);
603 data->fd = -1;
604 return NULL;
605 }
606 if (size < buf_size - 1) {
607 break;
608 }
609 /*
610 * Since we are reading /proc files we can't use fstat to find out
611 * the real size of the file. Double the buffer size and keep retrying.
612 */
613 if ((new_buf = realloc(buf, buf_size * 2)) == NULL) {
614 errno = ENOMEM;
615 return NULL;
616 }
617 buf = new_buf;
618 buf_size *= 2;
Suren Baghdasaryan6499e5e2018-04-13 12:43:41 -0700619 }
Suren Baghdasaryan6499e5e2018-04-13 12:43:41 -0700620 buf[size] = 0;
621
Suren Baghdasaryana77b3272019-07-15 13:35:04 -0700622 return buf;
Suren Baghdasaryan6499e5e2018-04-13 12:43:41 -0700623}
624
Todd Poynor3948f802013-07-09 19:35:14 -0700625static struct proc *pid_lookup(int pid) {
626 struct proc *procp;
627
628 for (procp = pidhash[pid_hashfn(pid)]; procp && procp->pid != pid;
629 procp = procp->pidhash_next)
630 ;
631
632 return procp;
633}
634
635static void adjslot_insert(struct adjslot_list *head, struct adjslot_list *new)
636{
637 struct adjslot_list *next = head->next;
638 new->prev = head;
639 new->next = next;
640 next->prev = new;
641 head->next = new;
642}
643
644static void adjslot_remove(struct adjslot_list *old)
645{
646 struct adjslot_list *prev = old->prev;
647 struct adjslot_list *next = old->next;
648 next->prev = prev;
649 prev->next = next;
650}
651
652static struct adjslot_list *adjslot_tail(struct adjslot_list *head) {
653 struct adjslot_list *asl = head->prev;
654
655 return asl == head ? NULL : asl;
656}
657
658static void proc_slot(struct proc *procp) {
659 int adjslot = ADJTOSLOT(procp->oomadj);
660
661 adjslot_insert(&procadjslot_list[adjslot], &procp->asl);
662}
663
664static void proc_unslot(struct proc *procp) {
665 adjslot_remove(&procp->asl);
666}
667
668static void proc_insert(struct proc *procp) {
669 int hval = pid_hashfn(procp->pid);
670
671 procp->pidhash_next = pidhash[hval];
672 pidhash[hval] = procp;
673 proc_slot(procp);
674}
675
676static int pid_remove(int pid) {
677 int hval = pid_hashfn(pid);
678 struct proc *procp;
679 struct proc *prevp;
680
681 for (procp = pidhash[hval], prevp = NULL; procp && procp->pid != pid;
682 procp = procp->pidhash_next)
683 prevp = procp;
684
685 if (!procp)
686 return -1;
687
688 if (!prevp)
689 pidhash[hval] = procp->pidhash_next;
690 else
691 prevp->pidhash_next = procp->pidhash_next;
692
693 proc_unslot(procp);
694 free(procp);
695 return 0;
696}
697
Suren Baghdasaryan1ffa2462018-03-20 13:53:17 -0700698/*
699 * Write a string to a file.
700 * Returns false if the file does not exist.
701 */
702static bool writefilestring(const char *path, const char *s,
703 bool err_if_missing) {
Nick Kralevichc68c8862015-12-18 20:52:37 -0800704 int fd = open(path, O_WRONLY | O_CLOEXEC);
Suren Baghdasaryan1ffa2462018-03-20 13:53:17 -0700705 ssize_t len = strlen(s);
706 ssize_t ret;
Todd Poynor3948f802013-07-09 19:35:14 -0700707
708 if (fd < 0) {
Suren Baghdasaryan1ffa2462018-03-20 13:53:17 -0700709 if (err_if_missing) {
710 ALOGE("Error opening %s; errno=%d", path, errno);
711 }
712 return false;
Todd Poynor3948f802013-07-09 19:35:14 -0700713 }
714
Suren Baghdasaryan1ffa2462018-03-20 13:53:17 -0700715 ret = TEMP_FAILURE_RETRY(write(fd, s, len));
Todd Poynor3948f802013-07-09 19:35:14 -0700716 if (ret < 0) {
717 ALOGE("Error writing %s; errno=%d", path, errno);
718 } else if (ret < len) {
Suren Baghdasaryan1ffa2462018-03-20 13:53:17 -0700719 ALOGE("Short write on %s; length=%zd", path, ret);
Todd Poynor3948f802013-07-09 19:35:14 -0700720 }
721
722 close(fd);
Suren Baghdasaryan1ffa2462018-03-20 13:53:17 -0700723 return true;
Todd Poynor3948f802013-07-09 19:35:14 -0700724}
725
Suren Baghdasaryan314a5052018-07-24 17:13:06 -0700726static inline long get_time_diff_ms(struct timespec *from,
727 struct timespec *to) {
728 return (to->tv_sec - from->tv_sec) * (long)MS_PER_SEC +
729 (to->tv_nsec - from->tv_nsec) / (long)NS_PER_MS;
730}
731
Suren Baghdasaryan0082ef12019-07-02 15:52:07 -0700732static int proc_get_tgid(int pid) {
733 char path[PATH_MAX];
734 char buf[PAGE_SIZE];
735 int fd;
736 ssize_t size;
737 char *pos;
738 int64_t tgid = -1;
739
740 snprintf(path, PATH_MAX, "/proc/%d/status", pid);
741 fd = open(path, O_RDONLY | O_CLOEXEC);
742 if (fd < 0) {
743 return -1;
744 }
745
746 size = read_all(fd, buf, sizeof(buf) - 1);
747 if (size < 0) {
748 goto out;
749 }
750 buf[size] = 0;
751
752 pos = buf;
753 while (true) {
754 pos = strstr(pos, PROC_STATUS_TGID_FIELD);
755 /* Stop if TGID tag not found or found at the line beginning */
756 if (pos == NULL || pos == buf || pos[-1] == '\n') {
757 break;
758 }
759 pos++;
760 }
761
762 if (pos == NULL) {
763 goto out;
764 }
765
766 pos += strlen(PROC_STATUS_TGID_FIELD);
767 while (*pos == ' ') pos++;
768 parse_int64(pos, &tgid);
769
770out:
771 close(fd);
772 return (int)tgid;
773}
774
Suren Baghdasaryan0f100512018-01-24 16:51:41 -0800775static void cmd_procprio(LMKD_CTRL_PACKET packet) {
Todd Poynor3948f802013-07-09 19:35:14 -0700776 struct proc *procp;
777 char path[80];
778 char val[20];
Robert Benea673e2762017-06-01 16:32:31 -0700779 int soft_limit_mult;
Suren Baghdasaryan0f100512018-01-24 16:51:41 -0800780 struct lmk_procprio params;
Suren Baghdasaryan4311d1e2018-03-20 16:03:29 -0700781 bool is_system_server;
782 struct passwd *pwdrec;
Suren Baghdasaryan0082ef12019-07-02 15:52:07 -0700783 int tgid;
Todd Poynor3948f802013-07-09 19:35:14 -0700784
Suren Baghdasaryan0f100512018-01-24 16:51:41 -0800785 lmkd_pack_get_procprio(packet, &params);
786
787 if (params.oomadj < OOM_SCORE_ADJ_MIN ||
788 params.oomadj > OOM_SCORE_ADJ_MAX) {
789 ALOGE("Invalid PROCPRIO oomadj argument %d", params.oomadj);
Todd Poynor3948f802013-07-09 19:35:14 -0700790 return;
791 }
792
Suren Baghdasaryan0082ef12019-07-02 15:52:07 -0700793 /* Check if registered process is a thread group leader */
794 tgid = proc_get_tgid(params.pid);
795 if (tgid >= 0 && tgid != params.pid) {
796 ALOGE("Attempt to register a task that is not a thread group leader (tid %d, tgid %d)",
797 params.pid, tgid);
798 return;
799 }
800
Mark Salyzyn64d97d82018-04-09 09:50:32 -0700801 /* gid containing AID_READPROC required */
802 /* CAP_SYS_RESOURCE required */
803 /* CAP_DAC_OVERRIDE required */
Suren Baghdasaryan0f100512018-01-24 16:51:41 -0800804 snprintf(path, sizeof(path), "/proc/%d/oom_score_adj", params.pid);
805 snprintf(val, sizeof(val), "%d", params.oomadj);
Suren Baghdasaryan1ffa2462018-03-20 13:53:17 -0700806 if (!writefilestring(path, val, false)) {
807 ALOGW("Failed to open %s; errno=%d: process %d might have been killed",
808 path, errno, params.pid);
809 /* If this file does not exist the process is dead. */
810 return;
811 }
Todd Poynor3948f802013-07-09 19:35:14 -0700812
Mark Salyzyn721d7c72018-03-21 12:24:58 -0700813 if (use_inkernel_interface) {
Jim Blacklerd2da8142019-09-10 15:30:05 +0100814#ifdef LMKD_LOG_STATS
815 stats_store_taskname(params.pid, proc_get_name(params.pid));
816#endif
Todd Poynor3948f802013-07-09 19:35:14 -0700817 return;
Mark Salyzyn721d7c72018-03-21 12:24:58 -0700818 }
Todd Poynor3948f802013-07-09 19:35:14 -0700819
Suren Baghdasaryance13cb52018-06-19 18:38:12 -0700820 if (per_app_memcg) {
Suren Baghdasaryan20686f02018-05-18 14:42:00 -0700821 if (params.oomadj >= 900) {
822 soft_limit_mult = 0;
823 } else if (params.oomadj >= 800) {
824 soft_limit_mult = 0;
825 } else if (params.oomadj >= 700) {
826 soft_limit_mult = 0;
827 } else if (params.oomadj >= 600) {
828 // Launcher should be perceptible, don't kill it.
829 params.oomadj = 200;
830 soft_limit_mult = 1;
831 } else if (params.oomadj >= 500) {
832 soft_limit_mult = 0;
833 } else if (params.oomadj >= 400) {
834 soft_limit_mult = 0;
835 } else if (params.oomadj >= 300) {
836 soft_limit_mult = 1;
837 } else if (params.oomadj >= 200) {
Srinivas Paladugu3eb20bc2018-10-09 14:21:10 -0700838 soft_limit_mult = 8;
Suren Baghdasaryan20686f02018-05-18 14:42:00 -0700839 } else if (params.oomadj >= 100) {
840 soft_limit_mult = 10;
841 } else if (params.oomadj >= 0) {
842 soft_limit_mult = 20;
843 } else {
844 // Persistent processes will have a large
845 // soft limit 512MB.
846 soft_limit_mult = 64;
847 }
Robert Benea673e2762017-06-01 16:32:31 -0700848
Suren Baghdasaryan3862dd32018-05-21 19:48:47 -0700849 snprintf(path, sizeof(path), MEMCG_SYSFS_PATH
850 "apps/uid_%d/pid_%d/memory.soft_limit_in_bytes",
851 params.uid, params.pid);
Suren Baghdasaryan20686f02018-05-18 14:42:00 -0700852 snprintf(val, sizeof(val), "%d", soft_limit_mult * EIGHT_MEGA);
Suren Baghdasaryan3862dd32018-05-21 19:48:47 -0700853
854 /*
855 * system_server process has no memcg under /dev/memcg/apps but should be
856 * registered with lmkd. This is the best way so far to identify it.
857 */
858 is_system_server = (params.oomadj == SYSTEM_ADJ &&
859 (pwdrec = getpwnam("system")) != NULL &&
860 params.uid == pwdrec->pw_uid);
861 writefilestring(path, val, !is_system_server);
Robert Benea673e2762017-06-01 16:32:31 -0700862 }
863
Suren Baghdasaryan0f100512018-01-24 16:51:41 -0800864 procp = pid_lookup(params.pid);
Todd Poynor3948f802013-07-09 19:35:14 -0700865 if (!procp) {
866 procp = malloc(sizeof(struct proc));
867 if (!procp) {
868 // Oh, the irony. May need to rebuild our state.
869 return;
870 }
871
Suren Baghdasaryan0f100512018-01-24 16:51:41 -0800872 procp->pid = params.pid;
873 procp->uid = params.uid;
874 procp->oomadj = params.oomadj;
Todd Poynor3948f802013-07-09 19:35:14 -0700875 proc_insert(procp);
876 } else {
877 proc_unslot(procp);
Suren Baghdasaryan0f100512018-01-24 16:51:41 -0800878 procp->oomadj = params.oomadj;
Todd Poynor3948f802013-07-09 19:35:14 -0700879 proc_slot(procp);
880 }
881}
882
Suren Baghdasaryan0f100512018-01-24 16:51:41 -0800883static void cmd_procremove(LMKD_CTRL_PACKET packet) {
884 struct lmk_procremove params;
885
Mark Salyzyn721d7c72018-03-21 12:24:58 -0700886 if (use_inkernel_interface) {
Jim Blacklerd2da8142019-09-10 15:30:05 +0100887#ifdef LMKD_LOG_STATS
888 /* Perform an extra check before the pid is removed, after which it
889 * will be impossible for poll_kernel to get the taskname. poll_kernel()
890 * is potentially a long-running blocking function; however this method
891 * handles AMS requests but does not block AMS.*/
892 if (enable_stats_log) {
893 poll_kernel();
894 }
895 stats_remove_taskname(params.pid);
896#endif
Todd Poynor3948f802013-07-09 19:35:14 -0700897 return;
Mark Salyzyn721d7c72018-03-21 12:24:58 -0700898 }
Todd Poynor3948f802013-07-09 19:35:14 -0700899
Suren Baghdasaryan0f100512018-01-24 16:51:41 -0800900 lmkd_pack_get_procremove(packet, &params);
Suren Baghdasaryan01063272018-10-12 11:28:33 -0700901 /*
902 * WARNING: After pid_remove() procp is freed and can't be used!
903 * Therefore placed at the end of the function.
904 */
Suren Baghdasaryan0f100512018-01-24 16:51:41 -0800905 pid_remove(params.pid);
Todd Poynor3948f802013-07-09 19:35:14 -0700906}
907
Suren Baghdasaryane3b60472018-10-10 14:17:17 -0700908static void cmd_procpurge() {
909 int i;
910 struct proc *procp;
911 struct proc *next;
912
913 if (use_inkernel_interface) {
Jim Blacklerd2da8142019-09-10 15:30:05 +0100914#ifdef LMKD_LOG_STATS
915 stats_purge_tasknames();
916#endif
Suren Baghdasaryane3b60472018-10-10 14:17:17 -0700917 return;
918 }
919
920 for (i = 0; i <= ADJTOSLOT(OOM_SCORE_ADJ_MAX); i++) {
921 procadjslot_list[i].next = &procadjslot_list[i];
922 procadjslot_list[i].prev = &procadjslot_list[i];
923 }
924
925 for (i = 0; i < PIDHASH_SZ; i++) {
926 procp = pidhash[i];
927 while (procp) {
928 next = procp->pidhash_next;
929 free(procp);
930 procp = next;
931 }
932 }
933 memset(&pidhash[0], 0, sizeof(pidhash));
934}
935
Suren Baghdasaryand4a29902018-10-12 11:07:40 -0700936static void inc_killcnt(int oomadj) {
937 int slot = ADJTOSLOT(oomadj);
938 uint8_t idx = killcnt_idx[slot];
939
940 if (idx == KILLCNT_INVALID_IDX) {
941 /* index is not assigned for this oomadj */
942 if (killcnt_free_idx < MAX_DISTINCT_OOM_ADJ) {
943 killcnt_idx[slot] = killcnt_free_idx;
944 killcnt[killcnt_free_idx] = 1;
945 killcnt_free_idx++;
946 } else {
947 ALOGW("Number of distinct oomadj levels exceeds %d",
948 MAX_DISTINCT_OOM_ADJ);
949 }
950 } else {
951 /*
952 * wraparound is highly unlikely and is detectable using total
953 * counter because it has to be equal to the sum of all counters
954 */
955 killcnt[idx]++;
956 }
957 /* increment total kill counter */
958 killcnt_total++;
959}
960
961static int get_killcnt(int min_oomadj, int max_oomadj) {
962 int slot;
963 int count = 0;
964
965 if (min_oomadj > max_oomadj)
966 return 0;
967
968 /* special case to get total kill count */
969 if (min_oomadj > OOM_SCORE_ADJ_MAX)
970 return killcnt_total;
971
972 while (min_oomadj <= max_oomadj &&
973 (slot = ADJTOSLOT(min_oomadj)) < ADJTOSLOT_COUNT) {
974 uint8_t idx = killcnt_idx[slot];
975 if (idx != KILLCNT_INVALID_IDX) {
976 count += killcnt[idx];
977 }
978 min_oomadj++;
979 }
980
981 return count;
982}
983
984static int cmd_getkillcnt(LMKD_CTRL_PACKET packet) {
985 struct lmk_getkillcnt params;
986
987 if (use_inkernel_interface) {
988 /* kernel driver does not expose this information */
989 return 0;
990 }
991
992 lmkd_pack_get_getkillcnt(packet, &params);
993
994 return get_killcnt(params.min_oomadj, params.max_oomadj);
995}
996
Suren Baghdasaryan0f100512018-01-24 16:51:41 -0800997static void cmd_target(int ntargets, LMKD_CTRL_PACKET packet) {
Todd Poynor3948f802013-07-09 19:35:14 -0700998 int i;
Suren Baghdasaryan0f100512018-01-24 16:51:41 -0800999 struct lmk_target target;
Suren Baghdasaryan314a5052018-07-24 17:13:06 -07001000 char minfree_str[PROPERTY_VALUE_MAX];
1001 char *pstr = minfree_str;
1002 char *pend = minfree_str + sizeof(minfree_str);
1003 static struct timespec last_req_tm;
1004 struct timespec curr_tm;
Todd Poynor3948f802013-07-09 19:35:14 -07001005
Suren Baghdasaryan314a5052018-07-24 17:13:06 -07001006 if (ntargets < 1 || ntargets > (int)ARRAY_SIZE(lowmem_adj))
Todd Poynor3948f802013-07-09 19:35:14 -07001007 return;
1008
Suren Baghdasaryan314a5052018-07-24 17:13:06 -07001009 /*
1010 * Ratelimit minfree updates to once per TARGET_UPDATE_MIN_INTERVAL_MS
1011 * to prevent DoS attacks
1012 */
1013 if (clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm) != 0) {
1014 ALOGE("Failed to get current time");
1015 return;
1016 }
1017
1018 if (get_time_diff_ms(&last_req_tm, &curr_tm) <
1019 TARGET_UPDATE_MIN_INTERVAL_MS) {
1020 ALOGE("Ignoring frequent updated to lmkd limits");
1021 return;
1022 }
1023
1024 last_req_tm = curr_tm;
1025
Todd Poynor3948f802013-07-09 19:35:14 -07001026 for (i = 0; i < ntargets; i++) {
Suren Baghdasaryan0f100512018-01-24 16:51:41 -08001027 lmkd_pack_get_target(packet, i, &target);
1028 lowmem_minfree[i] = target.minfree;
1029 lowmem_adj[i] = target.oom_adj_score;
Suren Baghdasaryan314a5052018-07-24 17:13:06 -07001030
1031 pstr += snprintf(pstr, pend - pstr, "%d:%d,", target.minfree,
1032 target.oom_adj_score);
1033 if (pstr >= pend) {
1034 /* if no more space in the buffer then terminate the loop */
1035 pstr = pend;
1036 break;
1037 }
Todd Poynor3948f802013-07-09 19:35:14 -07001038 }
1039
1040 lowmem_targets_size = ntargets;
1041
Suren Baghdasaryan314a5052018-07-24 17:13:06 -07001042 /* Override the last extra comma */
1043 pstr[-1] = '\0';
1044 property_set("sys.lmk.minfree_levels", minfree_str);
1045
Robert Benea164baeb2017-09-11 16:53:28 -07001046 if (has_inkernel_module) {
Todd Poynor3948f802013-07-09 19:35:14 -07001047 char minfreestr[128];
1048 char killpriostr[128];
1049
1050 minfreestr[0] = '\0';
1051 killpriostr[0] = '\0';
1052
1053 for (i = 0; i < lowmem_targets_size; i++) {
1054 char val[40];
1055
1056 if (i) {
1057 strlcat(minfreestr, ",", sizeof(minfreestr));
1058 strlcat(killpriostr, ",", sizeof(killpriostr));
1059 }
1060
Robert Benea164baeb2017-09-11 16:53:28 -07001061 snprintf(val, sizeof(val), "%d", use_inkernel_interface ? lowmem_minfree[i] : 0);
Todd Poynor3948f802013-07-09 19:35:14 -07001062 strlcat(minfreestr, val, sizeof(minfreestr));
Robert Benea164baeb2017-09-11 16:53:28 -07001063 snprintf(val, sizeof(val), "%d", use_inkernel_interface ? lowmem_adj[i] : 0);
Todd Poynor3948f802013-07-09 19:35:14 -07001064 strlcat(killpriostr, val, sizeof(killpriostr));
1065 }
1066
Suren Baghdasaryan1ffa2462018-03-20 13:53:17 -07001067 writefilestring(INKERNEL_MINFREE_PATH, minfreestr, true);
1068 writefilestring(INKERNEL_ADJ_PATH, killpriostr, true);
Todd Poynor3948f802013-07-09 19:35:14 -07001069 }
1070}
1071
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08001072static void ctrl_data_close(int dsock_idx) {
1073 struct epoll_event epev;
1074
1075 ALOGI("closing lmkd data connection");
1076 if (epoll_ctl(epollfd, EPOLL_CTL_DEL, data_sock[dsock_idx].sock, &epev) == -1) {
1077 // Log a warning and keep going
1078 ALOGW("epoll_ctl for data connection socket failed; errno=%d", errno);
1079 }
Todd Poynor3948f802013-07-09 19:35:14 -07001080 maxevents--;
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08001081
1082 close(data_sock[dsock_idx].sock);
1083 data_sock[dsock_idx].sock = -1;
Todd Poynor3948f802013-07-09 19:35:14 -07001084}
1085
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08001086static int ctrl_data_read(int dsock_idx, char *buf, size_t bufsz) {
Todd Poynor3948f802013-07-09 19:35:14 -07001087 int ret = 0;
1088
Suren Baghdasaryan6499e5e2018-04-13 12:43:41 -07001089 ret = TEMP_FAILURE_RETRY(read(data_sock[dsock_idx].sock, buf, bufsz));
Todd Poynor3948f802013-07-09 19:35:14 -07001090
1091 if (ret == -1) {
1092 ALOGE("control data socket read failed; errno=%d", errno);
1093 } else if (ret == 0) {
1094 ALOGE("Got EOF on control data socket");
1095 ret = -1;
1096 }
1097
1098 return ret;
1099}
1100
Suren Baghdasaryand4a29902018-10-12 11:07:40 -07001101static int ctrl_data_write(int dsock_idx, char *buf, size_t bufsz) {
1102 int ret = 0;
1103
1104 ret = TEMP_FAILURE_RETRY(write(data_sock[dsock_idx].sock, buf, bufsz));
1105
1106 if (ret == -1) {
1107 ALOGE("control data socket write failed; errno=%d", errno);
1108 } else if (ret == 0) {
1109 ALOGE("Got EOF on control data socket");
1110 ret = -1;
1111 }
1112
1113 return ret;
1114}
1115
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08001116static void ctrl_command_handler(int dsock_idx) {
Suren Baghdasaryan0f100512018-01-24 16:51:41 -08001117 LMKD_CTRL_PACKET packet;
Todd Poynor3948f802013-07-09 19:35:14 -07001118 int len;
Suren Baghdasaryan0f100512018-01-24 16:51:41 -08001119 enum lmk_cmd cmd;
Todd Poynor3948f802013-07-09 19:35:14 -07001120 int nargs;
1121 int targets;
Suren Baghdasaryand4a29902018-10-12 11:07:40 -07001122 int kill_cnt;
Todd Poynor3948f802013-07-09 19:35:14 -07001123
Suren Baghdasaryan0f100512018-01-24 16:51:41 -08001124 len = ctrl_data_read(dsock_idx, (char *)packet, CTRL_PACKET_MAX_SIZE);
Todd Poynor3948f802013-07-09 19:35:14 -07001125 if (len <= 0)
1126 return;
1127
Suren Baghdasaryan0f100512018-01-24 16:51:41 -08001128 if (len < (int)sizeof(int)) {
1129 ALOGE("Wrong control socket read length len=%d", len);
1130 return;
1131 }
1132
1133 cmd = lmkd_pack_get_cmd(packet);
Todd Poynor3948f802013-07-09 19:35:14 -07001134 nargs = len / sizeof(int) - 1;
1135 if (nargs < 0)
1136 goto wronglen;
1137
Todd Poynor3948f802013-07-09 19:35:14 -07001138 switch(cmd) {
1139 case LMK_TARGET:
1140 targets = nargs / 2;
1141 if (nargs & 0x1 || targets > (int)ARRAY_SIZE(lowmem_adj))
1142 goto wronglen;
Suren Baghdasaryan0f100512018-01-24 16:51:41 -08001143 cmd_target(targets, packet);
Todd Poynor3948f802013-07-09 19:35:14 -07001144 break;
1145 case LMK_PROCPRIO:
Colin Crossfbb78c62014-06-13 14:52:43 -07001146 if (nargs != 3)
Todd Poynor3948f802013-07-09 19:35:14 -07001147 goto wronglen;
Suren Baghdasaryan0f100512018-01-24 16:51:41 -08001148 cmd_procprio(packet);
Todd Poynor3948f802013-07-09 19:35:14 -07001149 break;
1150 case LMK_PROCREMOVE:
1151 if (nargs != 1)
1152 goto wronglen;
Suren Baghdasaryan0f100512018-01-24 16:51:41 -08001153 cmd_procremove(packet);
Todd Poynor3948f802013-07-09 19:35:14 -07001154 break;
Suren Baghdasaryane3b60472018-10-10 14:17:17 -07001155 case LMK_PROCPURGE:
1156 if (nargs != 0)
1157 goto wronglen;
1158 cmd_procpurge();
1159 break;
Suren Baghdasaryand4a29902018-10-12 11:07:40 -07001160 case LMK_GETKILLCNT:
1161 if (nargs != 2)
1162 goto wronglen;
1163 kill_cnt = cmd_getkillcnt(packet);
1164 len = lmkd_pack_set_getkillcnt_repl(packet, kill_cnt);
1165 if (ctrl_data_write(dsock_idx, (char *)packet, len) != len)
1166 return;
1167 break;
Todd Poynor3948f802013-07-09 19:35:14 -07001168 default:
1169 ALOGE("Received unknown command code %d", cmd);
1170 return;
1171 }
1172
1173 return;
1174
1175wronglen:
1176 ALOGE("Wrong control socket read length cmd=%d len=%d", cmd, len);
1177}
1178
Suren Baghdasaryanef3650f2019-07-15 14:50:49 -07001179static void ctrl_data_handler(int data, uint32_t events,
1180 struct polling_params *poll_params __unused) {
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08001181 if (events & EPOLLIN) {
1182 ctrl_command_handler(data);
Todd Poynor3948f802013-07-09 19:35:14 -07001183 }
1184}
1185
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08001186static int get_free_dsock() {
1187 for (int i = 0; i < MAX_DATA_CONN; i++) {
1188 if (data_sock[i].sock < 0) {
1189 return i;
1190 }
1191 }
1192 return -1;
1193}
Todd Poynor3948f802013-07-09 19:35:14 -07001194
Suren Baghdasaryanef3650f2019-07-15 14:50:49 -07001195static void ctrl_connect_handler(int data __unused, uint32_t events __unused,
1196 struct polling_params *poll_params __unused) {
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08001197 struct epoll_event epev;
1198 int free_dscock_idx = get_free_dsock();
1199
1200 if (free_dscock_idx < 0) {
1201 /*
1202 * Number of data connections exceeded max supported. This should not
1203 * happen but if it does we drop all existing connections and accept
1204 * the new one. This prevents inactive connections from monopolizing
1205 * data socket and if we drop ActivityManager connection it will
1206 * immediately reconnect.
1207 */
1208 for (int i = 0; i < MAX_DATA_CONN; i++) {
1209 ctrl_data_close(i);
1210 }
1211 free_dscock_idx = 0;
Todd Poynor3948f802013-07-09 19:35:14 -07001212 }
1213
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08001214 data_sock[free_dscock_idx].sock = accept(ctrl_sock.sock, NULL, NULL);
1215 if (data_sock[free_dscock_idx].sock < 0) {
Todd Poynor3948f802013-07-09 19:35:14 -07001216 ALOGE("lmkd control socket accept failed; errno=%d", errno);
1217 return;
1218 }
1219
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08001220 ALOGI("lmkd data connection established");
1221 /* use data to store data connection idx */
1222 data_sock[free_dscock_idx].handler_info.data = free_dscock_idx;
1223 data_sock[free_dscock_idx].handler_info.handler = ctrl_data_handler;
Todd Poynor3948f802013-07-09 19:35:14 -07001224 epev.events = EPOLLIN;
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08001225 epev.data.ptr = (void *)&(data_sock[free_dscock_idx].handler_info);
1226 if (epoll_ctl(epollfd, EPOLL_CTL_ADD, data_sock[free_dscock_idx].sock, &epev) == -1) {
Todd Poynor3948f802013-07-09 19:35:14 -07001227 ALOGE("epoll_ctl for data connection socket failed; errno=%d", errno);
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08001228 ctrl_data_close(free_dscock_idx);
Todd Poynor3948f802013-07-09 19:35:14 -07001229 return;
1230 }
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08001231 maxevents++;
Todd Poynor3948f802013-07-09 19:35:14 -07001232}
1233
Rajeev Kumar70450032018-01-31 17:54:56 -08001234#ifdef LMKD_LOG_STATS
Rajeev Kumar4dbc24d2018-10-05 12:34:59 -07001235static void memory_stat_parse_line(char* line, struct memory_stat* mem_st) {
Greg Kaiserf0da9b02018-03-23 14:16:12 -07001236 char key[LINE_MAX + 1];
Rajeev Kumar70450032018-01-31 17:54:56 -08001237 int64_t value;
1238
Greg Kaiserf0da9b02018-03-23 14:16:12 -07001239 sscanf(line, "%" STRINGIFY(LINE_MAX) "s %" SCNd64 "", key, &value);
Rajeev Kumar70450032018-01-31 17:54:56 -08001240
1241 if (strcmp(key, "total_") < 0) {
1242 return;
1243 }
1244
1245 if (!strcmp(key, "total_pgfault"))
1246 mem_st->pgfault = value;
1247 else if (!strcmp(key, "total_pgmajfault"))
1248 mem_st->pgmajfault = value;
1249 else if (!strcmp(key, "total_rss"))
1250 mem_st->rss_in_bytes = value;
1251 else if (!strcmp(key, "total_cache"))
1252 mem_st->cache_in_bytes = value;
1253 else if (!strcmp(key, "total_swap"))
1254 mem_st->swap_in_bytes = value;
1255}
1256
Rajeev Kumar4dbc24d2018-10-05 12:34:59 -07001257static int memory_stat_from_cgroup(struct memory_stat* mem_st, int pid, uid_t uid) {
Suren Baghdasaryan1d1c0022018-06-19 18:38:12 -07001258 FILE *fp;
1259 char buf[PATH_MAX];
Rajeev Kumar70450032018-01-31 17:54:56 -08001260
Suren Baghdasaryan1d1c0022018-06-19 18:38:12 -07001261 snprintf(buf, sizeof(buf), MEMCG_PROCESS_MEMORY_STAT_PATH, uid, pid);
Rajeev Kumar70450032018-01-31 17:54:56 -08001262
Suren Baghdasaryan1d1c0022018-06-19 18:38:12 -07001263 fp = fopen(buf, "r");
Rajeev Kumar70450032018-01-31 17:54:56 -08001264
Suren Baghdasaryan1d1c0022018-06-19 18:38:12 -07001265 if (fp == NULL) {
1266 ALOGE("%s open failed: %s", buf, strerror(errno));
1267 return -1;
1268 }
Rajeev Kumar70450032018-01-31 17:54:56 -08001269
Rajeev Kumar4dbc24d2018-10-05 12:34:59 -07001270 while (fgets(buf, PAGE_SIZE, fp) != NULL) {
Suren Baghdasaryan1d1c0022018-06-19 18:38:12 -07001271 memory_stat_parse_line(buf, mem_st);
1272 }
1273 fclose(fp);
1274
1275 return 0;
Rajeev Kumar70450032018-01-31 17:54:56 -08001276}
Rajeev Kumar4dbc24d2018-10-05 12:34:59 -07001277
1278static int memory_stat_from_procfs(struct memory_stat* mem_st, int pid) {
1279 char path[PATH_MAX];
1280 char buffer[PROC_STAT_BUFFER_SIZE];
1281 int fd, ret;
1282
1283 snprintf(path, sizeof(path), PROC_STAT_FILE_PATH, pid);
1284 if ((fd = open(path, O_RDONLY | O_CLOEXEC)) < 0) {
1285 ALOGE("%s open failed: %s", path, strerror(errno));
1286 return -1;
1287 }
1288
1289 ret = read(fd, buffer, sizeof(buffer));
1290 if (ret < 0) {
1291 ALOGE("%s read failed: %s", path, strerror(errno));
1292 close(fd);
1293 return -1;
1294 }
1295 close(fd);
1296
1297 // field 10 is pgfault
1298 // field 12 is pgmajfault
Jim Blackler1417cdb2018-11-21 16:22:36 +00001299 // field 22 is starttime
Rajeev Kumar4dbc24d2018-10-05 12:34:59 -07001300 // field 24 is rss_in_pages
Jim Blackler1417cdb2018-11-21 16:22:36 +00001301 int64_t pgfault = 0, pgmajfault = 0, starttime = 0, rss_in_pages = 0;
Rajeev Kumar4dbc24d2018-10-05 12:34:59 -07001302 if (sscanf(buffer,
1303 "%*u %*s %*s %*d %*d %*d %*d %*d %*d %" SCNd64 " %*d "
1304 "%" SCNd64 " %*d %*u %*u %*d %*d %*d %*d %*d %*d "
Jim Blackler1417cdb2018-11-21 16:22:36 +00001305 "%" SCNd64 " %*d %" SCNd64 "",
1306 &pgfault, &pgmajfault, &starttime, &rss_in_pages) != 4) {
Rajeev Kumar4dbc24d2018-10-05 12:34:59 -07001307 return -1;
1308 }
1309 mem_st->pgfault = pgfault;
1310 mem_st->pgmajfault = pgmajfault;
1311 mem_st->rss_in_bytes = (rss_in_pages * PAGE_SIZE);
Jim Blackler1417cdb2018-11-21 16:22:36 +00001312 mem_st->process_start_time_ns = starttime * (NS_PER_SEC / sysconf(_SC_CLK_TCK));
Rajeev Kumar4dbc24d2018-10-05 12:34:59 -07001313 return 0;
1314}
Rajeev Kumar70450032018-01-31 17:54:56 -08001315#endif
1316
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07001317/*
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07001318 * /proc/zoneinfo parsing routines
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07001319 * Expected file format is:
1320 *
1321 * Node <node_id>, zone <zone_name>
1322 * (
1323 * per-node stats
1324 * (<per-node field name> <value>)+
1325 * )?
1326 * (pages free <value>
1327 * (<per-zone field name> <value>)+
1328 * pagesets
1329 * (<unused fields>)*
1330 * )+
1331 * ...
1332 */
1333static void zoneinfo_parse_protection(char *buf, struct zoneinfo_zone *zone) {
1334 int zone_idx;
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001335 int64_t max = 0;
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001336 char *save_ptr;
1337
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07001338 for (buf = strtok_r(buf, "(), ", &save_ptr), zone_idx = 0;
1339 buf && zone_idx < MAX_NR_ZONES;
1340 buf = strtok_r(NULL, "), ", &save_ptr), zone_idx++) {
1341 long long zoneval = strtoll(buf, &buf, 0);
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001342 if (zoneval > max) {
1343 max = (zoneval > INT64_MAX) ? INT64_MAX : zoneval;
1344 }
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07001345 zone->protection[zone_idx] = zoneval;
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001346 }
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07001347 zone->max_protection = max;
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001348}
1349
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07001350static int zoneinfo_parse_zone(char **buf, struct zoneinfo_zone *zone) {
1351 for (char *line = strtok_r(NULL, "\n", buf); line;
1352 line = strtok_r(NULL, "\n", buf)) {
1353 char *cp;
1354 char *ap;
1355 char *save_ptr;
1356 int64_t val;
1357 int field_idx;
1358 enum field_match_result match_res;
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001359
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07001360 cp = strtok_r(line, " ", &save_ptr);
1361 if (!cp) {
1362 return false;
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001363 }
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07001364
1365 field_idx = find_field(cp, zoneinfo_zone_spec_field_names, ZI_ZONE_SPEC_FIELD_COUNT);
1366 if (field_idx >= 0) {
1367 /* special field */
1368 if (field_idx == ZI_ZONE_SPEC_PAGESETS) {
1369 /* no mode fields we are interested in */
1370 return true;
1371 }
1372
1373 /* protection field */
1374 ap = strtok_r(NULL, ")", &save_ptr);
1375 if (ap) {
1376 zoneinfo_parse_protection(ap, zone);
1377 }
1378 continue;
1379 }
1380
1381 ap = strtok_r(NULL, " ", &save_ptr);
1382 if (!ap) {
1383 continue;
1384 }
1385
1386 match_res = match_field(cp, ap, zoneinfo_zone_field_names, ZI_ZONE_FIELD_COUNT,
1387 &val, &field_idx);
1388 if (match_res == PARSE_FAIL) {
1389 return false;
1390 }
1391 if (match_res == PARSE_SUCCESS) {
1392 zone->fields.arr[field_idx] = val;
1393 }
1394 if (field_idx == ZI_ZONE_PRESENT && val == 0) {
1395 /* zone is not populated, stop parsing it */
1396 return true;
1397 }
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001398 }
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07001399 return false;
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001400}
1401
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07001402static int zoneinfo_parse_node(char **buf, struct zoneinfo_node *node) {
1403 int fields_to_match = ZI_NODE_FIELD_COUNT;
1404
1405 for (char *line = strtok_r(NULL, "\n", buf); line;
1406 line = strtok_r(NULL, "\n", buf)) {
1407 char *cp;
1408 char *ap;
1409 char *save_ptr;
1410 int64_t val;
1411 int field_idx;
1412 enum field_match_result match_res;
1413
1414 cp = strtok_r(line, " ", &save_ptr);
1415 if (!cp) {
1416 return false;
1417 }
1418
1419 ap = strtok_r(NULL, " ", &save_ptr);
1420 if (!ap) {
1421 return false;
1422 }
1423
1424 match_res = match_field(cp, ap, zoneinfo_node_field_names, ZI_NODE_FIELD_COUNT,
1425 &val, &field_idx);
1426 if (match_res == PARSE_FAIL) {
1427 return false;
1428 }
1429 if (match_res == PARSE_SUCCESS) {
1430 node->fields.arr[field_idx] = val;
1431 fields_to_match--;
1432 if (!fields_to_match) {
1433 return true;
1434 }
1435 }
1436 }
1437 return false;
1438}
1439
1440static int zoneinfo_parse(struct zoneinfo *zi) {
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001441 static struct reread_data file_data = {
1442 .filename = ZONEINFO_PATH,
1443 .fd = -1,
1444 };
Suren Baghdasaryana77b3272019-07-15 13:35:04 -07001445 char *buf;
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001446 char *save_ptr;
1447 char *line;
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07001448 char zone_name[LINE_MAX];
1449 struct zoneinfo_node *node = NULL;
1450 int node_idx = 0;
1451 int zone_idx = 0;
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001452
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07001453 memset(zi, 0, sizeof(struct zoneinfo));
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001454
Suren Baghdasaryana77b3272019-07-15 13:35:04 -07001455 if ((buf = reread_file(&file_data)) == NULL) {
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001456 return -1;
1457 }
1458
1459 for (line = strtok_r(buf, "\n", &save_ptr); line;
1460 line = strtok_r(NULL, "\n", &save_ptr)) {
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07001461 int node_id;
1462 if (sscanf(line, "Node %d, zone %" STRINGIFY(LINE_MAX) "s", &node_id, zone_name) == 2) {
1463 if (!node || node->id != node_id) {
1464 /* new node is found */
1465 if (node) {
1466 node->zone_count = zone_idx + 1;
1467 node_idx++;
1468 if (node_idx == MAX_NR_NODES) {
1469 /* max node count exceeded */
1470 ALOGE("%s parse error", file_data.filename);
1471 return -1;
1472 }
1473 }
1474 node = &zi->nodes[node_idx];
1475 node->id = node_id;
1476 zone_idx = 0;
1477 if (!zoneinfo_parse_node(&save_ptr, node)) {
1478 ALOGE("%s parse error", file_data.filename);
1479 return -1;
1480 }
1481 } else {
1482 /* new zone is found */
1483 zone_idx++;
1484 }
1485 if (!zoneinfo_parse_zone(&save_ptr, &node->zones[zone_idx])) {
1486 ALOGE("%s parse error", file_data.filename);
1487 return -1;
1488 }
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001489 }
1490 }
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07001491 if (!node) {
1492 ALOGE("%s parse error", file_data.filename);
1493 return -1;
1494 }
1495 node->zone_count = zone_idx + 1;
1496 zi->node_count = node_idx + 1;
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001497
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07001498 /* calculate totals fields */
1499 for (node_idx = 0; node_idx < zi->node_count; node_idx++) {
1500 node = &zi->nodes[node_idx];
1501 for (zone_idx = 0; zone_idx < node->zone_count; zone_idx++) {
1502 struct zoneinfo_zone *zone = &zi->nodes[node_idx].zones[zone_idx];
1503 zi->totalreserve_pages += zone->max_protection + zone->fields.field.high;
1504 }
1505 zi->total_inactive_file += node->fields.field.nr_inactive_file;
1506 zi->total_active_file += node->fields.field.nr_active_file;
1507 zi->total_workingset_refault += node->fields.field.workingset_refault;
1508 }
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001509 return 0;
1510}
1511
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07001512/* /proc/meminfo parsing routines */
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001513static bool meminfo_parse_line(char *line, union meminfo *mi) {
1514 char *cp = line;
1515 char *ap;
1516 char *save_ptr;
1517 int64_t val;
1518 int field_idx;
1519 enum field_match_result match_res;
1520
1521 cp = strtok_r(line, " ", &save_ptr);
1522 if (!cp) {
1523 return false;
1524 }
1525
1526 ap = strtok_r(NULL, " ", &save_ptr);
1527 if (!ap) {
1528 return false;
1529 }
1530
1531 match_res = match_field(cp, ap, meminfo_field_names, MI_FIELD_COUNT,
1532 &val, &field_idx);
1533 if (match_res == PARSE_SUCCESS) {
1534 mi->arr[field_idx] = val / page_k;
1535 }
1536 return (match_res != PARSE_FAIL);
1537}
1538
1539static int meminfo_parse(union meminfo *mi) {
1540 static struct reread_data file_data = {
1541 .filename = MEMINFO_PATH,
1542 .fd = -1,
1543 };
Suren Baghdasaryana77b3272019-07-15 13:35:04 -07001544 char *buf;
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001545 char *save_ptr;
1546 char *line;
1547
1548 memset(mi, 0, sizeof(union meminfo));
1549
Suren Baghdasaryana77b3272019-07-15 13:35:04 -07001550 if ((buf = reread_file(&file_data)) == NULL) {
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001551 return -1;
1552 }
1553
1554 for (line = strtok_r(buf, "\n", &save_ptr); line;
1555 line = strtok_r(NULL, "\n", &save_ptr)) {
1556 if (!meminfo_parse_line(line, mi)) {
1557 ALOGE("%s parse error", file_data.filename);
1558 return -1;
1559 }
1560 }
1561 mi->field.nr_file_pages = mi->field.cached + mi->field.swap_cached +
1562 mi->field.buffers;
1563
1564 return 0;
1565}
1566
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07001567/* /proc/vmstat parsing routines */
1568static bool vmstat_parse_line(char *line, union vmstat *vs) {
1569 char *cp;
1570 char *ap;
1571 char *save_ptr;
1572 int64_t val;
1573 int field_idx;
1574 enum field_match_result match_res;
1575
1576 cp = strtok_r(line, " ", &save_ptr);
1577 if (!cp) {
1578 return false;
1579 }
1580
1581 ap = strtok_r(NULL, " ", &save_ptr);
1582 if (!ap) {
1583 return false;
1584 }
1585
1586 match_res = match_field(cp, ap, vmstat_field_names, VS_FIELD_COUNT,
1587 &val, &field_idx);
1588 if (match_res == PARSE_SUCCESS) {
1589 vs->arr[field_idx] = val;
1590 }
1591 return (match_res != PARSE_FAIL);
1592}
1593
1594static int vmstat_parse(union vmstat *vs) {
1595 static struct reread_data file_data = {
1596 .filename = VMSTAT_PATH,
1597 .fd = -1,
1598 };
1599 char *buf;
1600 char *save_ptr;
1601 char *line;
1602
1603 memset(vs, 0, sizeof(union vmstat));
1604
1605 if ((buf = reread_file(&file_data)) == NULL) {
1606 return -1;
1607 }
1608
1609 for (line = strtok_r(buf, "\n", &save_ptr); line;
1610 line = strtok_r(NULL, "\n", &save_ptr)) {
1611 if (!vmstat_parse_line(line, vs)) {
1612 ALOGE("%s parse error", file_data.filename);
1613 return -1;
1614 }
1615 }
1616
1617 return 0;
1618}
1619
Suren Baghdasaryan282ad1a2018-07-26 16:34:27 -07001620static void meminfo_log(union meminfo *mi) {
1621 for (int field_idx = 0; field_idx < MI_FIELD_COUNT; field_idx++) {
1622 android_log_write_int32(ctx, (int32_t)min(mi->arr[field_idx] * page_k, INT32_MAX));
1623 }
1624
1625 android_log_write_list(ctx, LOG_ID_EVENTS);
1626 android_log_reset(ctx);
1627}
1628
Todd Poynor3948f802013-07-09 19:35:14 -07001629static int proc_get_size(int pid) {
1630 char path[PATH_MAX];
1631 char line[LINE_MAX];
Colin Crossce85d952014-07-11 17:53:27 -07001632 int fd;
Todd Poynor3948f802013-07-09 19:35:14 -07001633 int rss = 0;
1634 int total;
Colin Crossce85d952014-07-11 17:53:27 -07001635 ssize_t ret;
Todd Poynor3948f802013-07-09 19:35:14 -07001636
Mark Salyzyn64d97d82018-04-09 09:50:32 -07001637 /* gid containing AID_READPROC required */
Todd Poynor3948f802013-07-09 19:35:14 -07001638 snprintf(path, PATH_MAX, "/proc/%d/statm", pid);
Nick Kralevichc68c8862015-12-18 20:52:37 -08001639 fd = open(path, O_RDONLY | O_CLOEXEC);
Colin Crossce85d952014-07-11 17:53:27 -07001640 if (fd == -1)
Todd Poynor3948f802013-07-09 19:35:14 -07001641 return -1;
Colin Crossce85d952014-07-11 17:53:27 -07001642
1643 ret = read_all(fd, line, sizeof(line) - 1);
1644 if (ret < 0) {
1645 close(fd);
Todd Poynor3948f802013-07-09 19:35:14 -07001646 return -1;
1647 }
1648
1649 sscanf(line, "%d %d ", &total, &rss);
Colin Crossce85d952014-07-11 17:53:27 -07001650 close(fd);
Todd Poynor3948f802013-07-09 19:35:14 -07001651 return rss;
1652}
1653
1654static char *proc_get_name(int pid) {
1655 char path[PATH_MAX];
1656 static char line[LINE_MAX];
Colin Crossce85d952014-07-11 17:53:27 -07001657 int fd;
Todd Poynor3948f802013-07-09 19:35:14 -07001658 char *cp;
Colin Crossce85d952014-07-11 17:53:27 -07001659 ssize_t ret;
Todd Poynor3948f802013-07-09 19:35:14 -07001660
Mark Salyzyn64d97d82018-04-09 09:50:32 -07001661 /* gid containing AID_READPROC required */
Todd Poynor3948f802013-07-09 19:35:14 -07001662 snprintf(path, PATH_MAX, "/proc/%d/cmdline", pid);
Nick Kralevichc68c8862015-12-18 20:52:37 -08001663 fd = open(path, O_RDONLY | O_CLOEXEC);
Suren Baghdasaryan9e359db2019-09-27 16:56:50 -07001664 if (fd == -1) {
Todd Poynor3948f802013-07-09 19:35:14 -07001665 return NULL;
Suren Baghdasaryan9e359db2019-09-27 16:56:50 -07001666 }
Colin Crossce85d952014-07-11 17:53:27 -07001667 ret = read_all(fd, line, sizeof(line) - 1);
1668 close(fd);
1669 if (ret < 0) {
Todd Poynor3948f802013-07-09 19:35:14 -07001670 return NULL;
1671 }
1672
1673 cp = strchr(line, ' ');
Suren Baghdasaryan9e359db2019-09-27 16:56:50 -07001674 if (cp) {
Todd Poynor3948f802013-07-09 19:35:14 -07001675 *cp = '\0';
Suren Baghdasaryan9e359db2019-09-27 16:56:50 -07001676 } else {
1677 line[ret] = '\0';
1678 }
Todd Poynor3948f802013-07-09 19:35:14 -07001679
1680 return line;
1681}
1682
1683static struct proc *proc_adj_lru(int oomadj) {
1684 return (struct proc *)adjslot_tail(&procadjslot_list[ADJTOSLOT(oomadj)]);
1685}
1686
Suren Baghdasaryan662492a2017-12-08 13:17:06 -08001687static struct proc *proc_get_heaviest(int oomadj) {
1688 struct adjslot_list *head = &procadjslot_list[ADJTOSLOT(oomadj)];
1689 struct adjslot_list *curr = head->next;
1690 struct proc *maxprocp = NULL;
1691 int maxsize = 0;
1692 while (curr != head) {
1693 int pid = ((struct proc *)curr)->pid;
1694 int tasksize = proc_get_size(pid);
1695 if (tasksize <= 0) {
1696 struct adjslot_list *next = curr->next;
1697 pid_remove(pid);
1698 curr = next;
1699 } else {
1700 if (tasksize > maxsize) {
1701 maxsize = tasksize;
1702 maxprocp = (struct proc *)curr;
1703 }
1704 curr = curr->next;
1705 }
1706 }
1707 return maxprocp;
1708}
1709
Wei Wang2d95c102018-11-21 00:11:44 -08001710static void set_process_group_and_prio(int pid, SchedPolicy sp, int prio) {
1711 DIR* d;
1712 char proc_path[PATH_MAX];
1713 struct dirent* de;
1714
1715 snprintf(proc_path, sizeof(proc_path), "/proc/%d/task", pid);
1716 if (!(d = opendir(proc_path))) {
1717 ALOGW("Failed to open %s; errno=%d: process pid(%d) might have died", proc_path, errno,
1718 pid);
1719 return;
1720 }
1721
1722 while ((de = readdir(d))) {
1723 int t_pid;
1724
1725 if (de->d_name[0] == '.') continue;
1726 t_pid = atoi(de->d_name);
1727
1728 if (!t_pid) {
1729 ALOGW("Failed to get t_pid for '%s' of pid(%d)", de->d_name, pid);
1730 continue;
1731 }
1732
1733 if (setpriority(PRIO_PROCESS, t_pid, prio) && errno != ESRCH) {
1734 ALOGW("Unable to raise priority of killing t_pid (%d): errno=%d", t_pid, errno);
1735 }
1736
1737 if (set_cpuset_policy(t_pid, sp)) {
1738 ALOGW("Failed to set_cpuset_policy on pid(%d) t_pid(%d) to %d", pid, t_pid, (int)sp);
1739 continue;
1740 }
1741 }
1742 closedir(d);
1743}
1744
Tim Murraye7853f62018-10-25 17:05:41 -07001745static int last_killed_pid = -1;
1746
Colin Cross16b09462014-07-14 12:39:56 -07001747/* Kill one process specified by procp. Returns the size of the process killed */
Suren Baghdasaryanfd7518f2019-07-15 15:50:17 -07001748static int kill_one_process(struct proc* procp, int min_oom_score, const char *reason) {
Colin Cross16b09462014-07-14 12:39:56 -07001749 int pid = procp->pid;
1750 uid_t uid = procp->uid;
Suren Baghdasaryan0082ef12019-07-02 15:52:07 -07001751 int tgid;
Colin Cross16b09462014-07-14 12:39:56 -07001752 char *taskname;
1753 int tasksize;
1754 int r;
Suren Baghdasaryan01063272018-10-12 11:28:33 -07001755 int result = -1;
Colin Cross16b09462014-07-14 12:39:56 -07001756
Rajeev Kumar70450032018-01-31 17:54:56 -08001757#ifdef LMKD_LOG_STATS
Rajeev Kumar92b659b2018-02-21 19:08:15 -08001758 struct memory_stat mem_st = {};
Rajeev Kumar70450032018-01-31 17:54:56 -08001759 int memory_stat_parse_result = -1;
Suren Baghdasaryanec5e4c62019-03-04 11:07:39 -08001760#else
1761 /* To prevent unused parameter warning */
1762 (void)(min_oom_score);
Rajeev Kumar70450032018-01-31 17:54:56 -08001763#endif
1764
Suren Baghdasaryan0082ef12019-07-02 15:52:07 -07001765 tgid = proc_get_tgid(pid);
1766 if (tgid >= 0 && tgid != pid) {
1767 ALOGE("Possible pid reuse detected (pid %d, tgid %d)!", pid, tgid);
1768 goto out;
1769 }
1770
Colin Cross16b09462014-07-14 12:39:56 -07001771 taskname = proc_get_name(pid);
1772 if (!taskname) {
Suren Baghdasaryan01063272018-10-12 11:28:33 -07001773 goto out;
Colin Cross16b09462014-07-14 12:39:56 -07001774 }
1775
1776 tasksize = proc_get_size(pid);
1777 if (tasksize <= 0) {
Suren Baghdasaryan01063272018-10-12 11:28:33 -07001778 goto out;
Colin Cross16b09462014-07-14 12:39:56 -07001779 }
1780
Rajeev Kumar70450032018-01-31 17:54:56 -08001781#ifdef LMKD_LOG_STATS
1782 if (enable_stats_log) {
Rajeev Kumar4dbc24d2018-10-05 12:34:59 -07001783 if (per_app_memcg) {
1784 memory_stat_parse_result = memory_stat_from_cgroup(&mem_st, pid, uid);
1785 } else {
1786 memory_stat_parse_result = memory_stat_from_procfs(&mem_st, pid);
1787 }
Rajeev Kumar70450032018-01-31 17:54:56 -08001788 }
1789#endif
1790
Suren Baghdasaryanc7135592018-01-04 10:43:58 -08001791 TRACE_KILL_START(pid);
1792
Mark Salyzyn64d97d82018-04-09 09:50:32 -07001793 /* CAP_KILL required */
Suren Baghdasaryan96bf3a62017-12-08 12:58:52 -08001794 r = kill(pid, SIGKILL);
Wei Wang2d95c102018-11-21 00:11:44 -08001795
Suren Baghdasaryance862df2019-09-04 16:44:47 -07001796 TRACE_KILL_END();
1797
1798 if (r) {
1799 ALOGE("kill(%d): errno=%d", pid, errno);
1800 /* Delete process record even when we fail to kill so that we don't get stuck on it */
1801 goto out;
1802 }
1803
Wei Wang2d95c102018-11-21 00:11:44 -08001804 set_process_group_and_prio(pid, SP_FOREGROUND, ANDROID_PRIORITY_HIGHEST);
1805
Suren Baghdasaryand4a29902018-10-12 11:07:40 -07001806 inc_killcnt(procp->oomadj);
Suren Baghdasaryanfd7518f2019-07-15 15:50:17 -07001807 if (reason) {
1808 ALOGI("Kill '%s' (%d), uid %d, oom_adj %d to free %ldkB; reason: %s", taskname, pid,
1809 uid, procp->oomadj, tasksize * page_k, reason);
1810 } else {
1811 ALOGI("Kill '%s' (%d), uid %d, oom_adj %d to free %ldkB", taskname, pid,
1812 uid, procp->oomadj, tasksize * page_k);
1813 }
Colin Cross16b09462014-07-14 12:39:56 -07001814
Tim Murraye7853f62018-10-25 17:05:41 -07001815 last_killed_pid = pid;
1816
Rajeev Kumar70450032018-01-31 17:54:56 -08001817#ifdef LMKD_LOG_STATS
Suren Baghdasaryance862df2019-09-04 16:44:47 -07001818 if (memory_stat_parse_result == 0) {
1819 stats_write_lmk_kill_occurred(log_ctx, LMK_KILL_OCCURRED, uid, taskname,
1820 procp->oomadj, mem_st.pgfault, mem_st.pgmajfault, mem_st.rss_in_bytes,
1821 mem_st.cache_in_bytes, mem_st.swap_in_bytes, mem_st.process_start_time_ns,
1822 min_oom_score);
1823 } else if (enable_stats_log) {
1824 stats_write_lmk_kill_occurred(log_ctx, LMK_KILL_OCCURRED, uid, taskname, procp->oomadj,
1825 -1, -1, tasksize * BYTES_IN_KILOBYTE, -1, -1, -1,
1826 min_oom_score);
Colin Cross16b09462014-07-14 12:39:56 -07001827 }
Suren Baghdasaryance862df2019-09-04 16:44:47 -07001828#endif
1829 result = tasksize;
Mark Salyzyn919f5382018-02-04 15:27:23 -08001830
Suren Baghdasaryan01063272018-10-12 11:28:33 -07001831out:
1832 /*
1833 * WARNING: After pid_remove() procp is freed and can't be used!
1834 * Therefore placed at the end of the function.
1835 */
1836 pid_remove(pid);
1837 return result;
Colin Cross16b09462014-07-14 12:39:56 -07001838}
1839
1840/*
Suren Baghdasaryanf81b5f42018-10-26 11:32:15 -07001841 * Find one process to kill at or above the given oom_adj level.
1842 * Returns size of the killed process.
Colin Cross16b09462014-07-14 12:39:56 -07001843 */
Suren Baghdasaryanfd7518f2019-07-15 15:50:17 -07001844static int find_and_kill_process(int min_score_adj, const char *reason) {
Colin Cross16b09462014-07-14 12:39:56 -07001845 int i;
Suren Baghdasaryanf81b5f42018-10-26 11:32:15 -07001846 int killed_size = 0;
Colin Cross16b09462014-07-14 12:39:56 -07001847
Rajeev Kumar70450032018-01-31 17:54:56 -08001848#ifdef LMKD_LOG_STATS
Yang Lu5564f4e2018-05-15 04:59:44 +00001849 bool lmk_state_change_start = false;
Rajeev Kumar70450032018-01-31 17:54:56 -08001850#endif
1851
Chong Zhang0a4acdf2015-10-14 16:19:53 -07001852 for (i = OOM_SCORE_ADJ_MAX; i >= min_score_adj; i--) {
Colin Cross16b09462014-07-14 12:39:56 -07001853 struct proc *procp;
1854
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08001855 while (true) {
Suren Baghdasaryan818b59b2018-04-13 11:49:54 -07001856 procp = kill_heaviest_task ?
1857 proc_get_heaviest(i) : proc_adj_lru(i);
Colin Cross16b09462014-07-14 12:39:56 -07001858
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08001859 if (!procp)
1860 break;
1861
Suren Baghdasaryanfd7518f2019-07-15 15:50:17 -07001862 killed_size = kill_one_process(procp, min_score_adj, reason);
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08001863 if (killed_size >= 0) {
Yang Lu5564f4e2018-05-15 04:59:44 +00001864#ifdef LMKD_LOG_STATS
1865 if (enable_stats_log && !lmk_state_change_start) {
1866 lmk_state_change_start = true;
1867 stats_write_lmk_state_changed(log_ctx, LMK_STATE_CHANGED,
1868 LMK_STATE_CHANGE_START);
1869 }
1870#endif
Suren Baghdasaryanf81b5f42018-10-26 11:32:15 -07001871 break;
Colin Cross16b09462014-07-14 12:39:56 -07001872 }
1873 }
Suren Baghdasaryanf81b5f42018-10-26 11:32:15 -07001874 if (killed_size) {
1875 break;
1876 }
Colin Cross16b09462014-07-14 12:39:56 -07001877 }
1878
Rajeev Kumar70450032018-01-31 17:54:56 -08001879#ifdef LMKD_LOG_STATS
Yang Lu5564f4e2018-05-15 04:59:44 +00001880 if (enable_stats_log && lmk_state_change_start) {
Rajeev Kumar70450032018-01-31 17:54:56 -08001881 stats_write_lmk_state_changed(log_ctx, LMK_STATE_CHANGED, LMK_STATE_CHANGE_STOP);
1882 }
1883#endif
1884
Suren Baghdasaryanf81b5f42018-10-26 11:32:15 -07001885 return killed_size;
Colin Cross16b09462014-07-14 12:39:56 -07001886}
1887
Suren Baghdasaryan6499e5e2018-04-13 12:43:41 -07001888static int64_t get_memory_usage(struct reread_data *file_data) {
Robert Beneac47f2992017-08-21 15:18:31 -07001889 int ret;
1890 int64_t mem_usage;
Suren Baghdasaryana77b3272019-07-15 13:35:04 -07001891 char *buf;
Suren Baghdasaryan6499e5e2018-04-13 12:43:41 -07001892
Suren Baghdasaryana77b3272019-07-15 13:35:04 -07001893 if ((buf = reread_file(file_data)) == NULL) {
Robert Beneac47f2992017-08-21 15:18:31 -07001894 return -1;
1895 }
1896
Suren Baghdasaryan6499e5e2018-04-13 12:43:41 -07001897 if (!parse_int64(buf, &mem_usage)) {
1898 ALOGE("%s parse error", file_data->filename);
Robert Beneac47f2992017-08-21 15:18:31 -07001899 return -1;
1900 }
Robert Beneac47f2992017-08-21 15:18:31 -07001901 if (mem_usage == 0) {
1902 ALOGE("No memory!");
1903 return -1;
1904 }
1905 return mem_usage;
1906}
1907
Suren Baghdasaryan9926e572018-04-13 13:41:12 -07001908void record_low_pressure_levels(union meminfo *mi) {
1909 if (low_pressure_mem.min_nr_free_pages == -1 ||
1910 low_pressure_mem.min_nr_free_pages > mi->field.nr_free_pages) {
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08001911 if (debug_process_killing) {
Suren Baghdasaryan9926e572018-04-13 13:41:12 -07001912 ALOGI("Low pressure min memory update from %" PRId64 " to %" PRId64,
1913 low_pressure_mem.min_nr_free_pages, mi->field.nr_free_pages);
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08001914 }
Suren Baghdasaryan9926e572018-04-13 13:41:12 -07001915 low_pressure_mem.min_nr_free_pages = mi->field.nr_free_pages;
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08001916 }
1917 /*
1918 * Free memory at low vmpressure events occasionally gets spikes,
1919 * possibly a stale low vmpressure event with memory already
1920 * freed up (no memory pressure should have been reported).
Suren Baghdasaryan9926e572018-04-13 13:41:12 -07001921 * Ignore large jumps in max_nr_free_pages that would mess up our stats.
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08001922 */
Suren Baghdasaryan9926e572018-04-13 13:41:12 -07001923 if (low_pressure_mem.max_nr_free_pages == -1 ||
1924 (low_pressure_mem.max_nr_free_pages < mi->field.nr_free_pages &&
1925 mi->field.nr_free_pages - low_pressure_mem.max_nr_free_pages <
1926 low_pressure_mem.max_nr_free_pages * 0.1)) {
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08001927 if (debug_process_killing) {
Suren Baghdasaryan9926e572018-04-13 13:41:12 -07001928 ALOGI("Low pressure max memory update from %" PRId64 " to %" PRId64,
1929 low_pressure_mem.max_nr_free_pages, mi->field.nr_free_pages);
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08001930 }
Suren Baghdasaryan9926e572018-04-13 13:41:12 -07001931 low_pressure_mem.max_nr_free_pages = mi->field.nr_free_pages;
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08001932 }
1933}
1934
Suren Baghdasaryan96bf3a62017-12-08 12:58:52 -08001935enum vmpressure_level upgrade_level(enum vmpressure_level level) {
1936 return (enum vmpressure_level)((level < VMPRESS_LEVEL_CRITICAL) ?
1937 level + 1 : level);
1938}
1939
1940enum vmpressure_level downgrade_level(enum vmpressure_level level) {
1941 return (enum vmpressure_level)((level > VMPRESS_LEVEL_LOW) ?
1942 level - 1 : level);
1943}
1944
Tim Murraye7853f62018-10-25 17:05:41 -07001945static bool is_kill_pending(void) {
1946 char buf[24];
1947
1948 if (last_killed_pid < 0) {
1949 return false;
1950 }
1951
1952 snprintf(buf, sizeof(buf), "/proc/%d/", last_killed_pid);
1953 if (access(buf, F_OK) == 0) {
1954 return true;
1955 }
1956
1957 // reset last killed PID because there's nothing pending
1958 last_killed_pid = -1;
1959 return false;
1960}
1961
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07001962enum zone_watermark {
1963 WMARK_MIN = 0,
1964 WMARK_LOW,
1965 WMARK_HIGH,
1966 WMARK_NONE
1967};
1968
Suren Baghdasaryan4787ab42019-08-14 09:48:35 -07001969struct zone_watermarks {
1970 long high_wmark;
1971 long low_wmark;
1972 long min_wmark;
1973};
1974
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07001975/*
1976 * Returns lowest breached watermark or WMARK_NONE.
1977 */
Suren Baghdasaryan4787ab42019-08-14 09:48:35 -07001978static enum zone_watermark get_lowest_watermark(union meminfo *mi,
1979 struct zone_watermarks *watermarks)
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07001980{
Suren Baghdasaryan4787ab42019-08-14 09:48:35 -07001981 int64_t nr_free_pages = mi->field.nr_free_pages - mi->field.cma_free;
1982
1983 if (nr_free_pages < watermarks->min_wmark) {
1984 return WMARK_MIN;
1985 }
1986 if (nr_free_pages < watermarks->low_wmark) {
1987 return WMARK_LOW;
1988 }
1989 if (nr_free_pages < watermarks->high_wmark) {
1990 return WMARK_HIGH;
1991 }
1992 return WMARK_NONE;
1993}
1994
1995void calc_zone_watermarks(struct zoneinfo *zi, struct zone_watermarks *watermarks) {
1996 memset(watermarks, 0, sizeof(struct zone_watermarks));
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07001997
1998 for (int node_idx = 0; node_idx < zi->node_count; node_idx++) {
1999 struct zoneinfo_node *node = &zi->nodes[node_idx];
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002000 for (int zone_idx = 0; zone_idx < node->zone_count; zone_idx++) {
2001 struct zoneinfo_zone *zone = &node->zones[zone_idx];
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002002
2003 if (!zone->fields.field.present) {
2004 continue;
2005 }
2006
Suren Baghdasaryan4787ab42019-08-14 09:48:35 -07002007 watermarks->high_wmark += zone->max_protection + zone->fields.field.high;
2008 watermarks->low_wmark += zone->max_protection + zone->fields.field.low;
2009 watermarks->min_wmark += zone->max_protection + zone->fields.field.min;
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002010 }
2011 }
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002012}
2013
2014static void mp_event_psi(int data, uint32_t events, struct polling_params *poll_params) {
2015 enum kill_reasons {
2016 NONE = -1, /* To denote no kill condition */
2017 PRESSURE_AFTER_KILL = 0,
2018 NOT_RESPONDING,
2019 LOW_SWAP_AND_THRASHING,
2020 LOW_MEM_AND_SWAP,
2021 LOW_MEM_AND_THRASHING,
2022 DIRECT_RECL_AND_THRASHING,
2023 KILL_REASON_COUNT
2024 };
2025 enum reclaim_state {
2026 NO_RECLAIM = 0,
2027 KSWAPD_RECLAIM,
2028 DIRECT_RECLAIM,
2029 };
2030 static int64_t init_ws_refault;
2031 static int64_t base_file_lru;
2032 static int64_t init_pgscan_kswapd;
2033 static int64_t init_pgscan_direct;
2034 static int64_t swap_low_threshold;
2035 static bool killing;
2036 static int thrashing_limit;
2037 static bool in_reclaim;
Suren Baghdasaryan4787ab42019-08-14 09:48:35 -07002038 static struct zone_watermarks watermarks;
2039 static struct timespec wmark_update_tm;
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002040
2041 union meminfo mi;
2042 union vmstat vs;
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002043 struct timespec curr_tm;
2044 int64_t thrashing = 0;
2045 bool swap_is_low = false;
2046 enum vmpressure_level level = (enum vmpressure_level)data;
2047 enum kill_reasons kill_reason = NONE;
2048 bool cycle_after_kill = false;
2049 enum reclaim_state reclaim = NO_RECLAIM;
2050 enum zone_watermark wmark = WMARK_NONE;
Suren Baghdasaryanfd7518f2019-07-15 15:50:17 -07002051 char kill_desc[LINE_MAX];
Suren Baghdasaryan4b750882019-09-19 15:27:21 -07002052 bool cut_thrashing_limit = false;
2053 int min_score_adj = 0;
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002054
2055 /* Skip while still killing a process */
2056 if (is_kill_pending()) {
2057 /* TODO: replace this quick polling with pidfd polling if kernel supports */
2058 goto no_kill;
2059 }
2060
2061 if (clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm) != 0) {
2062 ALOGE("Failed to get current time");
2063 return;
2064 }
2065
2066 if (vmstat_parse(&vs) < 0) {
2067 ALOGE("Failed to parse vmstat!");
2068 return;
2069 }
2070
2071 if (meminfo_parse(&mi) < 0) {
2072 ALOGE("Failed to parse meminfo!");
2073 return;
2074 }
2075
2076 /* Reset states after process got killed */
2077 if (killing) {
2078 killing = false;
2079 cycle_after_kill = true;
2080 /* Reset file-backed pagecache size and refault amounts after a kill */
2081 base_file_lru = vs.field.nr_inactive_file + vs.field.nr_active_file;
2082 init_ws_refault = vs.field.workingset_refault;
2083 }
2084
2085 /* Check free swap levels */
2086 if (swap_free_low_percentage) {
2087 if (!swap_low_threshold) {
2088 swap_low_threshold = mi.field.total_swap * swap_free_low_percentage / 100;
2089 }
2090 swap_is_low = mi.field.free_swap < swap_low_threshold;
2091 }
2092
2093 /* Identify reclaim state */
2094 if (vs.field.pgscan_direct > init_pgscan_direct) {
2095 init_pgscan_direct = vs.field.pgscan_direct;
2096 init_pgscan_kswapd = vs.field.pgscan_kswapd;
2097 reclaim = DIRECT_RECLAIM;
2098 } else if (vs.field.pgscan_kswapd > init_pgscan_kswapd) {
2099 init_pgscan_kswapd = vs.field.pgscan_kswapd;
2100 reclaim = KSWAPD_RECLAIM;
2101 } else {
2102 in_reclaim = false;
2103 /* Skip if system is not reclaiming */
2104 goto no_kill;
2105 }
2106
2107 if (!in_reclaim) {
2108 /* Record file-backed pagecache size when entering reclaim cycle */
2109 base_file_lru = vs.field.nr_inactive_file + vs.field.nr_active_file;
2110 init_ws_refault = vs.field.workingset_refault;
2111 thrashing_limit = thrashing_limit_pct;
2112 } else {
2113 /* Calculate what % of the file-backed pagecache refaulted so far */
2114 thrashing = (vs.field.workingset_refault - init_ws_refault) * 100 / base_file_lru;
2115 }
2116 in_reclaim = true;
2117
Suren Baghdasaryan4787ab42019-08-14 09:48:35 -07002118 /*
2119 * Refresh watermarks once per min in case user updated one of the margins.
2120 * TODO: b/140521024 replace this periodic update with an API for AMS to notify LMKD
2121 * that zone watermarks were changed by the system software.
2122 */
2123 if (watermarks.high_wmark == 0 || get_time_diff_ms(&wmark_update_tm, &curr_tm) > 60000) {
2124 struct zoneinfo zi;
2125
2126 if (zoneinfo_parse(&zi) < 0) {
2127 ALOGE("Failed to parse zoneinfo!");
2128 return;
2129 }
2130
2131 calc_zone_watermarks(&zi, &watermarks);
2132 wmark_update_tm = curr_tm;
2133 }
2134
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002135 /* Find out which watermark is breached if any */
Suren Baghdasaryan4787ab42019-08-14 09:48:35 -07002136 wmark = get_lowest_watermark(&mi, &watermarks);
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002137
2138 /*
2139 * TODO: move this logic into a separate function
2140 * Decide if killing a process is necessary and record the reason
2141 */
2142 if (cycle_after_kill && wmark < WMARK_LOW) {
2143 /*
2144 * Prevent kills not freeing enough memory which might lead to OOM kill.
2145 * This might happen when a process is consuming memory faster than reclaim can
2146 * free even after a kill. Mostly happens when running memory stress tests.
2147 */
2148 kill_reason = PRESSURE_AFTER_KILL;
Suren Baghdasaryanfd7518f2019-07-15 15:50:17 -07002149 strncpy(kill_desc, "min watermark is breached even after kill", sizeof(kill_desc));
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002150 } else if (level == VMPRESS_LEVEL_CRITICAL && events != 0) {
2151 /*
2152 * Device is too busy reclaiming memory which might lead to ANR.
2153 * Critical level is triggered when PSI complete stall (all tasks are blocked because
2154 * of the memory congestion) breaches the configured threshold.
2155 */
2156 kill_reason = NOT_RESPONDING;
Suren Baghdasaryanfd7518f2019-07-15 15:50:17 -07002157 strncpy(kill_desc, "device is not responding", sizeof(kill_desc));
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002158 } else if (swap_is_low && thrashing > thrashing_limit_pct) {
2159 /* Page cache is thrashing while swap is low */
2160 kill_reason = LOW_SWAP_AND_THRASHING;
Suren Baghdasaryanfd7518f2019-07-15 15:50:17 -07002161 snprintf(kill_desc, sizeof(kill_desc), "device is low on swap (%" PRId64
2162 "kB < %" PRId64 "kB) and thrashing (%" PRId64 "%%)",
2163 mi.field.free_swap * page_k, swap_low_threshold * page_k, thrashing);
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002164 } else if (swap_is_low && wmark < WMARK_HIGH) {
2165 /* Both free memory and swap are low */
2166 kill_reason = LOW_MEM_AND_SWAP;
Suren Baghdasaryanfd7518f2019-07-15 15:50:17 -07002167 snprintf(kill_desc, sizeof(kill_desc), "%s watermark is breached and swap is low (%"
2168 PRId64 "kB < %" PRId64 "kB)", wmark > WMARK_LOW ? "min" : "low",
2169 mi.field.free_swap * page_k, swap_low_threshold * page_k);
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002170 } else if (wmark < WMARK_HIGH && thrashing > thrashing_limit) {
2171 /* Page cache is thrashing while memory is low */
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002172 kill_reason = LOW_MEM_AND_THRASHING;
Suren Baghdasaryanfd7518f2019-07-15 15:50:17 -07002173 snprintf(kill_desc, sizeof(kill_desc), "%s watermark is breached and thrashing (%"
2174 PRId64 "%%)", wmark > WMARK_LOW ? "min" : "low", thrashing);
Suren Baghdasaryan4b750882019-09-19 15:27:21 -07002175 cut_thrashing_limit = true;
2176 /* Do not kill perceptible apps because of thrashing */
2177 min_score_adj = PERCEPTIBLE_APP_ADJ;
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002178 } else if (reclaim == DIRECT_RECLAIM && thrashing > thrashing_limit) {
2179 /* Page cache is thrashing while in direct reclaim (mostly happens on lowram devices) */
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002180 kill_reason = DIRECT_RECL_AND_THRASHING;
Suren Baghdasaryanfd7518f2019-07-15 15:50:17 -07002181 snprintf(kill_desc, sizeof(kill_desc), "device is in direct reclaim and thrashing (%"
2182 PRId64 "%%)", thrashing);
Suren Baghdasaryan4b750882019-09-19 15:27:21 -07002183 cut_thrashing_limit = true;
2184 /* Do not kill perceptible apps because of thrashing */
2185 min_score_adj = PERCEPTIBLE_APP_ADJ;
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002186 }
2187
2188 /* Kill a process if necessary */
2189 if (kill_reason != NONE) {
Suren Baghdasaryan4b750882019-09-19 15:27:21 -07002190 int pages_freed = find_and_kill_process(min_score_adj, kill_desc);
2191 if (pages_freed > 0) {
2192 killing = true;
2193 if (cut_thrashing_limit) {
2194 /*
2195 * Cut thrasing limit by thrashing_limit_decay_pct percentage of the current
2196 * thrashing limit until the system stops thrashing.
2197 */
2198 thrashing_limit = (thrashing_limit * (100 - thrashing_limit_decay_pct)) / 100;
2199 }
2200 }
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002201 meminfo_log(&mi);
2202 }
2203
2204no_kill:
2205 /*
2206 * Start polling after initial PSI event;
2207 * extend polling while device is in direct reclaim or process is being killed;
2208 * do not extend when kswapd reclaims because that might go on for a long time
2209 * without causing memory pressure
2210 */
2211 if (events || killing || reclaim == DIRECT_RECLAIM) {
2212 poll_params->update = POLLING_START;
2213 }
2214
2215 /* Decide the polling interval */
2216 if (swap_is_low || killing) {
2217 /* Fast polling during and after a kill or when swap is low */
2218 poll_params->polling_interval_ms = PSI_POLL_PERIOD_SHORT_MS;
2219 } else {
2220 /* By default use long intervals */
2221 poll_params->polling_interval_ms = PSI_POLL_PERIOD_LONG_MS;
2222 }
2223}
2224
Suren Baghdasaryanef3650f2019-07-15 14:50:49 -07002225static void mp_event_common(int data, uint32_t events, struct polling_params *poll_params) {
Todd Poynor3948f802013-07-09 19:35:14 -07002226 int ret;
2227 unsigned long long evcount;
Robert Beneac47f2992017-08-21 15:18:31 -07002228 int64_t mem_usage, memsw_usage;
Robert Benea6e8e7102017-09-13 15:20:30 -07002229 int64_t mem_pressure;
Suren Baghdasaryane82e15c2018-01-04 09:16:21 -08002230 enum vmpressure_level lvl;
Suren Baghdasaryan9926e572018-04-13 13:41:12 -07002231 union meminfo mi;
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07002232 struct zoneinfo zi;
Suren Baghdasaryan36934412018-09-05 15:46:32 -07002233 struct timespec curr_tm;
Suren Baghdasaryan314a5052018-07-24 17:13:06 -07002234 static struct timespec last_kill_tm;
2235 static unsigned long kill_skip_count = 0;
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08002236 enum vmpressure_level level = (enum vmpressure_level)data;
Suren Baghdasaryanffdc4dd2018-04-13 13:53:43 -07002237 long other_free = 0, other_file = 0;
2238 int min_score_adj;
Suren Baghdasaryanffdc4dd2018-04-13 13:53:43 -07002239 int minfree = 0;
Suren Baghdasaryan6499e5e2018-04-13 12:43:41 -07002240 static struct reread_data mem_usage_file_data = {
2241 .filename = MEMCG_MEMORY_USAGE,
2242 .fd = -1,
2243 };
2244 static struct reread_data memsw_usage_file_data = {
2245 .filename = MEMCG_MEMORYSW_USAGE,
2246 .fd = -1,
2247 };
Todd Poynor3948f802013-07-09 19:35:14 -07002248
Suren Baghdasaryan77122e52019-01-08 12:54:48 -08002249 if (debug_process_killing) {
2250 ALOGI("%s memory pressure event is triggered", level_name[level]);
2251 }
2252
2253 if (!use_psi_monitors) {
2254 /*
2255 * Check all event counters from low to critical
2256 * and upgrade to the highest priority one. By reading
2257 * eventfd we also reset the event counters.
2258 */
2259 for (lvl = VMPRESS_LEVEL_LOW; lvl < VMPRESS_LEVEL_COUNT; lvl++) {
2260 if (mpevfd[lvl] != -1 &&
2261 TEMP_FAILURE_RETRY(read(mpevfd[lvl],
2262 &evcount, sizeof(evcount))) > 0 &&
2263 evcount > 0 && lvl > level) {
2264 level = lvl;
2265 }
Suren Baghdasaryane82e15c2018-01-04 09:16:21 -08002266 }
2267 }
Todd Poynor3948f802013-07-09 19:35:14 -07002268
Suren Baghdasaryanef3650f2019-07-15 14:50:49 -07002269 /* Start polling after initial PSI event */
2270 if (use_psi_monitors && events) {
2271 /* Override polling params only if current event is more critical */
2272 if (!poll_params->poll_handler || data > poll_params->poll_handler->data) {
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002273 poll_params->polling_interval_ms = PSI_POLL_PERIOD_SHORT_MS;
Suren Baghdasaryanef3650f2019-07-15 14:50:49 -07002274 poll_params->update = POLLING_START;
2275 }
2276 }
2277
Suren Baghdasaryan36934412018-09-05 15:46:32 -07002278 if (clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm) != 0) {
2279 ALOGE("Failed to get current time");
2280 return;
2281 }
2282
Suren Baghdasaryancaa2dc52018-01-17 17:28:01 -08002283 if (kill_timeout_ms) {
Tim Murraye7853f62018-10-25 17:05:41 -07002284 // If we're within the timeout, see if there's pending reclaim work
2285 // from the last killed process. If there is (as evidenced by
2286 // /proc/<pid> continuing to exist), skip killing for now.
2287 if ((get_time_diff_ms(&last_kill_tm, &curr_tm) < kill_timeout_ms) &&
2288 (low_ram_device || is_kill_pending())) {
Suren Baghdasaryan314a5052018-07-24 17:13:06 -07002289 kill_skip_count++;
Suren Baghdasaryancaa2dc52018-01-17 17:28:01 -08002290 return;
2291 }
2292 }
2293
Suren Baghdasaryan314a5052018-07-24 17:13:06 -07002294 if (kill_skip_count > 0) {
Suren Baghdasaryanda88b242018-05-10 16:10:56 -07002295 ALOGI("%lu memory pressure events were skipped after a kill!",
Suren Baghdasaryan314a5052018-07-24 17:13:06 -07002296 kill_skip_count);
2297 kill_skip_count = 0;
Suren Baghdasaryancaa2dc52018-01-17 17:28:01 -08002298 }
2299
Suren Baghdasaryanffdc4dd2018-04-13 13:53:43 -07002300 if (meminfo_parse(&mi) < 0 || zoneinfo_parse(&zi) < 0) {
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08002301 ALOGE("Failed to get free memory!");
2302 return;
2303 }
2304
Suren Baghdasaryanffdc4dd2018-04-13 13:53:43 -07002305 if (use_minfree_levels) {
2306 int i;
2307
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07002308 other_free = mi.field.nr_free_pages - zi.totalreserve_pages;
Suren Baghdasaryanffdc4dd2018-04-13 13:53:43 -07002309 if (mi.field.nr_file_pages > (mi.field.shmem + mi.field.unevictable + mi.field.swap_cached)) {
2310 other_file = (mi.field.nr_file_pages - mi.field.shmem -
2311 mi.field.unevictable - mi.field.swap_cached);
2312 } else {
2313 other_file = 0;
2314 }
2315
2316 min_score_adj = OOM_SCORE_ADJ_MAX + 1;
2317 for (i = 0; i < lowmem_targets_size; i++) {
2318 minfree = lowmem_minfree[i];
2319 if (other_free < minfree && other_file < minfree) {
2320 min_score_adj = lowmem_adj[i];
2321 break;
2322 }
2323 }
2324
Suren Baghdasaryan20686f02018-05-18 14:42:00 -07002325 if (min_score_adj == OOM_SCORE_ADJ_MAX + 1) {
2326 if (debug_process_killing) {
2327 ALOGI("Ignore %s memory pressure event "
2328 "(free memory=%ldkB, cache=%ldkB, limit=%ldkB)",
2329 level_name[level], other_free * page_k, other_file * page_k,
2330 (long)lowmem_minfree[lowmem_targets_size - 1] * page_k);
2331 }
Suren Baghdasaryanffdc4dd2018-04-13 13:53:43 -07002332 return;
Suren Baghdasaryan20686f02018-05-18 14:42:00 -07002333 }
Suren Baghdasaryanffdc4dd2018-04-13 13:53:43 -07002334
Suren Baghdasaryanffdc4dd2018-04-13 13:53:43 -07002335 goto do_kill;
2336 }
2337
Suren Baghdasaryan9926e572018-04-13 13:41:12 -07002338 if (level == VMPRESS_LEVEL_LOW) {
2339 record_low_pressure_levels(&mi);
2340 }
2341
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08002342 if (level_oomadj[level] > OOM_SCORE_ADJ_MAX) {
2343 /* Do not monitor this pressure level */
2344 return;
2345 }
2346
Suren Baghdasaryan6499e5e2018-04-13 12:43:41 -07002347 if ((mem_usage = get_memory_usage(&mem_usage_file_data)) < 0) {
2348 goto do_kill;
2349 }
2350 if ((memsw_usage = get_memory_usage(&memsw_usage_file_data)) < 0) {
Suren Baghdasaryan96bf3a62017-12-08 12:58:52 -08002351 goto do_kill;
Robert Benea6e8e7102017-09-13 15:20:30 -07002352 }
Robert Beneac47f2992017-08-21 15:18:31 -07002353
Robert Benea6e8e7102017-09-13 15:20:30 -07002354 // Calculate percent for swappinness.
2355 mem_pressure = (mem_usage * 100) / memsw_usage;
2356
Suren Baghdasaryan96bf3a62017-12-08 12:58:52 -08002357 if (enable_pressure_upgrade && level != VMPRESS_LEVEL_CRITICAL) {
Robert Benea6e8e7102017-09-13 15:20:30 -07002358 // We are swapping too much.
2359 if (mem_pressure < upgrade_pressure) {
Suren Baghdasaryan96bf3a62017-12-08 12:58:52 -08002360 level = upgrade_level(level);
2361 if (debug_process_killing) {
2362 ALOGI("Event upgraded to %s", level_name[level]);
2363 }
Robert Beneac47f2992017-08-21 15:18:31 -07002364 }
2365 }
2366
Vic Yang360a1132018-08-07 10:18:22 -07002367 // If we still have enough swap space available, check if we want to
2368 // ignore/downgrade pressure events.
2369 if (mi.field.free_swap >=
2370 mi.field.total_swap * swap_free_low_percentage / 100) {
2371 // If the pressure is larger than downgrade_pressure lmk will not
2372 // kill any process, since enough memory is available.
2373 if (mem_pressure > downgrade_pressure) {
2374 if (debug_process_killing) {
2375 ALOGI("Ignore %s memory pressure", level_name[level]);
2376 }
2377 return;
2378 } else if (level == VMPRESS_LEVEL_CRITICAL && mem_pressure > upgrade_pressure) {
2379 if (debug_process_killing) {
2380 ALOGI("Downgrade critical memory pressure");
2381 }
2382 // Downgrade event, since enough memory available.
2383 level = downgrade_level(level);
Robert Benea6e8e7102017-09-13 15:20:30 -07002384 }
Robert Benea6e8e7102017-09-13 15:20:30 -07002385 }
2386
Suren Baghdasaryan96bf3a62017-12-08 12:58:52 -08002387do_kill:
Suren Baghdasaryanff61afb2018-04-13 11:45:38 -07002388 if (low_ram_device) {
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08002389 /* For Go devices kill only one task */
Suren Baghdasaryanfd7518f2019-07-15 15:50:17 -07002390 if (find_and_kill_process(level_oomadj[level], NULL) == 0) {
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08002391 if (debug_process_killing) {
2392 ALOGI("Nothing to kill");
2393 }
Suren Baghdasaryan282ad1a2018-07-26 16:34:27 -07002394 } else {
2395 meminfo_log(&mi);
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08002396 }
2397 } else {
Suren Baghdasaryanffdc4dd2018-04-13 13:53:43 -07002398 int pages_freed;
Suren Baghdasaryan36934412018-09-05 15:46:32 -07002399 static struct timespec last_report_tm;
2400 static unsigned long report_skip_count = 0;
Suren Baghdasaryanffdc4dd2018-04-13 13:53:43 -07002401
2402 if (!use_minfree_levels) {
Suren Baghdasaryanffdc4dd2018-04-13 13:53:43 -07002403 /* Free up enough memory to downgrate the memory pressure to low level */
Suren Baghdasaryanf81b5f42018-10-26 11:32:15 -07002404 if (mi.field.nr_free_pages >= low_pressure_mem.max_nr_free_pages) {
Suren Baghdasaryanffdc4dd2018-04-13 13:53:43 -07002405 if (debug_process_killing) {
2406 ALOGI("Ignoring pressure since more memory is "
2407 "available (%" PRId64 ") than watermark (%" PRId64 ")",
2408 mi.field.nr_free_pages, low_pressure_mem.max_nr_free_pages);
2409 }
2410 return;
2411 }
2412 min_score_adj = level_oomadj[level];
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08002413 }
2414
Suren Baghdasaryanfd7518f2019-07-15 15:50:17 -07002415 pages_freed = find_and_kill_process(min_score_adj, NULL);
Suren Baghdasaryanda88b242018-05-10 16:10:56 -07002416
Suren Baghdasaryan36934412018-09-05 15:46:32 -07002417 if (pages_freed == 0) {
2418 /* Rate limit kill reports when nothing was reclaimed */
2419 if (get_time_diff_ms(&last_report_tm, &curr_tm) < FAIL_REPORT_RLIMIT_MS) {
2420 report_skip_count++;
Suren Baghdasaryan314a5052018-07-24 17:13:06 -07002421 return;
2422 }
Tim Murraye7853f62018-10-25 17:05:41 -07002423 } else {
2424 /* If we killed anything, update the last killed timestamp. */
2425 last_kill_tm = curr_tm;
Robert Beneacaeaa652017-08-11 16:03:20 -07002426 }
Suren Baghdasaryan36934412018-09-05 15:46:32 -07002427
2428 /* Log meminfo whenever we kill or when report rate limit allows */
2429 meminfo_log(&mi);
Suren Baghdasaryan36934412018-09-05 15:46:32 -07002430
2431 if (use_minfree_levels) {
Suren Baghdasaryanf81b5f42018-10-26 11:32:15 -07002432 ALOGI("Reclaimed %ldkB, cache(%ldkB) and "
Suren Baghdasaryan36934412018-09-05 15:46:32 -07002433 "free(%" PRId64 "kB)-reserved(%" PRId64 "kB) below min(%ldkB) for oom_adj %d",
Suren Baghdasaryanf81b5f42018-10-26 11:32:15 -07002434 pages_freed * page_k,
Suren Baghdasaryan36934412018-09-05 15:46:32 -07002435 other_file * page_k, mi.field.nr_free_pages * page_k,
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07002436 zi.totalreserve_pages * page_k,
Suren Baghdasaryan36934412018-09-05 15:46:32 -07002437 minfree * page_k, min_score_adj);
2438 } else {
Suren Baghdasaryanf81b5f42018-10-26 11:32:15 -07002439 ALOGI("Reclaimed %ldkB at oom_adj %d",
2440 pages_freed * page_k, min_score_adj);
Suren Baghdasaryan36934412018-09-05 15:46:32 -07002441 }
2442
2443 if (report_skip_count > 0) {
2444 ALOGI("Suppressed %lu failed kill reports", report_skip_count);
2445 report_skip_count = 0;
2446 }
2447
2448 last_report_tm = curr_tm;
Colin Crossf8857cc2014-07-11 17:16:56 -07002449 }
Todd Poynor3948f802013-07-09 19:35:14 -07002450}
2451
Suren Baghdasaryan844f26b2019-07-15 15:42:09 -07002452static bool init_mp_psi(enum vmpressure_level level, bool use_new_strategy) {
2453 int fd;
2454
2455 /* Do not register a handler if threshold_ms is not set */
2456 if (!psi_thresholds[level].threshold_ms) {
2457 return true;
2458 }
2459
2460 fd = init_psi_monitor(psi_thresholds[level].stall_type,
Suren Baghdasaryan77122e52019-01-08 12:54:48 -08002461 psi_thresholds[level].threshold_ms * US_PER_MS,
2462 PSI_WINDOW_SIZE_MS * US_PER_MS);
2463
2464 if (fd < 0) {
2465 return false;
2466 }
2467
Suren Baghdasaryan844f26b2019-07-15 15:42:09 -07002468 vmpressure_hinfo[level].handler = use_new_strategy ? mp_event_psi : mp_event_common;
Suren Baghdasaryan77122e52019-01-08 12:54:48 -08002469 vmpressure_hinfo[level].data = level;
2470 if (register_psi_monitor(epollfd, fd, &vmpressure_hinfo[level]) < 0) {
2471 destroy_psi_monitor(fd);
2472 return false;
2473 }
2474 maxevents++;
2475 mpevfd[level] = fd;
2476
2477 return true;
2478}
2479
2480static void destroy_mp_psi(enum vmpressure_level level) {
2481 int fd = mpevfd[level];
2482
2483 if (unregister_psi_monitor(epollfd, fd) < 0) {
2484 ALOGE("Failed to unregister psi monitor for %s memory pressure; errno=%d",
2485 level_name[level], errno);
2486 }
2487 destroy_psi_monitor(fd);
2488 mpevfd[level] = -1;
2489}
2490
2491static bool init_psi_monitors() {
Suren Baghdasaryan844f26b2019-07-15 15:42:09 -07002492 /*
2493 * When PSI is used on low-ram devices or on high-end devices without memfree levels
2494 * use new kill strategy based on zone watermarks, free swap and thrashing stats
2495 */
2496 bool use_new_strategy =
2497 property_get_bool("ro.lmk.use_new_strategy", low_ram_device || !use_minfree_levels);
2498
2499 /* In default PSI mode override stall amounts using system properties */
2500 if (use_new_strategy) {
2501 /* Do not use low pressure level */
2502 psi_thresholds[VMPRESS_LEVEL_LOW].threshold_ms = 0;
2503 psi_thresholds[VMPRESS_LEVEL_MEDIUM].threshold_ms = psi_partial_stall_ms;
2504 psi_thresholds[VMPRESS_LEVEL_CRITICAL].threshold_ms = psi_complete_stall_ms;
2505 }
2506
2507 if (!init_mp_psi(VMPRESS_LEVEL_LOW, use_new_strategy)) {
Suren Baghdasaryan77122e52019-01-08 12:54:48 -08002508 return false;
2509 }
Suren Baghdasaryan844f26b2019-07-15 15:42:09 -07002510 if (!init_mp_psi(VMPRESS_LEVEL_MEDIUM, use_new_strategy)) {
Suren Baghdasaryan77122e52019-01-08 12:54:48 -08002511 destroy_mp_psi(VMPRESS_LEVEL_LOW);
2512 return false;
2513 }
Suren Baghdasaryan844f26b2019-07-15 15:42:09 -07002514 if (!init_mp_psi(VMPRESS_LEVEL_CRITICAL, use_new_strategy)) {
Suren Baghdasaryan77122e52019-01-08 12:54:48 -08002515 destroy_mp_psi(VMPRESS_LEVEL_MEDIUM);
2516 destroy_mp_psi(VMPRESS_LEVEL_LOW);
2517 return false;
2518 }
2519 return true;
2520}
2521
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08002522static bool init_mp_common(enum vmpressure_level level) {
Todd Poynor3948f802013-07-09 19:35:14 -07002523 int mpfd;
2524 int evfd;
2525 int evctlfd;
2526 char buf[256];
2527 struct epoll_event epev;
2528 int ret;
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08002529 int level_idx = (int)level;
2530 const char *levelstr = level_name[level_idx];
Suren Baghdasaryan96bf3a62017-12-08 12:58:52 -08002531
Mark Salyzyn64d97d82018-04-09 09:50:32 -07002532 /* gid containing AID_SYSTEM required */
Nick Kralevichc68c8862015-12-18 20:52:37 -08002533 mpfd = open(MEMCG_SYSFS_PATH "memory.pressure_level", O_RDONLY | O_CLOEXEC);
Todd Poynor3948f802013-07-09 19:35:14 -07002534 if (mpfd < 0) {
2535 ALOGI("No kernel memory.pressure_level support (errno=%d)", errno);
2536 goto err_open_mpfd;
2537 }
2538
Nick Kralevichc68c8862015-12-18 20:52:37 -08002539 evctlfd = open(MEMCG_SYSFS_PATH "cgroup.event_control", O_WRONLY | O_CLOEXEC);
Todd Poynor3948f802013-07-09 19:35:14 -07002540 if (evctlfd < 0) {
2541 ALOGI("No kernel memory cgroup event control (errno=%d)", errno);
2542 goto err_open_evctlfd;
2543 }
2544
Nick Kralevichc68c8862015-12-18 20:52:37 -08002545 evfd = eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC);
Todd Poynor3948f802013-07-09 19:35:14 -07002546 if (evfd < 0) {
2547 ALOGE("eventfd failed for level %s; errno=%d", levelstr, errno);
2548 goto err_eventfd;
2549 }
2550
2551 ret = snprintf(buf, sizeof(buf), "%d %d %s", evfd, mpfd, levelstr);
2552 if (ret >= (ssize_t)sizeof(buf)) {
2553 ALOGE("cgroup.event_control line overflow for level %s", levelstr);
2554 goto err;
2555 }
2556
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08002557 ret = TEMP_FAILURE_RETRY(write(evctlfd, buf, strlen(buf) + 1));
Todd Poynor3948f802013-07-09 19:35:14 -07002558 if (ret == -1) {
2559 ALOGE("cgroup.event_control write failed for level %s; errno=%d",
2560 levelstr, errno);
2561 goto err;
2562 }
2563
2564 epev.events = EPOLLIN;
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08002565 /* use data to store event level */
2566 vmpressure_hinfo[level_idx].data = level_idx;
2567 vmpressure_hinfo[level_idx].handler = mp_event_common;
2568 epev.data.ptr = (void *)&vmpressure_hinfo[level_idx];
Todd Poynor3948f802013-07-09 19:35:14 -07002569 ret = epoll_ctl(epollfd, EPOLL_CTL_ADD, evfd, &epev);
2570 if (ret == -1) {
2571 ALOGE("epoll_ctl for level %s failed; errno=%d", levelstr, errno);
2572 goto err;
2573 }
2574 maxevents++;
Suren Baghdasaryan96bf3a62017-12-08 12:58:52 -08002575 mpevfd[level] = evfd;
Suren Baghdasaryan1bd2fc42018-01-04 08:54:53 -08002576 close(evctlfd);
Suren Baghdasaryan96bf3a62017-12-08 12:58:52 -08002577 return true;
Todd Poynor3948f802013-07-09 19:35:14 -07002578
2579err:
2580 close(evfd);
2581err_eventfd:
2582 close(evctlfd);
2583err_open_evctlfd:
2584 close(mpfd);
2585err_open_mpfd:
Suren Baghdasaryan96bf3a62017-12-08 12:58:52 -08002586 return false;
Robert Benea673e2762017-06-01 16:32:31 -07002587}
2588
Jim Blackler3947c932019-04-26 11:18:29 +01002589#ifdef LMKD_LOG_STATS
2590static int kernel_poll_fd = -1;
Jim Blackler3947c932019-04-26 11:18:29 +01002591static void poll_kernel() {
2592 if (kernel_poll_fd == -1) {
2593 // not waiting
2594 return;
2595 }
2596
2597 while (1) {
2598 char rd_buf[256];
2599 int bytes_read =
2600 TEMP_FAILURE_RETRY(pread(kernel_poll_fd, (void*)rd_buf, sizeof(rd_buf), 0));
2601 if (bytes_read <= 0) break;
2602 rd_buf[bytes_read] = '\0';
2603
2604 int64_t pid;
2605 int64_t uid;
2606 int64_t group_leader_pid;
2607 int64_t min_flt;
2608 int64_t maj_flt;
2609 int64_t rss_in_pages;
2610 int16_t oom_score_adj;
2611 int16_t min_score_adj;
2612 int64_t starttime;
2613 char* taskname = 0;
2614 int fields_read = sscanf(rd_buf,
2615 "%" SCNd64 " %" SCNd64 " %" SCNd64 " %" SCNd64 " %" SCNd64
2616 " %" SCNd64 " %" SCNd16 " %" SCNd16 " %" SCNd64 "\n%m[^\n]",
2617 &pid, &uid, &group_leader_pid, &min_flt, &maj_flt, &rss_in_pages,
2618 &oom_score_adj, &min_score_adj, &starttime, &taskname);
2619
2620 /* only the death of the group leader process is logged */
2621 if (fields_read == 10 && group_leader_pid == pid) {
2622 int64_t process_start_time_ns = starttime * (NS_PER_SEC / sysconf(_SC_CLK_TCK));
Jim Blacklerd2da8142019-09-10 15:30:05 +01002623 stats_write_lmk_kill_occurred_pid(log_ctx, LMK_KILL_OCCURRED, uid, pid, oom_score_adj,
2624 min_flt, maj_flt, rss_in_pages * PAGE_SIZE, 0, 0,
2625 process_start_time_ns, min_score_adj);
Jim Blackler3947c932019-04-26 11:18:29 +01002626 }
2627
2628 free(taskname);
2629 }
2630}
2631
2632static struct event_handler_info kernel_poll_hinfo = {0, poll_kernel};
2633
2634static void init_poll_kernel() {
2635 struct epoll_event epev;
2636 kernel_poll_fd =
2637 TEMP_FAILURE_RETRY(open("/proc/lowmemorykiller", O_RDONLY | O_NONBLOCK | O_CLOEXEC));
2638
2639 if (kernel_poll_fd < 0) {
2640 ALOGE("kernel lmk event file could not be opened; errno=%d", kernel_poll_fd);
2641 return;
2642 }
2643
2644 epev.events = EPOLLIN;
2645 epev.data.ptr = (void*)&kernel_poll_hinfo;
2646 if (epoll_ctl(epollfd, EPOLL_CTL_ADD, kernel_poll_fd, &epev) != 0) {
2647 ALOGE("epoll_ctl for lmk events failed; errno=%d", errno);
2648 close(kernel_poll_fd);
2649 kernel_poll_fd = -1;
2650 } else {
2651 maxevents++;
2652 }
2653}
2654#endif
2655
Todd Poynor3948f802013-07-09 19:35:14 -07002656static int init(void) {
Suren Baghdasaryana77b3272019-07-15 13:35:04 -07002657 struct reread_data file_data = {
2658 .filename = ZONEINFO_PATH,
2659 .fd = -1,
2660 };
Todd Poynor3948f802013-07-09 19:35:14 -07002661 struct epoll_event epev;
2662 int i;
2663 int ret;
2664
2665 page_k = sysconf(_SC_PAGESIZE);
2666 if (page_k == -1)
2667 page_k = PAGE_SIZE;
2668 page_k /= 1024;
2669
2670 epollfd = epoll_create(MAX_EPOLL_EVENTS);
2671 if (epollfd == -1) {
2672 ALOGE("epoll_create failed (errno=%d)", errno);
2673 return -1;
2674 }
2675
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08002676 // mark data connections as not connected
2677 for (int i = 0; i < MAX_DATA_CONN; i++) {
2678 data_sock[i].sock = -1;
2679 }
2680
2681 ctrl_sock.sock = android_get_control_socket("lmkd");
2682 if (ctrl_sock.sock < 0) {
Todd Poynor3948f802013-07-09 19:35:14 -07002683 ALOGE("get lmkd control socket failed");
2684 return -1;
2685 }
2686
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08002687 ret = listen(ctrl_sock.sock, MAX_DATA_CONN);
Todd Poynor3948f802013-07-09 19:35:14 -07002688 if (ret < 0) {
2689 ALOGE("lmkd control socket listen failed (errno=%d)", errno);
2690 return -1;
2691 }
2692
2693 epev.events = EPOLLIN;
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08002694 ctrl_sock.handler_info.handler = ctrl_connect_handler;
2695 epev.data.ptr = (void *)&(ctrl_sock.handler_info);
2696 if (epoll_ctl(epollfd, EPOLL_CTL_ADD, ctrl_sock.sock, &epev) == -1) {
Todd Poynor3948f802013-07-09 19:35:14 -07002697 ALOGE("epoll_ctl for lmkd control socket failed (errno=%d)", errno);
2698 return -1;
2699 }
2700 maxevents++;
2701
Robert Benea164baeb2017-09-11 16:53:28 -07002702 has_inkernel_module = !access(INKERNEL_MINFREE_PATH, W_OK);
Suren Baghdasaryan979591b2018-01-18 17:27:30 -08002703 use_inkernel_interface = has_inkernel_module;
Todd Poynor3948f802013-07-09 19:35:14 -07002704
2705 if (use_inkernel_interface) {
2706 ALOGI("Using in-kernel low memory killer interface");
Jim Blackler3947c932019-04-26 11:18:29 +01002707#ifdef LMKD_LOG_STATS
2708 if (enable_stats_log) {
2709 init_poll_kernel();
2710 }
2711#endif
Todd Poynor3948f802013-07-09 19:35:14 -07002712 } else {
Suren Baghdasaryan77122e52019-01-08 12:54:48 -08002713 /* Try to use psi monitor first if kernel has it */
2714 use_psi_monitors = property_get_bool("ro.lmk.use_psi", true) &&
2715 init_psi_monitors();
2716 /* Fall back to vmpressure */
2717 if (!use_psi_monitors &&
2718 (!init_mp_common(VMPRESS_LEVEL_LOW) ||
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08002719 !init_mp_common(VMPRESS_LEVEL_MEDIUM) ||
Suren Baghdasaryan77122e52019-01-08 12:54:48 -08002720 !init_mp_common(VMPRESS_LEVEL_CRITICAL))) {
Todd Poynor3948f802013-07-09 19:35:14 -07002721 ALOGE("Kernel does not support memory pressure events or in-kernel low memory killer");
Suren Baghdasaryan96bf3a62017-12-08 12:58:52 -08002722 return -1;
2723 }
Suren Baghdasaryan77122e52019-01-08 12:54:48 -08002724 if (use_psi_monitors) {
2725 ALOGI("Using psi monitors for memory pressure detection");
2726 } else {
2727 ALOGI("Using vmpressure for memory pressure detection");
2728 }
Todd Poynor3948f802013-07-09 19:35:14 -07002729 }
2730
Chong Zhang0a4acdf2015-10-14 16:19:53 -07002731 for (i = 0; i <= ADJTOSLOT(OOM_SCORE_ADJ_MAX); i++) {
Todd Poynor3948f802013-07-09 19:35:14 -07002732 procadjslot_list[i].next = &procadjslot_list[i];
2733 procadjslot_list[i].prev = &procadjslot_list[i];
2734 }
2735
Suren Baghdasaryand4a29902018-10-12 11:07:40 -07002736 memset(killcnt_idx, KILLCNT_INVALID_IDX, sizeof(killcnt_idx));
2737
Suren Baghdasaryana77b3272019-07-15 13:35:04 -07002738 /*
2739 * Read zoneinfo as the biggest file we read to create and size the initial
2740 * read buffer and avoid memory re-allocations during memory pressure
2741 */
2742 if (reread_file(&file_data) == NULL) {
2743 ALOGE("Failed to read %s: %s", file_data.filename, strerror(errno));
2744 }
2745
Todd Poynor3948f802013-07-09 19:35:14 -07002746 return 0;
2747}
2748
2749static void mainloop(void) {
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08002750 struct event_handler_info* handler_info;
Suren Baghdasaryanef3650f2019-07-15 14:50:49 -07002751 struct polling_params poll_params;
2752 struct timespec curr_tm;
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08002753 struct epoll_event *evt;
Suren Baghdasaryan77122e52019-01-08 12:54:48 -08002754 long delay = -1;
Suren Baghdasaryanef3650f2019-07-15 14:50:49 -07002755
2756 poll_params.poll_handler = NULL;
2757 poll_params.update = POLLING_DO_NOT_CHANGE;
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08002758
Todd Poynor3948f802013-07-09 19:35:14 -07002759 while (1) {
2760 struct epoll_event events[maxevents];
2761 int nevents;
2762 int i;
2763
Suren Baghdasaryanef3650f2019-07-15 14:50:49 -07002764 if (poll_params.poll_handler) {
Suren Baghdasaryan77122e52019-01-08 12:54:48 -08002765 /* Calculate next timeout */
2766 clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm);
Suren Baghdasaryanef3650f2019-07-15 14:50:49 -07002767 delay = get_time_diff_ms(&poll_params.last_poll_tm, &curr_tm);
2768 delay = (delay < poll_params.polling_interval_ms) ?
2769 poll_params.polling_interval_ms - delay : poll_params.polling_interval_ms;
Suren Baghdasaryan77122e52019-01-08 12:54:48 -08002770
2771 /* Wait for events until the next polling timeout */
2772 nevents = epoll_wait(epollfd, events, maxevents, delay);
2773
2774 clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm);
Suren Baghdasaryanef3650f2019-07-15 14:50:49 -07002775 if (get_time_diff_ms(&poll_params.last_poll_tm, &curr_tm) >=
2776 poll_params.polling_interval_ms) {
2777 /* Set input params for the call */
2778 poll_params.poll_handler->handler(poll_params.poll_handler->data, 0, &poll_params);
2779 poll_params.last_poll_tm = curr_tm;
2780
2781 if (poll_params.update != POLLING_DO_NOT_CHANGE) {
2782 switch (poll_params.update) {
2783 case POLLING_START:
2784 poll_params.poll_start_tm = curr_tm;
2785 break;
2786 case POLLING_STOP:
2787 poll_params.poll_handler = NULL;
2788 break;
2789 default:
2790 break;
2791 }
2792 poll_params.update = POLLING_DO_NOT_CHANGE;
2793 } else {
2794 if (get_time_diff_ms(&poll_params.poll_start_tm, &curr_tm) >
2795 PSI_WINDOW_SIZE_MS) {
2796 /* Polled for the duration of PSI window, time to stop */
2797 poll_params.poll_handler = NULL;
2798 }
2799 }
Suren Baghdasaryan77122e52019-01-08 12:54:48 -08002800 }
2801 } else {
2802 /* Wait for events with no timeout */
2803 nevents = epoll_wait(epollfd, events, maxevents, -1);
2804 }
Todd Poynor3948f802013-07-09 19:35:14 -07002805
2806 if (nevents == -1) {
2807 if (errno == EINTR)
2808 continue;
2809 ALOGE("epoll_wait failed (errno=%d)", errno);
2810 continue;
2811 }
2812
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08002813 /*
2814 * First pass to see if any data socket connections were dropped.
2815 * Dropped connection should be handled before any other events
2816 * to deallocate data connection and correctly handle cases when
2817 * connection gets dropped and reestablished in the same epoll cycle.
2818 * In such cases it's essential to handle connection closures first.
2819 */
2820 for (i = 0, evt = &events[0]; i < nevents; ++i, evt++) {
2821 if ((evt->events & EPOLLHUP) && evt->data.ptr) {
2822 ALOGI("lmkd data connection dropped");
2823 handler_info = (struct event_handler_info*)evt->data.ptr;
2824 ctrl_data_close(handler_info->data);
2825 }
2826 }
2827
2828 /* Second pass to handle all other events */
2829 for (i = 0, evt = &events[0]; i < nevents; ++i, evt++) {
Suren Baghdasaryanef3650f2019-07-15 14:50:49 -07002830 if (evt->events & EPOLLERR) {
Todd Poynor3948f802013-07-09 19:35:14 -07002831 ALOGD("EPOLLERR on event #%d", i);
Suren Baghdasaryanef3650f2019-07-15 14:50:49 -07002832 }
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08002833 if (evt->events & EPOLLHUP) {
2834 /* This case was handled in the first pass */
2835 continue;
2836 }
2837 if (evt->data.ptr) {
2838 handler_info = (struct event_handler_info*)evt->data.ptr;
Suren Baghdasaryanef3650f2019-07-15 14:50:49 -07002839 /* Set input params for the call */
2840 handler_info->handler(handler_info->data, evt->events, &poll_params);
Suren Baghdasaryan77122e52019-01-08 12:54:48 -08002841
Suren Baghdasaryanef3650f2019-07-15 14:50:49 -07002842 if (poll_params.update != POLLING_DO_NOT_CHANGE) {
2843 switch (poll_params.update) {
2844 case POLLING_START:
2845 /*
2846 * Poll for the duration of PSI_WINDOW_SIZE_MS after the
2847 * initial PSI event because psi events are rate-limited
2848 * at one per sec.
2849 */
2850 clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm);
2851 poll_params.poll_start_tm = poll_params.last_poll_tm = curr_tm;
2852 poll_params.poll_handler = handler_info;
2853 break;
2854 case POLLING_STOP:
2855 poll_params.poll_handler = NULL;
2856 break;
2857 default:
2858 break;
2859 }
2860 poll_params.update = POLLING_DO_NOT_CHANGE;
Suren Baghdasaryan77122e52019-01-08 12:54:48 -08002861 }
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08002862 }
Todd Poynor3948f802013-07-09 19:35:14 -07002863 }
2864 }
2865}
2866
Mark Salyzyne6ed68b2014-04-30 13:36:35 -07002867int main(int argc __unused, char **argv __unused) {
Colin Cross1a0d9be2014-07-14 14:31:15 -07002868 struct sched_param param = {
2869 .sched_priority = 1,
2870 };
2871
Suren Baghdasaryan96bf3a62017-12-08 12:58:52 -08002872 /* By default disable low level vmpressure events */
2873 level_oomadj[VMPRESS_LEVEL_LOW] =
2874 property_get_int32("ro.lmk.low", OOM_SCORE_ADJ_MAX + 1);
2875 level_oomadj[VMPRESS_LEVEL_MEDIUM] =
2876 property_get_int32("ro.lmk.medium", 800);
2877 level_oomadj[VMPRESS_LEVEL_CRITICAL] =
2878 property_get_int32("ro.lmk.critical", 0);
Robert Beneacaeaa652017-08-11 16:03:20 -07002879 debug_process_killing = property_get_bool("ro.lmk.debug", false);
Suren Baghdasaryanad2fd912017-12-08 13:08:41 -08002880
2881 /* By default disable upgrade/downgrade logic */
2882 enable_pressure_upgrade =
2883 property_get_bool("ro.lmk.critical_upgrade", false);
2884 upgrade_pressure =
2885 (int64_t)property_get_int32("ro.lmk.upgrade_pressure", 100);
2886 downgrade_pressure =
2887 (int64_t)property_get_int32("ro.lmk.downgrade_pressure", 100);
Suren Baghdasaryan662492a2017-12-08 13:17:06 -08002888 kill_heaviest_task =
Suren Baghdasaryan818b59b2018-04-13 11:49:54 -07002889 property_get_bool("ro.lmk.kill_heaviest_task", false);
Suren Baghdasaryanff61afb2018-04-13 11:45:38 -07002890 low_ram_device = property_get_bool("ro.config.low_ram", false);
Suren Baghdasaryancaa2dc52018-01-17 17:28:01 -08002891 kill_timeout_ms =
2892 (unsigned long)property_get_int32("ro.lmk.kill_timeout_ms", 0);
Suren Baghdasaryanffdc4dd2018-04-13 13:53:43 -07002893 use_minfree_levels =
2894 property_get_bool("ro.lmk.use_minfree_levels", false);
Suren Baghdasaryance13cb52018-06-19 18:38:12 -07002895 per_app_memcg =
2896 property_get_bool("ro.config.per_app_memcg", low_ram_device);
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002897 swap_free_low_percentage = clamp(0, 100, property_get_int32("ro.lmk.swap_free_low_percentage",
2898 low_ram_device ? DEF_LOW_SWAP_LOWRAM : DEF_LOW_SWAP));
Suren Baghdasaryan844f26b2019-07-15 15:42:09 -07002899 psi_partial_stall_ms = property_get_int32("ro.lmk.psi_partial_stall_ms",
2900 low_ram_device ? DEF_PARTIAL_STALL_LOWRAM : DEF_PARTIAL_STALL);
2901 psi_complete_stall_ms = property_get_int32("ro.lmk.psi_complete_stall_ms",
2902 DEF_COMPLETE_STALL);
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002903 thrashing_limit_pct = max(0, property_get_int32("ro.lmk.thrashing_limit",
2904 low_ram_device ? DEF_THRASHING_LOWRAM : DEF_THRASHING));
2905 thrashing_limit_decay_pct = clamp(0, 100, property_get_int32("ro.lmk.thrashing_limit_decay",
2906 low_ram_device ? DEF_THRASHING_DECAY_LOWRAM : DEF_THRASHING_DECAY));
Robert Benea58891d52017-07-31 17:15:20 -07002907
Suren Baghdasaryan282ad1a2018-07-26 16:34:27 -07002908 ctx = create_android_logger(MEMINFO_LOG_TAG);
2909
Rajeev Kumar70450032018-01-31 17:54:56 -08002910#ifdef LMKD_LOG_STATS
Rajeev Kumar1c669f72018-03-09 15:20:56 -08002911 statslog_init(&log_ctx, &enable_stats_log);
Rajeev Kumar70450032018-01-31 17:54:56 -08002912#endif
2913
Mark Salyzyn721d7c72018-03-21 12:24:58 -07002914 if (!init()) {
2915 if (!use_inkernel_interface) {
2916 /*
2917 * MCL_ONFAULT pins pages as they fault instead of loading
2918 * everything immediately all at once. (Which would be bad,
2919 * because as of this writing, we have a lot of mapped pages we
2920 * never use.) Old kernels will see MCL_ONFAULT and fail with
2921 * EINVAL; we ignore this failure.
2922 *
2923 * N.B. read the man page for mlockall. MCL_CURRENT | MCL_ONFAULT
2924 * pins ⊆ MCL_CURRENT, converging to just MCL_CURRENT as we fault
2925 * in pages.
2926 */
Mark Salyzyn64d97d82018-04-09 09:50:32 -07002927 /* CAP_IPC_LOCK required */
Mark Salyzyn721d7c72018-03-21 12:24:58 -07002928 if (mlockall(MCL_CURRENT | MCL_FUTURE | MCL_ONFAULT) && (errno != EINVAL)) {
2929 ALOGW("mlockall failed %s", strerror(errno));
2930 }
Daniel Colascione4dd5d002018-01-03 12:01:02 -08002931
Mark Salyzyn64d97d82018-04-09 09:50:32 -07002932 /* CAP_NICE required */
2933 if (sched_setscheduler(0, SCHED_FIFO, &param)) {
2934 ALOGW("set SCHED_FIFO failed %s", strerror(errno));
2935 }
Mark Salyzyn721d7c72018-03-21 12:24:58 -07002936 }
2937
Todd Poynor3948f802013-07-09 19:35:14 -07002938 mainloop();
Mark Salyzyn721d7c72018-03-21 12:24:58 -07002939 }
Todd Poynor3948f802013-07-09 19:35:14 -07002940
Rajeev Kumar70450032018-01-31 17:54:56 -08002941#ifdef LMKD_LOG_STATS
Rajeev Kumar1c669f72018-03-09 15:20:56 -08002942 statslog_destroy(&log_ctx);
Rajeev Kumar70450032018-01-31 17:54:56 -08002943#endif
2944
Suren Baghdasaryan282ad1a2018-07-26 16:34:27 -07002945 android_log_destroy(&ctx);
2946
Todd Poynor3948f802013-07-09 19:35:14 -07002947 ALOGI("exiting");
2948 return 0;
2949}