blob: 2ba3f44b6187fe1be958deeea630ce1cf19c3a80 [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
1796 set_process_group_and_prio(pid, SP_FOREGROUND, ANDROID_PRIORITY_HIGHEST);
1797
Suren Baghdasaryand4a29902018-10-12 11:07:40 -07001798 inc_killcnt(procp->oomadj);
Suren Baghdasaryanfd7518f2019-07-15 15:50:17 -07001799 if (reason) {
1800 ALOGI("Kill '%s' (%d), uid %d, oom_adj %d to free %ldkB; reason: %s", taskname, pid,
1801 uid, procp->oomadj, tasksize * page_k, reason);
1802 } else {
1803 ALOGI("Kill '%s' (%d), uid %d, oom_adj %d to free %ldkB", taskname, pid,
1804 uid, procp->oomadj, tasksize * page_k);
1805 }
Colin Cross16b09462014-07-14 12:39:56 -07001806
Suren Baghdasaryanc7135592018-01-04 10:43:58 -08001807 TRACE_KILL_END();
1808
Tim Murraye7853f62018-10-25 17:05:41 -07001809 last_killed_pid = pid;
1810
Colin Cross16b09462014-07-14 12:39:56 -07001811 if (r) {
Mark Salyzyn919f5382018-02-04 15:27:23 -08001812 ALOGE("kill(%d): errno=%d", pid, errno);
Suren Baghdasaryan01063272018-10-12 11:28:33 -07001813 goto out;
Rajeev Kumar70450032018-01-31 17:54:56 -08001814 } else {
1815#ifdef LMKD_LOG_STATS
1816 if (memory_stat_parse_result == 0) {
1817 stats_write_lmk_kill_occurred(log_ctx, LMK_KILL_OCCURRED, uid, taskname,
1818 procp->oomadj, mem_st.pgfault, mem_st.pgmajfault, mem_st.rss_in_bytes,
Suren Baghdasaryanec5e4c62019-03-04 11:07:39 -08001819 mem_st.cache_in_bytes, mem_st.swap_in_bytes, mem_st.process_start_time_ns,
1820 min_oom_score);
Rajeev Kumar4dbc24d2018-10-05 12:34:59 -07001821 } else if (enable_stats_log) {
1822 stats_write_lmk_kill_occurred(log_ctx, LMK_KILL_OCCURRED, uid, taskname, procp->oomadj,
Suren Baghdasaryanec5e4c62019-03-04 11:07:39 -08001823 -1, -1, tasksize * BYTES_IN_KILOBYTE, -1, -1, -1,
1824 min_oom_score);
Rajeev Kumar70450032018-01-31 17:54:56 -08001825 }
1826#endif
Suren Baghdasaryan01063272018-10-12 11:28:33 -07001827 result = tasksize;
Colin Cross16b09462014-07-14 12:39:56 -07001828 }
Mark Salyzyn919f5382018-02-04 15:27:23 -08001829
Suren Baghdasaryan01063272018-10-12 11:28:33 -07001830out:
1831 /*
1832 * WARNING: After pid_remove() procp is freed and can't be used!
1833 * Therefore placed at the end of the function.
1834 */
1835 pid_remove(pid);
1836 return result;
Colin Cross16b09462014-07-14 12:39:56 -07001837}
1838
1839/*
Suren Baghdasaryanf81b5f42018-10-26 11:32:15 -07001840 * Find one process to kill at or above the given oom_adj level.
1841 * Returns size of the killed process.
Colin Cross16b09462014-07-14 12:39:56 -07001842 */
Suren Baghdasaryanfd7518f2019-07-15 15:50:17 -07001843static int find_and_kill_process(int min_score_adj, const char *reason) {
Colin Cross16b09462014-07-14 12:39:56 -07001844 int i;
Suren Baghdasaryanf81b5f42018-10-26 11:32:15 -07001845 int killed_size = 0;
Colin Cross16b09462014-07-14 12:39:56 -07001846
Rajeev Kumar70450032018-01-31 17:54:56 -08001847#ifdef LMKD_LOG_STATS
Yang Lu5564f4e2018-05-15 04:59:44 +00001848 bool lmk_state_change_start = false;
Rajeev Kumar70450032018-01-31 17:54:56 -08001849#endif
1850
Chong Zhang0a4acdf2015-10-14 16:19:53 -07001851 for (i = OOM_SCORE_ADJ_MAX; i >= min_score_adj; i--) {
Colin Cross16b09462014-07-14 12:39:56 -07001852 struct proc *procp;
1853
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08001854 while (true) {
Suren Baghdasaryan818b59b2018-04-13 11:49:54 -07001855 procp = kill_heaviest_task ?
1856 proc_get_heaviest(i) : proc_adj_lru(i);
Colin Cross16b09462014-07-14 12:39:56 -07001857
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08001858 if (!procp)
1859 break;
1860
Suren Baghdasaryanfd7518f2019-07-15 15:50:17 -07001861 killed_size = kill_one_process(procp, min_score_adj, reason);
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08001862 if (killed_size >= 0) {
Yang Lu5564f4e2018-05-15 04:59:44 +00001863#ifdef LMKD_LOG_STATS
1864 if (enable_stats_log && !lmk_state_change_start) {
1865 lmk_state_change_start = true;
1866 stats_write_lmk_state_changed(log_ctx, LMK_STATE_CHANGED,
1867 LMK_STATE_CHANGE_START);
1868 }
1869#endif
Suren Baghdasaryanf81b5f42018-10-26 11:32:15 -07001870 break;
Colin Cross16b09462014-07-14 12:39:56 -07001871 }
1872 }
Suren Baghdasaryanf81b5f42018-10-26 11:32:15 -07001873 if (killed_size) {
1874 break;
1875 }
Colin Cross16b09462014-07-14 12:39:56 -07001876 }
1877
Rajeev Kumar70450032018-01-31 17:54:56 -08001878#ifdef LMKD_LOG_STATS
Yang Lu5564f4e2018-05-15 04:59:44 +00001879 if (enable_stats_log && lmk_state_change_start) {
Rajeev Kumar70450032018-01-31 17:54:56 -08001880 stats_write_lmk_state_changed(log_ctx, LMK_STATE_CHANGED, LMK_STATE_CHANGE_STOP);
1881 }
1882#endif
1883
Suren Baghdasaryanf81b5f42018-10-26 11:32:15 -07001884 return killed_size;
Colin Cross16b09462014-07-14 12:39:56 -07001885}
1886
Suren Baghdasaryan6499e5e2018-04-13 12:43:41 -07001887static int64_t get_memory_usage(struct reread_data *file_data) {
Robert Beneac47f2992017-08-21 15:18:31 -07001888 int ret;
1889 int64_t mem_usage;
Suren Baghdasaryana77b3272019-07-15 13:35:04 -07001890 char *buf;
Suren Baghdasaryan6499e5e2018-04-13 12:43:41 -07001891
Suren Baghdasaryana77b3272019-07-15 13:35:04 -07001892 if ((buf = reread_file(file_data)) == NULL) {
Robert Beneac47f2992017-08-21 15:18:31 -07001893 return -1;
1894 }
1895
Suren Baghdasaryan6499e5e2018-04-13 12:43:41 -07001896 if (!parse_int64(buf, &mem_usage)) {
1897 ALOGE("%s parse error", file_data->filename);
Robert Beneac47f2992017-08-21 15:18:31 -07001898 return -1;
1899 }
Robert Beneac47f2992017-08-21 15:18:31 -07001900 if (mem_usage == 0) {
1901 ALOGE("No memory!");
1902 return -1;
1903 }
1904 return mem_usage;
1905}
1906
Suren Baghdasaryan9926e572018-04-13 13:41:12 -07001907void record_low_pressure_levels(union meminfo *mi) {
1908 if (low_pressure_mem.min_nr_free_pages == -1 ||
1909 low_pressure_mem.min_nr_free_pages > mi->field.nr_free_pages) {
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08001910 if (debug_process_killing) {
Suren Baghdasaryan9926e572018-04-13 13:41:12 -07001911 ALOGI("Low pressure min memory update from %" PRId64 " to %" PRId64,
1912 low_pressure_mem.min_nr_free_pages, mi->field.nr_free_pages);
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08001913 }
Suren Baghdasaryan9926e572018-04-13 13:41:12 -07001914 low_pressure_mem.min_nr_free_pages = mi->field.nr_free_pages;
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08001915 }
1916 /*
1917 * Free memory at low vmpressure events occasionally gets spikes,
1918 * possibly a stale low vmpressure event with memory already
1919 * freed up (no memory pressure should have been reported).
Suren Baghdasaryan9926e572018-04-13 13:41:12 -07001920 * Ignore large jumps in max_nr_free_pages that would mess up our stats.
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08001921 */
Suren Baghdasaryan9926e572018-04-13 13:41:12 -07001922 if (low_pressure_mem.max_nr_free_pages == -1 ||
1923 (low_pressure_mem.max_nr_free_pages < mi->field.nr_free_pages &&
1924 mi->field.nr_free_pages - low_pressure_mem.max_nr_free_pages <
1925 low_pressure_mem.max_nr_free_pages * 0.1)) {
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08001926 if (debug_process_killing) {
Suren Baghdasaryan9926e572018-04-13 13:41:12 -07001927 ALOGI("Low pressure max memory update from %" PRId64 " to %" PRId64,
1928 low_pressure_mem.max_nr_free_pages, mi->field.nr_free_pages);
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08001929 }
Suren Baghdasaryan9926e572018-04-13 13:41:12 -07001930 low_pressure_mem.max_nr_free_pages = mi->field.nr_free_pages;
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08001931 }
1932}
1933
Suren Baghdasaryan96bf3a62017-12-08 12:58:52 -08001934enum vmpressure_level upgrade_level(enum vmpressure_level level) {
1935 return (enum vmpressure_level)((level < VMPRESS_LEVEL_CRITICAL) ?
1936 level + 1 : level);
1937}
1938
1939enum vmpressure_level downgrade_level(enum vmpressure_level level) {
1940 return (enum vmpressure_level)((level > VMPRESS_LEVEL_LOW) ?
1941 level - 1 : level);
1942}
1943
Tim Murraye7853f62018-10-25 17:05:41 -07001944static bool is_kill_pending(void) {
1945 char buf[24];
1946
1947 if (last_killed_pid < 0) {
1948 return false;
1949 }
1950
1951 snprintf(buf, sizeof(buf), "/proc/%d/", last_killed_pid);
1952 if (access(buf, F_OK) == 0) {
1953 return true;
1954 }
1955
1956 // reset last killed PID because there's nothing pending
1957 last_killed_pid = -1;
1958 return false;
1959}
1960
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07001961enum zone_watermark {
1962 WMARK_MIN = 0,
1963 WMARK_LOW,
1964 WMARK_HIGH,
1965 WMARK_NONE
1966};
1967
Suren Baghdasaryan4787ab42019-08-14 09:48:35 -07001968struct zone_watermarks {
1969 long high_wmark;
1970 long low_wmark;
1971 long min_wmark;
1972};
1973
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07001974/*
1975 * Returns lowest breached watermark or WMARK_NONE.
1976 */
Suren Baghdasaryan4787ab42019-08-14 09:48:35 -07001977static enum zone_watermark get_lowest_watermark(union meminfo *mi,
1978 struct zone_watermarks *watermarks)
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07001979{
Suren Baghdasaryan4787ab42019-08-14 09:48:35 -07001980 int64_t nr_free_pages = mi->field.nr_free_pages - mi->field.cma_free;
1981
1982 if (nr_free_pages < watermarks->min_wmark) {
1983 return WMARK_MIN;
1984 }
1985 if (nr_free_pages < watermarks->low_wmark) {
1986 return WMARK_LOW;
1987 }
1988 if (nr_free_pages < watermarks->high_wmark) {
1989 return WMARK_HIGH;
1990 }
1991 return WMARK_NONE;
1992}
1993
1994void calc_zone_watermarks(struct zoneinfo *zi, struct zone_watermarks *watermarks) {
1995 memset(watermarks, 0, sizeof(struct zone_watermarks));
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07001996
1997 for (int node_idx = 0; node_idx < zi->node_count; node_idx++) {
1998 struct zoneinfo_node *node = &zi->nodes[node_idx];
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07001999 for (int zone_idx = 0; zone_idx < node->zone_count; zone_idx++) {
2000 struct zoneinfo_zone *zone = &node->zones[zone_idx];
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002001
2002 if (!zone->fields.field.present) {
2003 continue;
2004 }
2005
Suren Baghdasaryan4787ab42019-08-14 09:48:35 -07002006 watermarks->high_wmark += zone->max_protection + zone->fields.field.high;
2007 watermarks->low_wmark += zone->max_protection + zone->fields.field.low;
2008 watermarks->min_wmark += zone->max_protection + zone->fields.field.min;
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002009 }
2010 }
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002011}
2012
2013static void mp_event_psi(int data, uint32_t events, struct polling_params *poll_params) {
2014 enum kill_reasons {
2015 NONE = -1, /* To denote no kill condition */
2016 PRESSURE_AFTER_KILL = 0,
2017 NOT_RESPONDING,
2018 LOW_SWAP_AND_THRASHING,
2019 LOW_MEM_AND_SWAP,
2020 LOW_MEM_AND_THRASHING,
2021 DIRECT_RECL_AND_THRASHING,
2022 KILL_REASON_COUNT
2023 };
2024 enum reclaim_state {
2025 NO_RECLAIM = 0,
2026 KSWAPD_RECLAIM,
2027 DIRECT_RECLAIM,
2028 };
2029 static int64_t init_ws_refault;
2030 static int64_t base_file_lru;
2031 static int64_t init_pgscan_kswapd;
2032 static int64_t init_pgscan_direct;
2033 static int64_t swap_low_threshold;
2034 static bool killing;
2035 static int thrashing_limit;
2036 static bool in_reclaim;
Suren Baghdasaryan4787ab42019-08-14 09:48:35 -07002037 static struct zone_watermarks watermarks;
2038 static struct timespec wmark_update_tm;
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002039
2040 union meminfo mi;
2041 union vmstat vs;
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002042 struct timespec curr_tm;
2043 int64_t thrashing = 0;
2044 bool swap_is_low = false;
2045 enum vmpressure_level level = (enum vmpressure_level)data;
2046 enum kill_reasons kill_reason = NONE;
2047 bool cycle_after_kill = false;
2048 enum reclaim_state reclaim = NO_RECLAIM;
2049 enum zone_watermark wmark = WMARK_NONE;
Suren Baghdasaryanfd7518f2019-07-15 15:50:17 -07002050 char kill_desc[LINE_MAX];
Suren Baghdasaryan4b750882019-09-19 15:27:21 -07002051 bool cut_thrashing_limit = false;
2052 int min_score_adj = 0;
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002053
2054 /* Skip while still killing a process */
2055 if (is_kill_pending()) {
2056 /* TODO: replace this quick polling with pidfd polling if kernel supports */
2057 goto no_kill;
2058 }
2059
2060 if (clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm) != 0) {
2061 ALOGE("Failed to get current time");
2062 return;
2063 }
2064
2065 if (vmstat_parse(&vs) < 0) {
2066 ALOGE("Failed to parse vmstat!");
2067 return;
2068 }
2069
2070 if (meminfo_parse(&mi) < 0) {
2071 ALOGE("Failed to parse meminfo!");
2072 return;
2073 }
2074
2075 /* Reset states after process got killed */
2076 if (killing) {
2077 killing = false;
2078 cycle_after_kill = true;
2079 /* Reset file-backed pagecache size and refault amounts after a kill */
2080 base_file_lru = vs.field.nr_inactive_file + vs.field.nr_active_file;
2081 init_ws_refault = vs.field.workingset_refault;
2082 }
2083
2084 /* Check free swap levels */
2085 if (swap_free_low_percentage) {
2086 if (!swap_low_threshold) {
2087 swap_low_threshold = mi.field.total_swap * swap_free_low_percentage / 100;
2088 }
2089 swap_is_low = mi.field.free_swap < swap_low_threshold;
2090 }
2091
2092 /* Identify reclaim state */
2093 if (vs.field.pgscan_direct > init_pgscan_direct) {
2094 init_pgscan_direct = vs.field.pgscan_direct;
2095 init_pgscan_kswapd = vs.field.pgscan_kswapd;
2096 reclaim = DIRECT_RECLAIM;
2097 } else if (vs.field.pgscan_kswapd > init_pgscan_kswapd) {
2098 init_pgscan_kswapd = vs.field.pgscan_kswapd;
2099 reclaim = KSWAPD_RECLAIM;
2100 } else {
2101 in_reclaim = false;
2102 /* Skip if system is not reclaiming */
2103 goto no_kill;
2104 }
2105
2106 if (!in_reclaim) {
2107 /* Record file-backed pagecache size when entering reclaim cycle */
2108 base_file_lru = vs.field.nr_inactive_file + vs.field.nr_active_file;
2109 init_ws_refault = vs.field.workingset_refault;
2110 thrashing_limit = thrashing_limit_pct;
2111 } else {
2112 /* Calculate what % of the file-backed pagecache refaulted so far */
2113 thrashing = (vs.field.workingset_refault - init_ws_refault) * 100 / base_file_lru;
2114 }
2115 in_reclaim = true;
2116
Suren Baghdasaryan4787ab42019-08-14 09:48:35 -07002117 /*
2118 * Refresh watermarks once per min in case user updated one of the margins.
2119 * TODO: b/140521024 replace this periodic update with an API for AMS to notify LMKD
2120 * that zone watermarks were changed by the system software.
2121 */
2122 if (watermarks.high_wmark == 0 || get_time_diff_ms(&wmark_update_tm, &curr_tm) > 60000) {
2123 struct zoneinfo zi;
2124
2125 if (zoneinfo_parse(&zi) < 0) {
2126 ALOGE("Failed to parse zoneinfo!");
2127 return;
2128 }
2129
2130 calc_zone_watermarks(&zi, &watermarks);
2131 wmark_update_tm = curr_tm;
2132 }
2133
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002134 /* Find out which watermark is breached if any */
Suren Baghdasaryan4787ab42019-08-14 09:48:35 -07002135 wmark = get_lowest_watermark(&mi, &watermarks);
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002136
2137 /*
2138 * TODO: move this logic into a separate function
2139 * Decide if killing a process is necessary and record the reason
2140 */
2141 if (cycle_after_kill && wmark < WMARK_LOW) {
2142 /*
2143 * Prevent kills not freeing enough memory which might lead to OOM kill.
2144 * This might happen when a process is consuming memory faster than reclaim can
2145 * free even after a kill. Mostly happens when running memory stress tests.
2146 */
2147 kill_reason = PRESSURE_AFTER_KILL;
Suren Baghdasaryanfd7518f2019-07-15 15:50:17 -07002148 strncpy(kill_desc, "min watermark is breached even after kill", sizeof(kill_desc));
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002149 } else if (level == VMPRESS_LEVEL_CRITICAL && events != 0) {
2150 /*
2151 * Device is too busy reclaiming memory which might lead to ANR.
2152 * Critical level is triggered when PSI complete stall (all tasks are blocked because
2153 * of the memory congestion) breaches the configured threshold.
2154 */
2155 kill_reason = NOT_RESPONDING;
Suren Baghdasaryanfd7518f2019-07-15 15:50:17 -07002156 strncpy(kill_desc, "device is not responding", sizeof(kill_desc));
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002157 } else if (swap_is_low && thrashing > thrashing_limit_pct) {
2158 /* Page cache is thrashing while swap is low */
2159 kill_reason = LOW_SWAP_AND_THRASHING;
Suren Baghdasaryanfd7518f2019-07-15 15:50:17 -07002160 snprintf(kill_desc, sizeof(kill_desc), "device is low on swap (%" PRId64
2161 "kB < %" PRId64 "kB) and thrashing (%" PRId64 "%%)",
2162 mi.field.free_swap * page_k, swap_low_threshold * page_k, thrashing);
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002163 } else if (swap_is_low && wmark < WMARK_HIGH) {
2164 /* Both free memory and swap are low */
2165 kill_reason = LOW_MEM_AND_SWAP;
Suren Baghdasaryanfd7518f2019-07-15 15:50:17 -07002166 snprintf(kill_desc, sizeof(kill_desc), "%s watermark is breached and swap is low (%"
2167 PRId64 "kB < %" PRId64 "kB)", wmark > WMARK_LOW ? "min" : "low",
2168 mi.field.free_swap * page_k, swap_low_threshold * page_k);
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002169 } else if (wmark < WMARK_HIGH && thrashing > thrashing_limit) {
2170 /* Page cache is thrashing while memory is low */
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002171 kill_reason = LOW_MEM_AND_THRASHING;
Suren Baghdasaryanfd7518f2019-07-15 15:50:17 -07002172 snprintf(kill_desc, sizeof(kill_desc), "%s watermark is breached and thrashing (%"
2173 PRId64 "%%)", wmark > WMARK_LOW ? "min" : "low", thrashing);
Suren Baghdasaryan4b750882019-09-19 15:27:21 -07002174 cut_thrashing_limit = true;
2175 /* Do not kill perceptible apps because of thrashing */
2176 min_score_adj = PERCEPTIBLE_APP_ADJ;
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002177 } else if (reclaim == DIRECT_RECLAIM && thrashing > thrashing_limit) {
2178 /* Page cache is thrashing while in direct reclaim (mostly happens on lowram devices) */
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002179 kill_reason = DIRECT_RECL_AND_THRASHING;
Suren Baghdasaryanfd7518f2019-07-15 15:50:17 -07002180 snprintf(kill_desc, sizeof(kill_desc), "device is in direct reclaim and thrashing (%"
2181 PRId64 "%%)", thrashing);
Suren Baghdasaryan4b750882019-09-19 15:27:21 -07002182 cut_thrashing_limit = true;
2183 /* Do not kill perceptible apps because of thrashing */
2184 min_score_adj = PERCEPTIBLE_APP_ADJ;
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002185 }
2186
2187 /* Kill a process if necessary */
2188 if (kill_reason != NONE) {
Suren Baghdasaryan4b750882019-09-19 15:27:21 -07002189 int pages_freed = find_and_kill_process(min_score_adj, kill_desc);
2190 if (pages_freed > 0) {
2191 killing = true;
2192 if (cut_thrashing_limit) {
2193 /*
2194 * Cut thrasing limit by thrashing_limit_decay_pct percentage of the current
2195 * thrashing limit until the system stops thrashing.
2196 */
2197 thrashing_limit = (thrashing_limit * (100 - thrashing_limit_decay_pct)) / 100;
2198 }
2199 }
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002200 meminfo_log(&mi);
2201 }
2202
2203no_kill:
2204 /*
2205 * Start polling after initial PSI event;
2206 * extend polling while device is in direct reclaim or process is being killed;
2207 * do not extend when kswapd reclaims because that might go on for a long time
2208 * without causing memory pressure
2209 */
2210 if (events || killing || reclaim == DIRECT_RECLAIM) {
2211 poll_params->update = POLLING_START;
2212 }
2213
2214 /* Decide the polling interval */
2215 if (swap_is_low || killing) {
2216 /* Fast polling during and after a kill or when swap is low */
2217 poll_params->polling_interval_ms = PSI_POLL_PERIOD_SHORT_MS;
2218 } else {
2219 /* By default use long intervals */
2220 poll_params->polling_interval_ms = PSI_POLL_PERIOD_LONG_MS;
2221 }
2222}
2223
Suren Baghdasaryanef3650f2019-07-15 14:50:49 -07002224static void mp_event_common(int data, uint32_t events, struct polling_params *poll_params) {
Todd Poynor3948f802013-07-09 19:35:14 -07002225 int ret;
2226 unsigned long long evcount;
Robert Beneac47f2992017-08-21 15:18:31 -07002227 int64_t mem_usage, memsw_usage;
Robert Benea6e8e7102017-09-13 15:20:30 -07002228 int64_t mem_pressure;
Suren Baghdasaryane82e15c2018-01-04 09:16:21 -08002229 enum vmpressure_level lvl;
Suren Baghdasaryan9926e572018-04-13 13:41:12 -07002230 union meminfo mi;
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07002231 struct zoneinfo zi;
Suren Baghdasaryan36934412018-09-05 15:46:32 -07002232 struct timespec curr_tm;
Suren Baghdasaryan314a5052018-07-24 17:13:06 -07002233 static struct timespec last_kill_tm;
2234 static unsigned long kill_skip_count = 0;
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08002235 enum vmpressure_level level = (enum vmpressure_level)data;
Suren Baghdasaryanffdc4dd2018-04-13 13:53:43 -07002236 long other_free = 0, other_file = 0;
2237 int min_score_adj;
Suren Baghdasaryanffdc4dd2018-04-13 13:53:43 -07002238 int minfree = 0;
Suren Baghdasaryan6499e5e2018-04-13 12:43:41 -07002239 static struct reread_data mem_usage_file_data = {
2240 .filename = MEMCG_MEMORY_USAGE,
2241 .fd = -1,
2242 };
2243 static struct reread_data memsw_usage_file_data = {
2244 .filename = MEMCG_MEMORYSW_USAGE,
2245 .fd = -1,
2246 };
Todd Poynor3948f802013-07-09 19:35:14 -07002247
Suren Baghdasaryan77122e52019-01-08 12:54:48 -08002248 if (debug_process_killing) {
2249 ALOGI("%s memory pressure event is triggered", level_name[level]);
2250 }
2251
2252 if (!use_psi_monitors) {
2253 /*
2254 * Check all event counters from low to critical
2255 * and upgrade to the highest priority one. By reading
2256 * eventfd we also reset the event counters.
2257 */
2258 for (lvl = VMPRESS_LEVEL_LOW; lvl < VMPRESS_LEVEL_COUNT; lvl++) {
2259 if (mpevfd[lvl] != -1 &&
2260 TEMP_FAILURE_RETRY(read(mpevfd[lvl],
2261 &evcount, sizeof(evcount))) > 0 &&
2262 evcount > 0 && lvl > level) {
2263 level = lvl;
2264 }
Suren Baghdasaryane82e15c2018-01-04 09:16:21 -08002265 }
2266 }
Todd Poynor3948f802013-07-09 19:35:14 -07002267
Suren Baghdasaryanef3650f2019-07-15 14:50:49 -07002268 /* Start polling after initial PSI event */
2269 if (use_psi_monitors && events) {
2270 /* Override polling params only if current event is more critical */
2271 if (!poll_params->poll_handler || data > poll_params->poll_handler->data) {
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002272 poll_params->polling_interval_ms = PSI_POLL_PERIOD_SHORT_MS;
Suren Baghdasaryanef3650f2019-07-15 14:50:49 -07002273 poll_params->update = POLLING_START;
2274 }
2275 }
2276
Suren Baghdasaryan36934412018-09-05 15:46:32 -07002277 if (clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm) != 0) {
2278 ALOGE("Failed to get current time");
2279 return;
2280 }
2281
Suren Baghdasaryancaa2dc52018-01-17 17:28:01 -08002282 if (kill_timeout_ms) {
Tim Murraye7853f62018-10-25 17:05:41 -07002283 // If we're within the timeout, see if there's pending reclaim work
2284 // from the last killed process. If there is (as evidenced by
2285 // /proc/<pid> continuing to exist), skip killing for now.
2286 if ((get_time_diff_ms(&last_kill_tm, &curr_tm) < kill_timeout_ms) &&
2287 (low_ram_device || is_kill_pending())) {
Suren Baghdasaryan314a5052018-07-24 17:13:06 -07002288 kill_skip_count++;
Suren Baghdasaryancaa2dc52018-01-17 17:28:01 -08002289 return;
2290 }
2291 }
2292
Suren Baghdasaryan314a5052018-07-24 17:13:06 -07002293 if (kill_skip_count > 0) {
Suren Baghdasaryanda88b242018-05-10 16:10:56 -07002294 ALOGI("%lu memory pressure events were skipped after a kill!",
Suren Baghdasaryan314a5052018-07-24 17:13:06 -07002295 kill_skip_count);
2296 kill_skip_count = 0;
Suren Baghdasaryancaa2dc52018-01-17 17:28:01 -08002297 }
2298
Suren Baghdasaryanffdc4dd2018-04-13 13:53:43 -07002299 if (meminfo_parse(&mi) < 0 || zoneinfo_parse(&zi) < 0) {
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08002300 ALOGE("Failed to get free memory!");
2301 return;
2302 }
2303
Suren Baghdasaryanffdc4dd2018-04-13 13:53:43 -07002304 if (use_minfree_levels) {
2305 int i;
2306
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07002307 other_free = mi.field.nr_free_pages - zi.totalreserve_pages;
Suren Baghdasaryanffdc4dd2018-04-13 13:53:43 -07002308 if (mi.field.nr_file_pages > (mi.field.shmem + mi.field.unevictable + mi.field.swap_cached)) {
2309 other_file = (mi.field.nr_file_pages - mi.field.shmem -
2310 mi.field.unevictable - mi.field.swap_cached);
2311 } else {
2312 other_file = 0;
2313 }
2314
2315 min_score_adj = OOM_SCORE_ADJ_MAX + 1;
2316 for (i = 0; i < lowmem_targets_size; i++) {
2317 minfree = lowmem_minfree[i];
2318 if (other_free < minfree && other_file < minfree) {
2319 min_score_adj = lowmem_adj[i];
2320 break;
2321 }
2322 }
2323
Suren Baghdasaryan20686f02018-05-18 14:42:00 -07002324 if (min_score_adj == OOM_SCORE_ADJ_MAX + 1) {
2325 if (debug_process_killing) {
2326 ALOGI("Ignore %s memory pressure event "
2327 "(free memory=%ldkB, cache=%ldkB, limit=%ldkB)",
2328 level_name[level], other_free * page_k, other_file * page_k,
2329 (long)lowmem_minfree[lowmem_targets_size - 1] * page_k);
2330 }
Suren Baghdasaryanffdc4dd2018-04-13 13:53:43 -07002331 return;
Suren Baghdasaryan20686f02018-05-18 14:42:00 -07002332 }
Suren Baghdasaryanffdc4dd2018-04-13 13:53:43 -07002333
Suren Baghdasaryanffdc4dd2018-04-13 13:53:43 -07002334 goto do_kill;
2335 }
2336
Suren Baghdasaryan9926e572018-04-13 13:41:12 -07002337 if (level == VMPRESS_LEVEL_LOW) {
2338 record_low_pressure_levels(&mi);
2339 }
2340
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08002341 if (level_oomadj[level] > OOM_SCORE_ADJ_MAX) {
2342 /* Do not monitor this pressure level */
2343 return;
2344 }
2345
Suren Baghdasaryan6499e5e2018-04-13 12:43:41 -07002346 if ((mem_usage = get_memory_usage(&mem_usage_file_data)) < 0) {
2347 goto do_kill;
2348 }
2349 if ((memsw_usage = get_memory_usage(&memsw_usage_file_data)) < 0) {
Suren Baghdasaryan96bf3a62017-12-08 12:58:52 -08002350 goto do_kill;
Robert Benea6e8e7102017-09-13 15:20:30 -07002351 }
Robert Beneac47f2992017-08-21 15:18:31 -07002352
Robert Benea6e8e7102017-09-13 15:20:30 -07002353 // Calculate percent for swappinness.
2354 mem_pressure = (mem_usage * 100) / memsw_usage;
2355
Suren Baghdasaryan96bf3a62017-12-08 12:58:52 -08002356 if (enable_pressure_upgrade && level != VMPRESS_LEVEL_CRITICAL) {
Robert Benea6e8e7102017-09-13 15:20:30 -07002357 // We are swapping too much.
2358 if (mem_pressure < upgrade_pressure) {
Suren Baghdasaryan96bf3a62017-12-08 12:58:52 -08002359 level = upgrade_level(level);
2360 if (debug_process_killing) {
2361 ALOGI("Event upgraded to %s", level_name[level]);
2362 }
Robert Beneac47f2992017-08-21 15:18:31 -07002363 }
2364 }
2365
Vic Yang360a1132018-08-07 10:18:22 -07002366 // If we still have enough swap space available, check if we want to
2367 // ignore/downgrade pressure events.
2368 if (mi.field.free_swap >=
2369 mi.field.total_swap * swap_free_low_percentage / 100) {
2370 // If the pressure is larger than downgrade_pressure lmk will not
2371 // kill any process, since enough memory is available.
2372 if (mem_pressure > downgrade_pressure) {
2373 if (debug_process_killing) {
2374 ALOGI("Ignore %s memory pressure", level_name[level]);
2375 }
2376 return;
2377 } else if (level == VMPRESS_LEVEL_CRITICAL && mem_pressure > upgrade_pressure) {
2378 if (debug_process_killing) {
2379 ALOGI("Downgrade critical memory pressure");
2380 }
2381 // Downgrade event, since enough memory available.
2382 level = downgrade_level(level);
Robert Benea6e8e7102017-09-13 15:20:30 -07002383 }
Robert Benea6e8e7102017-09-13 15:20:30 -07002384 }
2385
Suren Baghdasaryan96bf3a62017-12-08 12:58:52 -08002386do_kill:
Suren Baghdasaryanff61afb2018-04-13 11:45:38 -07002387 if (low_ram_device) {
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08002388 /* For Go devices kill only one task */
Suren Baghdasaryanfd7518f2019-07-15 15:50:17 -07002389 if (find_and_kill_process(level_oomadj[level], NULL) == 0) {
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08002390 if (debug_process_killing) {
2391 ALOGI("Nothing to kill");
2392 }
Suren Baghdasaryan282ad1a2018-07-26 16:34:27 -07002393 } else {
2394 meminfo_log(&mi);
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08002395 }
2396 } else {
Suren Baghdasaryanffdc4dd2018-04-13 13:53:43 -07002397 int pages_freed;
Suren Baghdasaryan36934412018-09-05 15:46:32 -07002398 static struct timespec last_report_tm;
2399 static unsigned long report_skip_count = 0;
Suren Baghdasaryanffdc4dd2018-04-13 13:53:43 -07002400
2401 if (!use_minfree_levels) {
Suren Baghdasaryanffdc4dd2018-04-13 13:53:43 -07002402 /* Free up enough memory to downgrate the memory pressure to low level */
Suren Baghdasaryanf81b5f42018-10-26 11:32:15 -07002403 if (mi.field.nr_free_pages >= low_pressure_mem.max_nr_free_pages) {
Suren Baghdasaryanffdc4dd2018-04-13 13:53:43 -07002404 if (debug_process_killing) {
2405 ALOGI("Ignoring pressure since more memory is "
2406 "available (%" PRId64 ") than watermark (%" PRId64 ")",
2407 mi.field.nr_free_pages, low_pressure_mem.max_nr_free_pages);
2408 }
2409 return;
2410 }
2411 min_score_adj = level_oomadj[level];
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08002412 }
2413
Suren Baghdasaryanfd7518f2019-07-15 15:50:17 -07002414 pages_freed = find_and_kill_process(min_score_adj, NULL);
Suren Baghdasaryanda88b242018-05-10 16:10:56 -07002415
Suren Baghdasaryan36934412018-09-05 15:46:32 -07002416 if (pages_freed == 0) {
2417 /* Rate limit kill reports when nothing was reclaimed */
2418 if (get_time_diff_ms(&last_report_tm, &curr_tm) < FAIL_REPORT_RLIMIT_MS) {
2419 report_skip_count++;
Suren Baghdasaryan314a5052018-07-24 17:13:06 -07002420 return;
2421 }
Tim Murraye7853f62018-10-25 17:05:41 -07002422 } else {
2423 /* If we killed anything, update the last killed timestamp. */
2424 last_kill_tm = curr_tm;
Robert Beneacaeaa652017-08-11 16:03:20 -07002425 }
Suren Baghdasaryan36934412018-09-05 15:46:32 -07002426
2427 /* Log meminfo whenever we kill or when report rate limit allows */
2428 meminfo_log(&mi);
Suren Baghdasaryan36934412018-09-05 15:46:32 -07002429
2430 if (use_minfree_levels) {
Suren Baghdasaryanf81b5f42018-10-26 11:32:15 -07002431 ALOGI("Reclaimed %ldkB, cache(%ldkB) and "
Suren Baghdasaryan36934412018-09-05 15:46:32 -07002432 "free(%" PRId64 "kB)-reserved(%" PRId64 "kB) below min(%ldkB) for oom_adj %d",
Suren Baghdasaryanf81b5f42018-10-26 11:32:15 -07002433 pages_freed * page_k,
Suren Baghdasaryan36934412018-09-05 15:46:32 -07002434 other_file * page_k, mi.field.nr_free_pages * page_k,
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07002435 zi.totalreserve_pages * page_k,
Suren Baghdasaryan36934412018-09-05 15:46:32 -07002436 minfree * page_k, min_score_adj);
2437 } else {
Suren Baghdasaryanf81b5f42018-10-26 11:32:15 -07002438 ALOGI("Reclaimed %ldkB at oom_adj %d",
2439 pages_freed * page_k, min_score_adj);
Suren Baghdasaryan36934412018-09-05 15:46:32 -07002440 }
2441
2442 if (report_skip_count > 0) {
2443 ALOGI("Suppressed %lu failed kill reports", report_skip_count);
2444 report_skip_count = 0;
2445 }
2446
2447 last_report_tm = curr_tm;
Colin Crossf8857cc2014-07-11 17:16:56 -07002448 }
Todd Poynor3948f802013-07-09 19:35:14 -07002449}
2450
Suren Baghdasaryan844f26b2019-07-15 15:42:09 -07002451static bool init_mp_psi(enum vmpressure_level level, bool use_new_strategy) {
2452 int fd;
2453
2454 /* Do not register a handler if threshold_ms is not set */
2455 if (!psi_thresholds[level].threshold_ms) {
2456 return true;
2457 }
2458
2459 fd = init_psi_monitor(psi_thresholds[level].stall_type,
Suren Baghdasaryan77122e52019-01-08 12:54:48 -08002460 psi_thresholds[level].threshold_ms * US_PER_MS,
2461 PSI_WINDOW_SIZE_MS * US_PER_MS);
2462
2463 if (fd < 0) {
2464 return false;
2465 }
2466
Suren Baghdasaryan844f26b2019-07-15 15:42:09 -07002467 vmpressure_hinfo[level].handler = use_new_strategy ? mp_event_psi : mp_event_common;
Suren Baghdasaryan77122e52019-01-08 12:54:48 -08002468 vmpressure_hinfo[level].data = level;
2469 if (register_psi_monitor(epollfd, fd, &vmpressure_hinfo[level]) < 0) {
2470 destroy_psi_monitor(fd);
2471 return false;
2472 }
2473 maxevents++;
2474 mpevfd[level] = fd;
2475
2476 return true;
2477}
2478
2479static void destroy_mp_psi(enum vmpressure_level level) {
2480 int fd = mpevfd[level];
2481
2482 if (unregister_psi_monitor(epollfd, fd) < 0) {
2483 ALOGE("Failed to unregister psi monitor for %s memory pressure; errno=%d",
2484 level_name[level], errno);
2485 }
2486 destroy_psi_monitor(fd);
2487 mpevfd[level] = -1;
2488}
2489
2490static bool init_psi_monitors() {
Suren Baghdasaryan844f26b2019-07-15 15:42:09 -07002491 /*
2492 * When PSI is used on low-ram devices or on high-end devices without memfree levels
2493 * use new kill strategy based on zone watermarks, free swap and thrashing stats
2494 */
2495 bool use_new_strategy =
2496 property_get_bool("ro.lmk.use_new_strategy", low_ram_device || !use_minfree_levels);
2497
2498 /* In default PSI mode override stall amounts using system properties */
2499 if (use_new_strategy) {
2500 /* Do not use low pressure level */
2501 psi_thresholds[VMPRESS_LEVEL_LOW].threshold_ms = 0;
2502 psi_thresholds[VMPRESS_LEVEL_MEDIUM].threshold_ms = psi_partial_stall_ms;
2503 psi_thresholds[VMPRESS_LEVEL_CRITICAL].threshold_ms = psi_complete_stall_ms;
2504 }
2505
2506 if (!init_mp_psi(VMPRESS_LEVEL_LOW, use_new_strategy)) {
Suren Baghdasaryan77122e52019-01-08 12:54:48 -08002507 return false;
2508 }
Suren Baghdasaryan844f26b2019-07-15 15:42:09 -07002509 if (!init_mp_psi(VMPRESS_LEVEL_MEDIUM, use_new_strategy)) {
Suren Baghdasaryan77122e52019-01-08 12:54:48 -08002510 destroy_mp_psi(VMPRESS_LEVEL_LOW);
2511 return false;
2512 }
Suren Baghdasaryan844f26b2019-07-15 15:42:09 -07002513 if (!init_mp_psi(VMPRESS_LEVEL_CRITICAL, use_new_strategy)) {
Suren Baghdasaryan77122e52019-01-08 12:54:48 -08002514 destroy_mp_psi(VMPRESS_LEVEL_MEDIUM);
2515 destroy_mp_psi(VMPRESS_LEVEL_LOW);
2516 return false;
2517 }
2518 return true;
2519}
2520
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08002521static bool init_mp_common(enum vmpressure_level level) {
Todd Poynor3948f802013-07-09 19:35:14 -07002522 int mpfd;
2523 int evfd;
2524 int evctlfd;
2525 char buf[256];
2526 struct epoll_event epev;
2527 int ret;
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08002528 int level_idx = (int)level;
2529 const char *levelstr = level_name[level_idx];
Suren Baghdasaryan96bf3a62017-12-08 12:58:52 -08002530
Mark Salyzyn64d97d82018-04-09 09:50:32 -07002531 /* gid containing AID_SYSTEM required */
Nick Kralevichc68c8862015-12-18 20:52:37 -08002532 mpfd = open(MEMCG_SYSFS_PATH "memory.pressure_level", O_RDONLY | O_CLOEXEC);
Todd Poynor3948f802013-07-09 19:35:14 -07002533 if (mpfd < 0) {
2534 ALOGI("No kernel memory.pressure_level support (errno=%d)", errno);
2535 goto err_open_mpfd;
2536 }
2537
Nick Kralevichc68c8862015-12-18 20:52:37 -08002538 evctlfd = open(MEMCG_SYSFS_PATH "cgroup.event_control", O_WRONLY | O_CLOEXEC);
Todd Poynor3948f802013-07-09 19:35:14 -07002539 if (evctlfd < 0) {
2540 ALOGI("No kernel memory cgroup event control (errno=%d)", errno);
2541 goto err_open_evctlfd;
2542 }
2543
Nick Kralevichc68c8862015-12-18 20:52:37 -08002544 evfd = eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC);
Todd Poynor3948f802013-07-09 19:35:14 -07002545 if (evfd < 0) {
2546 ALOGE("eventfd failed for level %s; errno=%d", levelstr, errno);
2547 goto err_eventfd;
2548 }
2549
2550 ret = snprintf(buf, sizeof(buf), "%d %d %s", evfd, mpfd, levelstr);
2551 if (ret >= (ssize_t)sizeof(buf)) {
2552 ALOGE("cgroup.event_control line overflow for level %s", levelstr);
2553 goto err;
2554 }
2555
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08002556 ret = TEMP_FAILURE_RETRY(write(evctlfd, buf, strlen(buf) + 1));
Todd Poynor3948f802013-07-09 19:35:14 -07002557 if (ret == -1) {
2558 ALOGE("cgroup.event_control write failed for level %s; errno=%d",
2559 levelstr, errno);
2560 goto err;
2561 }
2562
2563 epev.events = EPOLLIN;
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08002564 /* use data to store event level */
2565 vmpressure_hinfo[level_idx].data = level_idx;
2566 vmpressure_hinfo[level_idx].handler = mp_event_common;
2567 epev.data.ptr = (void *)&vmpressure_hinfo[level_idx];
Todd Poynor3948f802013-07-09 19:35:14 -07002568 ret = epoll_ctl(epollfd, EPOLL_CTL_ADD, evfd, &epev);
2569 if (ret == -1) {
2570 ALOGE("epoll_ctl for level %s failed; errno=%d", levelstr, errno);
2571 goto err;
2572 }
2573 maxevents++;
Suren Baghdasaryan96bf3a62017-12-08 12:58:52 -08002574 mpevfd[level] = evfd;
Suren Baghdasaryan1bd2fc42018-01-04 08:54:53 -08002575 close(evctlfd);
Suren Baghdasaryan96bf3a62017-12-08 12:58:52 -08002576 return true;
Todd Poynor3948f802013-07-09 19:35:14 -07002577
2578err:
2579 close(evfd);
2580err_eventfd:
2581 close(evctlfd);
2582err_open_evctlfd:
2583 close(mpfd);
2584err_open_mpfd:
Suren Baghdasaryan96bf3a62017-12-08 12:58:52 -08002585 return false;
Robert Benea673e2762017-06-01 16:32:31 -07002586}
2587
Jim Blackler3947c932019-04-26 11:18:29 +01002588#ifdef LMKD_LOG_STATS
2589static int kernel_poll_fd = -1;
Jim Blackler3947c932019-04-26 11:18:29 +01002590static void poll_kernel() {
2591 if (kernel_poll_fd == -1) {
2592 // not waiting
2593 return;
2594 }
2595
2596 while (1) {
2597 char rd_buf[256];
2598 int bytes_read =
2599 TEMP_FAILURE_RETRY(pread(kernel_poll_fd, (void*)rd_buf, sizeof(rd_buf), 0));
2600 if (bytes_read <= 0) break;
2601 rd_buf[bytes_read] = '\0';
2602
2603 int64_t pid;
2604 int64_t uid;
2605 int64_t group_leader_pid;
2606 int64_t min_flt;
2607 int64_t maj_flt;
2608 int64_t rss_in_pages;
2609 int16_t oom_score_adj;
2610 int16_t min_score_adj;
2611 int64_t starttime;
2612 char* taskname = 0;
2613 int fields_read = sscanf(rd_buf,
2614 "%" SCNd64 " %" SCNd64 " %" SCNd64 " %" SCNd64 " %" SCNd64
2615 " %" SCNd64 " %" SCNd16 " %" SCNd16 " %" SCNd64 "\n%m[^\n]",
2616 &pid, &uid, &group_leader_pid, &min_flt, &maj_flt, &rss_in_pages,
2617 &oom_score_adj, &min_score_adj, &starttime, &taskname);
2618
2619 /* only the death of the group leader process is logged */
2620 if (fields_read == 10 && group_leader_pid == pid) {
2621 int64_t process_start_time_ns = starttime * (NS_PER_SEC / sysconf(_SC_CLK_TCK));
Jim Blacklerd2da8142019-09-10 15:30:05 +01002622 stats_write_lmk_kill_occurred_pid(log_ctx, LMK_KILL_OCCURRED, uid, pid, oom_score_adj,
2623 min_flt, maj_flt, rss_in_pages * PAGE_SIZE, 0, 0,
2624 process_start_time_ns, min_score_adj);
Jim Blackler3947c932019-04-26 11:18:29 +01002625 }
2626
2627 free(taskname);
2628 }
2629}
2630
2631static struct event_handler_info kernel_poll_hinfo = {0, poll_kernel};
2632
2633static void init_poll_kernel() {
2634 struct epoll_event epev;
2635 kernel_poll_fd =
2636 TEMP_FAILURE_RETRY(open("/proc/lowmemorykiller", O_RDONLY | O_NONBLOCK | O_CLOEXEC));
2637
2638 if (kernel_poll_fd < 0) {
2639 ALOGE("kernel lmk event file could not be opened; errno=%d", kernel_poll_fd);
2640 return;
2641 }
2642
2643 epev.events = EPOLLIN;
2644 epev.data.ptr = (void*)&kernel_poll_hinfo;
2645 if (epoll_ctl(epollfd, EPOLL_CTL_ADD, kernel_poll_fd, &epev) != 0) {
2646 ALOGE("epoll_ctl for lmk events failed; errno=%d", errno);
2647 close(kernel_poll_fd);
2648 kernel_poll_fd = -1;
2649 } else {
2650 maxevents++;
2651 }
2652}
2653#endif
2654
Todd Poynor3948f802013-07-09 19:35:14 -07002655static int init(void) {
Suren Baghdasaryana77b3272019-07-15 13:35:04 -07002656 struct reread_data file_data = {
2657 .filename = ZONEINFO_PATH,
2658 .fd = -1,
2659 };
Todd Poynor3948f802013-07-09 19:35:14 -07002660 struct epoll_event epev;
2661 int i;
2662 int ret;
2663
2664 page_k = sysconf(_SC_PAGESIZE);
2665 if (page_k == -1)
2666 page_k = PAGE_SIZE;
2667 page_k /= 1024;
2668
2669 epollfd = epoll_create(MAX_EPOLL_EVENTS);
2670 if (epollfd == -1) {
2671 ALOGE("epoll_create failed (errno=%d)", errno);
2672 return -1;
2673 }
2674
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08002675 // mark data connections as not connected
2676 for (int i = 0; i < MAX_DATA_CONN; i++) {
2677 data_sock[i].sock = -1;
2678 }
2679
2680 ctrl_sock.sock = android_get_control_socket("lmkd");
2681 if (ctrl_sock.sock < 0) {
Todd Poynor3948f802013-07-09 19:35:14 -07002682 ALOGE("get lmkd control socket failed");
2683 return -1;
2684 }
2685
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08002686 ret = listen(ctrl_sock.sock, MAX_DATA_CONN);
Todd Poynor3948f802013-07-09 19:35:14 -07002687 if (ret < 0) {
2688 ALOGE("lmkd control socket listen failed (errno=%d)", errno);
2689 return -1;
2690 }
2691
2692 epev.events = EPOLLIN;
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08002693 ctrl_sock.handler_info.handler = ctrl_connect_handler;
2694 epev.data.ptr = (void *)&(ctrl_sock.handler_info);
2695 if (epoll_ctl(epollfd, EPOLL_CTL_ADD, ctrl_sock.sock, &epev) == -1) {
Todd Poynor3948f802013-07-09 19:35:14 -07002696 ALOGE("epoll_ctl for lmkd control socket failed (errno=%d)", errno);
2697 return -1;
2698 }
2699 maxevents++;
2700
Robert Benea164baeb2017-09-11 16:53:28 -07002701 has_inkernel_module = !access(INKERNEL_MINFREE_PATH, W_OK);
Suren Baghdasaryan979591b2018-01-18 17:27:30 -08002702 use_inkernel_interface = has_inkernel_module;
Todd Poynor3948f802013-07-09 19:35:14 -07002703
2704 if (use_inkernel_interface) {
2705 ALOGI("Using in-kernel low memory killer interface");
Jim Blackler3947c932019-04-26 11:18:29 +01002706#ifdef LMKD_LOG_STATS
2707 if (enable_stats_log) {
2708 init_poll_kernel();
2709 }
2710#endif
Todd Poynor3948f802013-07-09 19:35:14 -07002711 } else {
Suren Baghdasaryan77122e52019-01-08 12:54:48 -08002712 /* Try to use psi monitor first if kernel has it */
2713 use_psi_monitors = property_get_bool("ro.lmk.use_psi", true) &&
2714 init_psi_monitors();
2715 /* Fall back to vmpressure */
2716 if (!use_psi_monitors &&
2717 (!init_mp_common(VMPRESS_LEVEL_LOW) ||
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08002718 !init_mp_common(VMPRESS_LEVEL_MEDIUM) ||
Suren Baghdasaryan77122e52019-01-08 12:54:48 -08002719 !init_mp_common(VMPRESS_LEVEL_CRITICAL))) {
Todd Poynor3948f802013-07-09 19:35:14 -07002720 ALOGE("Kernel does not support memory pressure events or in-kernel low memory killer");
Suren Baghdasaryan96bf3a62017-12-08 12:58:52 -08002721 return -1;
2722 }
Suren Baghdasaryan77122e52019-01-08 12:54:48 -08002723 if (use_psi_monitors) {
2724 ALOGI("Using psi monitors for memory pressure detection");
2725 } else {
2726 ALOGI("Using vmpressure for memory pressure detection");
2727 }
Todd Poynor3948f802013-07-09 19:35:14 -07002728 }
2729
Chong Zhang0a4acdf2015-10-14 16:19:53 -07002730 for (i = 0; i <= ADJTOSLOT(OOM_SCORE_ADJ_MAX); i++) {
Todd Poynor3948f802013-07-09 19:35:14 -07002731 procadjslot_list[i].next = &procadjslot_list[i];
2732 procadjslot_list[i].prev = &procadjslot_list[i];
2733 }
2734
Suren Baghdasaryand4a29902018-10-12 11:07:40 -07002735 memset(killcnt_idx, KILLCNT_INVALID_IDX, sizeof(killcnt_idx));
2736
Suren Baghdasaryana77b3272019-07-15 13:35:04 -07002737 /*
2738 * Read zoneinfo as the biggest file we read to create and size the initial
2739 * read buffer and avoid memory re-allocations during memory pressure
2740 */
2741 if (reread_file(&file_data) == NULL) {
2742 ALOGE("Failed to read %s: %s", file_data.filename, strerror(errno));
2743 }
2744
Todd Poynor3948f802013-07-09 19:35:14 -07002745 return 0;
2746}
2747
2748static void mainloop(void) {
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08002749 struct event_handler_info* handler_info;
Suren Baghdasaryanef3650f2019-07-15 14:50:49 -07002750 struct polling_params poll_params;
2751 struct timespec curr_tm;
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08002752 struct epoll_event *evt;
Suren Baghdasaryan77122e52019-01-08 12:54:48 -08002753 long delay = -1;
Suren Baghdasaryanef3650f2019-07-15 14:50:49 -07002754
2755 poll_params.poll_handler = NULL;
2756 poll_params.update = POLLING_DO_NOT_CHANGE;
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08002757
Todd Poynor3948f802013-07-09 19:35:14 -07002758 while (1) {
2759 struct epoll_event events[maxevents];
2760 int nevents;
2761 int i;
2762
Suren Baghdasaryanef3650f2019-07-15 14:50:49 -07002763 if (poll_params.poll_handler) {
Suren Baghdasaryan77122e52019-01-08 12:54:48 -08002764 /* Calculate next timeout */
2765 clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm);
Suren Baghdasaryanef3650f2019-07-15 14:50:49 -07002766 delay = get_time_diff_ms(&poll_params.last_poll_tm, &curr_tm);
2767 delay = (delay < poll_params.polling_interval_ms) ?
2768 poll_params.polling_interval_ms - delay : poll_params.polling_interval_ms;
Suren Baghdasaryan77122e52019-01-08 12:54:48 -08002769
2770 /* Wait for events until the next polling timeout */
2771 nevents = epoll_wait(epollfd, events, maxevents, delay);
2772
2773 clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm);
Suren Baghdasaryanef3650f2019-07-15 14:50:49 -07002774 if (get_time_diff_ms(&poll_params.last_poll_tm, &curr_tm) >=
2775 poll_params.polling_interval_ms) {
2776 /* Set input params for the call */
2777 poll_params.poll_handler->handler(poll_params.poll_handler->data, 0, &poll_params);
2778 poll_params.last_poll_tm = curr_tm;
2779
2780 if (poll_params.update != POLLING_DO_NOT_CHANGE) {
2781 switch (poll_params.update) {
2782 case POLLING_START:
2783 poll_params.poll_start_tm = curr_tm;
2784 break;
2785 case POLLING_STOP:
2786 poll_params.poll_handler = NULL;
2787 break;
2788 default:
2789 break;
2790 }
2791 poll_params.update = POLLING_DO_NOT_CHANGE;
2792 } else {
2793 if (get_time_diff_ms(&poll_params.poll_start_tm, &curr_tm) >
2794 PSI_WINDOW_SIZE_MS) {
2795 /* Polled for the duration of PSI window, time to stop */
2796 poll_params.poll_handler = NULL;
2797 }
2798 }
Suren Baghdasaryan77122e52019-01-08 12:54:48 -08002799 }
2800 } else {
2801 /* Wait for events with no timeout */
2802 nevents = epoll_wait(epollfd, events, maxevents, -1);
2803 }
Todd Poynor3948f802013-07-09 19:35:14 -07002804
2805 if (nevents == -1) {
2806 if (errno == EINTR)
2807 continue;
2808 ALOGE("epoll_wait failed (errno=%d)", errno);
2809 continue;
2810 }
2811
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08002812 /*
2813 * First pass to see if any data socket connections were dropped.
2814 * Dropped connection should be handled before any other events
2815 * to deallocate data connection and correctly handle cases when
2816 * connection gets dropped and reestablished in the same epoll cycle.
2817 * In such cases it's essential to handle connection closures first.
2818 */
2819 for (i = 0, evt = &events[0]; i < nevents; ++i, evt++) {
2820 if ((evt->events & EPOLLHUP) && evt->data.ptr) {
2821 ALOGI("lmkd data connection dropped");
2822 handler_info = (struct event_handler_info*)evt->data.ptr;
2823 ctrl_data_close(handler_info->data);
2824 }
2825 }
2826
2827 /* Second pass to handle all other events */
2828 for (i = 0, evt = &events[0]; i < nevents; ++i, evt++) {
Suren Baghdasaryanef3650f2019-07-15 14:50:49 -07002829 if (evt->events & EPOLLERR) {
Todd Poynor3948f802013-07-09 19:35:14 -07002830 ALOGD("EPOLLERR on event #%d", i);
Suren Baghdasaryanef3650f2019-07-15 14:50:49 -07002831 }
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08002832 if (evt->events & EPOLLHUP) {
2833 /* This case was handled in the first pass */
2834 continue;
2835 }
2836 if (evt->data.ptr) {
2837 handler_info = (struct event_handler_info*)evt->data.ptr;
Suren Baghdasaryanef3650f2019-07-15 14:50:49 -07002838 /* Set input params for the call */
2839 handler_info->handler(handler_info->data, evt->events, &poll_params);
Suren Baghdasaryan77122e52019-01-08 12:54:48 -08002840
Suren Baghdasaryanef3650f2019-07-15 14:50:49 -07002841 if (poll_params.update != POLLING_DO_NOT_CHANGE) {
2842 switch (poll_params.update) {
2843 case POLLING_START:
2844 /*
2845 * Poll for the duration of PSI_WINDOW_SIZE_MS after the
2846 * initial PSI event because psi events are rate-limited
2847 * at one per sec.
2848 */
2849 clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm);
2850 poll_params.poll_start_tm = poll_params.last_poll_tm = curr_tm;
2851 poll_params.poll_handler = handler_info;
2852 break;
2853 case POLLING_STOP:
2854 poll_params.poll_handler = NULL;
2855 break;
2856 default:
2857 break;
2858 }
2859 poll_params.update = POLLING_DO_NOT_CHANGE;
Suren Baghdasaryan77122e52019-01-08 12:54:48 -08002860 }
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08002861 }
Todd Poynor3948f802013-07-09 19:35:14 -07002862 }
2863 }
2864}
2865
Mark Salyzyne6ed68b2014-04-30 13:36:35 -07002866int main(int argc __unused, char **argv __unused) {
Colin Cross1a0d9be2014-07-14 14:31:15 -07002867 struct sched_param param = {
2868 .sched_priority = 1,
2869 };
2870
Suren Baghdasaryan96bf3a62017-12-08 12:58:52 -08002871 /* By default disable low level vmpressure events */
2872 level_oomadj[VMPRESS_LEVEL_LOW] =
2873 property_get_int32("ro.lmk.low", OOM_SCORE_ADJ_MAX + 1);
2874 level_oomadj[VMPRESS_LEVEL_MEDIUM] =
2875 property_get_int32("ro.lmk.medium", 800);
2876 level_oomadj[VMPRESS_LEVEL_CRITICAL] =
2877 property_get_int32("ro.lmk.critical", 0);
Robert Beneacaeaa652017-08-11 16:03:20 -07002878 debug_process_killing = property_get_bool("ro.lmk.debug", false);
Suren Baghdasaryanad2fd912017-12-08 13:08:41 -08002879
2880 /* By default disable upgrade/downgrade logic */
2881 enable_pressure_upgrade =
2882 property_get_bool("ro.lmk.critical_upgrade", false);
2883 upgrade_pressure =
2884 (int64_t)property_get_int32("ro.lmk.upgrade_pressure", 100);
2885 downgrade_pressure =
2886 (int64_t)property_get_int32("ro.lmk.downgrade_pressure", 100);
Suren Baghdasaryan662492a2017-12-08 13:17:06 -08002887 kill_heaviest_task =
Suren Baghdasaryan818b59b2018-04-13 11:49:54 -07002888 property_get_bool("ro.lmk.kill_heaviest_task", false);
Suren Baghdasaryanff61afb2018-04-13 11:45:38 -07002889 low_ram_device = property_get_bool("ro.config.low_ram", false);
Suren Baghdasaryancaa2dc52018-01-17 17:28:01 -08002890 kill_timeout_ms =
2891 (unsigned long)property_get_int32("ro.lmk.kill_timeout_ms", 0);
Suren Baghdasaryanffdc4dd2018-04-13 13:53:43 -07002892 use_minfree_levels =
2893 property_get_bool("ro.lmk.use_minfree_levels", false);
Suren Baghdasaryance13cb52018-06-19 18:38:12 -07002894 per_app_memcg =
2895 property_get_bool("ro.config.per_app_memcg", low_ram_device);
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002896 swap_free_low_percentage = clamp(0, 100, property_get_int32("ro.lmk.swap_free_low_percentage",
2897 low_ram_device ? DEF_LOW_SWAP_LOWRAM : DEF_LOW_SWAP));
Suren Baghdasaryan844f26b2019-07-15 15:42:09 -07002898 psi_partial_stall_ms = property_get_int32("ro.lmk.psi_partial_stall_ms",
2899 low_ram_device ? DEF_PARTIAL_STALL_LOWRAM : DEF_PARTIAL_STALL);
2900 psi_complete_stall_ms = property_get_int32("ro.lmk.psi_complete_stall_ms",
2901 DEF_COMPLETE_STALL);
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002902 thrashing_limit_pct = max(0, property_get_int32("ro.lmk.thrashing_limit",
2903 low_ram_device ? DEF_THRASHING_LOWRAM : DEF_THRASHING));
2904 thrashing_limit_decay_pct = clamp(0, 100, property_get_int32("ro.lmk.thrashing_limit_decay",
2905 low_ram_device ? DEF_THRASHING_DECAY_LOWRAM : DEF_THRASHING_DECAY));
Robert Benea58891d52017-07-31 17:15:20 -07002906
Suren Baghdasaryan282ad1a2018-07-26 16:34:27 -07002907 ctx = create_android_logger(MEMINFO_LOG_TAG);
2908
Rajeev Kumar70450032018-01-31 17:54:56 -08002909#ifdef LMKD_LOG_STATS
Rajeev Kumar1c669f72018-03-09 15:20:56 -08002910 statslog_init(&log_ctx, &enable_stats_log);
Rajeev Kumar70450032018-01-31 17:54:56 -08002911#endif
2912
Mark Salyzyn721d7c72018-03-21 12:24:58 -07002913 if (!init()) {
2914 if (!use_inkernel_interface) {
2915 /*
2916 * MCL_ONFAULT pins pages as they fault instead of loading
2917 * everything immediately all at once. (Which would be bad,
2918 * because as of this writing, we have a lot of mapped pages we
2919 * never use.) Old kernels will see MCL_ONFAULT and fail with
2920 * EINVAL; we ignore this failure.
2921 *
2922 * N.B. read the man page for mlockall. MCL_CURRENT | MCL_ONFAULT
2923 * pins ⊆ MCL_CURRENT, converging to just MCL_CURRENT as we fault
2924 * in pages.
2925 */
Mark Salyzyn64d97d82018-04-09 09:50:32 -07002926 /* CAP_IPC_LOCK required */
Mark Salyzyn721d7c72018-03-21 12:24:58 -07002927 if (mlockall(MCL_CURRENT | MCL_FUTURE | MCL_ONFAULT) && (errno != EINVAL)) {
2928 ALOGW("mlockall failed %s", strerror(errno));
2929 }
Daniel Colascione4dd5d002018-01-03 12:01:02 -08002930
Mark Salyzyn64d97d82018-04-09 09:50:32 -07002931 /* CAP_NICE required */
2932 if (sched_setscheduler(0, SCHED_FIFO, &param)) {
2933 ALOGW("set SCHED_FIFO failed %s", strerror(errno));
2934 }
Mark Salyzyn721d7c72018-03-21 12:24:58 -07002935 }
2936
Todd Poynor3948f802013-07-09 19:35:14 -07002937 mainloop();
Mark Salyzyn721d7c72018-03-21 12:24:58 -07002938 }
Todd Poynor3948f802013-07-09 19:35:14 -07002939
Rajeev Kumar70450032018-01-31 17:54:56 -08002940#ifdef LMKD_LOG_STATS
Rajeev Kumar1c669f72018-03-09 15:20:56 -08002941 statslog_destroy(&log_ctx);
Rajeev Kumar70450032018-01-31 17:54:56 -08002942#endif
2943
Suren Baghdasaryan282ad1a2018-07-26 16:34:27 -07002944 android_log_destroy(&ctx);
2945
Todd Poynor3948f802013-07-09 19:35:14 -07002946 ALOGI("exiting");
2947 return 0;
2948}