blob: 35b4410c43a891170eefb519dcb02273cca8a607 [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
Yao Chen389aee12018-05-02 11:19:27 -070050#include "statslog.h"
Rajeev Kumar70450032018-01-31 17:54:56 -080051
Suren Baghdasaryanc7135592018-01-04 10:43:58 -080052/*
53 * Define LMKD_TRACE_KILLS to record lmkd kills in kernel traces
54 * to profile and correlate with OOM kills
55 */
56#ifdef LMKD_TRACE_KILLS
57
58#define ATRACE_TAG ATRACE_TAG_ALWAYS
59#include <cutils/trace.h>
60
61#define TRACE_KILL_START(pid) ATRACE_INT(__FUNCTION__, pid);
62#define TRACE_KILL_END() ATRACE_INT(__FUNCTION__, 0);
63
64#else /* LMKD_TRACE_KILLS */
65
Daniel Colascione347f6b42018-02-12 11:24:47 -080066#define TRACE_KILL_START(pid) ((void)(pid))
67#define TRACE_KILL_END() ((void)0)
Suren Baghdasaryanc7135592018-01-04 10:43:58 -080068
69#endif /* LMKD_TRACE_KILLS */
70
Mark Salyzyne6ed68b2014-04-30 13:36:35 -070071#ifndef __unused
72#define __unused __attribute__((__unused__))
73#endif
Todd Poynor3948f802013-07-09 19:35:14 -070074
75#define MEMCG_SYSFS_PATH "/dev/memcg/"
Robert Beneac47f2992017-08-21 15:18:31 -070076#define MEMCG_MEMORY_USAGE "/dev/memcg/memory.usage_in_bytes"
77#define MEMCG_MEMORYSW_USAGE "/dev/memcg/memory.memsw.usage_in_bytes"
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -070078#define ZONEINFO_PATH "/proc/zoneinfo"
79#define MEMINFO_PATH "/proc/meminfo"
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -070080#define VMSTAT_PATH "/proc/vmstat"
Suren Baghdasaryan0082ef12019-07-02 15:52:07 -070081#define PROC_STATUS_TGID_FIELD "Tgid:"
Todd Poynor3948f802013-07-09 19:35:14 -070082#define LINE_MAX 128
83
Suren Baghdasaryan4b750882019-09-19 15:27:21 -070084#define PERCEPTIBLE_APP_ADJ 200
85
Suren Baghdasaryan282ad1a2018-07-26 16:34:27 -070086/* Android Logger event logtags (see event.logtags) */
Suren Baghdasaryana7ac5782019-09-16 12:06:30 -070087#define KILLINFO_LOG_TAG 10195355
Suren Baghdasaryan282ad1a2018-07-26 16:34:27 -070088
Mark Salyzyn64d97d82018-04-09 09:50:32 -070089/* gid containing AID_SYSTEM required */
Todd Poynor3948f802013-07-09 19:35:14 -070090#define INKERNEL_MINFREE_PATH "/sys/module/lowmemorykiller/parameters/minfree"
91#define INKERNEL_ADJ_PATH "/sys/module/lowmemorykiller/parameters/adj"
92
93#define ARRAY_SIZE(x) (sizeof(x) / sizeof(*(x)))
Robert Benea673e2762017-06-01 16:32:31 -070094#define EIGHT_MEGA (1 << 23)
Todd Poynor3948f802013-07-09 19:35:14 -070095
Suren Baghdasaryan314a5052018-07-24 17:13:06 -070096#define TARGET_UPDATE_MIN_INTERVAL_MS 1000
97
98#define NS_PER_MS (NS_PER_SEC / MS_PER_SEC)
Suren Baghdasaryan77122e52019-01-08 12:54:48 -080099#define US_PER_MS (US_PER_SEC / MS_PER_SEC)
Suren Baghdasaryan314a5052018-07-24 17:13:06 -0700100
Suren Baghdasaryan4311d1e2018-03-20 16:03:29 -0700101/* Defined as ProcessList.SYSTEM_ADJ in ProcessList.java */
102#define SYSTEM_ADJ (-900)
103
Greg Kaiserf0da9b02018-03-23 14:16:12 -0700104#define STRINGIFY(x) STRINGIFY_INTERNAL(x)
105#define STRINGIFY_INTERNAL(x) #x
106
Suren Baghdasaryan77122e52019-01-08 12:54:48 -0800107/*
108 * PSI monitor tracking window size.
109 * PSI monitor generates events at most once per window,
110 * therefore we poll memory state for the duration of
111 * PSI_WINDOW_SIZE_MS after the event happens.
112 */
113#define PSI_WINDOW_SIZE_MS 1000
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -0700114/* Polling period after PSI signal when pressure is high */
115#define PSI_POLL_PERIOD_SHORT_MS 10
116/* Polling period after PSI signal when pressure is low */
117#define PSI_POLL_PERIOD_LONG_MS 100
Suren Baghdasaryan77122e52019-01-08 12:54:48 -0800118
Suren Baghdasaryan282ad1a2018-07-26 16:34:27 -0700119#define min(a, b) (((a) < (b)) ? (a) : (b))
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -0700120#define max(a, b) (((a) > (b)) ? (a) : (b))
Suren Baghdasaryan282ad1a2018-07-26 16:34:27 -0700121
Suren Baghdasaryan36934412018-09-05 15:46:32 -0700122#define FAIL_REPORT_RLIMIT_MS 1000
123
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -0700124/*
125 * System property defaults
126 */
127/* ro.lmk.swap_free_low_percentage property defaults */
128#define DEF_LOW_SWAP_LOWRAM 10
129#define DEF_LOW_SWAP 20
130/* ro.lmk.thrashing_limit property defaults */
131#define DEF_THRASHING_LOWRAM 30
132#define DEF_THRASHING 100
133/* ro.lmk.thrashing_limit_decay property defaults */
134#define DEF_THRASHING_DECAY_LOWRAM 50
135#define DEF_THRASHING_DECAY 10
Suren Baghdasaryan844f26b2019-07-15 15:42:09 -0700136/* ro.lmk.psi_partial_stall_ms property defaults */
137#define DEF_PARTIAL_STALL_LOWRAM 200
138#define DEF_PARTIAL_STALL 70
139/* ro.lmk.psi_complete_stall_ms property defaults */
140#define DEF_COMPLETE_STALL 700
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -0700141
Todd Poynor3948f802013-07-09 19:35:14 -0700142/* default to old in-kernel interface if no memory pressure events */
Mark Salyzyn721d7c72018-03-21 12:24:58 -0700143static bool use_inkernel_interface = true;
Robert Benea164baeb2017-09-11 16:53:28 -0700144static bool has_inkernel_module;
Todd Poynor3948f802013-07-09 19:35:14 -0700145
Suren Baghdasaryan96bf3a62017-12-08 12:58:52 -0800146/* memory pressure levels */
147enum vmpressure_level {
148 VMPRESS_LEVEL_LOW = 0,
149 VMPRESS_LEVEL_MEDIUM,
150 VMPRESS_LEVEL_CRITICAL,
151 VMPRESS_LEVEL_COUNT
152};
Todd Poynor3948f802013-07-09 19:35:14 -0700153
Suren Baghdasaryan96bf3a62017-12-08 12:58:52 -0800154static const char *level_name[] = {
155 "low",
156 "medium",
157 "critical"
158};
159
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -0800160struct {
Suren Baghdasaryan9926e572018-04-13 13:41:12 -0700161 int64_t min_nr_free_pages; /* recorded but not used yet */
162 int64_t max_nr_free_pages;
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -0800163} low_pressure_mem = { -1, -1 };
164
Suren Baghdasaryan77122e52019-01-08 12:54:48 -0800165struct psi_threshold {
166 enum psi_stall_type stall_type;
167 int threshold_ms;
168};
169
Suren Baghdasaryan96bf3a62017-12-08 12:58:52 -0800170static int level_oomadj[VMPRESS_LEVEL_COUNT];
Suren Baghdasaryane82e15c2018-01-04 09:16:21 -0800171static int mpevfd[VMPRESS_LEVEL_COUNT] = { -1, -1, -1 };
Robert Beneac47f2992017-08-21 15:18:31 -0700172static bool debug_process_killing;
173static bool enable_pressure_upgrade;
174static int64_t upgrade_pressure;
Robert Benea6e8e7102017-09-13 15:20:30 -0700175static int64_t downgrade_pressure;
Suren Baghdasaryanff61afb2018-04-13 11:45:38 -0700176static bool low_ram_device;
Suren Baghdasaryan662492a2017-12-08 13:17:06 -0800177static bool kill_heaviest_task;
Suren Baghdasaryancaa2dc52018-01-17 17:28:01 -0800178static unsigned long kill_timeout_ms;
Suren Baghdasaryanffdc4dd2018-04-13 13:53:43 -0700179static bool use_minfree_levels;
Suren Baghdasaryance13cb52018-06-19 18:38:12 -0700180static bool per_app_memcg;
Vic Yang360a1132018-08-07 10:18:22 -0700181static int swap_free_low_percentage;
Suren Baghdasaryan844f26b2019-07-15 15:42:09 -0700182static int psi_partial_stall_ms;
183static int psi_complete_stall_ms;
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -0700184static int thrashing_limit_pct;
185static int thrashing_limit_decay_pct;
Suren Baghdasaryan77122e52019-01-08 12:54:48 -0800186static bool use_psi_monitors = false;
Suren Baghdasaryanb72c6652019-09-04 19:12:29 -0700187static struct kernel_poll_info kpoll_info;
Suren Baghdasaryan77122e52019-01-08 12:54:48 -0800188static struct psi_threshold psi_thresholds[VMPRESS_LEVEL_COUNT] = {
189 { PSI_SOME, 70 }, /* 70ms out of 1sec for partial stall */
190 { PSI_SOME, 100 }, /* 100ms out of 1sec for partial stall */
191 { PSI_FULL, 70 }, /* 70ms out of 1sec for complete stall */
192};
Robert Benea58891d52017-07-31 17:15:20 -0700193
Suren Baghdasaryan282ad1a2018-07-26 16:34:27 -0700194static android_log_context ctx;
195
Suren Baghdasaryanef3650f2019-07-15 14:50:49 -0700196enum polling_update {
197 POLLING_DO_NOT_CHANGE,
198 POLLING_START,
199 POLLING_STOP,
200};
201
202/*
203 * Data used for periodic polling for the memory state of the device.
204 * Note that when system is not polling poll_handler is set to NULL,
205 * when polling starts poll_handler gets set and is reset back to
206 * NULL when polling stops.
207 */
208struct polling_params {
209 struct event_handler_info* poll_handler;
210 struct timespec poll_start_tm;
211 struct timespec last_poll_tm;
212 int polling_interval_ms;
213 enum polling_update update;
214};
215
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -0800216/* data required to handle events */
217struct event_handler_info {
218 int data;
Suren Baghdasaryanef3650f2019-07-15 14:50:49 -0700219 void (*handler)(int data, uint32_t events, struct polling_params *poll_params);
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -0800220};
Todd Poynor3948f802013-07-09 19:35:14 -0700221
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -0800222/* data required to handle socket events */
223struct sock_event_handler_info {
224 int sock;
225 struct event_handler_info handler_info;
226};
227
228/* max supported number of data connections */
229#define MAX_DATA_CONN 2
230
231/* socket event handler data */
232static struct sock_event_handler_info ctrl_sock;
233static struct sock_event_handler_info data_sock[MAX_DATA_CONN];
234
235/* vmpressure event handler data */
236static struct event_handler_info vmpressure_hinfo[VMPRESS_LEVEL_COUNT];
237
Jim Blackler3947c932019-04-26 11:18:29 +0100238/* 3 memory pressure levels, 1 ctrl listen socket, 2 ctrl data socket, 1 lmk events */
239#define MAX_EPOLL_EVENTS (2 + MAX_DATA_CONN + VMPRESS_LEVEL_COUNT)
Todd Poynor3948f802013-07-09 19:35:14 -0700240static int epollfd;
241static int maxevents;
242
Chong Zhang0a4acdf2015-10-14 16:19:53 -0700243/* OOM score values used by both kernel and framework */
Todd Poynor16b60992013-09-16 19:26:47 -0700244#define OOM_SCORE_ADJ_MIN (-1000)
245#define OOM_SCORE_ADJ_MAX 1000
246
Todd Poynor3948f802013-07-09 19:35:14 -0700247static int lowmem_adj[MAX_TARGETS];
248static int lowmem_minfree[MAX_TARGETS];
249static int lowmem_targets_size;
250
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -0700251/* Fields to parse in /proc/zoneinfo */
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -0700252/* zoneinfo per-zone fields */
253enum zoneinfo_zone_field {
254 ZI_ZONE_NR_FREE_PAGES = 0,
255 ZI_ZONE_MIN,
256 ZI_ZONE_LOW,
257 ZI_ZONE_HIGH,
258 ZI_ZONE_PRESENT,
259 ZI_ZONE_NR_FREE_CMA,
260 ZI_ZONE_FIELD_COUNT
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -0700261};
262
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -0700263static const char* const zoneinfo_zone_field_names[ZI_ZONE_FIELD_COUNT] = {
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -0700264 "nr_free_pages",
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -0700265 "min",
266 "low",
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -0700267 "high",
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -0700268 "present",
269 "nr_free_cma",
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -0700270};
271
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -0700272/* zoneinfo per-zone special fields */
273enum zoneinfo_zone_spec_field {
274 ZI_ZONE_SPEC_PROTECTION = 0,
275 ZI_ZONE_SPEC_PAGESETS,
276 ZI_ZONE_SPEC_FIELD_COUNT,
277};
278
279static const char* const zoneinfo_zone_spec_field_names[ZI_ZONE_SPEC_FIELD_COUNT] = {
280 "protection:",
281 "pagesets",
282};
283
284/* see __MAX_NR_ZONES definition in kernel mmzone.h */
285#define MAX_NR_ZONES 6
286
287union zoneinfo_zone_fields {
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -0700288 struct {
289 int64_t nr_free_pages;
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -0700290 int64_t min;
291 int64_t low;
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -0700292 int64_t high;
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -0700293 int64_t present;
294 int64_t nr_free_cma;
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -0700295 } field;
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -0700296 int64_t arr[ZI_ZONE_FIELD_COUNT];
297};
298
299struct zoneinfo_zone {
300 union zoneinfo_zone_fields fields;
301 int64_t protection[MAX_NR_ZONES];
302 int64_t max_protection;
303};
304
305/* zoneinfo per-node fields */
306enum zoneinfo_node_field {
307 ZI_NODE_NR_INACTIVE_FILE = 0,
308 ZI_NODE_NR_ACTIVE_FILE,
309 ZI_NODE_WORKINGSET_REFAULT,
310 ZI_NODE_FIELD_COUNT
311};
312
313static const char* const zoneinfo_node_field_names[ZI_NODE_FIELD_COUNT] = {
314 "nr_inactive_file",
315 "nr_active_file",
316 "workingset_refault",
317};
318
319union zoneinfo_node_fields {
320 struct {
321 int64_t nr_inactive_file;
322 int64_t nr_active_file;
323 int64_t workingset_refault;
324 } field;
325 int64_t arr[ZI_NODE_FIELD_COUNT];
326};
327
328struct zoneinfo_node {
329 int id;
330 int zone_count;
331 struct zoneinfo_zone zones[MAX_NR_ZONES];
332 union zoneinfo_node_fields fields;
333};
334
335/* for now two memory nodes is more than enough */
336#define MAX_NR_NODES 2
337
338struct zoneinfo {
339 int node_count;
340 struct zoneinfo_node nodes[MAX_NR_NODES];
341 int64_t totalreserve_pages;
342 int64_t total_inactive_file;
343 int64_t total_active_file;
344 int64_t total_workingset_refault;
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -0700345};
346
347/* Fields to parse in /proc/meminfo */
348enum meminfo_field {
349 MI_NR_FREE_PAGES = 0,
350 MI_CACHED,
351 MI_SWAP_CACHED,
352 MI_BUFFERS,
353 MI_SHMEM,
354 MI_UNEVICTABLE,
Vic Yang360a1132018-08-07 10:18:22 -0700355 MI_TOTAL_SWAP,
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -0700356 MI_FREE_SWAP,
Suren Baghdasaryan282ad1a2018-07-26 16:34:27 -0700357 MI_ACTIVE_ANON,
358 MI_INACTIVE_ANON,
359 MI_ACTIVE_FILE,
360 MI_INACTIVE_FILE,
361 MI_SRECLAIMABLE,
362 MI_SUNRECLAIM,
363 MI_KERNEL_STACK,
364 MI_PAGE_TABLES,
365 MI_ION_HELP,
366 MI_ION_HELP_POOL,
367 MI_CMA_FREE,
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -0700368 MI_FIELD_COUNT
369};
370
371static const char* const meminfo_field_names[MI_FIELD_COUNT] = {
372 "MemFree:",
373 "Cached:",
374 "SwapCached:",
375 "Buffers:",
376 "Shmem:",
377 "Unevictable:",
Vic Yang360a1132018-08-07 10:18:22 -0700378 "SwapTotal:",
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -0700379 "SwapFree:",
Suren Baghdasaryan282ad1a2018-07-26 16:34:27 -0700380 "Active(anon):",
381 "Inactive(anon):",
382 "Active(file):",
383 "Inactive(file):",
384 "SReclaimable:",
385 "SUnreclaim:",
386 "KernelStack:",
387 "PageTables:",
388 "ION_heap:",
389 "ION_heap_pool:",
390 "CmaFree:",
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -0700391};
392
393union meminfo {
394 struct {
395 int64_t nr_free_pages;
396 int64_t cached;
397 int64_t swap_cached;
398 int64_t buffers;
399 int64_t shmem;
400 int64_t unevictable;
Vic Yang360a1132018-08-07 10:18:22 -0700401 int64_t total_swap;
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -0700402 int64_t free_swap;
Suren Baghdasaryan282ad1a2018-07-26 16:34:27 -0700403 int64_t active_anon;
404 int64_t inactive_anon;
405 int64_t active_file;
406 int64_t inactive_file;
407 int64_t sreclaimable;
408 int64_t sunreclaimable;
409 int64_t kernel_stack;
410 int64_t page_tables;
411 int64_t ion_heap;
412 int64_t ion_heap_pool;
413 int64_t cma_free;
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -0700414 /* fields below are calculated rather than read from the file */
415 int64_t nr_file_pages;
416 } field;
417 int64_t arr[MI_FIELD_COUNT];
418};
419
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -0700420/* Fields to parse in /proc/vmstat */
421enum vmstat_field {
422 VS_FREE_PAGES,
423 VS_INACTIVE_FILE,
424 VS_ACTIVE_FILE,
425 VS_WORKINGSET_REFAULT,
426 VS_PGSCAN_KSWAPD,
427 VS_PGSCAN_DIRECT,
428 VS_PGSCAN_DIRECT_THROTTLE,
429 VS_FIELD_COUNT
430};
431
432static const char* const vmstat_field_names[MI_FIELD_COUNT] = {
433 "nr_free_pages",
434 "nr_inactive_file",
435 "nr_active_file",
436 "workingset_refault",
437 "pgscan_kswapd",
438 "pgscan_direct",
439 "pgscan_direct_throttle",
440};
441
442union vmstat {
443 struct {
444 int64_t nr_free_pages;
445 int64_t nr_inactive_file;
446 int64_t nr_active_file;
447 int64_t workingset_refault;
448 int64_t pgscan_kswapd;
449 int64_t pgscan_direct;
450 int64_t pgscan_direct_throttle;
451 } field;
452 int64_t arr[VS_FIELD_COUNT];
453};
454
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -0700455enum field_match_result {
456 NO_MATCH,
457 PARSE_FAIL,
458 PARSE_SUCCESS
459};
460
Todd Poynor3948f802013-07-09 19:35:14 -0700461struct adjslot_list {
462 struct adjslot_list *next;
463 struct adjslot_list *prev;
464};
465
466struct proc {
467 struct adjslot_list asl;
468 int pid;
Colin Crossfbb78c62014-06-13 14:52:43 -0700469 uid_t uid;
Todd Poynor3948f802013-07-09 19:35:14 -0700470 int oomadj;
471 struct proc *pidhash_next;
472};
473
Suren Baghdasaryan6499e5e2018-04-13 12:43:41 -0700474struct reread_data {
475 const char* const filename;
476 int fd;
477};
478
Todd Poynor3948f802013-07-09 19:35:14 -0700479#define PIDHASH_SZ 1024
480static struct proc *pidhash[PIDHASH_SZ];
481#define pid_hashfn(x) ((((x) >> 8) ^ (x)) & (PIDHASH_SZ - 1))
482
Chih-Hung Hsiehdaa13ea2016-05-19 16:02:22 -0700483#define ADJTOSLOT(adj) ((adj) + -OOM_SCORE_ADJ_MIN)
Suren Baghdasaryand4a29902018-10-12 11:07:40 -0700484#define ADJTOSLOT_COUNT (ADJTOSLOT(OOM_SCORE_ADJ_MAX) + 1)
485static struct adjslot_list procadjslot_list[ADJTOSLOT_COUNT];
486
487#define MAX_DISTINCT_OOM_ADJ 32
488#define KILLCNT_INVALID_IDX 0xFF
489/*
490 * Because killcnt array is sparse a two-level indirection is used
491 * to keep the size small. killcnt_idx stores index of the element in
492 * killcnt array. Index KILLCNT_INVALID_IDX indicates an unused slot.
493 */
494static uint8_t killcnt_idx[ADJTOSLOT_COUNT];
495static uint16_t killcnt[MAX_DISTINCT_OOM_ADJ];
496static int killcnt_free_idx = 0;
497static uint32_t killcnt_total = 0;
Todd Poynor3948f802013-07-09 19:35:14 -0700498
Todd Poynor3948f802013-07-09 19:35:14 -0700499/* PAGE_SIZE / 1024 */
500static long page_k;
501
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -0700502static int clamp(int low, int high, int value) {
503 return max(min(value, high), low);
504}
505
Suren Baghdasaryan6499e5e2018-04-13 12:43:41 -0700506static bool parse_int64(const char* str, int64_t* ret) {
507 char* endptr;
508 long long val = strtoll(str, &endptr, 10);
509 if (str == endptr || val > INT64_MAX) {
510 return false;
511 }
512 *ret = (int64_t)val;
513 return true;
514}
515
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -0700516static int find_field(const char* name, const char* const field_names[], int field_count) {
517 for (int i = 0; i < field_count; i++) {
518 if (!strcmp(name, field_names[i])) {
519 return i;
520 }
521 }
522 return -1;
523}
524
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -0700525static enum field_match_result match_field(const char* cp, const char* ap,
526 const char* const field_names[],
527 int field_count, int64_t* field,
528 int *field_idx) {
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -0700529 int i = find_field(cp, field_names, field_count);
530 if (i < 0) {
531 return NO_MATCH;
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -0700532 }
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -0700533 *field_idx = i;
534 return parse_int64(ap, field) ? PARSE_SUCCESS : PARSE_FAIL;
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -0700535}
536
Suren Baghdasaryan6499e5e2018-04-13 12:43:41 -0700537/*
538 * Read file content from the beginning up to max_len bytes or EOF
539 * whichever happens first.
540 */
Colin Crossce85d952014-07-11 17:53:27 -0700541static ssize_t read_all(int fd, char *buf, size_t max_len)
542{
543 ssize_t ret = 0;
Suren Baghdasaryan6499e5e2018-04-13 12:43:41 -0700544 off_t offset = 0;
Colin Crossce85d952014-07-11 17:53:27 -0700545
546 while (max_len > 0) {
Suren Baghdasaryan6499e5e2018-04-13 12:43:41 -0700547 ssize_t r = TEMP_FAILURE_RETRY(pread(fd, buf, max_len, offset));
Colin Crossce85d952014-07-11 17:53:27 -0700548 if (r == 0) {
549 break;
550 }
551 if (r == -1) {
552 return -1;
553 }
554 ret += r;
555 buf += r;
Suren Baghdasaryan6499e5e2018-04-13 12:43:41 -0700556 offset += r;
Colin Crossce85d952014-07-11 17:53:27 -0700557 max_len -= r;
558 }
559
560 return ret;
561}
562
Suren Baghdasaryan6499e5e2018-04-13 12:43:41 -0700563/*
564 * Read a new or already opened file from the beginning.
565 * If the file has not been opened yet data->fd should be set to -1.
566 * To be used with files which are read often and possibly during high
567 * memory pressure to minimize file opening which by itself requires kernel
568 * memory allocation and might result in a stall on memory stressed system.
569 */
Suren Baghdasaryana77b3272019-07-15 13:35:04 -0700570static char *reread_file(struct reread_data *data) {
571 /* start with page-size buffer and increase if needed */
572 static ssize_t buf_size = PAGE_SIZE;
573 static char *new_buf, *buf = NULL;
Suren Baghdasaryan6499e5e2018-04-13 12:43:41 -0700574 ssize_t size;
575
576 if (data->fd == -1) {
Suren Baghdasaryana77b3272019-07-15 13:35:04 -0700577 /* First-time buffer initialization */
578 if (!buf && (buf = malloc(buf_size)) == NULL) {
579 return NULL;
580 }
581
582 data->fd = TEMP_FAILURE_RETRY(open(data->filename, O_RDONLY | O_CLOEXEC));
583 if (data->fd < 0) {
Suren Baghdasaryan6499e5e2018-04-13 12:43:41 -0700584 ALOGE("%s open: %s", data->filename, strerror(errno));
Suren Baghdasaryana77b3272019-07-15 13:35:04 -0700585 return NULL;
Suren Baghdasaryan6499e5e2018-04-13 12:43:41 -0700586 }
587 }
588
Suren Baghdasaryana77b3272019-07-15 13:35:04 -0700589 while (true) {
590 size = read_all(data->fd, buf, buf_size - 1);
591 if (size < 0) {
592 ALOGE("%s read: %s", data->filename, strerror(errno));
593 close(data->fd);
594 data->fd = -1;
595 return NULL;
596 }
597 if (size < buf_size - 1) {
598 break;
599 }
600 /*
601 * Since we are reading /proc files we can't use fstat to find out
602 * the real size of the file. Double the buffer size and keep retrying.
603 */
604 if ((new_buf = realloc(buf, buf_size * 2)) == NULL) {
605 errno = ENOMEM;
606 return NULL;
607 }
608 buf = new_buf;
609 buf_size *= 2;
Suren Baghdasaryan6499e5e2018-04-13 12:43:41 -0700610 }
Suren Baghdasaryan6499e5e2018-04-13 12:43:41 -0700611 buf[size] = 0;
612
Suren Baghdasaryana77b3272019-07-15 13:35:04 -0700613 return buf;
Suren Baghdasaryan6499e5e2018-04-13 12:43:41 -0700614}
615
Todd Poynor3948f802013-07-09 19:35:14 -0700616static struct proc *pid_lookup(int pid) {
617 struct proc *procp;
618
619 for (procp = pidhash[pid_hashfn(pid)]; procp && procp->pid != pid;
620 procp = procp->pidhash_next)
621 ;
622
623 return procp;
624}
625
626static void adjslot_insert(struct adjslot_list *head, struct adjslot_list *new)
627{
628 struct adjslot_list *next = head->next;
629 new->prev = head;
630 new->next = next;
631 next->prev = new;
632 head->next = new;
633}
634
635static void adjslot_remove(struct adjslot_list *old)
636{
637 struct adjslot_list *prev = old->prev;
638 struct adjslot_list *next = old->next;
639 next->prev = prev;
640 prev->next = next;
641}
642
643static struct adjslot_list *adjslot_tail(struct adjslot_list *head) {
644 struct adjslot_list *asl = head->prev;
645
646 return asl == head ? NULL : asl;
647}
648
649static void proc_slot(struct proc *procp) {
650 int adjslot = ADJTOSLOT(procp->oomadj);
651
652 adjslot_insert(&procadjslot_list[adjslot], &procp->asl);
653}
654
655static void proc_unslot(struct proc *procp) {
656 adjslot_remove(&procp->asl);
657}
658
659static void proc_insert(struct proc *procp) {
660 int hval = pid_hashfn(procp->pid);
661
662 procp->pidhash_next = pidhash[hval];
663 pidhash[hval] = procp;
664 proc_slot(procp);
665}
666
667static int pid_remove(int pid) {
668 int hval = pid_hashfn(pid);
669 struct proc *procp;
670 struct proc *prevp;
671
672 for (procp = pidhash[hval], prevp = NULL; procp && procp->pid != pid;
673 procp = procp->pidhash_next)
674 prevp = procp;
675
676 if (!procp)
677 return -1;
678
679 if (!prevp)
680 pidhash[hval] = procp->pidhash_next;
681 else
682 prevp->pidhash_next = procp->pidhash_next;
683
684 proc_unslot(procp);
685 free(procp);
686 return 0;
687}
688
Suren Baghdasaryan1ffa2462018-03-20 13:53:17 -0700689/*
690 * Write a string to a file.
691 * Returns false if the file does not exist.
692 */
693static bool writefilestring(const char *path, const char *s,
694 bool err_if_missing) {
Nick Kralevichc68c8862015-12-18 20:52:37 -0800695 int fd = open(path, O_WRONLY | O_CLOEXEC);
Suren Baghdasaryan1ffa2462018-03-20 13:53:17 -0700696 ssize_t len = strlen(s);
697 ssize_t ret;
Todd Poynor3948f802013-07-09 19:35:14 -0700698
699 if (fd < 0) {
Suren Baghdasaryan1ffa2462018-03-20 13:53:17 -0700700 if (err_if_missing) {
701 ALOGE("Error opening %s; errno=%d", path, errno);
702 }
703 return false;
Todd Poynor3948f802013-07-09 19:35:14 -0700704 }
705
Suren Baghdasaryan1ffa2462018-03-20 13:53:17 -0700706 ret = TEMP_FAILURE_RETRY(write(fd, s, len));
Todd Poynor3948f802013-07-09 19:35:14 -0700707 if (ret < 0) {
708 ALOGE("Error writing %s; errno=%d", path, errno);
709 } else if (ret < len) {
Suren Baghdasaryan1ffa2462018-03-20 13:53:17 -0700710 ALOGE("Short write on %s; length=%zd", path, ret);
Todd Poynor3948f802013-07-09 19:35:14 -0700711 }
712
713 close(fd);
Suren Baghdasaryan1ffa2462018-03-20 13:53:17 -0700714 return true;
Todd Poynor3948f802013-07-09 19:35:14 -0700715}
716
Suren Baghdasaryan314a5052018-07-24 17:13:06 -0700717static inline long get_time_diff_ms(struct timespec *from,
718 struct timespec *to) {
719 return (to->tv_sec - from->tv_sec) * (long)MS_PER_SEC +
720 (to->tv_nsec - from->tv_nsec) / (long)NS_PER_MS;
721}
722
Suren Baghdasaryan0082ef12019-07-02 15:52:07 -0700723static int proc_get_tgid(int pid) {
724 char path[PATH_MAX];
725 char buf[PAGE_SIZE];
726 int fd;
727 ssize_t size;
728 char *pos;
729 int64_t tgid = -1;
730
731 snprintf(path, PATH_MAX, "/proc/%d/status", pid);
732 fd = open(path, O_RDONLY | O_CLOEXEC);
733 if (fd < 0) {
734 return -1;
735 }
736
737 size = read_all(fd, buf, sizeof(buf) - 1);
738 if (size < 0) {
739 goto out;
740 }
741 buf[size] = 0;
742
743 pos = buf;
744 while (true) {
745 pos = strstr(pos, PROC_STATUS_TGID_FIELD);
746 /* Stop if TGID tag not found or found at the line beginning */
747 if (pos == NULL || pos == buf || pos[-1] == '\n') {
748 break;
749 }
750 pos++;
751 }
752
753 if (pos == NULL) {
754 goto out;
755 }
756
757 pos += strlen(PROC_STATUS_TGID_FIELD);
758 while (*pos == ' ') pos++;
759 parse_int64(pos, &tgid);
760
761out:
762 close(fd);
763 return (int)tgid;
764}
765
Suren Baghdasaryanb72c6652019-09-04 19:12:29 -0700766static int proc_get_size(int pid) {
767 char path[PATH_MAX];
768 char line[LINE_MAX];
769 int fd;
770 int rss = 0;
771 int total;
772 ssize_t ret;
773
774 /* gid containing AID_READPROC required */
775 snprintf(path, PATH_MAX, "/proc/%d/statm", pid);
776 fd = open(path, O_RDONLY | O_CLOEXEC);
777 if (fd == -1)
778 return -1;
779
780 ret = read_all(fd, line, sizeof(line) - 1);
781 if (ret < 0) {
782 close(fd);
783 return -1;
784 }
785
786 sscanf(line, "%d %d ", &total, &rss);
787 close(fd);
788 return rss;
789}
790
791static char *proc_get_name(int pid) {
792 char path[PATH_MAX];
793 static char line[LINE_MAX];
794 int fd;
795 char *cp;
796 ssize_t ret;
797
798 /* gid containing AID_READPROC required */
799 snprintf(path, PATH_MAX, "/proc/%d/cmdline", pid);
800 fd = open(path, O_RDONLY | O_CLOEXEC);
801 if (fd == -1) {
802 return NULL;
803 }
804 ret = read_all(fd, line, sizeof(line) - 1);
805 close(fd);
806 if (ret < 0) {
807 return NULL;
808 }
809
810 cp = strchr(line, ' ');
811 if (cp) {
812 *cp = '\0';
813 } else {
814 line[ret] = '\0';
815 }
816
817 return line;
818}
819
Suren Baghdasaryan0f100512018-01-24 16:51:41 -0800820static void cmd_procprio(LMKD_CTRL_PACKET packet) {
Todd Poynor3948f802013-07-09 19:35:14 -0700821 struct proc *procp;
822 char path[80];
823 char val[20];
Robert Benea673e2762017-06-01 16:32:31 -0700824 int soft_limit_mult;
Suren Baghdasaryan0f100512018-01-24 16:51:41 -0800825 struct lmk_procprio params;
Suren Baghdasaryan4311d1e2018-03-20 16:03:29 -0700826 bool is_system_server;
827 struct passwd *pwdrec;
Suren Baghdasaryan0082ef12019-07-02 15:52:07 -0700828 int tgid;
Todd Poynor3948f802013-07-09 19:35:14 -0700829
Suren Baghdasaryan0f100512018-01-24 16:51:41 -0800830 lmkd_pack_get_procprio(packet, &params);
831
832 if (params.oomadj < OOM_SCORE_ADJ_MIN ||
833 params.oomadj > OOM_SCORE_ADJ_MAX) {
834 ALOGE("Invalid PROCPRIO oomadj argument %d", params.oomadj);
Todd Poynor3948f802013-07-09 19:35:14 -0700835 return;
836 }
837
Suren Baghdasaryan0082ef12019-07-02 15:52:07 -0700838 /* Check if registered process is a thread group leader */
839 tgid = proc_get_tgid(params.pid);
840 if (tgid >= 0 && tgid != params.pid) {
841 ALOGE("Attempt to register a task that is not a thread group leader (tid %d, tgid %d)",
842 params.pid, tgid);
843 return;
844 }
845
Mark Salyzyn64d97d82018-04-09 09:50:32 -0700846 /* gid containing AID_READPROC required */
847 /* CAP_SYS_RESOURCE required */
848 /* CAP_DAC_OVERRIDE required */
Suren Baghdasaryan0f100512018-01-24 16:51:41 -0800849 snprintf(path, sizeof(path), "/proc/%d/oom_score_adj", params.pid);
850 snprintf(val, sizeof(val), "%d", params.oomadj);
Suren Baghdasaryan1ffa2462018-03-20 13:53:17 -0700851 if (!writefilestring(path, val, false)) {
852 ALOGW("Failed to open %s; errno=%d: process %d might have been killed",
853 path, errno, params.pid);
854 /* If this file does not exist the process is dead. */
855 return;
856 }
Todd Poynor3948f802013-07-09 19:35:14 -0700857
Mark Salyzyn721d7c72018-03-21 12:24:58 -0700858 if (use_inkernel_interface) {
Suren Baghdasaryanb72c6652019-09-04 19:12:29 -0700859 stats_store_taskname(params.pid, proc_get_name(params.pid), kpoll_info.poll_fd);
Todd Poynor3948f802013-07-09 19:35:14 -0700860 return;
Mark Salyzyn721d7c72018-03-21 12:24:58 -0700861 }
Todd Poynor3948f802013-07-09 19:35:14 -0700862
Suren Baghdasaryance13cb52018-06-19 18:38:12 -0700863 if (per_app_memcg) {
Suren Baghdasaryan20686f02018-05-18 14:42:00 -0700864 if (params.oomadj >= 900) {
865 soft_limit_mult = 0;
866 } else if (params.oomadj >= 800) {
867 soft_limit_mult = 0;
868 } else if (params.oomadj >= 700) {
869 soft_limit_mult = 0;
870 } else if (params.oomadj >= 600) {
871 // Launcher should be perceptible, don't kill it.
872 params.oomadj = 200;
873 soft_limit_mult = 1;
874 } else if (params.oomadj >= 500) {
875 soft_limit_mult = 0;
876 } else if (params.oomadj >= 400) {
877 soft_limit_mult = 0;
878 } else if (params.oomadj >= 300) {
879 soft_limit_mult = 1;
880 } else if (params.oomadj >= 200) {
Srinivas Paladugu3eb20bc2018-10-09 14:21:10 -0700881 soft_limit_mult = 8;
Suren Baghdasaryan20686f02018-05-18 14:42:00 -0700882 } else if (params.oomadj >= 100) {
883 soft_limit_mult = 10;
884 } else if (params.oomadj >= 0) {
885 soft_limit_mult = 20;
886 } else {
887 // Persistent processes will have a large
888 // soft limit 512MB.
889 soft_limit_mult = 64;
890 }
Robert Benea673e2762017-06-01 16:32:31 -0700891
Suren Baghdasaryan3862dd32018-05-21 19:48:47 -0700892 snprintf(path, sizeof(path), MEMCG_SYSFS_PATH
893 "apps/uid_%d/pid_%d/memory.soft_limit_in_bytes",
894 params.uid, params.pid);
Suren Baghdasaryan20686f02018-05-18 14:42:00 -0700895 snprintf(val, sizeof(val), "%d", soft_limit_mult * EIGHT_MEGA);
Suren Baghdasaryan3862dd32018-05-21 19:48:47 -0700896
897 /*
898 * system_server process has no memcg under /dev/memcg/apps but should be
899 * registered with lmkd. This is the best way so far to identify it.
900 */
901 is_system_server = (params.oomadj == SYSTEM_ADJ &&
902 (pwdrec = getpwnam("system")) != NULL &&
903 params.uid == pwdrec->pw_uid);
904 writefilestring(path, val, !is_system_server);
Robert Benea673e2762017-06-01 16:32:31 -0700905 }
906
Suren Baghdasaryan0f100512018-01-24 16:51:41 -0800907 procp = pid_lookup(params.pid);
Todd Poynor3948f802013-07-09 19:35:14 -0700908 if (!procp) {
909 procp = malloc(sizeof(struct proc));
910 if (!procp) {
911 // Oh, the irony. May need to rebuild our state.
912 return;
913 }
914
Suren Baghdasaryan0f100512018-01-24 16:51:41 -0800915 procp->pid = params.pid;
916 procp->uid = params.uid;
917 procp->oomadj = params.oomadj;
Todd Poynor3948f802013-07-09 19:35:14 -0700918 proc_insert(procp);
919 } else {
920 proc_unslot(procp);
Suren Baghdasaryan0f100512018-01-24 16:51:41 -0800921 procp->oomadj = params.oomadj;
Todd Poynor3948f802013-07-09 19:35:14 -0700922 proc_slot(procp);
923 }
924}
925
Suren Baghdasaryan0f100512018-01-24 16:51:41 -0800926static void cmd_procremove(LMKD_CTRL_PACKET packet) {
927 struct lmk_procremove params;
928
Mark Salyzyn721d7c72018-03-21 12:24:58 -0700929 if (use_inkernel_interface) {
Suren Baghdasaryanb72c6652019-09-04 19:12:29 -0700930 stats_remove_taskname(params.pid, kpoll_info.poll_fd);
Todd Poynor3948f802013-07-09 19:35:14 -0700931 return;
Mark Salyzyn721d7c72018-03-21 12:24:58 -0700932 }
Todd Poynor3948f802013-07-09 19:35:14 -0700933
Suren Baghdasaryan0f100512018-01-24 16:51:41 -0800934 lmkd_pack_get_procremove(packet, &params);
Suren Baghdasaryan01063272018-10-12 11:28:33 -0700935 /*
936 * WARNING: After pid_remove() procp is freed and can't be used!
937 * Therefore placed at the end of the function.
938 */
Suren Baghdasaryan0f100512018-01-24 16:51:41 -0800939 pid_remove(params.pid);
Todd Poynor3948f802013-07-09 19:35:14 -0700940}
941
Suren Baghdasaryane3b60472018-10-10 14:17:17 -0700942static void cmd_procpurge() {
943 int i;
944 struct proc *procp;
945 struct proc *next;
946
947 if (use_inkernel_interface) {
Jim Blacklerd2da8142019-09-10 15:30:05 +0100948 stats_purge_tasknames();
Suren Baghdasaryane3b60472018-10-10 14:17:17 -0700949 return;
950 }
951
952 for (i = 0; i <= ADJTOSLOT(OOM_SCORE_ADJ_MAX); i++) {
953 procadjslot_list[i].next = &procadjslot_list[i];
954 procadjslot_list[i].prev = &procadjslot_list[i];
955 }
956
957 for (i = 0; i < PIDHASH_SZ; i++) {
958 procp = pidhash[i];
959 while (procp) {
960 next = procp->pidhash_next;
961 free(procp);
962 procp = next;
963 }
964 }
965 memset(&pidhash[0], 0, sizeof(pidhash));
966}
967
Suren Baghdasaryand4a29902018-10-12 11:07:40 -0700968static void inc_killcnt(int oomadj) {
969 int slot = ADJTOSLOT(oomadj);
970 uint8_t idx = killcnt_idx[slot];
971
972 if (idx == KILLCNT_INVALID_IDX) {
973 /* index is not assigned for this oomadj */
974 if (killcnt_free_idx < MAX_DISTINCT_OOM_ADJ) {
975 killcnt_idx[slot] = killcnt_free_idx;
976 killcnt[killcnt_free_idx] = 1;
977 killcnt_free_idx++;
978 } else {
979 ALOGW("Number of distinct oomadj levels exceeds %d",
980 MAX_DISTINCT_OOM_ADJ);
981 }
982 } else {
983 /*
984 * wraparound is highly unlikely and is detectable using total
985 * counter because it has to be equal to the sum of all counters
986 */
987 killcnt[idx]++;
988 }
989 /* increment total kill counter */
990 killcnt_total++;
991}
992
993static int get_killcnt(int min_oomadj, int max_oomadj) {
994 int slot;
995 int count = 0;
996
997 if (min_oomadj > max_oomadj)
998 return 0;
999
1000 /* special case to get total kill count */
1001 if (min_oomadj > OOM_SCORE_ADJ_MAX)
1002 return killcnt_total;
1003
1004 while (min_oomadj <= max_oomadj &&
1005 (slot = ADJTOSLOT(min_oomadj)) < ADJTOSLOT_COUNT) {
1006 uint8_t idx = killcnt_idx[slot];
1007 if (idx != KILLCNT_INVALID_IDX) {
1008 count += killcnt[idx];
1009 }
1010 min_oomadj++;
1011 }
1012
1013 return count;
1014}
1015
1016static int cmd_getkillcnt(LMKD_CTRL_PACKET packet) {
1017 struct lmk_getkillcnt params;
1018
1019 if (use_inkernel_interface) {
1020 /* kernel driver does not expose this information */
1021 return 0;
1022 }
1023
1024 lmkd_pack_get_getkillcnt(packet, &params);
1025
1026 return get_killcnt(params.min_oomadj, params.max_oomadj);
1027}
1028
Suren Baghdasaryan0f100512018-01-24 16:51:41 -08001029static void cmd_target(int ntargets, LMKD_CTRL_PACKET packet) {
Todd Poynor3948f802013-07-09 19:35:14 -07001030 int i;
Suren Baghdasaryan0f100512018-01-24 16:51:41 -08001031 struct lmk_target target;
Suren Baghdasaryan314a5052018-07-24 17:13:06 -07001032 char minfree_str[PROPERTY_VALUE_MAX];
1033 char *pstr = minfree_str;
1034 char *pend = minfree_str + sizeof(minfree_str);
1035 static struct timespec last_req_tm;
1036 struct timespec curr_tm;
Todd Poynor3948f802013-07-09 19:35:14 -07001037
Suren Baghdasaryan314a5052018-07-24 17:13:06 -07001038 if (ntargets < 1 || ntargets > (int)ARRAY_SIZE(lowmem_adj))
Todd Poynor3948f802013-07-09 19:35:14 -07001039 return;
1040
Suren Baghdasaryan314a5052018-07-24 17:13:06 -07001041 /*
1042 * Ratelimit minfree updates to once per TARGET_UPDATE_MIN_INTERVAL_MS
1043 * to prevent DoS attacks
1044 */
1045 if (clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm) != 0) {
1046 ALOGE("Failed to get current time");
1047 return;
1048 }
1049
1050 if (get_time_diff_ms(&last_req_tm, &curr_tm) <
1051 TARGET_UPDATE_MIN_INTERVAL_MS) {
1052 ALOGE("Ignoring frequent updated to lmkd limits");
1053 return;
1054 }
1055
1056 last_req_tm = curr_tm;
1057
Todd Poynor3948f802013-07-09 19:35:14 -07001058 for (i = 0; i < ntargets; i++) {
Suren Baghdasaryan0f100512018-01-24 16:51:41 -08001059 lmkd_pack_get_target(packet, i, &target);
1060 lowmem_minfree[i] = target.minfree;
1061 lowmem_adj[i] = target.oom_adj_score;
Suren Baghdasaryan314a5052018-07-24 17:13:06 -07001062
1063 pstr += snprintf(pstr, pend - pstr, "%d:%d,", target.minfree,
1064 target.oom_adj_score);
1065 if (pstr >= pend) {
1066 /* if no more space in the buffer then terminate the loop */
1067 pstr = pend;
1068 break;
1069 }
Todd Poynor3948f802013-07-09 19:35:14 -07001070 }
1071
1072 lowmem_targets_size = ntargets;
1073
Suren Baghdasaryan314a5052018-07-24 17:13:06 -07001074 /* Override the last extra comma */
1075 pstr[-1] = '\0';
1076 property_set("sys.lmk.minfree_levels", minfree_str);
1077
Robert Benea164baeb2017-09-11 16:53:28 -07001078 if (has_inkernel_module) {
Todd Poynor3948f802013-07-09 19:35:14 -07001079 char minfreestr[128];
1080 char killpriostr[128];
1081
1082 minfreestr[0] = '\0';
1083 killpriostr[0] = '\0';
1084
1085 for (i = 0; i < lowmem_targets_size; i++) {
1086 char val[40];
1087
1088 if (i) {
1089 strlcat(minfreestr, ",", sizeof(minfreestr));
1090 strlcat(killpriostr, ",", sizeof(killpriostr));
1091 }
1092
Robert Benea164baeb2017-09-11 16:53:28 -07001093 snprintf(val, sizeof(val), "%d", use_inkernel_interface ? lowmem_minfree[i] : 0);
Todd Poynor3948f802013-07-09 19:35:14 -07001094 strlcat(minfreestr, val, sizeof(minfreestr));
Robert Benea164baeb2017-09-11 16:53:28 -07001095 snprintf(val, sizeof(val), "%d", use_inkernel_interface ? lowmem_adj[i] : 0);
Todd Poynor3948f802013-07-09 19:35:14 -07001096 strlcat(killpriostr, val, sizeof(killpriostr));
1097 }
1098
Suren Baghdasaryan1ffa2462018-03-20 13:53:17 -07001099 writefilestring(INKERNEL_MINFREE_PATH, minfreestr, true);
1100 writefilestring(INKERNEL_ADJ_PATH, killpriostr, true);
Todd Poynor3948f802013-07-09 19:35:14 -07001101 }
1102}
1103
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08001104static void ctrl_data_close(int dsock_idx) {
1105 struct epoll_event epev;
1106
1107 ALOGI("closing lmkd data connection");
1108 if (epoll_ctl(epollfd, EPOLL_CTL_DEL, data_sock[dsock_idx].sock, &epev) == -1) {
1109 // Log a warning and keep going
1110 ALOGW("epoll_ctl for data connection socket failed; errno=%d", errno);
1111 }
Todd Poynor3948f802013-07-09 19:35:14 -07001112 maxevents--;
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08001113
1114 close(data_sock[dsock_idx].sock);
1115 data_sock[dsock_idx].sock = -1;
Todd Poynor3948f802013-07-09 19:35:14 -07001116}
1117
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08001118static int ctrl_data_read(int dsock_idx, char *buf, size_t bufsz) {
Todd Poynor3948f802013-07-09 19:35:14 -07001119 int ret = 0;
1120
Suren Baghdasaryan6499e5e2018-04-13 12:43:41 -07001121 ret = TEMP_FAILURE_RETRY(read(data_sock[dsock_idx].sock, buf, bufsz));
Todd Poynor3948f802013-07-09 19:35:14 -07001122
1123 if (ret == -1) {
1124 ALOGE("control data socket read failed; errno=%d", errno);
1125 } else if (ret == 0) {
1126 ALOGE("Got EOF on control data socket");
1127 ret = -1;
1128 }
1129
1130 return ret;
1131}
1132
Suren Baghdasaryand4a29902018-10-12 11:07:40 -07001133static int ctrl_data_write(int dsock_idx, char *buf, size_t bufsz) {
1134 int ret = 0;
1135
1136 ret = TEMP_FAILURE_RETRY(write(data_sock[dsock_idx].sock, buf, bufsz));
1137
1138 if (ret == -1) {
1139 ALOGE("control data socket write failed; errno=%d", errno);
1140 } else if (ret == 0) {
1141 ALOGE("Got EOF on control data socket");
1142 ret = -1;
1143 }
1144
1145 return ret;
1146}
1147
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08001148static void ctrl_command_handler(int dsock_idx) {
Suren Baghdasaryan0f100512018-01-24 16:51:41 -08001149 LMKD_CTRL_PACKET packet;
Todd Poynor3948f802013-07-09 19:35:14 -07001150 int len;
Suren Baghdasaryan0f100512018-01-24 16:51:41 -08001151 enum lmk_cmd cmd;
Todd Poynor3948f802013-07-09 19:35:14 -07001152 int nargs;
1153 int targets;
Suren Baghdasaryand4a29902018-10-12 11:07:40 -07001154 int kill_cnt;
Todd Poynor3948f802013-07-09 19:35:14 -07001155
Suren Baghdasaryan0f100512018-01-24 16:51:41 -08001156 len = ctrl_data_read(dsock_idx, (char *)packet, CTRL_PACKET_MAX_SIZE);
Todd Poynor3948f802013-07-09 19:35:14 -07001157 if (len <= 0)
1158 return;
1159
Suren Baghdasaryan0f100512018-01-24 16:51:41 -08001160 if (len < (int)sizeof(int)) {
1161 ALOGE("Wrong control socket read length len=%d", len);
1162 return;
1163 }
1164
1165 cmd = lmkd_pack_get_cmd(packet);
Todd Poynor3948f802013-07-09 19:35:14 -07001166 nargs = len / sizeof(int) - 1;
1167 if (nargs < 0)
1168 goto wronglen;
1169
Todd Poynor3948f802013-07-09 19:35:14 -07001170 switch(cmd) {
1171 case LMK_TARGET:
1172 targets = nargs / 2;
1173 if (nargs & 0x1 || targets > (int)ARRAY_SIZE(lowmem_adj))
1174 goto wronglen;
Suren Baghdasaryan0f100512018-01-24 16:51:41 -08001175 cmd_target(targets, packet);
Todd Poynor3948f802013-07-09 19:35:14 -07001176 break;
1177 case LMK_PROCPRIO:
Colin Crossfbb78c62014-06-13 14:52:43 -07001178 if (nargs != 3)
Todd Poynor3948f802013-07-09 19:35:14 -07001179 goto wronglen;
Suren Baghdasaryan0f100512018-01-24 16:51:41 -08001180 cmd_procprio(packet);
Todd Poynor3948f802013-07-09 19:35:14 -07001181 break;
1182 case LMK_PROCREMOVE:
1183 if (nargs != 1)
1184 goto wronglen;
Suren Baghdasaryan0f100512018-01-24 16:51:41 -08001185 cmd_procremove(packet);
Todd Poynor3948f802013-07-09 19:35:14 -07001186 break;
Suren Baghdasaryane3b60472018-10-10 14:17:17 -07001187 case LMK_PROCPURGE:
1188 if (nargs != 0)
1189 goto wronglen;
1190 cmd_procpurge();
1191 break;
Suren Baghdasaryand4a29902018-10-12 11:07:40 -07001192 case LMK_GETKILLCNT:
1193 if (nargs != 2)
1194 goto wronglen;
1195 kill_cnt = cmd_getkillcnt(packet);
1196 len = lmkd_pack_set_getkillcnt_repl(packet, kill_cnt);
1197 if (ctrl_data_write(dsock_idx, (char *)packet, len) != len)
1198 return;
1199 break;
Todd Poynor3948f802013-07-09 19:35:14 -07001200 default:
1201 ALOGE("Received unknown command code %d", cmd);
1202 return;
1203 }
1204
1205 return;
1206
1207wronglen:
1208 ALOGE("Wrong control socket read length cmd=%d len=%d", cmd, len);
1209}
1210
Suren Baghdasaryanef3650f2019-07-15 14:50:49 -07001211static void ctrl_data_handler(int data, uint32_t events,
1212 struct polling_params *poll_params __unused) {
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08001213 if (events & EPOLLIN) {
1214 ctrl_command_handler(data);
Todd Poynor3948f802013-07-09 19:35:14 -07001215 }
1216}
1217
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08001218static int get_free_dsock() {
1219 for (int i = 0; i < MAX_DATA_CONN; i++) {
1220 if (data_sock[i].sock < 0) {
1221 return i;
1222 }
1223 }
1224 return -1;
1225}
Todd Poynor3948f802013-07-09 19:35:14 -07001226
Suren Baghdasaryanef3650f2019-07-15 14:50:49 -07001227static void ctrl_connect_handler(int data __unused, uint32_t events __unused,
1228 struct polling_params *poll_params __unused) {
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08001229 struct epoll_event epev;
1230 int free_dscock_idx = get_free_dsock();
1231
1232 if (free_dscock_idx < 0) {
1233 /*
1234 * Number of data connections exceeded max supported. This should not
1235 * happen but if it does we drop all existing connections and accept
1236 * the new one. This prevents inactive connections from monopolizing
1237 * data socket and if we drop ActivityManager connection it will
1238 * immediately reconnect.
1239 */
1240 for (int i = 0; i < MAX_DATA_CONN; i++) {
1241 ctrl_data_close(i);
1242 }
1243 free_dscock_idx = 0;
Todd Poynor3948f802013-07-09 19:35:14 -07001244 }
1245
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08001246 data_sock[free_dscock_idx].sock = accept(ctrl_sock.sock, NULL, NULL);
1247 if (data_sock[free_dscock_idx].sock < 0) {
Todd Poynor3948f802013-07-09 19:35:14 -07001248 ALOGE("lmkd control socket accept failed; errno=%d", errno);
1249 return;
1250 }
1251
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08001252 ALOGI("lmkd data connection established");
1253 /* use data to store data connection idx */
1254 data_sock[free_dscock_idx].handler_info.data = free_dscock_idx;
1255 data_sock[free_dscock_idx].handler_info.handler = ctrl_data_handler;
Todd Poynor3948f802013-07-09 19:35:14 -07001256 epev.events = EPOLLIN;
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08001257 epev.data.ptr = (void *)&(data_sock[free_dscock_idx].handler_info);
1258 if (epoll_ctl(epollfd, EPOLL_CTL_ADD, data_sock[free_dscock_idx].sock, &epev) == -1) {
Todd Poynor3948f802013-07-09 19:35:14 -07001259 ALOGE("epoll_ctl for data connection socket failed; errno=%d", errno);
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08001260 ctrl_data_close(free_dscock_idx);
Todd Poynor3948f802013-07-09 19:35:14 -07001261 return;
1262 }
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08001263 maxevents++;
Todd Poynor3948f802013-07-09 19:35:14 -07001264}
1265
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07001266/*
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07001267 * /proc/zoneinfo parsing routines
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07001268 * Expected file format is:
1269 *
1270 * Node <node_id>, zone <zone_name>
1271 * (
1272 * per-node stats
1273 * (<per-node field name> <value>)+
1274 * )?
1275 * (pages free <value>
1276 * (<per-zone field name> <value>)+
1277 * pagesets
1278 * (<unused fields>)*
1279 * )+
1280 * ...
1281 */
1282static void zoneinfo_parse_protection(char *buf, struct zoneinfo_zone *zone) {
1283 int zone_idx;
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001284 int64_t max = 0;
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001285 char *save_ptr;
1286
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07001287 for (buf = strtok_r(buf, "(), ", &save_ptr), zone_idx = 0;
1288 buf && zone_idx < MAX_NR_ZONES;
1289 buf = strtok_r(NULL, "), ", &save_ptr), zone_idx++) {
1290 long long zoneval = strtoll(buf, &buf, 0);
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001291 if (zoneval > max) {
1292 max = (zoneval > INT64_MAX) ? INT64_MAX : zoneval;
1293 }
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07001294 zone->protection[zone_idx] = zoneval;
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001295 }
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07001296 zone->max_protection = max;
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001297}
1298
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07001299static int zoneinfo_parse_zone(char **buf, struct zoneinfo_zone *zone) {
1300 for (char *line = strtok_r(NULL, "\n", buf); line;
1301 line = strtok_r(NULL, "\n", buf)) {
1302 char *cp;
1303 char *ap;
1304 char *save_ptr;
1305 int64_t val;
1306 int field_idx;
1307 enum field_match_result match_res;
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001308
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07001309 cp = strtok_r(line, " ", &save_ptr);
1310 if (!cp) {
1311 return false;
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001312 }
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07001313
1314 field_idx = find_field(cp, zoneinfo_zone_spec_field_names, ZI_ZONE_SPEC_FIELD_COUNT);
1315 if (field_idx >= 0) {
1316 /* special field */
1317 if (field_idx == ZI_ZONE_SPEC_PAGESETS) {
1318 /* no mode fields we are interested in */
1319 return true;
1320 }
1321
1322 /* protection field */
1323 ap = strtok_r(NULL, ")", &save_ptr);
1324 if (ap) {
1325 zoneinfo_parse_protection(ap, zone);
1326 }
1327 continue;
1328 }
1329
1330 ap = strtok_r(NULL, " ", &save_ptr);
1331 if (!ap) {
1332 continue;
1333 }
1334
1335 match_res = match_field(cp, ap, zoneinfo_zone_field_names, ZI_ZONE_FIELD_COUNT,
1336 &val, &field_idx);
1337 if (match_res == PARSE_FAIL) {
1338 return false;
1339 }
1340 if (match_res == PARSE_SUCCESS) {
1341 zone->fields.arr[field_idx] = val;
1342 }
1343 if (field_idx == ZI_ZONE_PRESENT && val == 0) {
1344 /* zone is not populated, stop parsing it */
1345 return true;
1346 }
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001347 }
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07001348 return false;
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001349}
1350
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07001351static int zoneinfo_parse_node(char **buf, struct zoneinfo_node *node) {
1352 int fields_to_match = ZI_NODE_FIELD_COUNT;
1353
1354 for (char *line = strtok_r(NULL, "\n", buf); line;
1355 line = strtok_r(NULL, "\n", buf)) {
1356 char *cp;
1357 char *ap;
1358 char *save_ptr;
1359 int64_t val;
1360 int field_idx;
1361 enum field_match_result match_res;
1362
1363 cp = strtok_r(line, " ", &save_ptr);
1364 if (!cp) {
1365 return false;
1366 }
1367
1368 ap = strtok_r(NULL, " ", &save_ptr);
1369 if (!ap) {
1370 return false;
1371 }
1372
1373 match_res = match_field(cp, ap, zoneinfo_node_field_names, ZI_NODE_FIELD_COUNT,
1374 &val, &field_idx);
1375 if (match_res == PARSE_FAIL) {
1376 return false;
1377 }
1378 if (match_res == PARSE_SUCCESS) {
1379 node->fields.arr[field_idx] = val;
1380 fields_to_match--;
1381 if (!fields_to_match) {
1382 return true;
1383 }
1384 }
1385 }
1386 return false;
1387}
1388
1389static int zoneinfo_parse(struct zoneinfo *zi) {
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001390 static struct reread_data file_data = {
1391 .filename = ZONEINFO_PATH,
1392 .fd = -1,
1393 };
Suren Baghdasaryana77b3272019-07-15 13:35:04 -07001394 char *buf;
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001395 char *save_ptr;
1396 char *line;
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07001397 char zone_name[LINE_MAX];
1398 struct zoneinfo_node *node = NULL;
1399 int node_idx = 0;
1400 int zone_idx = 0;
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001401
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07001402 memset(zi, 0, sizeof(struct zoneinfo));
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001403
Suren Baghdasaryana77b3272019-07-15 13:35:04 -07001404 if ((buf = reread_file(&file_data)) == NULL) {
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001405 return -1;
1406 }
1407
1408 for (line = strtok_r(buf, "\n", &save_ptr); line;
1409 line = strtok_r(NULL, "\n", &save_ptr)) {
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07001410 int node_id;
1411 if (sscanf(line, "Node %d, zone %" STRINGIFY(LINE_MAX) "s", &node_id, zone_name) == 2) {
1412 if (!node || node->id != node_id) {
1413 /* new node is found */
1414 if (node) {
1415 node->zone_count = zone_idx + 1;
1416 node_idx++;
1417 if (node_idx == MAX_NR_NODES) {
1418 /* max node count exceeded */
1419 ALOGE("%s parse error", file_data.filename);
1420 return -1;
1421 }
1422 }
1423 node = &zi->nodes[node_idx];
1424 node->id = node_id;
1425 zone_idx = 0;
1426 if (!zoneinfo_parse_node(&save_ptr, node)) {
1427 ALOGE("%s parse error", file_data.filename);
1428 return -1;
1429 }
1430 } else {
1431 /* new zone is found */
1432 zone_idx++;
1433 }
1434 if (!zoneinfo_parse_zone(&save_ptr, &node->zones[zone_idx])) {
1435 ALOGE("%s parse error", file_data.filename);
1436 return -1;
1437 }
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001438 }
1439 }
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07001440 if (!node) {
1441 ALOGE("%s parse error", file_data.filename);
1442 return -1;
1443 }
1444 node->zone_count = zone_idx + 1;
1445 zi->node_count = node_idx + 1;
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001446
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07001447 /* calculate totals fields */
1448 for (node_idx = 0; node_idx < zi->node_count; node_idx++) {
1449 node = &zi->nodes[node_idx];
1450 for (zone_idx = 0; zone_idx < node->zone_count; zone_idx++) {
1451 struct zoneinfo_zone *zone = &zi->nodes[node_idx].zones[zone_idx];
1452 zi->totalreserve_pages += zone->max_protection + zone->fields.field.high;
1453 }
1454 zi->total_inactive_file += node->fields.field.nr_inactive_file;
1455 zi->total_active_file += node->fields.field.nr_active_file;
1456 zi->total_workingset_refault += node->fields.field.workingset_refault;
1457 }
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001458 return 0;
1459}
1460
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07001461/* /proc/meminfo parsing routines */
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001462static bool meminfo_parse_line(char *line, union meminfo *mi) {
1463 char *cp = line;
1464 char *ap;
1465 char *save_ptr;
1466 int64_t val;
1467 int field_idx;
1468 enum field_match_result match_res;
1469
1470 cp = strtok_r(line, " ", &save_ptr);
1471 if (!cp) {
1472 return false;
1473 }
1474
1475 ap = strtok_r(NULL, " ", &save_ptr);
1476 if (!ap) {
1477 return false;
1478 }
1479
1480 match_res = match_field(cp, ap, meminfo_field_names, MI_FIELD_COUNT,
1481 &val, &field_idx);
1482 if (match_res == PARSE_SUCCESS) {
1483 mi->arr[field_idx] = val / page_k;
1484 }
1485 return (match_res != PARSE_FAIL);
1486}
1487
1488static int meminfo_parse(union meminfo *mi) {
1489 static struct reread_data file_data = {
1490 .filename = MEMINFO_PATH,
1491 .fd = -1,
1492 };
Suren Baghdasaryana77b3272019-07-15 13:35:04 -07001493 char *buf;
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001494 char *save_ptr;
1495 char *line;
1496
1497 memset(mi, 0, sizeof(union meminfo));
1498
Suren Baghdasaryana77b3272019-07-15 13:35:04 -07001499 if ((buf = reread_file(&file_data)) == NULL) {
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001500 return -1;
1501 }
1502
1503 for (line = strtok_r(buf, "\n", &save_ptr); line;
1504 line = strtok_r(NULL, "\n", &save_ptr)) {
1505 if (!meminfo_parse_line(line, mi)) {
1506 ALOGE("%s parse error", file_data.filename);
1507 return -1;
1508 }
1509 }
1510 mi->field.nr_file_pages = mi->field.cached + mi->field.swap_cached +
1511 mi->field.buffers;
1512
1513 return 0;
1514}
1515
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07001516/* /proc/vmstat parsing routines */
1517static bool vmstat_parse_line(char *line, union vmstat *vs) {
1518 char *cp;
1519 char *ap;
1520 char *save_ptr;
1521 int64_t val;
1522 int field_idx;
1523 enum field_match_result match_res;
1524
1525 cp = strtok_r(line, " ", &save_ptr);
1526 if (!cp) {
1527 return false;
1528 }
1529
1530 ap = strtok_r(NULL, " ", &save_ptr);
1531 if (!ap) {
1532 return false;
1533 }
1534
1535 match_res = match_field(cp, ap, vmstat_field_names, VS_FIELD_COUNT,
1536 &val, &field_idx);
1537 if (match_res == PARSE_SUCCESS) {
1538 vs->arr[field_idx] = val;
1539 }
1540 return (match_res != PARSE_FAIL);
1541}
1542
1543static int vmstat_parse(union vmstat *vs) {
1544 static struct reread_data file_data = {
1545 .filename = VMSTAT_PATH,
1546 .fd = -1,
1547 };
1548 char *buf;
1549 char *save_ptr;
1550 char *line;
1551
1552 memset(vs, 0, sizeof(union vmstat));
1553
1554 if ((buf = reread_file(&file_data)) == NULL) {
1555 return -1;
1556 }
1557
1558 for (line = strtok_r(buf, "\n", &save_ptr); line;
1559 line = strtok_r(NULL, "\n", &save_ptr)) {
1560 if (!vmstat_parse_line(line, vs)) {
1561 ALOGE("%s parse error", file_data.filename);
1562 return -1;
1563 }
1564 }
1565
1566 return 0;
1567}
1568
Suren Baghdasaryana7ac5782019-09-16 12:06:30 -07001569static void killinfo_log(struct proc* procp, int min_oom_score, int tasksize,
1570 int kill_reason, union meminfo *mi) {
1571 /* log process information */
1572 android_log_write_int32(ctx, procp->pid);
1573 android_log_write_int32(ctx, procp->uid);
1574 android_log_write_int32(ctx, procp->oomadj);
1575 android_log_write_int32(ctx, min_oom_score);
1576 android_log_write_int32(ctx, (int32_t)min(tasksize * page_k, INT32_MAX));
1577 android_log_write_int32(ctx, kill_reason);
1578
1579 /* log meminfo fields */
Suren Baghdasaryan282ad1a2018-07-26 16:34:27 -07001580 for (int field_idx = 0; field_idx < MI_FIELD_COUNT; field_idx++) {
1581 android_log_write_int32(ctx, (int32_t)min(mi->arr[field_idx] * page_k, INT32_MAX));
1582 }
1583
1584 android_log_write_list(ctx, LOG_ID_EVENTS);
1585 android_log_reset(ctx);
1586}
1587
Todd Poynor3948f802013-07-09 19:35:14 -07001588static struct proc *proc_adj_lru(int oomadj) {
1589 return (struct proc *)adjslot_tail(&procadjslot_list[ADJTOSLOT(oomadj)]);
1590}
1591
Suren Baghdasaryan662492a2017-12-08 13:17:06 -08001592static struct proc *proc_get_heaviest(int oomadj) {
1593 struct adjslot_list *head = &procadjslot_list[ADJTOSLOT(oomadj)];
1594 struct adjslot_list *curr = head->next;
1595 struct proc *maxprocp = NULL;
1596 int maxsize = 0;
1597 while (curr != head) {
1598 int pid = ((struct proc *)curr)->pid;
1599 int tasksize = proc_get_size(pid);
1600 if (tasksize <= 0) {
1601 struct adjslot_list *next = curr->next;
1602 pid_remove(pid);
1603 curr = next;
1604 } else {
1605 if (tasksize > maxsize) {
1606 maxsize = tasksize;
1607 maxprocp = (struct proc *)curr;
1608 }
1609 curr = curr->next;
1610 }
1611 }
1612 return maxprocp;
1613}
1614
Wei Wang2d95c102018-11-21 00:11:44 -08001615static void set_process_group_and_prio(int pid, SchedPolicy sp, int prio) {
1616 DIR* d;
1617 char proc_path[PATH_MAX];
1618 struct dirent* de;
1619
1620 snprintf(proc_path, sizeof(proc_path), "/proc/%d/task", pid);
1621 if (!(d = opendir(proc_path))) {
1622 ALOGW("Failed to open %s; errno=%d: process pid(%d) might have died", proc_path, errno,
1623 pid);
1624 return;
1625 }
1626
1627 while ((de = readdir(d))) {
1628 int t_pid;
1629
1630 if (de->d_name[0] == '.') continue;
1631 t_pid = atoi(de->d_name);
1632
1633 if (!t_pid) {
1634 ALOGW("Failed to get t_pid for '%s' of pid(%d)", de->d_name, pid);
1635 continue;
1636 }
1637
1638 if (setpriority(PRIO_PROCESS, t_pid, prio) && errno != ESRCH) {
1639 ALOGW("Unable to raise priority of killing t_pid (%d): errno=%d", t_pid, errno);
1640 }
1641
1642 if (set_cpuset_policy(t_pid, sp)) {
1643 ALOGW("Failed to set_cpuset_policy on pid(%d) t_pid(%d) to %d", pid, t_pid, (int)sp);
1644 continue;
1645 }
1646 }
1647 closedir(d);
1648}
1649
Tim Murraye7853f62018-10-25 17:05:41 -07001650static int last_killed_pid = -1;
1651
Colin Cross16b09462014-07-14 12:39:56 -07001652/* Kill one process specified by procp. Returns the size of the process killed */
Suren Baghdasaryana7ac5782019-09-16 12:06:30 -07001653static int kill_one_process(struct proc* procp, int min_oom_score, int kill_reason,
1654 const char *kill_desc, union meminfo *mi) {
Colin Cross16b09462014-07-14 12:39:56 -07001655 int pid = procp->pid;
1656 uid_t uid = procp->uid;
Suren Baghdasaryan0082ef12019-07-02 15:52:07 -07001657 int tgid;
Colin Cross16b09462014-07-14 12:39:56 -07001658 char *taskname;
1659 int tasksize;
1660 int r;
Suren Baghdasaryan01063272018-10-12 11:28:33 -07001661 int result = -1;
Suren Baghdasaryanb72c6652019-09-04 19:12:29 -07001662 struct memory_stat *mem_st;
Rajeev Kumar70450032018-01-31 17:54:56 -08001663
Suren Baghdasaryan0082ef12019-07-02 15:52:07 -07001664 tgid = proc_get_tgid(pid);
1665 if (tgid >= 0 && tgid != pid) {
1666 ALOGE("Possible pid reuse detected (pid %d, tgid %d)!", pid, tgid);
1667 goto out;
1668 }
1669
Colin Cross16b09462014-07-14 12:39:56 -07001670 taskname = proc_get_name(pid);
1671 if (!taskname) {
Suren Baghdasaryan01063272018-10-12 11:28:33 -07001672 goto out;
Colin Cross16b09462014-07-14 12:39:56 -07001673 }
1674
1675 tasksize = proc_get_size(pid);
1676 if (tasksize <= 0) {
Suren Baghdasaryan01063272018-10-12 11:28:33 -07001677 goto out;
Colin Cross16b09462014-07-14 12:39:56 -07001678 }
1679
Suren Baghdasaryanb72c6652019-09-04 19:12:29 -07001680 mem_st = stats_read_memory_stat(per_app_memcg, pid, uid);
Rajeev Kumar70450032018-01-31 17:54:56 -08001681
Suren Baghdasaryanc7135592018-01-04 10:43:58 -08001682 TRACE_KILL_START(pid);
1683
Mark Salyzyn64d97d82018-04-09 09:50:32 -07001684 /* CAP_KILL required */
Suren Baghdasaryan96bf3a62017-12-08 12:58:52 -08001685 r = kill(pid, SIGKILL);
Wei Wang2d95c102018-11-21 00:11:44 -08001686
Suren Baghdasaryance862df2019-09-04 16:44:47 -07001687 TRACE_KILL_END();
1688
1689 if (r) {
1690 ALOGE("kill(%d): errno=%d", pid, errno);
1691 /* Delete process record even when we fail to kill so that we don't get stuck on it */
1692 goto out;
1693 }
1694
Wei Wang2d95c102018-11-21 00:11:44 -08001695 set_process_group_and_prio(pid, SP_FOREGROUND, ANDROID_PRIORITY_HIGHEST);
1696
Suren Baghdasaryand4a29902018-10-12 11:07:40 -07001697 inc_killcnt(procp->oomadj);
Suren Baghdasaryana7ac5782019-09-16 12:06:30 -07001698
1699 killinfo_log(procp, min_oom_score, tasksize, kill_reason, mi);
1700
1701 if (kill_desc) {
Suren Baghdasaryanfd7518f2019-07-15 15:50:17 -07001702 ALOGI("Kill '%s' (%d), uid %d, oom_adj %d to free %ldkB; reason: %s", taskname, pid,
Suren Baghdasaryana7ac5782019-09-16 12:06:30 -07001703 uid, procp->oomadj, tasksize * page_k, kill_desc);
Suren Baghdasaryanfd7518f2019-07-15 15:50:17 -07001704 } else {
1705 ALOGI("Kill '%s' (%d), uid %d, oom_adj %d to free %ldkB", taskname, pid,
1706 uid, procp->oomadj, tasksize * page_k);
1707 }
Colin Cross16b09462014-07-14 12:39:56 -07001708
Tim Murraye7853f62018-10-25 17:05:41 -07001709 last_killed_pid = pid;
1710
Suren Baghdasaryanb72c6652019-09-04 19:12:29 -07001711 stats_write_lmk_kill_occurred(LMK_KILL_OCCURRED, uid, taskname,
1712 procp->oomadj, min_oom_score, tasksize, mem_st);
1713
Suren Baghdasaryance862df2019-09-04 16:44:47 -07001714 result = tasksize;
Mark Salyzyn919f5382018-02-04 15:27:23 -08001715
Suren Baghdasaryan01063272018-10-12 11:28:33 -07001716out:
1717 /*
1718 * WARNING: After pid_remove() procp is freed and can't be used!
1719 * Therefore placed at the end of the function.
1720 */
1721 pid_remove(pid);
1722 return result;
Colin Cross16b09462014-07-14 12:39:56 -07001723}
1724
1725/*
Suren Baghdasaryanf81b5f42018-10-26 11:32:15 -07001726 * Find one process to kill at or above the given oom_adj level.
1727 * Returns size of the killed process.
Colin Cross16b09462014-07-14 12:39:56 -07001728 */
Suren Baghdasaryana7ac5782019-09-16 12:06:30 -07001729static int find_and_kill_process(int min_score_adj, int kill_reason, const char *kill_desc,
1730 union meminfo *mi) {
Colin Cross16b09462014-07-14 12:39:56 -07001731 int i;
Suren Baghdasaryanf81b5f42018-10-26 11:32:15 -07001732 int killed_size = 0;
Yang Lu5564f4e2018-05-15 04:59:44 +00001733 bool lmk_state_change_start = false;
Rajeev Kumar70450032018-01-31 17:54:56 -08001734
Chong Zhang0a4acdf2015-10-14 16:19:53 -07001735 for (i = OOM_SCORE_ADJ_MAX; i >= min_score_adj; i--) {
Colin Cross16b09462014-07-14 12:39:56 -07001736 struct proc *procp;
1737
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08001738 while (true) {
Suren Baghdasaryan818b59b2018-04-13 11:49:54 -07001739 procp = kill_heaviest_task ?
1740 proc_get_heaviest(i) : proc_adj_lru(i);
Colin Cross16b09462014-07-14 12:39:56 -07001741
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08001742 if (!procp)
1743 break;
1744
Suren Baghdasaryana7ac5782019-09-16 12:06:30 -07001745 killed_size = kill_one_process(procp, min_score_adj, kill_reason, kill_desc, mi);
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08001746 if (killed_size >= 0) {
Suren Baghdasaryanb72c6652019-09-04 19:12:29 -07001747 if (!lmk_state_change_start) {
Yang Lu5564f4e2018-05-15 04:59:44 +00001748 lmk_state_change_start = true;
Suren Baghdasaryanb72c6652019-09-04 19:12:29 -07001749 stats_write_lmk_state_changed(LMK_STATE_CHANGED,
Yang Lu5564f4e2018-05-15 04:59:44 +00001750 LMK_STATE_CHANGE_START);
1751 }
Suren Baghdasaryanf81b5f42018-10-26 11:32:15 -07001752 break;
Colin Cross16b09462014-07-14 12:39:56 -07001753 }
1754 }
Suren Baghdasaryanf81b5f42018-10-26 11:32:15 -07001755 if (killed_size) {
1756 break;
1757 }
Colin Cross16b09462014-07-14 12:39:56 -07001758 }
1759
Suren Baghdasaryanb72c6652019-09-04 19:12:29 -07001760 if (lmk_state_change_start) {
1761 stats_write_lmk_state_changed(LMK_STATE_CHANGED, LMK_STATE_CHANGE_STOP);
Rajeev Kumar70450032018-01-31 17:54:56 -08001762 }
Rajeev Kumar70450032018-01-31 17:54:56 -08001763
Suren Baghdasaryanf81b5f42018-10-26 11:32:15 -07001764 return killed_size;
Colin Cross16b09462014-07-14 12:39:56 -07001765}
1766
Suren Baghdasaryan6499e5e2018-04-13 12:43:41 -07001767static int64_t get_memory_usage(struct reread_data *file_data) {
Robert Beneac47f2992017-08-21 15:18:31 -07001768 int ret;
1769 int64_t mem_usage;
Suren Baghdasaryana77b3272019-07-15 13:35:04 -07001770 char *buf;
Suren Baghdasaryan6499e5e2018-04-13 12:43:41 -07001771
Suren Baghdasaryana77b3272019-07-15 13:35:04 -07001772 if ((buf = reread_file(file_data)) == NULL) {
Robert Beneac47f2992017-08-21 15:18:31 -07001773 return -1;
1774 }
1775
Suren Baghdasaryan6499e5e2018-04-13 12:43:41 -07001776 if (!parse_int64(buf, &mem_usage)) {
1777 ALOGE("%s parse error", file_data->filename);
Robert Beneac47f2992017-08-21 15:18:31 -07001778 return -1;
1779 }
Robert Beneac47f2992017-08-21 15:18:31 -07001780 if (mem_usage == 0) {
1781 ALOGE("No memory!");
1782 return -1;
1783 }
1784 return mem_usage;
1785}
1786
Suren Baghdasaryan9926e572018-04-13 13:41:12 -07001787void record_low_pressure_levels(union meminfo *mi) {
1788 if (low_pressure_mem.min_nr_free_pages == -1 ||
1789 low_pressure_mem.min_nr_free_pages > mi->field.nr_free_pages) {
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08001790 if (debug_process_killing) {
Suren Baghdasaryan9926e572018-04-13 13:41:12 -07001791 ALOGI("Low pressure min memory update from %" PRId64 " to %" PRId64,
1792 low_pressure_mem.min_nr_free_pages, mi->field.nr_free_pages);
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08001793 }
Suren Baghdasaryan9926e572018-04-13 13:41:12 -07001794 low_pressure_mem.min_nr_free_pages = mi->field.nr_free_pages;
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08001795 }
1796 /*
1797 * Free memory at low vmpressure events occasionally gets spikes,
1798 * possibly a stale low vmpressure event with memory already
1799 * freed up (no memory pressure should have been reported).
Suren Baghdasaryan9926e572018-04-13 13:41:12 -07001800 * Ignore large jumps in max_nr_free_pages that would mess up our stats.
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08001801 */
Suren Baghdasaryan9926e572018-04-13 13:41:12 -07001802 if (low_pressure_mem.max_nr_free_pages == -1 ||
1803 (low_pressure_mem.max_nr_free_pages < mi->field.nr_free_pages &&
1804 mi->field.nr_free_pages - low_pressure_mem.max_nr_free_pages <
1805 low_pressure_mem.max_nr_free_pages * 0.1)) {
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08001806 if (debug_process_killing) {
Suren Baghdasaryan9926e572018-04-13 13:41:12 -07001807 ALOGI("Low pressure max memory update from %" PRId64 " to %" PRId64,
1808 low_pressure_mem.max_nr_free_pages, mi->field.nr_free_pages);
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08001809 }
Suren Baghdasaryan9926e572018-04-13 13:41:12 -07001810 low_pressure_mem.max_nr_free_pages = mi->field.nr_free_pages;
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08001811 }
1812}
1813
Suren Baghdasaryan96bf3a62017-12-08 12:58:52 -08001814enum vmpressure_level upgrade_level(enum vmpressure_level level) {
1815 return (enum vmpressure_level)((level < VMPRESS_LEVEL_CRITICAL) ?
1816 level + 1 : level);
1817}
1818
1819enum vmpressure_level downgrade_level(enum vmpressure_level level) {
1820 return (enum vmpressure_level)((level > VMPRESS_LEVEL_LOW) ?
1821 level - 1 : level);
1822}
1823
Tim Murraye7853f62018-10-25 17:05:41 -07001824static bool is_kill_pending(void) {
1825 char buf[24];
1826
1827 if (last_killed_pid < 0) {
1828 return false;
1829 }
1830
1831 snprintf(buf, sizeof(buf), "/proc/%d/", last_killed_pid);
1832 if (access(buf, F_OK) == 0) {
1833 return true;
1834 }
1835
1836 // reset last killed PID because there's nothing pending
1837 last_killed_pid = -1;
1838 return false;
1839}
1840
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07001841enum zone_watermark {
1842 WMARK_MIN = 0,
1843 WMARK_LOW,
1844 WMARK_HIGH,
1845 WMARK_NONE
1846};
1847
Suren Baghdasaryan4787ab42019-08-14 09:48:35 -07001848struct zone_watermarks {
1849 long high_wmark;
1850 long low_wmark;
1851 long min_wmark;
1852};
1853
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07001854/*
1855 * Returns lowest breached watermark or WMARK_NONE.
1856 */
Suren Baghdasaryan4787ab42019-08-14 09:48:35 -07001857static enum zone_watermark get_lowest_watermark(union meminfo *mi,
1858 struct zone_watermarks *watermarks)
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07001859{
Suren Baghdasaryan4787ab42019-08-14 09:48:35 -07001860 int64_t nr_free_pages = mi->field.nr_free_pages - mi->field.cma_free;
1861
1862 if (nr_free_pages < watermarks->min_wmark) {
1863 return WMARK_MIN;
1864 }
1865 if (nr_free_pages < watermarks->low_wmark) {
1866 return WMARK_LOW;
1867 }
1868 if (nr_free_pages < watermarks->high_wmark) {
1869 return WMARK_HIGH;
1870 }
1871 return WMARK_NONE;
1872}
1873
1874void calc_zone_watermarks(struct zoneinfo *zi, struct zone_watermarks *watermarks) {
1875 memset(watermarks, 0, sizeof(struct zone_watermarks));
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07001876
1877 for (int node_idx = 0; node_idx < zi->node_count; node_idx++) {
1878 struct zoneinfo_node *node = &zi->nodes[node_idx];
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07001879 for (int zone_idx = 0; zone_idx < node->zone_count; zone_idx++) {
1880 struct zoneinfo_zone *zone = &node->zones[zone_idx];
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07001881
1882 if (!zone->fields.field.present) {
1883 continue;
1884 }
1885
Suren Baghdasaryan4787ab42019-08-14 09:48:35 -07001886 watermarks->high_wmark += zone->max_protection + zone->fields.field.high;
1887 watermarks->low_wmark += zone->max_protection + zone->fields.field.low;
1888 watermarks->min_wmark += zone->max_protection + zone->fields.field.min;
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07001889 }
1890 }
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07001891}
1892
1893static void mp_event_psi(int data, uint32_t events, struct polling_params *poll_params) {
1894 enum kill_reasons {
1895 NONE = -1, /* To denote no kill condition */
1896 PRESSURE_AFTER_KILL = 0,
1897 NOT_RESPONDING,
1898 LOW_SWAP_AND_THRASHING,
1899 LOW_MEM_AND_SWAP,
1900 LOW_MEM_AND_THRASHING,
1901 DIRECT_RECL_AND_THRASHING,
1902 KILL_REASON_COUNT
1903 };
1904 enum reclaim_state {
1905 NO_RECLAIM = 0,
1906 KSWAPD_RECLAIM,
1907 DIRECT_RECLAIM,
1908 };
1909 static int64_t init_ws_refault;
1910 static int64_t base_file_lru;
1911 static int64_t init_pgscan_kswapd;
1912 static int64_t init_pgscan_direct;
1913 static int64_t swap_low_threshold;
1914 static bool killing;
1915 static int thrashing_limit;
1916 static bool in_reclaim;
Suren Baghdasaryan4787ab42019-08-14 09:48:35 -07001917 static struct zone_watermarks watermarks;
1918 static struct timespec wmark_update_tm;
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07001919
1920 union meminfo mi;
1921 union vmstat vs;
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07001922 struct timespec curr_tm;
1923 int64_t thrashing = 0;
1924 bool swap_is_low = false;
1925 enum vmpressure_level level = (enum vmpressure_level)data;
1926 enum kill_reasons kill_reason = NONE;
1927 bool cycle_after_kill = false;
1928 enum reclaim_state reclaim = NO_RECLAIM;
1929 enum zone_watermark wmark = WMARK_NONE;
Suren Baghdasaryanfd7518f2019-07-15 15:50:17 -07001930 char kill_desc[LINE_MAX];
Suren Baghdasaryan4b750882019-09-19 15:27:21 -07001931 bool cut_thrashing_limit = false;
1932 int min_score_adj = 0;
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07001933
1934 /* Skip while still killing a process */
1935 if (is_kill_pending()) {
1936 /* TODO: replace this quick polling with pidfd polling if kernel supports */
1937 goto no_kill;
1938 }
1939
1940 if (clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm) != 0) {
1941 ALOGE("Failed to get current time");
1942 return;
1943 }
1944
1945 if (vmstat_parse(&vs) < 0) {
1946 ALOGE("Failed to parse vmstat!");
1947 return;
1948 }
1949
1950 if (meminfo_parse(&mi) < 0) {
1951 ALOGE("Failed to parse meminfo!");
1952 return;
1953 }
1954
1955 /* Reset states after process got killed */
1956 if (killing) {
1957 killing = false;
1958 cycle_after_kill = true;
1959 /* Reset file-backed pagecache size and refault amounts after a kill */
1960 base_file_lru = vs.field.nr_inactive_file + vs.field.nr_active_file;
1961 init_ws_refault = vs.field.workingset_refault;
1962 }
1963
1964 /* Check free swap levels */
1965 if (swap_free_low_percentage) {
1966 if (!swap_low_threshold) {
1967 swap_low_threshold = mi.field.total_swap * swap_free_low_percentage / 100;
1968 }
1969 swap_is_low = mi.field.free_swap < swap_low_threshold;
1970 }
1971
1972 /* Identify reclaim state */
1973 if (vs.field.pgscan_direct > init_pgscan_direct) {
1974 init_pgscan_direct = vs.field.pgscan_direct;
1975 init_pgscan_kswapd = vs.field.pgscan_kswapd;
1976 reclaim = DIRECT_RECLAIM;
1977 } else if (vs.field.pgscan_kswapd > init_pgscan_kswapd) {
1978 init_pgscan_kswapd = vs.field.pgscan_kswapd;
1979 reclaim = KSWAPD_RECLAIM;
1980 } else {
1981 in_reclaim = false;
1982 /* Skip if system is not reclaiming */
1983 goto no_kill;
1984 }
1985
1986 if (!in_reclaim) {
1987 /* Record file-backed pagecache size when entering reclaim cycle */
1988 base_file_lru = vs.field.nr_inactive_file + vs.field.nr_active_file;
1989 init_ws_refault = vs.field.workingset_refault;
1990 thrashing_limit = thrashing_limit_pct;
1991 } else {
1992 /* Calculate what % of the file-backed pagecache refaulted so far */
1993 thrashing = (vs.field.workingset_refault - init_ws_refault) * 100 / base_file_lru;
1994 }
1995 in_reclaim = true;
1996
Suren Baghdasaryan4787ab42019-08-14 09:48:35 -07001997 /*
1998 * Refresh watermarks once per min in case user updated one of the margins.
1999 * TODO: b/140521024 replace this periodic update with an API for AMS to notify LMKD
2000 * that zone watermarks were changed by the system software.
2001 */
2002 if (watermarks.high_wmark == 0 || get_time_diff_ms(&wmark_update_tm, &curr_tm) > 60000) {
2003 struct zoneinfo zi;
2004
2005 if (zoneinfo_parse(&zi) < 0) {
2006 ALOGE("Failed to parse zoneinfo!");
2007 return;
2008 }
2009
2010 calc_zone_watermarks(&zi, &watermarks);
2011 wmark_update_tm = curr_tm;
2012 }
2013
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002014 /* Find out which watermark is breached if any */
Suren Baghdasaryan4787ab42019-08-14 09:48:35 -07002015 wmark = get_lowest_watermark(&mi, &watermarks);
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002016
2017 /*
2018 * TODO: move this logic into a separate function
2019 * Decide if killing a process is necessary and record the reason
2020 */
2021 if (cycle_after_kill && wmark < WMARK_LOW) {
2022 /*
2023 * Prevent kills not freeing enough memory which might lead to OOM kill.
2024 * This might happen when a process is consuming memory faster than reclaim can
2025 * free even after a kill. Mostly happens when running memory stress tests.
2026 */
2027 kill_reason = PRESSURE_AFTER_KILL;
Suren Baghdasaryanfd7518f2019-07-15 15:50:17 -07002028 strncpy(kill_desc, "min watermark is breached even after kill", sizeof(kill_desc));
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002029 } else if (level == VMPRESS_LEVEL_CRITICAL && events != 0) {
2030 /*
2031 * Device is too busy reclaiming memory which might lead to ANR.
2032 * Critical level is triggered when PSI complete stall (all tasks are blocked because
2033 * of the memory congestion) breaches the configured threshold.
2034 */
2035 kill_reason = NOT_RESPONDING;
Suren Baghdasaryanfd7518f2019-07-15 15:50:17 -07002036 strncpy(kill_desc, "device is not responding", sizeof(kill_desc));
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002037 } else if (swap_is_low && thrashing > thrashing_limit_pct) {
2038 /* Page cache is thrashing while swap is low */
2039 kill_reason = LOW_SWAP_AND_THRASHING;
Suren Baghdasaryanfd7518f2019-07-15 15:50:17 -07002040 snprintf(kill_desc, sizeof(kill_desc), "device is low on swap (%" PRId64
2041 "kB < %" PRId64 "kB) and thrashing (%" PRId64 "%%)",
2042 mi.field.free_swap * page_k, swap_low_threshold * page_k, thrashing);
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002043 } else if (swap_is_low && wmark < WMARK_HIGH) {
2044 /* Both free memory and swap are low */
2045 kill_reason = LOW_MEM_AND_SWAP;
Suren Baghdasaryanfd7518f2019-07-15 15:50:17 -07002046 snprintf(kill_desc, sizeof(kill_desc), "%s watermark is breached and swap is low (%"
2047 PRId64 "kB < %" PRId64 "kB)", wmark > WMARK_LOW ? "min" : "low",
2048 mi.field.free_swap * page_k, swap_low_threshold * page_k);
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002049 } else if (wmark < WMARK_HIGH && thrashing > thrashing_limit) {
2050 /* Page cache is thrashing while memory is low */
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002051 kill_reason = LOW_MEM_AND_THRASHING;
Suren Baghdasaryanfd7518f2019-07-15 15:50:17 -07002052 snprintf(kill_desc, sizeof(kill_desc), "%s watermark is breached and thrashing (%"
2053 PRId64 "%%)", wmark > WMARK_LOW ? "min" : "low", thrashing);
Suren Baghdasaryan4b750882019-09-19 15:27:21 -07002054 cut_thrashing_limit = true;
2055 /* Do not kill perceptible apps because of thrashing */
2056 min_score_adj = PERCEPTIBLE_APP_ADJ;
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002057 } else if (reclaim == DIRECT_RECLAIM && thrashing > thrashing_limit) {
2058 /* Page cache is thrashing while in direct reclaim (mostly happens on lowram devices) */
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002059 kill_reason = DIRECT_RECL_AND_THRASHING;
Suren Baghdasaryanfd7518f2019-07-15 15:50:17 -07002060 snprintf(kill_desc, sizeof(kill_desc), "device is in direct reclaim and thrashing (%"
2061 PRId64 "%%)", thrashing);
Suren Baghdasaryan4b750882019-09-19 15:27:21 -07002062 cut_thrashing_limit = true;
2063 /* Do not kill perceptible apps because of thrashing */
2064 min_score_adj = PERCEPTIBLE_APP_ADJ;
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002065 }
2066
2067 /* Kill a process if necessary */
2068 if (kill_reason != NONE) {
Suren Baghdasaryana7ac5782019-09-16 12:06:30 -07002069 int pages_freed = find_and_kill_process(min_score_adj, kill_reason, kill_desc, &mi);
Suren Baghdasaryan4b750882019-09-19 15:27:21 -07002070 if (pages_freed > 0) {
2071 killing = true;
2072 if (cut_thrashing_limit) {
2073 /*
2074 * Cut thrasing limit by thrashing_limit_decay_pct percentage of the current
2075 * thrashing limit until the system stops thrashing.
2076 */
2077 thrashing_limit = (thrashing_limit * (100 - thrashing_limit_decay_pct)) / 100;
2078 }
2079 }
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002080 }
2081
2082no_kill:
2083 /*
2084 * Start polling after initial PSI event;
2085 * extend polling while device is in direct reclaim or process is being killed;
2086 * do not extend when kswapd reclaims because that might go on for a long time
2087 * without causing memory pressure
2088 */
2089 if (events || killing || reclaim == DIRECT_RECLAIM) {
2090 poll_params->update = POLLING_START;
2091 }
2092
2093 /* Decide the polling interval */
2094 if (swap_is_low || killing) {
2095 /* Fast polling during and after a kill or when swap is low */
2096 poll_params->polling_interval_ms = PSI_POLL_PERIOD_SHORT_MS;
2097 } else {
2098 /* By default use long intervals */
2099 poll_params->polling_interval_ms = PSI_POLL_PERIOD_LONG_MS;
2100 }
2101}
2102
Suren Baghdasaryanef3650f2019-07-15 14:50:49 -07002103static void mp_event_common(int data, uint32_t events, struct polling_params *poll_params) {
Todd Poynor3948f802013-07-09 19:35:14 -07002104 int ret;
2105 unsigned long long evcount;
Robert Beneac47f2992017-08-21 15:18:31 -07002106 int64_t mem_usage, memsw_usage;
Robert Benea6e8e7102017-09-13 15:20:30 -07002107 int64_t mem_pressure;
Suren Baghdasaryane82e15c2018-01-04 09:16:21 -08002108 enum vmpressure_level lvl;
Suren Baghdasaryan9926e572018-04-13 13:41:12 -07002109 union meminfo mi;
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07002110 struct zoneinfo zi;
Suren Baghdasaryan36934412018-09-05 15:46:32 -07002111 struct timespec curr_tm;
Suren Baghdasaryan314a5052018-07-24 17:13:06 -07002112 static struct timespec last_kill_tm;
2113 static unsigned long kill_skip_count = 0;
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08002114 enum vmpressure_level level = (enum vmpressure_level)data;
Suren Baghdasaryanffdc4dd2018-04-13 13:53:43 -07002115 long other_free = 0, other_file = 0;
2116 int min_score_adj;
Suren Baghdasaryanffdc4dd2018-04-13 13:53:43 -07002117 int minfree = 0;
Suren Baghdasaryan6499e5e2018-04-13 12:43:41 -07002118 static struct reread_data mem_usage_file_data = {
2119 .filename = MEMCG_MEMORY_USAGE,
2120 .fd = -1,
2121 };
2122 static struct reread_data memsw_usage_file_data = {
2123 .filename = MEMCG_MEMORYSW_USAGE,
2124 .fd = -1,
2125 };
Todd Poynor3948f802013-07-09 19:35:14 -07002126
Suren Baghdasaryan77122e52019-01-08 12:54:48 -08002127 if (debug_process_killing) {
2128 ALOGI("%s memory pressure event is triggered", level_name[level]);
2129 }
2130
2131 if (!use_psi_monitors) {
2132 /*
2133 * Check all event counters from low to critical
2134 * and upgrade to the highest priority one. By reading
2135 * eventfd we also reset the event counters.
2136 */
2137 for (lvl = VMPRESS_LEVEL_LOW; lvl < VMPRESS_LEVEL_COUNT; lvl++) {
2138 if (mpevfd[lvl] != -1 &&
2139 TEMP_FAILURE_RETRY(read(mpevfd[lvl],
2140 &evcount, sizeof(evcount))) > 0 &&
2141 evcount > 0 && lvl > level) {
2142 level = lvl;
2143 }
Suren Baghdasaryane82e15c2018-01-04 09:16:21 -08002144 }
2145 }
Todd Poynor3948f802013-07-09 19:35:14 -07002146
Suren Baghdasaryanef3650f2019-07-15 14:50:49 -07002147 /* Start polling after initial PSI event */
2148 if (use_psi_monitors && events) {
2149 /* Override polling params only if current event is more critical */
2150 if (!poll_params->poll_handler || data > poll_params->poll_handler->data) {
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002151 poll_params->polling_interval_ms = PSI_POLL_PERIOD_SHORT_MS;
Suren Baghdasaryanef3650f2019-07-15 14:50:49 -07002152 poll_params->update = POLLING_START;
2153 }
2154 }
2155
Suren Baghdasaryan36934412018-09-05 15:46:32 -07002156 if (clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm) != 0) {
2157 ALOGE("Failed to get current time");
2158 return;
2159 }
2160
Suren Baghdasaryancaa2dc52018-01-17 17:28:01 -08002161 if (kill_timeout_ms) {
Tim Murraye7853f62018-10-25 17:05:41 -07002162 // If we're within the timeout, see if there's pending reclaim work
2163 // from the last killed process. If there is (as evidenced by
2164 // /proc/<pid> continuing to exist), skip killing for now.
2165 if ((get_time_diff_ms(&last_kill_tm, &curr_tm) < kill_timeout_ms) &&
2166 (low_ram_device || is_kill_pending())) {
Suren Baghdasaryan314a5052018-07-24 17:13:06 -07002167 kill_skip_count++;
Suren Baghdasaryancaa2dc52018-01-17 17:28:01 -08002168 return;
2169 }
2170 }
2171
Suren Baghdasaryan314a5052018-07-24 17:13:06 -07002172 if (kill_skip_count > 0) {
Suren Baghdasaryanda88b242018-05-10 16:10:56 -07002173 ALOGI("%lu memory pressure events were skipped after a kill!",
Suren Baghdasaryan314a5052018-07-24 17:13:06 -07002174 kill_skip_count);
2175 kill_skip_count = 0;
Suren Baghdasaryancaa2dc52018-01-17 17:28:01 -08002176 }
2177
Suren Baghdasaryanffdc4dd2018-04-13 13:53:43 -07002178 if (meminfo_parse(&mi) < 0 || zoneinfo_parse(&zi) < 0) {
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08002179 ALOGE("Failed to get free memory!");
2180 return;
2181 }
2182
Suren Baghdasaryanffdc4dd2018-04-13 13:53:43 -07002183 if (use_minfree_levels) {
2184 int i;
2185
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07002186 other_free = mi.field.nr_free_pages - zi.totalreserve_pages;
Suren Baghdasaryanffdc4dd2018-04-13 13:53:43 -07002187 if (mi.field.nr_file_pages > (mi.field.shmem + mi.field.unevictable + mi.field.swap_cached)) {
2188 other_file = (mi.field.nr_file_pages - mi.field.shmem -
2189 mi.field.unevictable - mi.field.swap_cached);
2190 } else {
2191 other_file = 0;
2192 }
2193
2194 min_score_adj = OOM_SCORE_ADJ_MAX + 1;
2195 for (i = 0; i < lowmem_targets_size; i++) {
2196 minfree = lowmem_minfree[i];
2197 if (other_free < minfree && other_file < minfree) {
2198 min_score_adj = lowmem_adj[i];
2199 break;
2200 }
2201 }
2202
Suren Baghdasaryan20686f02018-05-18 14:42:00 -07002203 if (min_score_adj == OOM_SCORE_ADJ_MAX + 1) {
2204 if (debug_process_killing) {
2205 ALOGI("Ignore %s memory pressure event "
2206 "(free memory=%ldkB, cache=%ldkB, limit=%ldkB)",
2207 level_name[level], other_free * page_k, other_file * page_k,
2208 (long)lowmem_minfree[lowmem_targets_size - 1] * page_k);
2209 }
Suren Baghdasaryanffdc4dd2018-04-13 13:53:43 -07002210 return;
Suren Baghdasaryan20686f02018-05-18 14:42:00 -07002211 }
Suren Baghdasaryanffdc4dd2018-04-13 13:53:43 -07002212
Suren Baghdasaryanffdc4dd2018-04-13 13:53:43 -07002213 goto do_kill;
2214 }
2215
Suren Baghdasaryan9926e572018-04-13 13:41:12 -07002216 if (level == VMPRESS_LEVEL_LOW) {
2217 record_low_pressure_levels(&mi);
2218 }
2219
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08002220 if (level_oomadj[level] > OOM_SCORE_ADJ_MAX) {
2221 /* Do not monitor this pressure level */
2222 return;
2223 }
2224
Suren Baghdasaryan6499e5e2018-04-13 12:43:41 -07002225 if ((mem_usage = get_memory_usage(&mem_usage_file_data)) < 0) {
2226 goto do_kill;
2227 }
2228 if ((memsw_usage = get_memory_usage(&memsw_usage_file_data)) < 0) {
Suren Baghdasaryan96bf3a62017-12-08 12:58:52 -08002229 goto do_kill;
Robert Benea6e8e7102017-09-13 15:20:30 -07002230 }
Robert Beneac47f2992017-08-21 15:18:31 -07002231
Robert Benea6e8e7102017-09-13 15:20:30 -07002232 // Calculate percent for swappinness.
2233 mem_pressure = (mem_usage * 100) / memsw_usage;
2234
Suren Baghdasaryan96bf3a62017-12-08 12:58:52 -08002235 if (enable_pressure_upgrade && level != VMPRESS_LEVEL_CRITICAL) {
Robert Benea6e8e7102017-09-13 15:20:30 -07002236 // We are swapping too much.
2237 if (mem_pressure < upgrade_pressure) {
Suren Baghdasaryan96bf3a62017-12-08 12:58:52 -08002238 level = upgrade_level(level);
2239 if (debug_process_killing) {
2240 ALOGI("Event upgraded to %s", level_name[level]);
2241 }
Robert Beneac47f2992017-08-21 15:18:31 -07002242 }
2243 }
2244
Vic Yang360a1132018-08-07 10:18:22 -07002245 // If we still have enough swap space available, check if we want to
2246 // ignore/downgrade pressure events.
2247 if (mi.field.free_swap >=
2248 mi.field.total_swap * swap_free_low_percentage / 100) {
2249 // If the pressure is larger than downgrade_pressure lmk will not
2250 // kill any process, since enough memory is available.
2251 if (mem_pressure > downgrade_pressure) {
2252 if (debug_process_killing) {
2253 ALOGI("Ignore %s memory pressure", level_name[level]);
2254 }
2255 return;
2256 } else if (level == VMPRESS_LEVEL_CRITICAL && mem_pressure > upgrade_pressure) {
2257 if (debug_process_killing) {
2258 ALOGI("Downgrade critical memory pressure");
2259 }
2260 // Downgrade event, since enough memory available.
2261 level = downgrade_level(level);
Robert Benea6e8e7102017-09-13 15:20:30 -07002262 }
Robert Benea6e8e7102017-09-13 15:20:30 -07002263 }
2264
Suren Baghdasaryan96bf3a62017-12-08 12:58:52 -08002265do_kill:
Suren Baghdasaryanff61afb2018-04-13 11:45:38 -07002266 if (low_ram_device) {
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08002267 /* For Go devices kill only one task */
Suren Baghdasaryana7ac5782019-09-16 12:06:30 -07002268 if (find_and_kill_process(level_oomadj[level], -1, NULL, &mi) == 0) {
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08002269 if (debug_process_killing) {
2270 ALOGI("Nothing to kill");
2271 }
2272 }
2273 } else {
Suren Baghdasaryanffdc4dd2018-04-13 13:53:43 -07002274 int pages_freed;
Suren Baghdasaryan36934412018-09-05 15:46:32 -07002275 static struct timespec last_report_tm;
2276 static unsigned long report_skip_count = 0;
Suren Baghdasaryanffdc4dd2018-04-13 13:53:43 -07002277
2278 if (!use_minfree_levels) {
Suren Baghdasaryanffdc4dd2018-04-13 13:53:43 -07002279 /* Free up enough memory to downgrate the memory pressure to low level */
Suren Baghdasaryanf81b5f42018-10-26 11:32:15 -07002280 if (mi.field.nr_free_pages >= low_pressure_mem.max_nr_free_pages) {
Suren Baghdasaryanffdc4dd2018-04-13 13:53:43 -07002281 if (debug_process_killing) {
2282 ALOGI("Ignoring pressure since more memory is "
2283 "available (%" PRId64 ") than watermark (%" PRId64 ")",
2284 mi.field.nr_free_pages, low_pressure_mem.max_nr_free_pages);
2285 }
2286 return;
2287 }
2288 min_score_adj = level_oomadj[level];
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08002289 }
2290
Suren Baghdasaryana7ac5782019-09-16 12:06:30 -07002291 pages_freed = find_and_kill_process(min_score_adj, -1, NULL, &mi);
Suren Baghdasaryanda88b242018-05-10 16:10:56 -07002292
Suren Baghdasaryan36934412018-09-05 15:46:32 -07002293 if (pages_freed == 0) {
2294 /* Rate limit kill reports when nothing was reclaimed */
2295 if (get_time_diff_ms(&last_report_tm, &curr_tm) < FAIL_REPORT_RLIMIT_MS) {
2296 report_skip_count++;
Suren Baghdasaryan314a5052018-07-24 17:13:06 -07002297 return;
2298 }
Tim Murraye7853f62018-10-25 17:05:41 -07002299 } else {
2300 /* If we killed anything, update the last killed timestamp. */
2301 last_kill_tm = curr_tm;
Robert Beneacaeaa652017-08-11 16:03:20 -07002302 }
Suren Baghdasaryan36934412018-09-05 15:46:32 -07002303
Suren Baghdasaryana7ac5782019-09-16 12:06:30 -07002304 /* Log whenever we kill or when report rate limit allows */
Suren Baghdasaryan36934412018-09-05 15:46:32 -07002305 if (use_minfree_levels) {
Suren Baghdasaryanf81b5f42018-10-26 11:32:15 -07002306 ALOGI("Reclaimed %ldkB, cache(%ldkB) and "
Suren Baghdasaryan36934412018-09-05 15:46:32 -07002307 "free(%" PRId64 "kB)-reserved(%" PRId64 "kB) below min(%ldkB) for oom_adj %d",
Suren Baghdasaryanf81b5f42018-10-26 11:32:15 -07002308 pages_freed * page_k,
Suren Baghdasaryan36934412018-09-05 15:46:32 -07002309 other_file * page_k, mi.field.nr_free_pages * page_k,
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07002310 zi.totalreserve_pages * page_k,
Suren Baghdasaryan36934412018-09-05 15:46:32 -07002311 minfree * page_k, min_score_adj);
2312 } else {
Suren Baghdasaryanf81b5f42018-10-26 11:32:15 -07002313 ALOGI("Reclaimed %ldkB at oom_adj %d",
2314 pages_freed * page_k, min_score_adj);
Suren Baghdasaryan36934412018-09-05 15:46:32 -07002315 }
2316
2317 if (report_skip_count > 0) {
2318 ALOGI("Suppressed %lu failed kill reports", report_skip_count);
2319 report_skip_count = 0;
2320 }
2321
2322 last_report_tm = curr_tm;
Colin Crossf8857cc2014-07-11 17:16:56 -07002323 }
Todd Poynor3948f802013-07-09 19:35:14 -07002324}
2325
Suren Baghdasaryan844f26b2019-07-15 15:42:09 -07002326static bool init_mp_psi(enum vmpressure_level level, bool use_new_strategy) {
2327 int fd;
2328
2329 /* Do not register a handler if threshold_ms is not set */
2330 if (!psi_thresholds[level].threshold_ms) {
2331 return true;
2332 }
2333
2334 fd = init_psi_monitor(psi_thresholds[level].stall_type,
Suren Baghdasaryan77122e52019-01-08 12:54:48 -08002335 psi_thresholds[level].threshold_ms * US_PER_MS,
2336 PSI_WINDOW_SIZE_MS * US_PER_MS);
2337
2338 if (fd < 0) {
2339 return false;
2340 }
2341
Suren Baghdasaryan844f26b2019-07-15 15:42:09 -07002342 vmpressure_hinfo[level].handler = use_new_strategy ? mp_event_psi : mp_event_common;
Suren Baghdasaryan77122e52019-01-08 12:54:48 -08002343 vmpressure_hinfo[level].data = level;
2344 if (register_psi_monitor(epollfd, fd, &vmpressure_hinfo[level]) < 0) {
2345 destroy_psi_monitor(fd);
2346 return false;
2347 }
2348 maxevents++;
2349 mpevfd[level] = fd;
2350
2351 return true;
2352}
2353
2354static void destroy_mp_psi(enum vmpressure_level level) {
2355 int fd = mpevfd[level];
2356
2357 if (unregister_psi_monitor(epollfd, fd) < 0) {
2358 ALOGE("Failed to unregister psi monitor for %s memory pressure; errno=%d",
2359 level_name[level], errno);
2360 }
2361 destroy_psi_monitor(fd);
2362 mpevfd[level] = -1;
2363}
2364
2365static bool init_psi_monitors() {
Suren Baghdasaryan844f26b2019-07-15 15:42:09 -07002366 /*
2367 * When PSI is used on low-ram devices or on high-end devices without memfree levels
2368 * use new kill strategy based on zone watermarks, free swap and thrashing stats
2369 */
2370 bool use_new_strategy =
2371 property_get_bool("ro.lmk.use_new_strategy", low_ram_device || !use_minfree_levels);
2372
2373 /* In default PSI mode override stall amounts using system properties */
2374 if (use_new_strategy) {
2375 /* Do not use low pressure level */
2376 psi_thresholds[VMPRESS_LEVEL_LOW].threshold_ms = 0;
2377 psi_thresholds[VMPRESS_LEVEL_MEDIUM].threshold_ms = psi_partial_stall_ms;
2378 psi_thresholds[VMPRESS_LEVEL_CRITICAL].threshold_ms = psi_complete_stall_ms;
2379 }
2380
2381 if (!init_mp_psi(VMPRESS_LEVEL_LOW, use_new_strategy)) {
Suren Baghdasaryan77122e52019-01-08 12:54:48 -08002382 return false;
2383 }
Suren Baghdasaryan844f26b2019-07-15 15:42:09 -07002384 if (!init_mp_psi(VMPRESS_LEVEL_MEDIUM, use_new_strategy)) {
Suren Baghdasaryan77122e52019-01-08 12:54:48 -08002385 destroy_mp_psi(VMPRESS_LEVEL_LOW);
2386 return false;
2387 }
Suren Baghdasaryan844f26b2019-07-15 15:42:09 -07002388 if (!init_mp_psi(VMPRESS_LEVEL_CRITICAL, use_new_strategy)) {
Suren Baghdasaryan77122e52019-01-08 12:54:48 -08002389 destroy_mp_psi(VMPRESS_LEVEL_MEDIUM);
2390 destroy_mp_psi(VMPRESS_LEVEL_LOW);
2391 return false;
2392 }
2393 return true;
2394}
2395
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08002396static bool init_mp_common(enum vmpressure_level level) {
Todd Poynor3948f802013-07-09 19:35:14 -07002397 int mpfd;
2398 int evfd;
2399 int evctlfd;
2400 char buf[256];
2401 struct epoll_event epev;
2402 int ret;
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08002403 int level_idx = (int)level;
2404 const char *levelstr = level_name[level_idx];
Suren Baghdasaryan96bf3a62017-12-08 12:58:52 -08002405
Mark Salyzyn64d97d82018-04-09 09:50:32 -07002406 /* gid containing AID_SYSTEM required */
Nick Kralevichc68c8862015-12-18 20:52:37 -08002407 mpfd = open(MEMCG_SYSFS_PATH "memory.pressure_level", O_RDONLY | O_CLOEXEC);
Todd Poynor3948f802013-07-09 19:35:14 -07002408 if (mpfd < 0) {
2409 ALOGI("No kernel memory.pressure_level support (errno=%d)", errno);
2410 goto err_open_mpfd;
2411 }
2412
Nick Kralevichc68c8862015-12-18 20:52:37 -08002413 evctlfd = open(MEMCG_SYSFS_PATH "cgroup.event_control", O_WRONLY | O_CLOEXEC);
Todd Poynor3948f802013-07-09 19:35:14 -07002414 if (evctlfd < 0) {
2415 ALOGI("No kernel memory cgroup event control (errno=%d)", errno);
2416 goto err_open_evctlfd;
2417 }
2418
Nick Kralevichc68c8862015-12-18 20:52:37 -08002419 evfd = eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC);
Todd Poynor3948f802013-07-09 19:35:14 -07002420 if (evfd < 0) {
2421 ALOGE("eventfd failed for level %s; errno=%d", levelstr, errno);
2422 goto err_eventfd;
2423 }
2424
2425 ret = snprintf(buf, sizeof(buf), "%d %d %s", evfd, mpfd, levelstr);
2426 if (ret >= (ssize_t)sizeof(buf)) {
2427 ALOGE("cgroup.event_control line overflow for level %s", levelstr);
2428 goto err;
2429 }
2430
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08002431 ret = TEMP_FAILURE_RETRY(write(evctlfd, buf, strlen(buf) + 1));
Todd Poynor3948f802013-07-09 19:35:14 -07002432 if (ret == -1) {
2433 ALOGE("cgroup.event_control write failed for level %s; errno=%d",
2434 levelstr, errno);
2435 goto err;
2436 }
2437
2438 epev.events = EPOLLIN;
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08002439 /* use data to store event level */
2440 vmpressure_hinfo[level_idx].data = level_idx;
2441 vmpressure_hinfo[level_idx].handler = mp_event_common;
2442 epev.data.ptr = (void *)&vmpressure_hinfo[level_idx];
Todd Poynor3948f802013-07-09 19:35:14 -07002443 ret = epoll_ctl(epollfd, EPOLL_CTL_ADD, evfd, &epev);
2444 if (ret == -1) {
2445 ALOGE("epoll_ctl for level %s failed; errno=%d", levelstr, errno);
2446 goto err;
2447 }
2448 maxevents++;
Suren Baghdasaryan96bf3a62017-12-08 12:58:52 -08002449 mpevfd[level] = evfd;
Suren Baghdasaryan1bd2fc42018-01-04 08:54:53 -08002450 close(evctlfd);
Suren Baghdasaryan96bf3a62017-12-08 12:58:52 -08002451 return true;
Todd Poynor3948f802013-07-09 19:35:14 -07002452
2453err:
2454 close(evfd);
2455err_eventfd:
2456 close(evctlfd);
2457err_open_evctlfd:
2458 close(mpfd);
2459err_open_mpfd:
Suren Baghdasaryan96bf3a62017-12-08 12:58:52 -08002460 return false;
Robert Benea673e2762017-06-01 16:32:31 -07002461}
2462
Suren Baghdasaryanb72c6652019-09-04 19:12:29 -07002463static void kernel_event_handler(int data __unused, uint32_t events __unused,
2464 struct polling_params *poll_params __unused) {
2465 kpoll_info.handler(kpoll_info.poll_fd);
Jim Blackler3947c932019-04-26 11:18:29 +01002466}
2467
Todd Poynor3948f802013-07-09 19:35:14 -07002468static int init(void) {
Suren Baghdasaryanb72c6652019-09-04 19:12:29 -07002469 static struct event_handler_info kernel_poll_hinfo = { 0, kernel_event_handler };
Suren Baghdasaryana77b3272019-07-15 13:35:04 -07002470 struct reread_data file_data = {
2471 .filename = ZONEINFO_PATH,
2472 .fd = -1,
2473 };
Todd Poynor3948f802013-07-09 19:35:14 -07002474 struct epoll_event epev;
2475 int i;
2476 int ret;
2477
2478 page_k = sysconf(_SC_PAGESIZE);
2479 if (page_k == -1)
2480 page_k = PAGE_SIZE;
2481 page_k /= 1024;
2482
2483 epollfd = epoll_create(MAX_EPOLL_EVENTS);
2484 if (epollfd == -1) {
2485 ALOGE("epoll_create failed (errno=%d)", errno);
2486 return -1;
2487 }
2488
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08002489 // mark data connections as not connected
2490 for (int i = 0; i < MAX_DATA_CONN; i++) {
2491 data_sock[i].sock = -1;
2492 }
2493
2494 ctrl_sock.sock = android_get_control_socket("lmkd");
2495 if (ctrl_sock.sock < 0) {
Todd Poynor3948f802013-07-09 19:35:14 -07002496 ALOGE("get lmkd control socket failed");
2497 return -1;
2498 }
2499
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08002500 ret = listen(ctrl_sock.sock, MAX_DATA_CONN);
Todd Poynor3948f802013-07-09 19:35:14 -07002501 if (ret < 0) {
2502 ALOGE("lmkd control socket listen failed (errno=%d)", errno);
2503 return -1;
2504 }
2505
2506 epev.events = EPOLLIN;
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08002507 ctrl_sock.handler_info.handler = ctrl_connect_handler;
2508 epev.data.ptr = (void *)&(ctrl_sock.handler_info);
2509 if (epoll_ctl(epollfd, EPOLL_CTL_ADD, ctrl_sock.sock, &epev) == -1) {
Todd Poynor3948f802013-07-09 19:35:14 -07002510 ALOGE("epoll_ctl for lmkd control socket failed (errno=%d)", errno);
2511 return -1;
2512 }
2513 maxevents++;
2514
Robert Benea164baeb2017-09-11 16:53:28 -07002515 has_inkernel_module = !access(INKERNEL_MINFREE_PATH, W_OK);
Suren Baghdasaryan979591b2018-01-18 17:27:30 -08002516 use_inkernel_interface = has_inkernel_module;
Todd Poynor3948f802013-07-09 19:35:14 -07002517
2518 if (use_inkernel_interface) {
2519 ALOGI("Using in-kernel low memory killer interface");
Suren Baghdasaryanb72c6652019-09-04 19:12:29 -07002520 if (init_poll_kernel(&kpoll_info)) {
2521 epev.events = EPOLLIN;
2522 epev.data.ptr = (void*)&kernel_poll_hinfo;
2523 if (epoll_ctl(epollfd, EPOLL_CTL_ADD, kpoll_info.poll_fd, &epev) != 0) {
2524 ALOGE("epoll_ctl for lmk events failed (errno=%d)", errno);
2525 close(kpoll_info.poll_fd);
2526 kpoll_info.poll_fd = -1;
2527 } else {
2528 maxevents++;
2529 }
Jim Blackler3947c932019-04-26 11:18:29 +01002530 }
Todd Poynor3948f802013-07-09 19:35:14 -07002531 } else {
Suren Baghdasaryan77122e52019-01-08 12:54:48 -08002532 /* Try to use psi monitor first if kernel has it */
2533 use_psi_monitors = property_get_bool("ro.lmk.use_psi", true) &&
2534 init_psi_monitors();
2535 /* Fall back to vmpressure */
2536 if (!use_psi_monitors &&
2537 (!init_mp_common(VMPRESS_LEVEL_LOW) ||
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08002538 !init_mp_common(VMPRESS_LEVEL_MEDIUM) ||
Suren Baghdasaryan77122e52019-01-08 12:54:48 -08002539 !init_mp_common(VMPRESS_LEVEL_CRITICAL))) {
Todd Poynor3948f802013-07-09 19:35:14 -07002540 ALOGE("Kernel does not support memory pressure events or in-kernel low memory killer");
Suren Baghdasaryan96bf3a62017-12-08 12:58:52 -08002541 return -1;
2542 }
Suren Baghdasaryan77122e52019-01-08 12:54:48 -08002543 if (use_psi_monitors) {
2544 ALOGI("Using psi monitors for memory pressure detection");
2545 } else {
2546 ALOGI("Using vmpressure for memory pressure detection");
2547 }
Todd Poynor3948f802013-07-09 19:35:14 -07002548 }
2549
Chong Zhang0a4acdf2015-10-14 16:19:53 -07002550 for (i = 0; i <= ADJTOSLOT(OOM_SCORE_ADJ_MAX); i++) {
Todd Poynor3948f802013-07-09 19:35:14 -07002551 procadjslot_list[i].next = &procadjslot_list[i];
2552 procadjslot_list[i].prev = &procadjslot_list[i];
2553 }
2554
Suren Baghdasaryand4a29902018-10-12 11:07:40 -07002555 memset(killcnt_idx, KILLCNT_INVALID_IDX, sizeof(killcnt_idx));
2556
Suren Baghdasaryana77b3272019-07-15 13:35:04 -07002557 /*
2558 * Read zoneinfo as the biggest file we read to create and size the initial
2559 * read buffer and avoid memory re-allocations during memory pressure
2560 */
2561 if (reread_file(&file_data) == NULL) {
2562 ALOGE("Failed to read %s: %s", file_data.filename, strerror(errno));
2563 }
2564
Todd Poynor3948f802013-07-09 19:35:14 -07002565 return 0;
2566}
2567
2568static void mainloop(void) {
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08002569 struct event_handler_info* handler_info;
Suren Baghdasaryanef3650f2019-07-15 14:50:49 -07002570 struct polling_params poll_params;
2571 struct timespec curr_tm;
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08002572 struct epoll_event *evt;
Suren Baghdasaryan77122e52019-01-08 12:54:48 -08002573 long delay = -1;
Suren Baghdasaryanef3650f2019-07-15 14:50:49 -07002574
2575 poll_params.poll_handler = NULL;
2576 poll_params.update = POLLING_DO_NOT_CHANGE;
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08002577
Todd Poynor3948f802013-07-09 19:35:14 -07002578 while (1) {
2579 struct epoll_event events[maxevents];
2580 int nevents;
2581 int i;
2582
Suren Baghdasaryanef3650f2019-07-15 14:50:49 -07002583 if (poll_params.poll_handler) {
Suren Baghdasaryan77122e52019-01-08 12:54:48 -08002584 /* Calculate next timeout */
2585 clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm);
Suren Baghdasaryanef3650f2019-07-15 14:50:49 -07002586 delay = get_time_diff_ms(&poll_params.last_poll_tm, &curr_tm);
2587 delay = (delay < poll_params.polling_interval_ms) ?
2588 poll_params.polling_interval_ms - delay : poll_params.polling_interval_ms;
Suren Baghdasaryan77122e52019-01-08 12:54:48 -08002589
2590 /* Wait for events until the next polling timeout */
2591 nevents = epoll_wait(epollfd, events, maxevents, delay);
2592
2593 clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm);
Suren Baghdasaryanef3650f2019-07-15 14:50:49 -07002594 if (get_time_diff_ms(&poll_params.last_poll_tm, &curr_tm) >=
2595 poll_params.polling_interval_ms) {
2596 /* Set input params for the call */
2597 poll_params.poll_handler->handler(poll_params.poll_handler->data, 0, &poll_params);
2598 poll_params.last_poll_tm = curr_tm;
2599
2600 if (poll_params.update != POLLING_DO_NOT_CHANGE) {
2601 switch (poll_params.update) {
2602 case POLLING_START:
2603 poll_params.poll_start_tm = curr_tm;
2604 break;
2605 case POLLING_STOP:
2606 poll_params.poll_handler = NULL;
2607 break;
2608 default:
2609 break;
2610 }
2611 poll_params.update = POLLING_DO_NOT_CHANGE;
2612 } else {
2613 if (get_time_diff_ms(&poll_params.poll_start_tm, &curr_tm) >
2614 PSI_WINDOW_SIZE_MS) {
2615 /* Polled for the duration of PSI window, time to stop */
2616 poll_params.poll_handler = NULL;
2617 }
2618 }
Suren Baghdasaryan77122e52019-01-08 12:54:48 -08002619 }
2620 } else {
2621 /* Wait for events with no timeout */
2622 nevents = epoll_wait(epollfd, events, maxevents, -1);
2623 }
Todd Poynor3948f802013-07-09 19:35:14 -07002624
2625 if (nevents == -1) {
2626 if (errno == EINTR)
2627 continue;
2628 ALOGE("epoll_wait failed (errno=%d)", errno);
2629 continue;
2630 }
2631
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08002632 /*
2633 * First pass to see if any data socket connections were dropped.
2634 * Dropped connection should be handled before any other events
2635 * to deallocate data connection and correctly handle cases when
2636 * connection gets dropped and reestablished in the same epoll cycle.
2637 * In such cases it's essential to handle connection closures first.
2638 */
2639 for (i = 0, evt = &events[0]; i < nevents; ++i, evt++) {
2640 if ((evt->events & EPOLLHUP) && evt->data.ptr) {
2641 ALOGI("lmkd data connection dropped");
2642 handler_info = (struct event_handler_info*)evt->data.ptr;
2643 ctrl_data_close(handler_info->data);
2644 }
2645 }
2646
2647 /* Second pass to handle all other events */
2648 for (i = 0, evt = &events[0]; i < nevents; ++i, evt++) {
Suren Baghdasaryanef3650f2019-07-15 14:50:49 -07002649 if (evt->events & EPOLLERR) {
Todd Poynor3948f802013-07-09 19:35:14 -07002650 ALOGD("EPOLLERR on event #%d", i);
Suren Baghdasaryanef3650f2019-07-15 14:50:49 -07002651 }
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08002652 if (evt->events & EPOLLHUP) {
2653 /* This case was handled in the first pass */
2654 continue;
2655 }
2656 if (evt->data.ptr) {
2657 handler_info = (struct event_handler_info*)evt->data.ptr;
Suren Baghdasaryanef3650f2019-07-15 14:50:49 -07002658 /* Set input params for the call */
2659 handler_info->handler(handler_info->data, evt->events, &poll_params);
Suren Baghdasaryan77122e52019-01-08 12:54:48 -08002660
Suren Baghdasaryanef3650f2019-07-15 14:50:49 -07002661 if (poll_params.update != POLLING_DO_NOT_CHANGE) {
2662 switch (poll_params.update) {
2663 case POLLING_START:
2664 /*
2665 * Poll for the duration of PSI_WINDOW_SIZE_MS after the
2666 * initial PSI event because psi events are rate-limited
2667 * at one per sec.
2668 */
2669 clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm);
2670 poll_params.poll_start_tm = poll_params.last_poll_tm = curr_tm;
2671 poll_params.poll_handler = handler_info;
2672 break;
2673 case POLLING_STOP:
2674 poll_params.poll_handler = NULL;
2675 break;
2676 default:
2677 break;
2678 }
2679 poll_params.update = POLLING_DO_NOT_CHANGE;
Suren Baghdasaryan77122e52019-01-08 12:54:48 -08002680 }
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08002681 }
Todd Poynor3948f802013-07-09 19:35:14 -07002682 }
2683 }
2684}
2685
Mark Salyzyne6ed68b2014-04-30 13:36:35 -07002686int main(int argc __unused, char **argv __unused) {
Colin Cross1a0d9be2014-07-14 14:31:15 -07002687 struct sched_param param = {
2688 .sched_priority = 1,
2689 };
2690
Suren Baghdasaryan96bf3a62017-12-08 12:58:52 -08002691 /* By default disable low level vmpressure events */
2692 level_oomadj[VMPRESS_LEVEL_LOW] =
2693 property_get_int32("ro.lmk.low", OOM_SCORE_ADJ_MAX + 1);
2694 level_oomadj[VMPRESS_LEVEL_MEDIUM] =
2695 property_get_int32("ro.lmk.medium", 800);
2696 level_oomadj[VMPRESS_LEVEL_CRITICAL] =
2697 property_get_int32("ro.lmk.critical", 0);
Robert Beneacaeaa652017-08-11 16:03:20 -07002698 debug_process_killing = property_get_bool("ro.lmk.debug", false);
Suren Baghdasaryanad2fd912017-12-08 13:08:41 -08002699
2700 /* By default disable upgrade/downgrade logic */
2701 enable_pressure_upgrade =
2702 property_get_bool("ro.lmk.critical_upgrade", false);
2703 upgrade_pressure =
2704 (int64_t)property_get_int32("ro.lmk.upgrade_pressure", 100);
2705 downgrade_pressure =
2706 (int64_t)property_get_int32("ro.lmk.downgrade_pressure", 100);
Suren Baghdasaryan662492a2017-12-08 13:17:06 -08002707 kill_heaviest_task =
Suren Baghdasaryan818b59b2018-04-13 11:49:54 -07002708 property_get_bool("ro.lmk.kill_heaviest_task", false);
Suren Baghdasaryanff61afb2018-04-13 11:45:38 -07002709 low_ram_device = property_get_bool("ro.config.low_ram", false);
Suren Baghdasaryancaa2dc52018-01-17 17:28:01 -08002710 kill_timeout_ms =
2711 (unsigned long)property_get_int32("ro.lmk.kill_timeout_ms", 0);
Suren Baghdasaryanffdc4dd2018-04-13 13:53:43 -07002712 use_minfree_levels =
2713 property_get_bool("ro.lmk.use_minfree_levels", false);
Suren Baghdasaryance13cb52018-06-19 18:38:12 -07002714 per_app_memcg =
2715 property_get_bool("ro.config.per_app_memcg", low_ram_device);
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002716 swap_free_low_percentage = clamp(0, 100, property_get_int32("ro.lmk.swap_free_low_percentage",
2717 low_ram_device ? DEF_LOW_SWAP_LOWRAM : DEF_LOW_SWAP));
Suren Baghdasaryan844f26b2019-07-15 15:42:09 -07002718 psi_partial_stall_ms = property_get_int32("ro.lmk.psi_partial_stall_ms",
2719 low_ram_device ? DEF_PARTIAL_STALL_LOWRAM : DEF_PARTIAL_STALL);
2720 psi_complete_stall_ms = property_get_int32("ro.lmk.psi_complete_stall_ms",
2721 DEF_COMPLETE_STALL);
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002722 thrashing_limit_pct = max(0, property_get_int32("ro.lmk.thrashing_limit",
2723 low_ram_device ? DEF_THRASHING_LOWRAM : DEF_THRASHING));
2724 thrashing_limit_decay_pct = clamp(0, 100, property_get_int32("ro.lmk.thrashing_limit_decay",
2725 low_ram_device ? DEF_THRASHING_DECAY_LOWRAM : DEF_THRASHING_DECAY));
Robert Benea58891d52017-07-31 17:15:20 -07002726
Suren Baghdasaryana7ac5782019-09-16 12:06:30 -07002727 ctx = create_android_logger(KILLINFO_LOG_TAG);
Suren Baghdasaryan282ad1a2018-07-26 16:34:27 -07002728
Suren Baghdasaryanb72c6652019-09-04 19:12:29 -07002729 statslog_init();
Rajeev Kumar70450032018-01-31 17:54:56 -08002730
Mark Salyzyn721d7c72018-03-21 12:24:58 -07002731 if (!init()) {
2732 if (!use_inkernel_interface) {
2733 /*
2734 * MCL_ONFAULT pins pages as they fault instead of loading
2735 * everything immediately all at once. (Which would be bad,
2736 * because as of this writing, we have a lot of mapped pages we
2737 * never use.) Old kernels will see MCL_ONFAULT and fail with
2738 * EINVAL; we ignore this failure.
2739 *
2740 * N.B. read the man page for mlockall. MCL_CURRENT | MCL_ONFAULT
2741 * pins ⊆ MCL_CURRENT, converging to just MCL_CURRENT as we fault
2742 * in pages.
2743 */
Mark Salyzyn64d97d82018-04-09 09:50:32 -07002744 /* CAP_IPC_LOCK required */
Mark Salyzyn721d7c72018-03-21 12:24:58 -07002745 if (mlockall(MCL_CURRENT | MCL_FUTURE | MCL_ONFAULT) && (errno != EINVAL)) {
2746 ALOGW("mlockall failed %s", strerror(errno));
2747 }
Daniel Colascione4dd5d002018-01-03 12:01:02 -08002748
Mark Salyzyn64d97d82018-04-09 09:50:32 -07002749 /* CAP_NICE required */
2750 if (sched_setscheduler(0, SCHED_FIFO, &param)) {
2751 ALOGW("set SCHED_FIFO failed %s", strerror(errno));
2752 }
Mark Salyzyn721d7c72018-03-21 12:24:58 -07002753 }
2754
Todd Poynor3948f802013-07-09 19:35:14 -07002755 mainloop();
Mark Salyzyn721d7c72018-03-21 12:24:58 -07002756 }
Todd Poynor3948f802013-07-09 19:35:14 -07002757
Suren Baghdasaryanb72c6652019-09-04 19:12:29 -07002758 statslog_destroy();
Rajeev Kumar70450032018-01-31 17:54:56 -08002759
Suren Baghdasaryan282ad1a2018-07-26 16:34:27 -07002760 android_log_destroy(&ctx);
2761
Todd Poynor3948f802013-07-09 19:35:14 -07002762 ALOGI("exiting");
2763 return 0;
2764}