blob: 42e3db33ea5907de0d35d098285a1cc26656db51 [file] [log] [blame]
Todd Poynor3948f802013-07-09 19:35:14 -07001/*
2 * Copyright (C) 2013 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "lowmemorykiller"
18
Wei Wang2d95c102018-11-21 00:11:44 -080019#include <dirent.h>
Todd Poynor3948f802013-07-09 19:35:14 -070020#include <errno.h>
Robert Beneac47f2992017-08-21 15:18:31 -070021#include <inttypes.h>
Suren Baghdasaryan4311d1e2018-03-20 16:03:29 -070022#include <pwd.h>
Mark Salyzyncfd5b082016-10-17 14:28:00 -070023#include <sched.h>
Todd Poynor3948f802013-07-09 19:35:14 -070024#include <signal.h>
Suren Baghdasaryan1ffa2462018-03-20 13:53:17 -070025#include <stdbool.h>
Todd Poynor3948f802013-07-09 19:35:14 -070026#include <stdlib.h>
27#include <string.h>
Mark Salyzyne6ed68b2014-04-30 13:36:35 -070028#include <sys/cdefs.h>
Todd Poynor3948f802013-07-09 19:35:14 -070029#include <sys/epoll.h>
30#include <sys/eventfd.h>
Colin Crossb28ff912014-07-11 17:15:44 -070031#include <sys/mman.h>
Wei Wang2d95c102018-11-21 00:11:44 -080032#include <sys/resource.h>
Todd Poynor3948f802013-07-09 19:35:14 -070033#include <sys/socket.h>
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -080034#include <sys/sysinfo.h>
Wei Wang2d95c102018-11-21 00:11:44 -080035#include <sys/time.h>
Mark Salyzyn721d7c72018-03-21 12:24:58 -070036#include <sys/types.h>
Suren Baghdasaryan314a5052018-07-24 17:13:06 -070037#include <time.h>
Mark Salyzyne6ed68b2014-04-30 13:36:35 -070038#include <unistd.h>
39
Robert Benea58891d52017-07-31 17:15:20 -070040#include <cutils/properties.h>
Wei Wang2d95c102018-11-21 00:11:44 -080041#include <cutils/sched_policy.h>
Todd Poynor3948f802013-07-09 19:35:14 -070042#include <cutils/sockets.h>
Suren Baghdasaryan0f100512018-01-24 16:51:41 -080043#include <lmkd.h>
Mark Salyzyn30f991f2017-01-10 13:19:54 -080044#include <log/log.h>
Suren Baghdasaryan282ad1a2018-07-26 16:34:27 -070045#include <log/log_event_list.h>
Suren Baghdasaryan314a5052018-07-24 17:13:06 -070046#include <log/log_time.h>
Suren Baghdasaryan77122e52019-01-08 12:54:48 -080047#include <psi/psi.h>
Wei Wang2d95c102018-11-21 00:11:44 -080048#include <system/thread_defs.h>
Mark Salyzyne6ed68b2014-04-30 13:36:35 -070049
Rajeev Kumar70450032018-01-31 17:54:56 -080050#ifdef LMKD_LOG_STATS
Yao Chen389aee12018-05-02 11:19:27 -070051#include "statslog.h"
Rajeev Kumar70450032018-01-31 17:54:56 -080052#endif
53
Suren Baghdasaryanc7135592018-01-04 10:43:58 -080054/*
55 * Define LMKD_TRACE_KILLS to record lmkd kills in kernel traces
56 * to profile and correlate with OOM kills
57 */
58#ifdef LMKD_TRACE_KILLS
59
60#define ATRACE_TAG ATRACE_TAG_ALWAYS
61#include <cutils/trace.h>
62
63#define TRACE_KILL_START(pid) ATRACE_INT(__FUNCTION__, pid);
64#define TRACE_KILL_END() ATRACE_INT(__FUNCTION__, 0);
65
66#else /* LMKD_TRACE_KILLS */
67
Daniel Colascione347f6b42018-02-12 11:24:47 -080068#define TRACE_KILL_START(pid) ((void)(pid))
69#define TRACE_KILL_END() ((void)0)
Suren Baghdasaryanc7135592018-01-04 10:43:58 -080070
71#endif /* LMKD_TRACE_KILLS */
72
Mark Salyzyne6ed68b2014-04-30 13:36:35 -070073#ifndef __unused
74#define __unused __attribute__((__unused__))
75#endif
Todd Poynor3948f802013-07-09 19:35:14 -070076
77#define MEMCG_SYSFS_PATH "/dev/memcg/"
Robert Beneac47f2992017-08-21 15:18:31 -070078#define MEMCG_MEMORY_USAGE "/dev/memcg/memory.usage_in_bytes"
79#define MEMCG_MEMORYSW_USAGE "/dev/memcg/memory.memsw.usage_in_bytes"
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -070080#define ZONEINFO_PATH "/proc/zoneinfo"
81#define MEMINFO_PATH "/proc/meminfo"
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -070082#define VMSTAT_PATH "/proc/vmstat"
Suren Baghdasaryan0082ef12019-07-02 15:52:07 -070083#define PROC_STATUS_TGID_FIELD "Tgid:"
Todd Poynor3948f802013-07-09 19:35:14 -070084#define LINE_MAX 128
85
Suren Baghdasaryan282ad1a2018-07-26 16:34:27 -070086/* Android Logger event logtags (see event.logtags) */
87#define MEMINFO_LOG_TAG 10195355
88
Mark Salyzyn64d97d82018-04-09 09:50:32 -070089/* gid containing AID_SYSTEM required */
Todd Poynor3948f802013-07-09 19:35:14 -070090#define INKERNEL_MINFREE_PATH "/sys/module/lowmemorykiller/parameters/minfree"
91#define INKERNEL_ADJ_PATH "/sys/module/lowmemorykiller/parameters/adj"
92
93#define ARRAY_SIZE(x) (sizeof(x) / sizeof(*(x)))
Robert Benea673e2762017-06-01 16:32:31 -070094#define EIGHT_MEGA (1 << 23)
Todd Poynor3948f802013-07-09 19:35:14 -070095
Suren Baghdasaryan314a5052018-07-24 17:13:06 -070096#define TARGET_UPDATE_MIN_INTERVAL_MS 1000
97
98#define NS_PER_MS (NS_PER_SEC / MS_PER_SEC)
Suren Baghdasaryan77122e52019-01-08 12:54:48 -080099#define US_PER_MS (US_PER_SEC / MS_PER_SEC)
Suren Baghdasaryan314a5052018-07-24 17:13:06 -0700100
Suren Baghdasaryan4311d1e2018-03-20 16:03:29 -0700101/* Defined as ProcessList.SYSTEM_ADJ in ProcessList.java */
102#define SYSTEM_ADJ (-900)
103
Greg Kaiserf0da9b02018-03-23 14:16:12 -0700104#define STRINGIFY(x) STRINGIFY_INTERNAL(x)
105#define STRINGIFY_INTERNAL(x) #x
106
Suren Baghdasaryan77122e52019-01-08 12:54:48 -0800107/*
108 * PSI monitor tracking window size.
109 * PSI monitor generates events at most once per window,
110 * therefore we poll memory state for the duration of
111 * PSI_WINDOW_SIZE_MS after the event happens.
112 */
113#define PSI_WINDOW_SIZE_MS 1000
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -0700114/* Polling period after PSI signal when pressure is high */
115#define PSI_POLL_PERIOD_SHORT_MS 10
116/* Polling period after PSI signal when pressure is low */
117#define PSI_POLL_PERIOD_LONG_MS 100
Suren Baghdasaryan77122e52019-01-08 12:54:48 -0800118
Suren Baghdasaryan282ad1a2018-07-26 16:34:27 -0700119#define min(a, b) (((a) < (b)) ? (a) : (b))
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -0700120#define max(a, b) (((a) > (b)) ? (a) : (b))
Suren Baghdasaryan282ad1a2018-07-26 16:34:27 -0700121
Suren Baghdasaryan36934412018-09-05 15:46:32 -0700122#define FAIL_REPORT_RLIMIT_MS 1000
123
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -0700124/*
125 * System property defaults
126 */
127/* ro.lmk.swap_free_low_percentage property defaults */
128#define DEF_LOW_SWAP_LOWRAM 10
129#define DEF_LOW_SWAP 20
130/* ro.lmk.thrashing_limit property defaults */
131#define DEF_THRASHING_LOWRAM 30
132#define DEF_THRASHING 100
133/* ro.lmk.thrashing_limit_decay property defaults */
134#define DEF_THRASHING_DECAY_LOWRAM 50
135#define DEF_THRASHING_DECAY 10
136
Todd Poynor3948f802013-07-09 19:35:14 -0700137/* default to old in-kernel interface if no memory pressure events */
Mark Salyzyn721d7c72018-03-21 12:24:58 -0700138static bool use_inkernel_interface = true;
Robert Benea164baeb2017-09-11 16:53:28 -0700139static bool has_inkernel_module;
Todd Poynor3948f802013-07-09 19:35:14 -0700140
Suren Baghdasaryan96bf3a62017-12-08 12:58:52 -0800141/* memory pressure levels */
142enum vmpressure_level {
143 VMPRESS_LEVEL_LOW = 0,
144 VMPRESS_LEVEL_MEDIUM,
145 VMPRESS_LEVEL_CRITICAL,
146 VMPRESS_LEVEL_COUNT
147};
Todd Poynor3948f802013-07-09 19:35:14 -0700148
Suren Baghdasaryan96bf3a62017-12-08 12:58:52 -0800149static const char *level_name[] = {
150 "low",
151 "medium",
152 "critical"
153};
154
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -0800155struct {
Suren Baghdasaryan9926e572018-04-13 13:41:12 -0700156 int64_t min_nr_free_pages; /* recorded but not used yet */
157 int64_t max_nr_free_pages;
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -0800158} low_pressure_mem = { -1, -1 };
159
Suren Baghdasaryan77122e52019-01-08 12:54:48 -0800160struct psi_threshold {
161 enum psi_stall_type stall_type;
162 int threshold_ms;
163};
164
Suren Baghdasaryan96bf3a62017-12-08 12:58:52 -0800165static int level_oomadj[VMPRESS_LEVEL_COUNT];
Suren Baghdasaryane82e15c2018-01-04 09:16:21 -0800166static int mpevfd[VMPRESS_LEVEL_COUNT] = { -1, -1, -1 };
Robert Beneac47f2992017-08-21 15:18:31 -0700167static bool debug_process_killing;
168static bool enable_pressure_upgrade;
169static int64_t upgrade_pressure;
Robert Benea6e8e7102017-09-13 15:20:30 -0700170static int64_t downgrade_pressure;
Suren Baghdasaryanff61afb2018-04-13 11:45:38 -0700171static bool low_ram_device;
Suren Baghdasaryan662492a2017-12-08 13:17:06 -0800172static bool kill_heaviest_task;
Suren Baghdasaryancaa2dc52018-01-17 17:28:01 -0800173static unsigned long kill_timeout_ms;
Suren Baghdasaryanffdc4dd2018-04-13 13:53:43 -0700174static bool use_minfree_levels;
Suren Baghdasaryance13cb52018-06-19 18:38:12 -0700175static bool per_app_memcg;
Vic Yang360a1132018-08-07 10:18:22 -0700176static int swap_free_low_percentage;
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -0700177static int thrashing_limit_pct;
178static int thrashing_limit_decay_pct;
Suren Baghdasaryan77122e52019-01-08 12:54:48 -0800179static bool use_psi_monitors = false;
180static struct psi_threshold psi_thresholds[VMPRESS_LEVEL_COUNT] = {
181 { PSI_SOME, 70 }, /* 70ms out of 1sec for partial stall */
182 { PSI_SOME, 100 }, /* 100ms out of 1sec for partial stall */
183 { PSI_FULL, 70 }, /* 70ms out of 1sec for complete stall */
184};
Robert Benea58891d52017-07-31 17:15:20 -0700185
Suren Baghdasaryan282ad1a2018-07-26 16:34:27 -0700186static android_log_context ctx;
187
Suren Baghdasaryanef3650f2019-07-15 14:50:49 -0700188enum polling_update {
189 POLLING_DO_NOT_CHANGE,
190 POLLING_START,
191 POLLING_STOP,
192};
193
194/*
195 * Data used for periodic polling for the memory state of the device.
196 * Note that when system is not polling poll_handler is set to NULL,
197 * when polling starts poll_handler gets set and is reset back to
198 * NULL when polling stops.
199 */
200struct polling_params {
201 struct event_handler_info* poll_handler;
202 struct timespec poll_start_tm;
203 struct timespec last_poll_tm;
204 int polling_interval_ms;
205 enum polling_update update;
206};
207
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -0800208/* data required to handle events */
209struct event_handler_info {
210 int data;
Suren Baghdasaryanef3650f2019-07-15 14:50:49 -0700211 void (*handler)(int data, uint32_t events, struct polling_params *poll_params);
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -0800212};
Todd Poynor3948f802013-07-09 19:35:14 -0700213
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -0800214/* data required to handle socket events */
215struct sock_event_handler_info {
216 int sock;
217 struct event_handler_info handler_info;
218};
219
220/* max supported number of data connections */
221#define MAX_DATA_CONN 2
222
223/* socket event handler data */
224static struct sock_event_handler_info ctrl_sock;
225static struct sock_event_handler_info data_sock[MAX_DATA_CONN];
226
227/* vmpressure event handler data */
228static struct event_handler_info vmpressure_hinfo[VMPRESS_LEVEL_COUNT];
229
Jim Blackler3947c932019-04-26 11:18:29 +0100230/* 3 memory pressure levels, 1 ctrl listen socket, 2 ctrl data socket, 1 lmk events */
231#define MAX_EPOLL_EVENTS (2 + MAX_DATA_CONN + VMPRESS_LEVEL_COUNT)
Todd Poynor3948f802013-07-09 19:35:14 -0700232static int epollfd;
233static int maxevents;
234
Chong Zhang0a4acdf2015-10-14 16:19:53 -0700235/* OOM score values used by both kernel and framework */
Todd Poynor16b60992013-09-16 19:26:47 -0700236#define OOM_SCORE_ADJ_MIN (-1000)
237#define OOM_SCORE_ADJ_MAX 1000
238
Todd Poynor3948f802013-07-09 19:35:14 -0700239static int lowmem_adj[MAX_TARGETS];
240static int lowmem_minfree[MAX_TARGETS];
241static int lowmem_targets_size;
242
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -0700243/* Fields to parse in /proc/zoneinfo */
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -0700244/* zoneinfo per-zone fields */
245enum zoneinfo_zone_field {
246 ZI_ZONE_NR_FREE_PAGES = 0,
247 ZI_ZONE_MIN,
248 ZI_ZONE_LOW,
249 ZI_ZONE_HIGH,
250 ZI_ZONE_PRESENT,
251 ZI_ZONE_NR_FREE_CMA,
252 ZI_ZONE_FIELD_COUNT
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -0700253};
254
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -0700255static const char* const zoneinfo_zone_field_names[ZI_ZONE_FIELD_COUNT] = {
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -0700256 "nr_free_pages",
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -0700257 "min",
258 "low",
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -0700259 "high",
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -0700260 "present",
261 "nr_free_cma",
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -0700262};
263
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -0700264/* zoneinfo per-zone special fields */
265enum zoneinfo_zone_spec_field {
266 ZI_ZONE_SPEC_PROTECTION = 0,
267 ZI_ZONE_SPEC_PAGESETS,
268 ZI_ZONE_SPEC_FIELD_COUNT,
269};
270
271static const char* const zoneinfo_zone_spec_field_names[ZI_ZONE_SPEC_FIELD_COUNT] = {
272 "protection:",
273 "pagesets",
274};
275
276/* see __MAX_NR_ZONES definition in kernel mmzone.h */
277#define MAX_NR_ZONES 6
278
279union zoneinfo_zone_fields {
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -0700280 struct {
281 int64_t nr_free_pages;
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -0700282 int64_t min;
283 int64_t low;
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -0700284 int64_t high;
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -0700285 int64_t present;
286 int64_t nr_free_cma;
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -0700287 } field;
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -0700288 int64_t arr[ZI_ZONE_FIELD_COUNT];
289};
290
291struct zoneinfo_zone {
292 union zoneinfo_zone_fields fields;
293 int64_t protection[MAX_NR_ZONES];
294 int64_t max_protection;
295};
296
297/* zoneinfo per-node fields */
298enum zoneinfo_node_field {
299 ZI_NODE_NR_INACTIVE_FILE = 0,
300 ZI_NODE_NR_ACTIVE_FILE,
301 ZI_NODE_WORKINGSET_REFAULT,
302 ZI_NODE_FIELD_COUNT
303};
304
305static const char* const zoneinfo_node_field_names[ZI_NODE_FIELD_COUNT] = {
306 "nr_inactive_file",
307 "nr_active_file",
308 "workingset_refault",
309};
310
311union zoneinfo_node_fields {
312 struct {
313 int64_t nr_inactive_file;
314 int64_t nr_active_file;
315 int64_t workingset_refault;
316 } field;
317 int64_t arr[ZI_NODE_FIELD_COUNT];
318};
319
320struct zoneinfo_node {
321 int id;
322 int zone_count;
323 struct zoneinfo_zone zones[MAX_NR_ZONES];
324 union zoneinfo_node_fields fields;
325};
326
327/* for now two memory nodes is more than enough */
328#define MAX_NR_NODES 2
329
330struct zoneinfo {
331 int node_count;
332 struct zoneinfo_node nodes[MAX_NR_NODES];
333 int64_t totalreserve_pages;
334 int64_t total_inactive_file;
335 int64_t total_active_file;
336 int64_t total_workingset_refault;
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -0700337};
338
339/* Fields to parse in /proc/meminfo */
340enum meminfo_field {
341 MI_NR_FREE_PAGES = 0,
342 MI_CACHED,
343 MI_SWAP_CACHED,
344 MI_BUFFERS,
345 MI_SHMEM,
346 MI_UNEVICTABLE,
Vic Yang360a1132018-08-07 10:18:22 -0700347 MI_TOTAL_SWAP,
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -0700348 MI_FREE_SWAP,
Suren Baghdasaryan282ad1a2018-07-26 16:34:27 -0700349 MI_ACTIVE_ANON,
350 MI_INACTIVE_ANON,
351 MI_ACTIVE_FILE,
352 MI_INACTIVE_FILE,
353 MI_SRECLAIMABLE,
354 MI_SUNRECLAIM,
355 MI_KERNEL_STACK,
356 MI_PAGE_TABLES,
357 MI_ION_HELP,
358 MI_ION_HELP_POOL,
359 MI_CMA_FREE,
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -0700360 MI_FIELD_COUNT
361};
362
363static const char* const meminfo_field_names[MI_FIELD_COUNT] = {
364 "MemFree:",
365 "Cached:",
366 "SwapCached:",
367 "Buffers:",
368 "Shmem:",
369 "Unevictable:",
Vic Yang360a1132018-08-07 10:18:22 -0700370 "SwapTotal:",
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -0700371 "SwapFree:",
Suren Baghdasaryan282ad1a2018-07-26 16:34:27 -0700372 "Active(anon):",
373 "Inactive(anon):",
374 "Active(file):",
375 "Inactive(file):",
376 "SReclaimable:",
377 "SUnreclaim:",
378 "KernelStack:",
379 "PageTables:",
380 "ION_heap:",
381 "ION_heap_pool:",
382 "CmaFree:",
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -0700383};
384
385union meminfo {
386 struct {
387 int64_t nr_free_pages;
388 int64_t cached;
389 int64_t swap_cached;
390 int64_t buffers;
391 int64_t shmem;
392 int64_t unevictable;
Vic Yang360a1132018-08-07 10:18:22 -0700393 int64_t total_swap;
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -0700394 int64_t free_swap;
Suren Baghdasaryan282ad1a2018-07-26 16:34:27 -0700395 int64_t active_anon;
396 int64_t inactive_anon;
397 int64_t active_file;
398 int64_t inactive_file;
399 int64_t sreclaimable;
400 int64_t sunreclaimable;
401 int64_t kernel_stack;
402 int64_t page_tables;
403 int64_t ion_heap;
404 int64_t ion_heap_pool;
405 int64_t cma_free;
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -0700406 /* fields below are calculated rather than read from the file */
407 int64_t nr_file_pages;
408 } field;
409 int64_t arr[MI_FIELD_COUNT];
410};
411
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -0700412/* Fields to parse in /proc/vmstat */
413enum vmstat_field {
414 VS_FREE_PAGES,
415 VS_INACTIVE_FILE,
416 VS_ACTIVE_FILE,
417 VS_WORKINGSET_REFAULT,
418 VS_PGSCAN_KSWAPD,
419 VS_PGSCAN_DIRECT,
420 VS_PGSCAN_DIRECT_THROTTLE,
421 VS_FIELD_COUNT
422};
423
424static const char* const vmstat_field_names[MI_FIELD_COUNT] = {
425 "nr_free_pages",
426 "nr_inactive_file",
427 "nr_active_file",
428 "workingset_refault",
429 "pgscan_kswapd",
430 "pgscan_direct",
431 "pgscan_direct_throttle",
432};
433
434union vmstat {
435 struct {
436 int64_t nr_free_pages;
437 int64_t nr_inactive_file;
438 int64_t nr_active_file;
439 int64_t workingset_refault;
440 int64_t pgscan_kswapd;
441 int64_t pgscan_direct;
442 int64_t pgscan_direct_throttle;
443 } field;
444 int64_t arr[VS_FIELD_COUNT];
445};
446
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -0700447enum field_match_result {
448 NO_MATCH,
449 PARSE_FAIL,
450 PARSE_SUCCESS
451};
452
Todd Poynor3948f802013-07-09 19:35:14 -0700453struct adjslot_list {
454 struct adjslot_list *next;
455 struct adjslot_list *prev;
456};
457
458struct proc {
459 struct adjslot_list asl;
460 int pid;
Colin Crossfbb78c62014-06-13 14:52:43 -0700461 uid_t uid;
Todd Poynor3948f802013-07-09 19:35:14 -0700462 int oomadj;
463 struct proc *pidhash_next;
464};
465
Suren Baghdasaryan6499e5e2018-04-13 12:43:41 -0700466struct reread_data {
467 const char* const filename;
468 int fd;
469};
470
Rajeev Kumar70450032018-01-31 17:54:56 -0800471#ifdef LMKD_LOG_STATS
Rajeev Kumar70450032018-01-31 17:54:56 -0800472static bool enable_stats_log;
473static android_log_context log_ctx;
474#endif
475
Todd Poynor3948f802013-07-09 19:35:14 -0700476#define PIDHASH_SZ 1024
477static struct proc *pidhash[PIDHASH_SZ];
478#define pid_hashfn(x) ((((x) >> 8) ^ (x)) & (PIDHASH_SZ - 1))
479
Chih-Hung Hsiehdaa13ea2016-05-19 16:02:22 -0700480#define ADJTOSLOT(adj) ((adj) + -OOM_SCORE_ADJ_MIN)
Suren Baghdasaryand4a29902018-10-12 11:07:40 -0700481#define ADJTOSLOT_COUNT (ADJTOSLOT(OOM_SCORE_ADJ_MAX) + 1)
482static struct adjslot_list procadjslot_list[ADJTOSLOT_COUNT];
483
484#define MAX_DISTINCT_OOM_ADJ 32
485#define KILLCNT_INVALID_IDX 0xFF
486/*
487 * Because killcnt array is sparse a two-level indirection is used
488 * to keep the size small. killcnt_idx stores index of the element in
489 * killcnt array. Index KILLCNT_INVALID_IDX indicates an unused slot.
490 */
491static uint8_t killcnt_idx[ADJTOSLOT_COUNT];
492static uint16_t killcnt[MAX_DISTINCT_OOM_ADJ];
493static int killcnt_free_idx = 0;
494static uint32_t killcnt_total = 0;
Todd Poynor3948f802013-07-09 19:35:14 -0700495
Todd Poynor3948f802013-07-09 19:35:14 -0700496/* PAGE_SIZE / 1024 */
497static long page_k;
498
Jim Blacklerd2da8142019-09-10 15:30:05 +0100499static char* proc_get_name(int pid);
500static void poll_kernel();
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 Baghdasaryan0f100512018-01-24 16:51:41 -0800766static void cmd_procprio(LMKD_CTRL_PACKET packet) {
Todd Poynor3948f802013-07-09 19:35:14 -0700767 struct proc *procp;
768 char path[80];
769 char val[20];
Robert Benea673e2762017-06-01 16:32:31 -0700770 int soft_limit_mult;
Suren Baghdasaryan0f100512018-01-24 16:51:41 -0800771 struct lmk_procprio params;
Suren Baghdasaryan4311d1e2018-03-20 16:03:29 -0700772 bool is_system_server;
773 struct passwd *pwdrec;
Suren Baghdasaryan0082ef12019-07-02 15:52:07 -0700774 int tgid;
Todd Poynor3948f802013-07-09 19:35:14 -0700775
Suren Baghdasaryan0f100512018-01-24 16:51:41 -0800776 lmkd_pack_get_procprio(packet, &params);
777
778 if (params.oomadj < OOM_SCORE_ADJ_MIN ||
779 params.oomadj > OOM_SCORE_ADJ_MAX) {
780 ALOGE("Invalid PROCPRIO oomadj argument %d", params.oomadj);
Todd Poynor3948f802013-07-09 19:35:14 -0700781 return;
782 }
783
Suren Baghdasaryan0082ef12019-07-02 15:52:07 -0700784 /* Check if registered process is a thread group leader */
785 tgid = proc_get_tgid(params.pid);
786 if (tgid >= 0 && tgid != params.pid) {
787 ALOGE("Attempt to register a task that is not a thread group leader (tid %d, tgid %d)",
788 params.pid, tgid);
789 return;
790 }
791
Mark Salyzyn64d97d82018-04-09 09:50:32 -0700792 /* gid containing AID_READPROC required */
793 /* CAP_SYS_RESOURCE required */
794 /* CAP_DAC_OVERRIDE required */
Suren Baghdasaryan0f100512018-01-24 16:51:41 -0800795 snprintf(path, sizeof(path), "/proc/%d/oom_score_adj", params.pid);
796 snprintf(val, sizeof(val), "%d", params.oomadj);
Suren Baghdasaryan1ffa2462018-03-20 13:53:17 -0700797 if (!writefilestring(path, val, false)) {
798 ALOGW("Failed to open %s; errno=%d: process %d might have been killed",
799 path, errno, params.pid);
800 /* If this file does not exist the process is dead. */
801 return;
802 }
Todd Poynor3948f802013-07-09 19:35:14 -0700803
Mark Salyzyn721d7c72018-03-21 12:24:58 -0700804 if (use_inkernel_interface) {
Jim Blacklerd2da8142019-09-10 15:30:05 +0100805#ifdef LMKD_LOG_STATS
806 stats_store_taskname(params.pid, proc_get_name(params.pid));
807#endif
Todd Poynor3948f802013-07-09 19:35:14 -0700808 return;
Mark Salyzyn721d7c72018-03-21 12:24:58 -0700809 }
Todd Poynor3948f802013-07-09 19:35:14 -0700810
Suren Baghdasaryance13cb52018-06-19 18:38:12 -0700811 if (per_app_memcg) {
Suren Baghdasaryan20686f02018-05-18 14:42:00 -0700812 if (params.oomadj >= 900) {
813 soft_limit_mult = 0;
814 } else if (params.oomadj >= 800) {
815 soft_limit_mult = 0;
816 } else if (params.oomadj >= 700) {
817 soft_limit_mult = 0;
818 } else if (params.oomadj >= 600) {
819 // Launcher should be perceptible, don't kill it.
820 params.oomadj = 200;
821 soft_limit_mult = 1;
822 } else if (params.oomadj >= 500) {
823 soft_limit_mult = 0;
824 } else if (params.oomadj >= 400) {
825 soft_limit_mult = 0;
826 } else if (params.oomadj >= 300) {
827 soft_limit_mult = 1;
828 } else if (params.oomadj >= 200) {
Srinivas Paladugu3eb20bc2018-10-09 14:21:10 -0700829 soft_limit_mult = 8;
Suren Baghdasaryan20686f02018-05-18 14:42:00 -0700830 } else if (params.oomadj >= 100) {
831 soft_limit_mult = 10;
832 } else if (params.oomadj >= 0) {
833 soft_limit_mult = 20;
834 } else {
835 // Persistent processes will have a large
836 // soft limit 512MB.
837 soft_limit_mult = 64;
838 }
Robert Benea673e2762017-06-01 16:32:31 -0700839
Suren Baghdasaryan3862dd32018-05-21 19:48:47 -0700840 snprintf(path, sizeof(path), MEMCG_SYSFS_PATH
841 "apps/uid_%d/pid_%d/memory.soft_limit_in_bytes",
842 params.uid, params.pid);
Suren Baghdasaryan20686f02018-05-18 14:42:00 -0700843 snprintf(val, sizeof(val), "%d", soft_limit_mult * EIGHT_MEGA);
Suren Baghdasaryan3862dd32018-05-21 19:48:47 -0700844
845 /*
846 * system_server process has no memcg under /dev/memcg/apps but should be
847 * registered with lmkd. This is the best way so far to identify it.
848 */
849 is_system_server = (params.oomadj == SYSTEM_ADJ &&
850 (pwdrec = getpwnam("system")) != NULL &&
851 params.uid == pwdrec->pw_uid);
852 writefilestring(path, val, !is_system_server);
Robert Benea673e2762017-06-01 16:32:31 -0700853 }
854
Suren Baghdasaryan0f100512018-01-24 16:51:41 -0800855 procp = pid_lookup(params.pid);
Todd Poynor3948f802013-07-09 19:35:14 -0700856 if (!procp) {
857 procp = malloc(sizeof(struct proc));
858 if (!procp) {
859 // Oh, the irony. May need to rebuild our state.
860 return;
861 }
862
Suren Baghdasaryan0f100512018-01-24 16:51:41 -0800863 procp->pid = params.pid;
864 procp->uid = params.uid;
865 procp->oomadj = params.oomadj;
Todd Poynor3948f802013-07-09 19:35:14 -0700866 proc_insert(procp);
867 } else {
868 proc_unslot(procp);
Suren Baghdasaryan0f100512018-01-24 16:51:41 -0800869 procp->oomadj = params.oomadj;
Todd Poynor3948f802013-07-09 19:35:14 -0700870 proc_slot(procp);
871 }
872}
873
Suren Baghdasaryan0f100512018-01-24 16:51:41 -0800874static void cmd_procremove(LMKD_CTRL_PACKET packet) {
875 struct lmk_procremove params;
876
Mark Salyzyn721d7c72018-03-21 12:24:58 -0700877 if (use_inkernel_interface) {
Jim Blacklerd2da8142019-09-10 15:30:05 +0100878#ifdef LMKD_LOG_STATS
879 /* Perform an extra check before the pid is removed, after which it
880 * will be impossible for poll_kernel to get the taskname. poll_kernel()
881 * is potentially a long-running blocking function; however this method
882 * handles AMS requests but does not block AMS.*/
883 if (enable_stats_log) {
884 poll_kernel();
885 }
886 stats_remove_taskname(params.pid);
887#endif
Todd Poynor3948f802013-07-09 19:35:14 -0700888 return;
Mark Salyzyn721d7c72018-03-21 12:24:58 -0700889 }
Todd Poynor3948f802013-07-09 19:35:14 -0700890
Suren Baghdasaryan0f100512018-01-24 16:51:41 -0800891 lmkd_pack_get_procremove(packet, &params);
Suren Baghdasaryan01063272018-10-12 11:28:33 -0700892 /*
893 * WARNING: After pid_remove() procp is freed and can't be used!
894 * Therefore placed at the end of the function.
895 */
Suren Baghdasaryan0f100512018-01-24 16:51:41 -0800896 pid_remove(params.pid);
Todd Poynor3948f802013-07-09 19:35:14 -0700897}
898
Suren Baghdasaryane3b60472018-10-10 14:17:17 -0700899static void cmd_procpurge() {
900 int i;
901 struct proc *procp;
902 struct proc *next;
903
904 if (use_inkernel_interface) {
Jim Blacklerd2da8142019-09-10 15:30:05 +0100905#ifdef LMKD_LOG_STATS
906 stats_purge_tasknames();
907#endif
Suren Baghdasaryane3b60472018-10-10 14:17:17 -0700908 return;
909 }
910
911 for (i = 0; i <= ADJTOSLOT(OOM_SCORE_ADJ_MAX); i++) {
912 procadjslot_list[i].next = &procadjslot_list[i];
913 procadjslot_list[i].prev = &procadjslot_list[i];
914 }
915
916 for (i = 0; i < PIDHASH_SZ; i++) {
917 procp = pidhash[i];
918 while (procp) {
919 next = procp->pidhash_next;
920 free(procp);
921 procp = next;
922 }
923 }
924 memset(&pidhash[0], 0, sizeof(pidhash));
925}
926
Suren Baghdasaryand4a29902018-10-12 11:07:40 -0700927static void inc_killcnt(int oomadj) {
928 int slot = ADJTOSLOT(oomadj);
929 uint8_t idx = killcnt_idx[slot];
930
931 if (idx == KILLCNT_INVALID_IDX) {
932 /* index is not assigned for this oomadj */
933 if (killcnt_free_idx < MAX_DISTINCT_OOM_ADJ) {
934 killcnt_idx[slot] = killcnt_free_idx;
935 killcnt[killcnt_free_idx] = 1;
936 killcnt_free_idx++;
937 } else {
938 ALOGW("Number of distinct oomadj levels exceeds %d",
939 MAX_DISTINCT_OOM_ADJ);
940 }
941 } else {
942 /*
943 * wraparound is highly unlikely and is detectable using total
944 * counter because it has to be equal to the sum of all counters
945 */
946 killcnt[idx]++;
947 }
948 /* increment total kill counter */
949 killcnt_total++;
950}
951
952static int get_killcnt(int min_oomadj, int max_oomadj) {
953 int slot;
954 int count = 0;
955
956 if (min_oomadj > max_oomadj)
957 return 0;
958
959 /* special case to get total kill count */
960 if (min_oomadj > OOM_SCORE_ADJ_MAX)
961 return killcnt_total;
962
963 while (min_oomadj <= max_oomadj &&
964 (slot = ADJTOSLOT(min_oomadj)) < ADJTOSLOT_COUNT) {
965 uint8_t idx = killcnt_idx[slot];
966 if (idx != KILLCNT_INVALID_IDX) {
967 count += killcnt[idx];
968 }
969 min_oomadj++;
970 }
971
972 return count;
973}
974
975static int cmd_getkillcnt(LMKD_CTRL_PACKET packet) {
976 struct lmk_getkillcnt params;
977
978 if (use_inkernel_interface) {
979 /* kernel driver does not expose this information */
980 return 0;
981 }
982
983 lmkd_pack_get_getkillcnt(packet, &params);
984
985 return get_killcnt(params.min_oomadj, params.max_oomadj);
986}
987
Suren Baghdasaryan0f100512018-01-24 16:51:41 -0800988static void cmd_target(int ntargets, LMKD_CTRL_PACKET packet) {
Todd Poynor3948f802013-07-09 19:35:14 -0700989 int i;
Suren Baghdasaryan0f100512018-01-24 16:51:41 -0800990 struct lmk_target target;
Suren Baghdasaryan314a5052018-07-24 17:13:06 -0700991 char minfree_str[PROPERTY_VALUE_MAX];
992 char *pstr = minfree_str;
993 char *pend = minfree_str + sizeof(minfree_str);
994 static struct timespec last_req_tm;
995 struct timespec curr_tm;
Todd Poynor3948f802013-07-09 19:35:14 -0700996
Suren Baghdasaryan314a5052018-07-24 17:13:06 -0700997 if (ntargets < 1 || ntargets > (int)ARRAY_SIZE(lowmem_adj))
Todd Poynor3948f802013-07-09 19:35:14 -0700998 return;
999
Suren Baghdasaryan314a5052018-07-24 17:13:06 -07001000 /*
1001 * Ratelimit minfree updates to once per TARGET_UPDATE_MIN_INTERVAL_MS
1002 * to prevent DoS attacks
1003 */
1004 if (clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm) != 0) {
1005 ALOGE("Failed to get current time");
1006 return;
1007 }
1008
1009 if (get_time_diff_ms(&last_req_tm, &curr_tm) <
1010 TARGET_UPDATE_MIN_INTERVAL_MS) {
1011 ALOGE("Ignoring frequent updated to lmkd limits");
1012 return;
1013 }
1014
1015 last_req_tm = curr_tm;
1016
Todd Poynor3948f802013-07-09 19:35:14 -07001017 for (i = 0; i < ntargets; i++) {
Suren Baghdasaryan0f100512018-01-24 16:51:41 -08001018 lmkd_pack_get_target(packet, i, &target);
1019 lowmem_minfree[i] = target.minfree;
1020 lowmem_adj[i] = target.oom_adj_score;
Suren Baghdasaryan314a5052018-07-24 17:13:06 -07001021
1022 pstr += snprintf(pstr, pend - pstr, "%d:%d,", target.minfree,
1023 target.oom_adj_score);
1024 if (pstr >= pend) {
1025 /* if no more space in the buffer then terminate the loop */
1026 pstr = pend;
1027 break;
1028 }
Todd Poynor3948f802013-07-09 19:35:14 -07001029 }
1030
1031 lowmem_targets_size = ntargets;
1032
Suren Baghdasaryan314a5052018-07-24 17:13:06 -07001033 /* Override the last extra comma */
1034 pstr[-1] = '\0';
1035 property_set("sys.lmk.minfree_levels", minfree_str);
1036
Robert Benea164baeb2017-09-11 16:53:28 -07001037 if (has_inkernel_module) {
Todd Poynor3948f802013-07-09 19:35:14 -07001038 char minfreestr[128];
1039 char killpriostr[128];
1040
1041 minfreestr[0] = '\0';
1042 killpriostr[0] = '\0';
1043
1044 for (i = 0; i < lowmem_targets_size; i++) {
1045 char val[40];
1046
1047 if (i) {
1048 strlcat(minfreestr, ",", sizeof(minfreestr));
1049 strlcat(killpriostr, ",", sizeof(killpriostr));
1050 }
1051
Robert Benea164baeb2017-09-11 16:53:28 -07001052 snprintf(val, sizeof(val), "%d", use_inkernel_interface ? lowmem_minfree[i] : 0);
Todd Poynor3948f802013-07-09 19:35:14 -07001053 strlcat(minfreestr, val, sizeof(minfreestr));
Robert Benea164baeb2017-09-11 16:53:28 -07001054 snprintf(val, sizeof(val), "%d", use_inkernel_interface ? lowmem_adj[i] : 0);
Todd Poynor3948f802013-07-09 19:35:14 -07001055 strlcat(killpriostr, val, sizeof(killpriostr));
1056 }
1057
Suren Baghdasaryan1ffa2462018-03-20 13:53:17 -07001058 writefilestring(INKERNEL_MINFREE_PATH, minfreestr, true);
1059 writefilestring(INKERNEL_ADJ_PATH, killpriostr, true);
Todd Poynor3948f802013-07-09 19:35:14 -07001060 }
1061}
1062
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08001063static void ctrl_data_close(int dsock_idx) {
1064 struct epoll_event epev;
1065
1066 ALOGI("closing lmkd data connection");
1067 if (epoll_ctl(epollfd, EPOLL_CTL_DEL, data_sock[dsock_idx].sock, &epev) == -1) {
1068 // Log a warning and keep going
1069 ALOGW("epoll_ctl for data connection socket failed; errno=%d", errno);
1070 }
Todd Poynor3948f802013-07-09 19:35:14 -07001071 maxevents--;
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08001072
1073 close(data_sock[dsock_idx].sock);
1074 data_sock[dsock_idx].sock = -1;
Todd Poynor3948f802013-07-09 19:35:14 -07001075}
1076
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08001077static int ctrl_data_read(int dsock_idx, char *buf, size_t bufsz) {
Todd Poynor3948f802013-07-09 19:35:14 -07001078 int ret = 0;
1079
Suren Baghdasaryan6499e5e2018-04-13 12:43:41 -07001080 ret = TEMP_FAILURE_RETRY(read(data_sock[dsock_idx].sock, buf, bufsz));
Todd Poynor3948f802013-07-09 19:35:14 -07001081
1082 if (ret == -1) {
1083 ALOGE("control data socket read failed; errno=%d", errno);
1084 } else if (ret == 0) {
1085 ALOGE("Got EOF on control data socket");
1086 ret = -1;
1087 }
1088
1089 return ret;
1090}
1091
Suren Baghdasaryand4a29902018-10-12 11:07:40 -07001092static int ctrl_data_write(int dsock_idx, char *buf, size_t bufsz) {
1093 int ret = 0;
1094
1095 ret = TEMP_FAILURE_RETRY(write(data_sock[dsock_idx].sock, buf, bufsz));
1096
1097 if (ret == -1) {
1098 ALOGE("control data socket write failed; errno=%d", errno);
1099 } else if (ret == 0) {
1100 ALOGE("Got EOF on control data socket");
1101 ret = -1;
1102 }
1103
1104 return ret;
1105}
1106
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08001107static void ctrl_command_handler(int dsock_idx) {
Suren Baghdasaryan0f100512018-01-24 16:51:41 -08001108 LMKD_CTRL_PACKET packet;
Todd Poynor3948f802013-07-09 19:35:14 -07001109 int len;
Suren Baghdasaryan0f100512018-01-24 16:51:41 -08001110 enum lmk_cmd cmd;
Todd Poynor3948f802013-07-09 19:35:14 -07001111 int nargs;
1112 int targets;
Suren Baghdasaryand4a29902018-10-12 11:07:40 -07001113 int kill_cnt;
Todd Poynor3948f802013-07-09 19:35:14 -07001114
Suren Baghdasaryan0f100512018-01-24 16:51:41 -08001115 len = ctrl_data_read(dsock_idx, (char *)packet, CTRL_PACKET_MAX_SIZE);
Todd Poynor3948f802013-07-09 19:35:14 -07001116 if (len <= 0)
1117 return;
1118
Suren Baghdasaryan0f100512018-01-24 16:51:41 -08001119 if (len < (int)sizeof(int)) {
1120 ALOGE("Wrong control socket read length len=%d", len);
1121 return;
1122 }
1123
1124 cmd = lmkd_pack_get_cmd(packet);
Todd Poynor3948f802013-07-09 19:35:14 -07001125 nargs = len / sizeof(int) - 1;
1126 if (nargs < 0)
1127 goto wronglen;
1128
Todd Poynor3948f802013-07-09 19:35:14 -07001129 switch(cmd) {
1130 case LMK_TARGET:
1131 targets = nargs / 2;
1132 if (nargs & 0x1 || targets > (int)ARRAY_SIZE(lowmem_adj))
1133 goto wronglen;
Suren Baghdasaryan0f100512018-01-24 16:51:41 -08001134 cmd_target(targets, packet);
Todd Poynor3948f802013-07-09 19:35:14 -07001135 break;
1136 case LMK_PROCPRIO:
Colin Crossfbb78c62014-06-13 14:52:43 -07001137 if (nargs != 3)
Todd Poynor3948f802013-07-09 19:35:14 -07001138 goto wronglen;
Suren Baghdasaryan0f100512018-01-24 16:51:41 -08001139 cmd_procprio(packet);
Todd Poynor3948f802013-07-09 19:35:14 -07001140 break;
1141 case LMK_PROCREMOVE:
1142 if (nargs != 1)
1143 goto wronglen;
Suren Baghdasaryan0f100512018-01-24 16:51:41 -08001144 cmd_procremove(packet);
Todd Poynor3948f802013-07-09 19:35:14 -07001145 break;
Suren Baghdasaryane3b60472018-10-10 14:17:17 -07001146 case LMK_PROCPURGE:
1147 if (nargs != 0)
1148 goto wronglen;
1149 cmd_procpurge();
1150 break;
Suren Baghdasaryand4a29902018-10-12 11:07:40 -07001151 case LMK_GETKILLCNT:
1152 if (nargs != 2)
1153 goto wronglen;
1154 kill_cnt = cmd_getkillcnt(packet);
1155 len = lmkd_pack_set_getkillcnt_repl(packet, kill_cnt);
1156 if (ctrl_data_write(dsock_idx, (char *)packet, len) != len)
1157 return;
1158 break;
Todd Poynor3948f802013-07-09 19:35:14 -07001159 default:
1160 ALOGE("Received unknown command code %d", cmd);
1161 return;
1162 }
1163
1164 return;
1165
1166wronglen:
1167 ALOGE("Wrong control socket read length cmd=%d len=%d", cmd, len);
1168}
1169
Suren Baghdasaryanef3650f2019-07-15 14:50:49 -07001170static void ctrl_data_handler(int data, uint32_t events,
1171 struct polling_params *poll_params __unused) {
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08001172 if (events & EPOLLIN) {
1173 ctrl_command_handler(data);
Todd Poynor3948f802013-07-09 19:35:14 -07001174 }
1175}
1176
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08001177static int get_free_dsock() {
1178 for (int i = 0; i < MAX_DATA_CONN; i++) {
1179 if (data_sock[i].sock < 0) {
1180 return i;
1181 }
1182 }
1183 return -1;
1184}
Todd Poynor3948f802013-07-09 19:35:14 -07001185
Suren Baghdasaryanef3650f2019-07-15 14:50:49 -07001186static void ctrl_connect_handler(int data __unused, uint32_t events __unused,
1187 struct polling_params *poll_params __unused) {
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08001188 struct epoll_event epev;
1189 int free_dscock_idx = get_free_dsock();
1190
1191 if (free_dscock_idx < 0) {
1192 /*
1193 * Number of data connections exceeded max supported. This should not
1194 * happen but if it does we drop all existing connections and accept
1195 * the new one. This prevents inactive connections from monopolizing
1196 * data socket and if we drop ActivityManager connection it will
1197 * immediately reconnect.
1198 */
1199 for (int i = 0; i < MAX_DATA_CONN; i++) {
1200 ctrl_data_close(i);
1201 }
1202 free_dscock_idx = 0;
Todd Poynor3948f802013-07-09 19:35:14 -07001203 }
1204
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08001205 data_sock[free_dscock_idx].sock = accept(ctrl_sock.sock, NULL, NULL);
1206 if (data_sock[free_dscock_idx].sock < 0) {
Todd Poynor3948f802013-07-09 19:35:14 -07001207 ALOGE("lmkd control socket accept failed; errno=%d", errno);
1208 return;
1209 }
1210
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08001211 ALOGI("lmkd data connection established");
1212 /* use data to store data connection idx */
1213 data_sock[free_dscock_idx].handler_info.data = free_dscock_idx;
1214 data_sock[free_dscock_idx].handler_info.handler = ctrl_data_handler;
Todd Poynor3948f802013-07-09 19:35:14 -07001215 epev.events = EPOLLIN;
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08001216 epev.data.ptr = (void *)&(data_sock[free_dscock_idx].handler_info);
1217 if (epoll_ctl(epollfd, EPOLL_CTL_ADD, data_sock[free_dscock_idx].sock, &epev) == -1) {
Todd Poynor3948f802013-07-09 19:35:14 -07001218 ALOGE("epoll_ctl for data connection socket failed; errno=%d", errno);
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08001219 ctrl_data_close(free_dscock_idx);
Todd Poynor3948f802013-07-09 19:35:14 -07001220 return;
1221 }
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08001222 maxevents++;
Todd Poynor3948f802013-07-09 19:35:14 -07001223}
1224
Rajeev Kumar70450032018-01-31 17:54:56 -08001225#ifdef LMKD_LOG_STATS
Rajeev Kumar4dbc24d2018-10-05 12:34:59 -07001226static void memory_stat_parse_line(char* line, struct memory_stat* mem_st) {
Greg Kaiserf0da9b02018-03-23 14:16:12 -07001227 char key[LINE_MAX + 1];
Rajeev Kumar70450032018-01-31 17:54:56 -08001228 int64_t value;
1229
Greg Kaiserf0da9b02018-03-23 14:16:12 -07001230 sscanf(line, "%" STRINGIFY(LINE_MAX) "s %" SCNd64 "", key, &value);
Rajeev Kumar70450032018-01-31 17:54:56 -08001231
1232 if (strcmp(key, "total_") < 0) {
1233 return;
1234 }
1235
1236 if (!strcmp(key, "total_pgfault"))
1237 mem_st->pgfault = value;
1238 else if (!strcmp(key, "total_pgmajfault"))
1239 mem_st->pgmajfault = value;
1240 else if (!strcmp(key, "total_rss"))
1241 mem_st->rss_in_bytes = value;
1242 else if (!strcmp(key, "total_cache"))
1243 mem_st->cache_in_bytes = value;
1244 else if (!strcmp(key, "total_swap"))
1245 mem_st->swap_in_bytes = value;
1246}
1247
Rajeev Kumar4dbc24d2018-10-05 12:34:59 -07001248static int memory_stat_from_cgroup(struct memory_stat* mem_st, int pid, uid_t uid) {
Suren Baghdasaryan1d1c0022018-06-19 18:38:12 -07001249 FILE *fp;
1250 char buf[PATH_MAX];
Rajeev Kumar70450032018-01-31 17:54:56 -08001251
Suren Baghdasaryan1d1c0022018-06-19 18:38:12 -07001252 snprintf(buf, sizeof(buf), MEMCG_PROCESS_MEMORY_STAT_PATH, uid, pid);
Rajeev Kumar70450032018-01-31 17:54:56 -08001253
Suren Baghdasaryan1d1c0022018-06-19 18:38:12 -07001254 fp = fopen(buf, "r");
Rajeev Kumar70450032018-01-31 17:54:56 -08001255
Suren Baghdasaryan1d1c0022018-06-19 18:38:12 -07001256 if (fp == NULL) {
1257 ALOGE("%s open failed: %s", buf, strerror(errno));
1258 return -1;
1259 }
Rajeev Kumar70450032018-01-31 17:54:56 -08001260
Rajeev Kumar4dbc24d2018-10-05 12:34:59 -07001261 while (fgets(buf, PAGE_SIZE, fp) != NULL) {
Suren Baghdasaryan1d1c0022018-06-19 18:38:12 -07001262 memory_stat_parse_line(buf, mem_st);
1263 }
1264 fclose(fp);
1265
1266 return 0;
Rajeev Kumar70450032018-01-31 17:54:56 -08001267}
Rajeev Kumar4dbc24d2018-10-05 12:34:59 -07001268
1269static int memory_stat_from_procfs(struct memory_stat* mem_st, int pid) {
1270 char path[PATH_MAX];
1271 char buffer[PROC_STAT_BUFFER_SIZE];
1272 int fd, ret;
1273
1274 snprintf(path, sizeof(path), PROC_STAT_FILE_PATH, pid);
1275 if ((fd = open(path, O_RDONLY | O_CLOEXEC)) < 0) {
1276 ALOGE("%s open failed: %s", path, strerror(errno));
1277 return -1;
1278 }
1279
1280 ret = read(fd, buffer, sizeof(buffer));
1281 if (ret < 0) {
1282 ALOGE("%s read failed: %s", path, strerror(errno));
1283 close(fd);
1284 return -1;
1285 }
1286 close(fd);
1287
1288 // field 10 is pgfault
1289 // field 12 is pgmajfault
Jim Blackler1417cdb2018-11-21 16:22:36 +00001290 // field 22 is starttime
Rajeev Kumar4dbc24d2018-10-05 12:34:59 -07001291 // field 24 is rss_in_pages
Jim Blackler1417cdb2018-11-21 16:22:36 +00001292 int64_t pgfault = 0, pgmajfault = 0, starttime = 0, rss_in_pages = 0;
Rajeev Kumar4dbc24d2018-10-05 12:34:59 -07001293 if (sscanf(buffer,
1294 "%*u %*s %*s %*d %*d %*d %*d %*d %*d %" SCNd64 " %*d "
1295 "%" SCNd64 " %*d %*u %*u %*d %*d %*d %*d %*d %*d "
Jim Blackler1417cdb2018-11-21 16:22:36 +00001296 "%" SCNd64 " %*d %" SCNd64 "",
1297 &pgfault, &pgmajfault, &starttime, &rss_in_pages) != 4) {
Rajeev Kumar4dbc24d2018-10-05 12:34:59 -07001298 return -1;
1299 }
1300 mem_st->pgfault = pgfault;
1301 mem_st->pgmajfault = pgmajfault;
1302 mem_st->rss_in_bytes = (rss_in_pages * PAGE_SIZE);
Jim Blackler1417cdb2018-11-21 16:22:36 +00001303 mem_st->process_start_time_ns = starttime * (NS_PER_SEC / sysconf(_SC_CLK_TCK));
Rajeev Kumar4dbc24d2018-10-05 12:34:59 -07001304 return 0;
1305}
Rajeev Kumar70450032018-01-31 17:54:56 -08001306#endif
1307
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07001308/*
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07001309 * /proc/zoneinfo parsing routines
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07001310 * Expected file format is:
1311 *
1312 * Node <node_id>, zone <zone_name>
1313 * (
1314 * per-node stats
1315 * (<per-node field name> <value>)+
1316 * )?
1317 * (pages free <value>
1318 * (<per-zone field name> <value>)+
1319 * pagesets
1320 * (<unused fields>)*
1321 * )+
1322 * ...
1323 */
1324static void zoneinfo_parse_protection(char *buf, struct zoneinfo_zone *zone) {
1325 int zone_idx;
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001326 int64_t max = 0;
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001327 char *save_ptr;
1328
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07001329 for (buf = strtok_r(buf, "(), ", &save_ptr), zone_idx = 0;
1330 buf && zone_idx < MAX_NR_ZONES;
1331 buf = strtok_r(NULL, "), ", &save_ptr), zone_idx++) {
1332 long long zoneval = strtoll(buf, &buf, 0);
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001333 if (zoneval > max) {
1334 max = (zoneval > INT64_MAX) ? INT64_MAX : zoneval;
1335 }
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07001336 zone->protection[zone_idx] = zoneval;
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001337 }
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07001338 zone->max_protection = max;
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001339}
1340
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07001341static int zoneinfo_parse_zone(char **buf, struct zoneinfo_zone *zone) {
1342 for (char *line = strtok_r(NULL, "\n", buf); line;
1343 line = strtok_r(NULL, "\n", buf)) {
1344 char *cp;
1345 char *ap;
1346 char *save_ptr;
1347 int64_t val;
1348 int field_idx;
1349 enum field_match_result match_res;
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001350
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07001351 cp = strtok_r(line, " ", &save_ptr);
1352 if (!cp) {
1353 return false;
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001354 }
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07001355
1356 field_idx = find_field(cp, zoneinfo_zone_spec_field_names, ZI_ZONE_SPEC_FIELD_COUNT);
1357 if (field_idx >= 0) {
1358 /* special field */
1359 if (field_idx == ZI_ZONE_SPEC_PAGESETS) {
1360 /* no mode fields we are interested in */
1361 return true;
1362 }
1363
1364 /* protection field */
1365 ap = strtok_r(NULL, ")", &save_ptr);
1366 if (ap) {
1367 zoneinfo_parse_protection(ap, zone);
1368 }
1369 continue;
1370 }
1371
1372 ap = strtok_r(NULL, " ", &save_ptr);
1373 if (!ap) {
1374 continue;
1375 }
1376
1377 match_res = match_field(cp, ap, zoneinfo_zone_field_names, ZI_ZONE_FIELD_COUNT,
1378 &val, &field_idx);
1379 if (match_res == PARSE_FAIL) {
1380 return false;
1381 }
1382 if (match_res == PARSE_SUCCESS) {
1383 zone->fields.arr[field_idx] = val;
1384 }
1385 if (field_idx == ZI_ZONE_PRESENT && val == 0) {
1386 /* zone is not populated, stop parsing it */
1387 return true;
1388 }
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001389 }
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07001390 return false;
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001391}
1392
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07001393static int zoneinfo_parse_node(char **buf, struct zoneinfo_node *node) {
1394 int fields_to_match = ZI_NODE_FIELD_COUNT;
1395
1396 for (char *line = strtok_r(NULL, "\n", buf); line;
1397 line = strtok_r(NULL, "\n", buf)) {
1398 char *cp;
1399 char *ap;
1400 char *save_ptr;
1401 int64_t val;
1402 int field_idx;
1403 enum field_match_result match_res;
1404
1405 cp = strtok_r(line, " ", &save_ptr);
1406 if (!cp) {
1407 return false;
1408 }
1409
1410 ap = strtok_r(NULL, " ", &save_ptr);
1411 if (!ap) {
1412 return false;
1413 }
1414
1415 match_res = match_field(cp, ap, zoneinfo_node_field_names, ZI_NODE_FIELD_COUNT,
1416 &val, &field_idx);
1417 if (match_res == PARSE_FAIL) {
1418 return false;
1419 }
1420 if (match_res == PARSE_SUCCESS) {
1421 node->fields.arr[field_idx] = val;
1422 fields_to_match--;
1423 if (!fields_to_match) {
1424 return true;
1425 }
1426 }
1427 }
1428 return false;
1429}
1430
1431static int zoneinfo_parse(struct zoneinfo *zi) {
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001432 static struct reread_data file_data = {
1433 .filename = ZONEINFO_PATH,
1434 .fd = -1,
1435 };
Suren Baghdasaryana77b3272019-07-15 13:35:04 -07001436 char *buf;
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001437 char *save_ptr;
1438 char *line;
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07001439 char zone_name[LINE_MAX];
1440 struct zoneinfo_node *node = NULL;
1441 int node_idx = 0;
1442 int zone_idx = 0;
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001443
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07001444 memset(zi, 0, sizeof(struct zoneinfo));
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001445
Suren Baghdasaryana77b3272019-07-15 13:35:04 -07001446 if ((buf = reread_file(&file_data)) == NULL) {
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001447 return -1;
1448 }
1449
1450 for (line = strtok_r(buf, "\n", &save_ptr); line;
1451 line = strtok_r(NULL, "\n", &save_ptr)) {
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07001452 int node_id;
1453 if (sscanf(line, "Node %d, zone %" STRINGIFY(LINE_MAX) "s", &node_id, zone_name) == 2) {
1454 if (!node || node->id != node_id) {
1455 /* new node is found */
1456 if (node) {
1457 node->zone_count = zone_idx + 1;
1458 node_idx++;
1459 if (node_idx == MAX_NR_NODES) {
1460 /* max node count exceeded */
1461 ALOGE("%s parse error", file_data.filename);
1462 return -1;
1463 }
1464 }
1465 node = &zi->nodes[node_idx];
1466 node->id = node_id;
1467 zone_idx = 0;
1468 if (!zoneinfo_parse_node(&save_ptr, node)) {
1469 ALOGE("%s parse error", file_data.filename);
1470 return -1;
1471 }
1472 } else {
1473 /* new zone is found */
1474 zone_idx++;
1475 }
1476 if (!zoneinfo_parse_zone(&save_ptr, &node->zones[zone_idx])) {
1477 ALOGE("%s parse error", file_data.filename);
1478 return -1;
1479 }
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001480 }
1481 }
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07001482 if (!node) {
1483 ALOGE("%s parse error", file_data.filename);
1484 return -1;
1485 }
1486 node->zone_count = zone_idx + 1;
1487 zi->node_count = node_idx + 1;
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001488
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07001489 /* calculate totals fields */
1490 for (node_idx = 0; node_idx < zi->node_count; node_idx++) {
1491 node = &zi->nodes[node_idx];
1492 for (zone_idx = 0; zone_idx < node->zone_count; zone_idx++) {
1493 struct zoneinfo_zone *zone = &zi->nodes[node_idx].zones[zone_idx];
1494 zi->totalreserve_pages += zone->max_protection + zone->fields.field.high;
1495 }
1496 zi->total_inactive_file += node->fields.field.nr_inactive_file;
1497 zi->total_active_file += node->fields.field.nr_active_file;
1498 zi->total_workingset_refault += node->fields.field.workingset_refault;
1499 }
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001500 return 0;
1501}
1502
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07001503/* /proc/meminfo parsing routines */
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001504static bool meminfo_parse_line(char *line, union meminfo *mi) {
1505 char *cp = line;
1506 char *ap;
1507 char *save_ptr;
1508 int64_t val;
1509 int field_idx;
1510 enum field_match_result match_res;
1511
1512 cp = strtok_r(line, " ", &save_ptr);
1513 if (!cp) {
1514 return false;
1515 }
1516
1517 ap = strtok_r(NULL, " ", &save_ptr);
1518 if (!ap) {
1519 return false;
1520 }
1521
1522 match_res = match_field(cp, ap, meminfo_field_names, MI_FIELD_COUNT,
1523 &val, &field_idx);
1524 if (match_res == PARSE_SUCCESS) {
1525 mi->arr[field_idx] = val / page_k;
1526 }
1527 return (match_res != PARSE_FAIL);
1528}
1529
1530static int meminfo_parse(union meminfo *mi) {
1531 static struct reread_data file_data = {
1532 .filename = MEMINFO_PATH,
1533 .fd = -1,
1534 };
Suren Baghdasaryana77b3272019-07-15 13:35:04 -07001535 char *buf;
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001536 char *save_ptr;
1537 char *line;
1538
1539 memset(mi, 0, sizeof(union meminfo));
1540
Suren Baghdasaryana77b3272019-07-15 13:35:04 -07001541 if ((buf = reread_file(&file_data)) == NULL) {
Suren Baghdasaryan8b9deaf2018-04-13 13:11:51 -07001542 return -1;
1543 }
1544
1545 for (line = strtok_r(buf, "\n", &save_ptr); line;
1546 line = strtok_r(NULL, "\n", &save_ptr)) {
1547 if (!meminfo_parse_line(line, mi)) {
1548 ALOGE("%s parse error", file_data.filename);
1549 return -1;
1550 }
1551 }
1552 mi->field.nr_file_pages = mi->field.cached + mi->field.swap_cached +
1553 mi->field.buffers;
1554
1555 return 0;
1556}
1557
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07001558/* /proc/vmstat parsing routines */
1559static bool vmstat_parse_line(char *line, union vmstat *vs) {
1560 char *cp;
1561 char *ap;
1562 char *save_ptr;
1563 int64_t val;
1564 int field_idx;
1565 enum field_match_result match_res;
1566
1567 cp = strtok_r(line, " ", &save_ptr);
1568 if (!cp) {
1569 return false;
1570 }
1571
1572 ap = strtok_r(NULL, " ", &save_ptr);
1573 if (!ap) {
1574 return false;
1575 }
1576
1577 match_res = match_field(cp, ap, vmstat_field_names, VS_FIELD_COUNT,
1578 &val, &field_idx);
1579 if (match_res == PARSE_SUCCESS) {
1580 vs->arr[field_idx] = val;
1581 }
1582 return (match_res != PARSE_FAIL);
1583}
1584
1585static int vmstat_parse(union vmstat *vs) {
1586 static struct reread_data file_data = {
1587 .filename = VMSTAT_PATH,
1588 .fd = -1,
1589 };
1590 char *buf;
1591 char *save_ptr;
1592 char *line;
1593
1594 memset(vs, 0, sizeof(union vmstat));
1595
1596 if ((buf = reread_file(&file_data)) == NULL) {
1597 return -1;
1598 }
1599
1600 for (line = strtok_r(buf, "\n", &save_ptr); line;
1601 line = strtok_r(NULL, "\n", &save_ptr)) {
1602 if (!vmstat_parse_line(line, vs)) {
1603 ALOGE("%s parse error", file_data.filename);
1604 return -1;
1605 }
1606 }
1607
1608 return 0;
1609}
1610
Suren Baghdasaryan282ad1a2018-07-26 16:34:27 -07001611static void meminfo_log(union meminfo *mi) {
1612 for (int field_idx = 0; field_idx < MI_FIELD_COUNT; field_idx++) {
1613 android_log_write_int32(ctx, (int32_t)min(mi->arr[field_idx] * page_k, INT32_MAX));
1614 }
1615
1616 android_log_write_list(ctx, LOG_ID_EVENTS);
1617 android_log_reset(ctx);
1618}
1619
Todd Poynor3948f802013-07-09 19:35:14 -07001620static int proc_get_size(int pid) {
1621 char path[PATH_MAX];
1622 char line[LINE_MAX];
Colin Crossce85d952014-07-11 17:53:27 -07001623 int fd;
Todd Poynor3948f802013-07-09 19:35:14 -07001624 int rss = 0;
1625 int total;
Colin Crossce85d952014-07-11 17:53:27 -07001626 ssize_t ret;
Todd Poynor3948f802013-07-09 19:35:14 -07001627
Mark Salyzyn64d97d82018-04-09 09:50:32 -07001628 /* gid containing AID_READPROC required */
Todd Poynor3948f802013-07-09 19:35:14 -07001629 snprintf(path, PATH_MAX, "/proc/%d/statm", pid);
Nick Kralevichc68c8862015-12-18 20:52:37 -08001630 fd = open(path, O_RDONLY | O_CLOEXEC);
Colin Crossce85d952014-07-11 17:53:27 -07001631 if (fd == -1)
Todd Poynor3948f802013-07-09 19:35:14 -07001632 return -1;
Colin Crossce85d952014-07-11 17:53:27 -07001633
1634 ret = read_all(fd, line, sizeof(line) - 1);
1635 if (ret < 0) {
1636 close(fd);
Todd Poynor3948f802013-07-09 19:35:14 -07001637 return -1;
1638 }
1639
1640 sscanf(line, "%d %d ", &total, &rss);
Colin Crossce85d952014-07-11 17:53:27 -07001641 close(fd);
Todd Poynor3948f802013-07-09 19:35:14 -07001642 return rss;
1643}
1644
1645static char *proc_get_name(int pid) {
1646 char path[PATH_MAX];
1647 static char line[LINE_MAX];
Colin Crossce85d952014-07-11 17:53:27 -07001648 int fd;
Todd Poynor3948f802013-07-09 19:35:14 -07001649 char *cp;
Colin Crossce85d952014-07-11 17:53:27 -07001650 ssize_t ret;
Todd Poynor3948f802013-07-09 19:35:14 -07001651
Mark Salyzyn64d97d82018-04-09 09:50:32 -07001652 /* gid containing AID_READPROC required */
Todd Poynor3948f802013-07-09 19:35:14 -07001653 snprintf(path, PATH_MAX, "/proc/%d/cmdline", pid);
Nick Kralevichc68c8862015-12-18 20:52:37 -08001654 fd = open(path, O_RDONLY | O_CLOEXEC);
Suren Baghdasaryan9e359db2019-09-27 16:56:50 -07001655 if (fd == -1) {
Todd Poynor3948f802013-07-09 19:35:14 -07001656 return NULL;
Suren Baghdasaryan9e359db2019-09-27 16:56:50 -07001657 }
Colin Crossce85d952014-07-11 17:53:27 -07001658 ret = read_all(fd, line, sizeof(line) - 1);
1659 close(fd);
1660 if (ret < 0) {
Todd Poynor3948f802013-07-09 19:35:14 -07001661 return NULL;
1662 }
1663
1664 cp = strchr(line, ' ');
Suren Baghdasaryan9e359db2019-09-27 16:56:50 -07001665 if (cp) {
Todd Poynor3948f802013-07-09 19:35:14 -07001666 *cp = '\0';
Suren Baghdasaryan9e359db2019-09-27 16:56:50 -07001667 } else {
1668 line[ret] = '\0';
1669 }
Todd Poynor3948f802013-07-09 19:35:14 -07001670
1671 return line;
1672}
1673
1674static struct proc *proc_adj_lru(int oomadj) {
1675 return (struct proc *)adjslot_tail(&procadjslot_list[ADJTOSLOT(oomadj)]);
1676}
1677
Suren Baghdasaryan662492a2017-12-08 13:17:06 -08001678static struct proc *proc_get_heaviest(int oomadj) {
1679 struct adjslot_list *head = &procadjslot_list[ADJTOSLOT(oomadj)];
1680 struct adjslot_list *curr = head->next;
1681 struct proc *maxprocp = NULL;
1682 int maxsize = 0;
1683 while (curr != head) {
1684 int pid = ((struct proc *)curr)->pid;
1685 int tasksize = proc_get_size(pid);
1686 if (tasksize <= 0) {
1687 struct adjslot_list *next = curr->next;
1688 pid_remove(pid);
1689 curr = next;
1690 } else {
1691 if (tasksize > maxsize) {
1692 maxsize = tasksize;
1693 maxprocp = (struct proc *)curr;
1694 }
1695 curr = curr->next;
1696 }
1697 }
1698 return maxprocp;
1699}
1700
Wei Wang2d95c102018-11-21 00:11:44 -08001701static void set_process_group_and_prio(int pid, SchedPolicy sp, int prio) {
1702 DIR* d;
1703 char proc_path[PATH_MAX];
1704 struct dirent* de;
1705
1706 snprintf(proc_path, sizeof(proc_path), "/proc/%d/task", pid);
1707 if (!(d = opendir(proc_path))) {
1708 ALOGW("Failed to open %s; errno=%d: process pid(%d) might have died", proc_path, errno,
1709 pid);
1710 return;
1711 }
1712
1713 while ((de = readdir(d))) {
1714 int t_pid;
1715
1716 if (de->d_name[0] == '.') continue;
1717 t_pid = atoi(de->d_name);
1718
1719 if (!t_pid) {
1720 ALOGW("Failed to get t_pid for '%s' of pid(%d)", de->d_name, pid);
1721 continue;
1722 }
1723
1724 if (setpriority(PRIO_PROCESS, t_pid, prio) && errno != ESRCH) {
1725 ALOGW("Unable to raise priority of killing t_pid (%d): errno=%d", t_pid, errno);
1726 }
1727
1728 if (set_cpuset_policy(t_pid, sp)) {
1729 ALOGW("Failed to set_cpuset_policy on pid(%d) t_pid(%d) to %d", pid, t_pid, (int)sp);
1730 continue;
1731 }
1732 }
1733 closedir(d);
1734}
1735
Tim Murraye7853f62018-10-25 17:05:41 -07001736static int last_killed_pid = -1;
1737
Colin Cross16b09462014-07-14 12:39:56 -07001738/* Kill one process specified by procp. Returns the size of the process killed */
Suren Baghdasaryanec5e4c62019-03-04 11:07:39 -08001739static int kill_one_process(struct proc* procp, int min_oom_score) {
Colin Cross16b09462014-07-14 12:39:56 -07001740 int pid = procp->pid;
1741 uid_t uid = procp->uid;
Suren Baghdasaryan0082ef12019-07-02 15:52:07 -07001742 int tgid;
Colin Cross16b09462014-07-14 12:39:56 -07001743 char *taskname;
1744 int tasksize;
1745 int r;
Suren Baghdasaryan01063272018-10-12 11:28:33 -07001746 int result = -1;
Colin Cross16b09462014-07-14 12:39:56 -07001747
Rajeev Kumar70450032018-01-31 17:54:56 -08001748#ifdef LMKD_LOG_STATS
Rajeev Kumar92b659b2018-02-21 19:08:15 -08001749 struct memory_stat mem_st = {};
Rajeev Kumar70450032018-01-31 17:54:56 -08001750 int memory_stat_parse_result = -1;
Suren Baghdasaryanec5e4c62019-03-04 11:07:39 -08001751#else
1752 /* To prevent unused parameter warning */
1753 (void)(min_oom_score);
Rajeev Kumar70450032018-01-31 17:54:56 -08001754#endif
1755
Suren Baghdasaryan0082ef12019-07-02 15:52:07 -07001756 tgid = proc_get_tgid(pid);
1757 if (tgid >= 0 && tgid != pid) {
1758 ALOGE("Possible pid reuse detected (pid %d, tgid %d)!", pid, tgid);
1759 goto out;
1760 }
1761
Colin Cross16b09462014-07-14 12:39:56 -07001762 taskname = proc_get_name(pid);
1763 if (!taskname) {
Suren Baghdasaryan01063272018-10-12 11:28:33 -07001764 goto out;
Colin Cross16b09462014-07-14 12:39:56 -07001765 }
1766
1767 tasksize = proc_get_size(pid);
1768 if (tasksize <= 0) {
Suren Baghdasaryan01063272018-10-12 11:28:33 -07001769 goto out;
Colin Cross16b09462014-07-14 12:39:56 -07001770 }
1771
Rajeev Kumar70450032018-01-31 17:54:56 -08001772#ifdef LMKD_LOG_STATS
1773 if (enable_stats_log) {
Rajeev Kumar4dbc24d2018-10-05 12:34:59 -07001774 if (per_app_memcg) {
1775 memory_stat_parse_result = memory_stat_from_cgroup(&mem_st, pid, uid);
1776 } else {
1777 memory_stat_parse_result = memory_stat_from_procfs(&mem_st, pid);
1778 }
Rajeev Kumar70450032018-01-31 17:54:56 -08001779 }
1780#endif
1781
Suren Baghdasaryanc7135592018-01-04 10:43:58 -08001782 TRACE_KILL_START(pid);
1783
Mark Salyzyn64d97d82018-04-09 09:50:32 -07001784 /* CAP_KILL required */
Suren Baghdasaryan96bf3a62017-12-08 12:58:52 -08001785 r = kill(pid, SIGKILL);
Wei Wang2d95c102018-11-21 00:11:44 -08001786
1787 set_process_group_and_prio(pid, SP_FOREGROUND, ANDROID_PRIORITY_HIGHEST);
1788
Suren Baghdasaryand4a29902018-10-12 11:07:40 -07001789 inc_killcnt(procp->oomadj);
Tim Murrayb62b3ef2019-05-28 12:15:34 -07001790 ALOGE("Kill '%s' (%d), uid %d, oom_adj %d to free %ldkB", taskname, pid, uid, procp->oomadj,
1791 tasksize * page_k);
Colin Cross16b09462014-07-14 12:39:56 -07001792
Suren Baghdasaryanc7135592018-01-04 10:43:58 -08001793 TRACE_KILL_END();
1794
Tim Murraye7853f62018-10-25 17:05:41 -07001795 last_killed_pid = pid;
1796
Colin Cross16b09462014-07-14 12:39:56 -07001797 if (r) {
Mark Salyzyn919f5382018-02-04 15:27:23 -08001798 ALOGE("kill(%d): errno=%d", pid, errno);
Suren Baghdasaryan01063272018-10-12 11:28:33 -07001799 goto out;
Rajeev Kumar70450032018-01-31 17:54:56 -08001800 } else {
1801#ifdef LMKD_LOG_STATS
1802 if (memory_stat_parse_result == 0) {
1803 stats_write_lmk_kill_occurred(log_ctx, LMK_KILL_OCCURRED, uid, taskname,
1804 procp->oomadj, mem_st.pgfault, mem_st.pgmajfault, mem_st.rss_in_bytes,
Suren Baghdasaryanec5e4c62019-03-04 11:07:39 -08001805 mem_st.cache_in_bytes, mem_st.swap_in_bytes, mem_st.process_start_time_ns,
1806 min_oom_score);
Rajeev Kumar4dbc24d2018-10-05 12:34:59 -07001807 } else if (enable_stats_log) {
1808 stats_write_lmk_kill_occurred(log_ctx, LMK_KILL_OCCURRED, uid, taskname, procp->oomadj,
Suren Baghdasaryanec5e4c62019-03-04 11:07:39 -08001809 -1, -1, tasksize * BYTES_IN_KILOBYTE, -1, -1, -1,
1810 min_oom_score);
Rajeev Kumar70450032018-01-31 17:54:56 -08001811 }
1812#endif
Suren Baghdasaryan01063272018-10-12 11:28:33 -07001813 result = tasksize;
Colin Cross16b09462014-07-14 12:39:56 -07001814 }
Mark Salyzyn919f5382018-02-04 15:27:23 -08001815
Suren Baghdasaryan01063272018-10-12 11:28:33 -07001816out:
1817 /*
1818 * WARNING: After pid_remove() procp is freed and can't be used!
1819 * Therefore placed at the end of the function.
1820 */
1821 pid_remove(pid);
1822 return result;
Colin Cross16b09462014-07-14 12:39:56 -07001823}
1824
1825/*
Suren Baghdasaryanf81b5f42018-10-26 11:32:15 -07001826 * Find one process to kill at or above the given oom_adj level.
1827 * Returns size of the killed process.
Colin Cross16b09462014-07-14 12:39:56 -07001828 */
Suren Baghdasaryanf81b5f42018-10-26 11:32:15 -07001829static int find_and_kill_process(int min_score_adj) {
Colin Cross16b09462014-07-14 12:39:56 -07001830 int i;
Suren Baghdasaryanf81b5f42018-10-26 11:32:15 -07001831 int killed_size = 0;
Colin Cross16b09462014-07-14 12:39:56 -07001832
Rajeev Kumar70450032018-01-31 17:54:56 -08001833#ifdef LMKD_LOG_STATS
Yang Lu5564f4e2018-05-15 04:59:44 +00001834 bool lmk_state_change_start = false;
Rajeev Kumar70450032018-01-31 17:54:56 -08001835#endif
1836
Chong Zhang0a4acdf2015-10-14 16:19:53 -07001837 for (i = OOM_SCORE_ADJ_MAX; i >= min_score_adj; i--) {
Colin Cross16b09462014-07-14 12:39:56 -07001838 struct proc *procp;
1839
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08001840 while (true) {
Suren Baghdasaryan818b59b2018-04-13 11:49:54 -07001841 procp = kill_heaviest_task ?
1842 proc_get_heaviest(i) : proc_adj_lru(i);
Colin Cross16b09462014-07-14 12:39:56 -07001843
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08001844 if (!procp)
1845 break;
1846
Suren Baghdasaryanec5e4c62019-03-04 11:07:39 -08001847 killed_size = kill_one_process(procp, min_score_adj);
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08001848 if (killed_size >= 0) {
Yang Lu5564f4e2018-05-15 04:59:44 +00001849#ifdef LMKD_LOG_STATS
1850 if (enable_stats_log && !lmk_state_change_start) {
1851 lmk_state_change_start = true;
1852 stats_write_lmk_state_changed(log_ctx, LMK_STATE_CHANGED,
1853 LMK_STATE_CHANGE_START);
1854 }
1855#endif
Suren Baghdasaryanf81b5f42018-10-26 11:32:15 -07001856 break;
Colin Cross16b09462014-07-14 12:39:56 -07001857 }
1858 }
Suren Baghdasaryanf81b5f42018-10-26 11:32:15 -07001859 if (killed_size) {
1860 break;
1861 }
Colin Cross16b09462014-07-14 12:39:56 -07001862 }
1863
Rajeev Kumar70450032018-01-31 17:54:56 -08001864#ifdef LMKD_LOG_STATS
Yang Lu5564f4e2018-05-15 04:59:44 +00001865 if (enable_stats_log && lmk_state_change_start) {
Rajeev Kumar70450032018-01-31 17:54:56 -08001866 stats_write_lmk_state_changed(log_ctx, LMK_STATE_CHANGED, LMK_STATE_CHANGE_STOP);
1867 }
1868#endif
1869
Suren Baghdasaryanf81b5f42018-10-26 11:32:15 -07001870 return killed_size;
Colin Cross16b09462014-07-14 12:39:56 -07001871}
1872
Suren Baghdasaryan6499e5e2018-04-13 12:43:41 -07001873static int64_t get_memory_usage(struct reread_data *file_data) {
Robert Beneac47f2992017-08-21 15:18:31 -07001874 int ret;
1875 int64_t mem_usage;
Suren Baghdasaryana77b3272019-07-15 13:35:04 -07001876 char *buf;
Suren Baghdasaryan6499e5e2018-04-13 12:43:41 -07001877
Suren Baghdasaryana77b3272019-07-15 13:35:04 -07001878 if ((buf = reread_file(file_data)) == NULL) {
Robert Beneac47f2992017-08-21 15:18:31 -07001879 return -1;
1880 }
1881
Suren Baghdasaryan6499e5e2018-04-13 12:43:41 -07001882 if (!parse_int64(buf, &mem_usage)) {
1883 ALOGE("%s parse error", file_data->filename);
Robert Beneac47f2992017-08-21 15:18:31 -07001884 return -1;
1885 }
Robert Beneac47f2992017-08-21 15:18:31 -07001886 if (mem_usage == 0) {
1887 ALOGE("No memory!");
1888 return -1;
1889 }
1890 return mem_usage;
1891}
1892
Suren Baghdasaryan9926e572018-04-13 13:41:12 -07001893void record_low_pressure_levels(union meminfo *mi) {
1894 if (low_pressure_mem.min_nr_free_pages == -1 ||
1895 low_pressure_mem.min_nr_free_pages > mi->field.nr_free_pages) {
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08001896 if (debug_process_killing) {
Suren Baghdasaryan9926e572018-04-13 13:41:12 -07001897 ALOGI("Low pressure min memory update from %" PRId64 " to %" PRId64,
1898 low_pressure_mem.min_nr_free_pages, mi->field.nr_free_pages);
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08001899 }
Suren Baghdasaryan9926e572018-04-13 13:41:12 -07001900 low_pressure_mem.min_nr_free_pages = mi->field.nr_free_pages;
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08001901 }
1902 /*
1903 * Free memory at low vmpressure events occasionally gets spikes,
1904 * possibly a stale low vmpressure event with memory already
1905 * freed up (no memory pressure should have been reported).
Suren Baghdasaryan9926e572018-04-13 13:41:12 -07001906 * Ignore large jumps in max_nr_free_pages that would mess up our stats.
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08001907 */
Suren Baghdasaryan9926e572018-04-13 13:41:12 -07001908 if (low_pressure_mem.max_nr_free_pages == -1 ||
1909 (low_pressure_mem.max_nr_free_pages < mi->field.nr_free_pages &&
1910 mi->field.nr_free_pages - low_pressure_mem.max_nr_free_pages <
1911 low_pressure_mem.max_nr_free_pages * 0.1)) {
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08001912 if (debug_process_killing) {
Suren Baghdasaryan9926e572018-04-13 13:41:12 -07001913 ALOGI("Low pressure max memory update from %" PRId64 " to %" PRId64,
1914 low_pressure_mem.max_nr_free_pages, mi->field.nr_free_pages);
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08001915 }
Suren Baghdasaryan9926e572018-04-13 13:41:12 -07001916 low_pressure_mem.max_nr_free_pages = mi->field.nr_free_pages;
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08001917 }
1918}
1919
Suren Baghdasaryan96bf3a62017-12-08 12:58:52 -08001920enum vmpressure_level upgrade_level(enum vmpressure_level level) {
1921 return (enum vmpressure_level)((level < VMPRESS_LEVEL_CRITICAL) ?
1922 level + 1 : level);
1923}
1924
1925enum vmpressure_level downgrade_level(enum vmpressure_level level) {
1926 return (enum vmpressure_level)((level > VMPRESS_LEVEL_LOW) ?
1927 level - 1 : level);
1928}
1929
Tim Murraye7853f62018-10-25 17:05:41 -07001930static bool is_kill_pending(void) {
1931 char buf[24];
1932
1933 if (last_killed_pid < 0) {
1934 return false;
1935 }
1936
1937 snprintf(buf, sizeof(buf), "/proc/%d/", last_killed_pid);
1938 if (access(buf, F_OK) == 0) {
1939 return true;
1940 }
1941
1942 // reset last killed PID because there's nothing pending
1943 last_killed_pid = -1;
1944 return false;
1945}
1946
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07001947enum zone_watermark {
1948 WMARK_MIN = 0,
1949 WMARK_LOW,
1950 WMARK_HIGH,
1951 WMARK_NONE
1952};
1953
Suren Baghdasaryan4787ab42019-08-14 09:48:35 -07001954struct zone_watermarks {
1955 long high_wmark;
1956 long low_wmark;
1957 long min_wmark;
1958};
1959
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07001960/*
1961 * Returns lowest breached watermark or WMARK_NONE.
1962 */
Suren Baghdasaryan4787ab42019-08-14 09:48:35 -07001963static enum zone_watermark get_lowest_watermark(union meminfo *mi,
1964 struct zone_watermarks *watermarks)
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07001965{
Suren Baghdasaryan4787ab42019-08-14 09:48:35 -07001966 int64_t nr_free_pages = mi->field.nr_free_pages - mi->field.cma_free;
1967
1968 if (nr_free_pages < watermarks->min_wmark) {
1969 return WMARK_MIN;
1970 }
1971 if (nr_free_pages < watermarks->low_wmark) {
1972 return WMARK_LOW;
1973 }
1974 if (nr_free_pages < watermarks->high_wmark) {
1975 return WMARK_HIGH;
1976 }
1977 return WMARK_NONE;
1978}
1979
1980void calc_zone_watermarks(struct zoneinfo *zi, struct zone_watermarks *watermarks) {
1981 memset(watermarks, 0, sizeof(struct zone_watermarks));
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07001982
1983 for (int node_idx = 0; node_idx < zi->node_count; node_idx++) {
1984 struct zoneinfo_node *node = &zi->nodes[node_idx];
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07001985 for (int zone_idx = 0; zone_idx < node->zone_count; zone_idx++) {
1986 struct zoneinfo_zone *zone = &node->zones[zone_idx];
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07001987
1988 if (!zone->fields.field.present) {
1989 continue;
1990 }
1991
Suren Baghdasaryan4787ab42019-08-14 09:48:35 -07001992 watermarks->high_wmark += zone->max_protection + zone->fields.field.high;
1993 watermarks->low_wmark += zone->max_protection + zone->fields.field.low;
1994 watermarks->min_wmark += zone->max_protection + zone->fields.field.min;
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07001995 }
1996 }
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07001997}
1998
1999static void mp_event_psi(int data, uint32_t events, struct polling_params *poll_params) {
2000 enum kill_reasons {
2001 NONE = -1, /* To denote no kill condition */
2002 PRESSURE_AFTER_KILL = 0,
2003 NOT_RESPONDING,
2004 LOW_SWAP_AND_THRASHING,
2005 LOW_MEM_AND_SWAP,
2006 LOW_MEM_AND_THRASHING,
2007 DIRECT_RECL_AND_THRASHING,
2008 KILL_REASON_COUNT
2009 };
2010 enum reclaim_state {
2011 NO_RECLAIM = 0,
2012 KSWAPD_RECLAIM,
2013 DIRECT_RECLAIM,
2014 };
2015 static int64_t init_ws_refault;
2016 static int64_t base_file_lru;
2017 static int64_t init_pgscan_kswapd;
2018 static int64_t init_pgscan_direct;
2019 static int64_t swap_low_threshold;
2020 static bool killing;
2021 static int thrashing_limit;
2022 static bool in_reclaim;
Suren Baghdasaryan4787ab42019-08-14 09:48:35 -07002023 static struct zone_watermarks watermarks;
2024 static struct timespec wmark_update_tm;
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002025
2026 union meminfo mi;
2027 union vmstat vs;
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002028 struct timespec curr_tm;
2029 int64_t thrashing = 0;
2030 bool swap_is_low = false;
2031 enum vmpressure_level level = (enum vmpressure_level)data;
2032 enum kill_reasons kill_reason = NONE;
2033 bool cycle_after_kill = false;
2034 enum reclaim_state reclaim = NO_RECLAIM;
2035 enum zone_watermark wmark = WMARK_NONE;
2036
2037 /* Skip while still killing a process */
2038 if (is_kill_pending()) {
2039 /* TODO: replace this quick polling with pidfd polling if kernel supports */
2040 goto no_kill;
2041 }
2042
2043 if (clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm) != 0) {
2044 ALOGE("Failed to get current time");
2045 return;
2046 }
2047
2048 if (vmstat_parse(&vs) < 0) {
2049 ALOGE("Failed to parse vmstat!");
2050 return;
2051 }
2052
2053 if (meminfo_parse(&mi) < 0) {
2054 ALOGE("Failed to parse meminfo!");
2055 return;
2056 }
2057
2058 /* Reset states after process got killed */
2059 if (killing) {
2060 killing = false;
2061 cycle_after_kill = true;
2062 /* Reset file-backed pagecache size and refault amounts after a kill */
2063 base_file_lru = vs.field.nr_inactive_file + vs.field.nr_active_file;
2064 init_ws_refault = vs.field.workingset_refault;
2065 }
2066
2067 /* Check free swap levels */
2068 if (swap_free_low_percentage) {
2069 if (!swap_low_threshold) {
2070 swap_low_threshold = mi.field.total_swap * swap_free_low_percentage / 100;
2071 }
2072 swap_is_low = mi.field.free_swap < swap_low_threshold;
2073 }
2074
2075 /* Identify reclaim state */
2076 if (vs.field.pgscan_direct > init_pgscan_direct) {
2077 init_pgscan_direct = vs.field.pgscan_direct;
2078 init_pgscan_kswapd = vs.field.pgscan_kswapd;
2079 reclaim = DIRECT_RECLAIM;
2080 } else if (vs.field.pgscan_kswapd > init_pgscan_kswapd) {
2081 init_pgscan_kswapd = vs.field.pgscan_kswapd;
2082 reclaim = KSWAPD_RECLAIM;
2083 } else {
2084 in_reclaim = false;
2085 /* Skip if system is not reclaiming */
2086 goto no_kill;
2087 }
2088
2089 if (!in_reclaim) {
2090 /* Record file-backed pagecache size when entering reclaim cycle */
2091 base_file_lru = vs.field.nr_inactive_file + vs.field.nr_active_file;
2092 init_ws_refault = vs.field.workingset_refault;
2093 thrashing_limit = thrashing_limit_pct;
2094 } else {
2095 /* Calculate what % of the file-backed pagecache refaulted so far */
2096 thrashing = (vs.field.workingset_refault - init_ws_refault) * 100 / base_file_lru;
2097 }
2098 in_reclaim = true;
2099
Suren Baghdasaryan4787ab42019-08-14 09:48:35 -07002100 /*
2101 * Refresh watermarks once per min in case user updated one of the margins.
2102 * TODO: b/140521024 replace this periodic update with an API for AMS to notify LMKD
2103 * that zone watermarks were changed by the system software.
2104 */
2105 if (watermarks.high_wmark == 0 || get_time_diff_ms(&wmark_update_tm, &curr_tm) > 60000) {
2106 struct zoneinfo zi;
2107
2108 if (zoneinfo_parse(&zi) < 0) {
2109 ALOGE("Failed to parse zoneinfo!");
2110 return;
2111 }
2112
2113 calc_zone_watermarks(&zi, &watermarks);
2114 wmark_update_tm = curr_tm;
2115 }
2116
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002117 /* Find out which watermark is breached if any */
Suren Baghdasaryan4787ab42019-08-14 09:48:35 -07002118 wmark = get_lowest_watermark(&mi, &watermarks);
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002119
2120 /*
2121 * TODO: move this logic into a separate function
2122 * Decide if killing a process is necessary and record the reason
2123 */
2124 if (cycle_after_kill && wmark < WMARK_LOW) {
2125 /*
2126 * Prevent kills not freeing enough memory which might lead to OOM kill.
2127 * This might happen when a process is consuming memory faster than reclaim can
2128 * free even after a kill. Mostly happens when running memory stress tests.
2129 */
2130 kill_reason = PRESSURE_AFTER_KILL;
2131 } else if (level == VMPRESS_LEVEL_CRITICAL && events != 0) {
2132 /*
2133 * Device is too busy reclaiming memory which might lead to ANR.
2134 * Critical level is triggered when PSI complete stall (all tasks are blocked because
2135 * of the memory congestion) breaches the configured threshold.
2136 */
2137 kill_reason = NOT_RESPONDING;
2138 } else if (swap_is_low && thrashing > thrashing_limit_pct) {
2139 /* Page cache is thrashing while swap is low */
2140 kill_reason = LOW_SWAP_AND_THRASHING;
2141 } else if (swap_is_low && wmark < WMARK_HIGH) {
2142 /* Both free memory and swap are low */
2143 kill_reason = LOW_MEM_AND_SWAP;
2144 } else if (wmark < WMARK_HIGH && thrashing > thrashing_limit) {
2145 /* Page cache is thrashing while memory is low */
2146 thrashing_limit = (thrashing_limit * (100 - thrashing_limit_decay_pct)) / 100;
2147 kill_reason = LOW_MEM_AND_THRASHING;
2148 } else if (reclaim == DIRECT_RECLAIM && thrashing > thrashing_limit) {
2149 /* Page cache is thrashing while in direct reclaim (mostly happens on lowram devices) */
2150 thrashing_limit = (thrashing_limit * (100 - thrashing_limit_decay_pct)) / 100;
2151 kill_reason = DIRECT_RECL_AND_THRASHING;
2152 }
2153
2154 /* Kill a process if necessary */
2155 if (kill_reason != NONE) {
2156 int pages_freed = find_and_kill_process(0);
2157 killing = (pages_freed > 0);
2158 meminfo_log(&mi);
2159 }
2160
2161no_kill:
2162 /*
2163 * Start polling after initial PSI event;
2164 * extend polling while device is in direct reclaim or process is being killed;
2165 * do not extend when kswapd reclaims because that might go on for a long time
2166 * without causing memory pressure
2167 */
2168 if (events || killing || reclaim == DIRECT_RECLAIM) {
2169 poll_params->update = POLLING_START;
2170 }
2171
2172 /* Decide the polling interval */
2173 if (swap_is_low || killing) {
2174 /* Fast polling during and after a kill or when swap is low */
2175 poll_params->polling_interval_ms = PSI_POLL_PERIOD_SHORT_MS;
2176 } else {
2177 /* By default use long intervals */
2178 poll_params->polling_interval_ms = PSI_POLL_PERIOD_LONG_MS;
2179 }
2180}
2181
Suren Baghdasaryanef3650f2019-07-15 14:50:49 -07002182static void mp_event_common(int data, uint32_t events, struct polling_params *poll_params) {
Todd Poynor3948f802013-07-09 19:35:14 -07002183 int ret;
2184 unsigned long long evcount;
Robert Beneac47f2992017-08-21 15:18:31 -07002185 int64_t mem_usage, memsw_usage;
Robert Benea6e8e7102017-09-13 15:20:30 -07002186 int64_t mem_pressure;
Suren Baghdasaryane82e15c2018-01-04 09:16:21 -08002187 enum vmpressure_level lvl;
Suren Baghdasaryan9926e572018-04-13 13:41:12 -07002188 union meminfo mi;
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07002189 struct zoneinfo zi;
Suren Baghdasaryan36934412018-09-05 15:46:32 -07002190 struct timespec curr_tm;
Suren Baghdasaryan314a5052018-07-24 17:13:06 -07002191 static struct timespec last_kill_tm;
2192 static unsigned long kill_skip_count = 0;
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08002193 enum vmpressure_level level = (enum vmpressure_level)data;
Suren Baghdasaryanffdc4dd2018-04-13 13:53:43 -07002194 long other_free = 0, other_file = 0;
2195 int min_score_adj;
Suren Baghdasaryanffdc4dd2018-04-13 13:53:43 -07002196 int minfree = 0;
Suren Baghdasaryan6499e5e2018-04-13 12:43:41 -07002197 static struct reread_data mem_usage_file_data = {
2198 .filename = MEMCG_MEMORY_USAGE,
2199 .fd = -1,
2200 };
2201 static struct reread_data memsw_usage_file_data = {
2202 .filename = MEMCG_MEMORYSW_USAGE,
2203 .fd = -1,
2204 };
Todd Poynor3948f802013-07-09 19:35:14 -07002205
Suren Baghdasaryan77122e52019-01-08 12:54:48 -08002206 if (debug_process_killing) {
2207 ALOGI("%s memory pressure event is triggered", level_name[level]);
2208 }
2209
2210 if (!use_psi_monitors) {
2211 /*
2212 * Check all event counters from low to critical
2213 * and upgrade to the highest priority one. By reading
2214 * eventfd we also reset the event counters.
2215 */
2216 for (lvl = VMPRESS_LEVEL_LOW; lvl < VMPRESS_LEVEL_COUNT; lvl++) {
2217 if (mpevfd[lvl] != -1 &&
2218 TEMP_FAILURE_RETRY(read(mpevfd[lvl],
2219 &evcount, sizeof(evcount))) > 0 &&
2220 evcount > 0 && lvl > level) {
2221 level = lvl;
2222 }
Suren Baghdasaryane82e15c2018-01-04 09:16:21 -08002223 }
2224 }
Todd Poynor3948f802013-07-09 19:35:14 -07002225
Suren Baghdasaryanef3650f2019-07-15 14:50:49 -07002226 /* Start polling after initial PSI event */
2227 if (use_psi_monitors && events) {
2228 /* Override polling params only if current event is more critical */
2229 if (!poll_params->poll_handler || data > poll_params->poll_handler->data) {
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002230 poll_params->polling_interval_ms = PSI_POLL_PERIOD_SHORT_MS;
Suren Baghdasaryanef3650f2019-07-15 14:50:49 -07002231 poll_params->update = POLLING_START;
2232 }
2233 }
2234
Suren Baghdasaryan36934412018-09-05 15:46:32 -07002235 if (clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm) != 0) {
2236 ALOGE("Failed to get current time");
2237 return;
2238 }
2239
Suren Baghdasaryancaa2dc52018-01-17 17:28:01 -08002240 if (kill_timeout_ms) {
Tim Murraye7853f62018-10-25 17:05:41 -07002241 // If we're within the timeout, see if there's pending reclaim work
2242 // from the last killed process. If there is (as evidenced by
2243 // /proc/<pid> continuing to exist), skip killing for now.
2244 if ((get_time_diff_ms(&last_kill_tm, &curr_tm) < kill_timeout_ms) &&
2245 (low_ram_device || is_kill_pending())) {
Suren Baghdasaryan314a5052018-07-24 17:13:06 -07002246 kill_skip_count++;
Suren Baghdasaryancaa2dc52018-01-17 17:28:01 -08002247 return;
2248 }
2249 }
2250
Suren Baghdasaryan314a5052018-07-24 17:13:06 -07002251 if (kill_skip_count > 0) {
Suren Baghdasaryanda88b242018-05-10 16:10:56 -07002252 ALOGI("%lu memory pressure events were skipped after a kill!",
Suren Baghdasaryan314a5052018-07-24 17:13:06 -07002253 kill_skip_count);
2254 kill_skip_count = 0;
Suren Baghdasaryancaa2dc52018-01-17 17:28:01 -08002255 }
2256
Suren Baghdasaryanffdc4dd2018-04-13 13:53:43 -07002257 if (meminfo_parse(&mi) < 0 || zoneinfo_parse(&zi) < 0) {
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08002258 ALOGE("Failed to get free memory!");
2259 return;
2260 }
2261
Suren Baghdasaryanffdc4dd2018-04-13 13:53:43 -07002262 if (use_minfree_levels) {
2263 int i;
2264
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07002265 other_free = mi.field.nr_free_pages - zi.totalreserve_pages;
Suren Baghdasaryanffdc4dd2018-04-13 13:53:43 -07002266 if (mi.field.nr_file_pages > (mi.field.shmem + mi.field.unevictable + mi.field.swap_cached)) {
2267 other_file = (mi.field.nr_file_pages - mi.field.shmem -
2268 mi.field.unevictable - mi.field.swap_cached);
2269 } else {
2270 other_file = 0;
2271 }
2272
2273 min_score_adj = OOM_SCORE_ADJ_MAX + 1;
2274 for (i = 0; i < lowmem_targets_size; i++) {
2275 minfree = lowmem_minfree[i];
2276 if (other_free < minfree && other_file < minfree) {
2277 min_score_adj = lowmem_adj[i];
2278 break;
2279 }
2280 }
2281
Suren Baghdasaryan20686f02018-05-18 14:42:00 -07002282 if (min_score_adj == OOM_SCORE_ADJ_MAX + 1) {
2283 if (debug_process_killing) {
2284 ALOGI("Ignore %s memory pressure event "
2285 "(free memory=%ldkB, cache=%ldkB, limit=%ldkB)",
2286 level_name[level], other_free * page_k, other_file * page_k,
2287 (long)lowmem_minfree[lowmem_targets_size - 1] * page_k);
2288 }
Suren Baghdasaryanffdc4dd2018-04-13 13:53:43 -07002289 return;
Suren Baghdasaryan20686f02018-05-18 14:42:00 -07002290 }
Suren Baghdasaryanffdc4dd2018-04-13 13:53:43 -07002291
Suren Baghdasaryanffdc4dd2018-04-13 13:53:43 -07002292 goto do_kill;
2293 }
2294
Suren Baghdasaryan9926e572018-04-13 13:41:12 -07002295 if (level == VMPRESS_LEVEL_LOW) {
2296 record_low_pressure_levels(&mi);
2297 }
2298
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08002299 if (level_oomadj[level] > OOM_SCORE_ADJ_MAX) {
2300 /* Do not monitor this pressure level */
2301 return;
2302 }
2303
Suren Baghdasaryan6499e5e2018-04-13 12:43:41 -07002304 if ((mem_usage = get_memory_usage(&mem_usage_file_data)) < 0) {
2305 goto do_kill;
2306 }
2307 if ((memsw_usage = get_memory_usage(&memsw_usage_file_data)) < 0) {
Suren Baghdasaryan96bf3a62017-12-08 12:58:52 -08002308 goto do_kill;
Robert Benea6e8e7102017-09-13 15:20:30 -07002309 }
Robert Beneac47f2992017-08-21 15:18:31 -07002310
Robert Benea6e8e7102017-09-13 15:20:30 -07002311 // Calculate percent for swappinness.
2312 mem_pressure = (mem_usage * 100) / memsw_usage;
2313
Suren Baghdasaryan96bf3a62017-12-08 12:58:52 -08002314 if (enable_pressure_upgrade && level != VMPRESS_LEVEL_CRITICAL) {
Robert Benea6e8e7102017-09-13 15:20:30 -07002315 // We are swapping too much.
2316 if (mem_pressure < upgrade_pressure) {
Suren Baghdasaryan96bf3a62017-12-08 12:58:52 -08002317 level = upgrade_level(level);
2318 if (debug_process_killing) {
2319 ALOGI("Event upgraded to %s", level_name[level]);
2320 }
Robert Beneac47f2992017-08-21 15:18:31 -07002321 }
2322 }
2323
Vic Yang360a1132018-08-07 10:18:22 -07002324 // If we still have enough swap space available, check if we want to
2325 // ignore/downgrade pressure events.
2326 if (mi.field.free_swap >=
2327 mi.field.total_swap * swap_free_low_percentage / 100) {
2328 // If the pressure is larger than downgrade_pressure lmk will not
2329 // kill any process, since enough memory is available.
2330 if (mem_pressure > downgrade_pressure) {
2331 if (debug_process_killing) {
2332 ALOGI("Ignore %s memory pressure", level_name[level]);
2333 }
2334 return;
2335 } else if (level == VMPRESS_LEVEL_CRITICAL && mem_pressure > upgrade_pressure) {
2336 if (debug_process_killing) {
2337 ALOGI("Downgrade critical memory pressure");
2338 }
2339 // Downgrade event, since enough memory available.
2340 level = downgrade_level(level);
Robert Benea6e8e7102017-09-13 15:20:30 -07002341 }
Robert Benea6e8e7102017-09-13 15:20:30 -07002342 }
2343
Suren Baghdasaryan96bf3a62017-12-08 12:58:52 -08002344do_kill:
Suren Baghdasaryanff61afb2018-04-13 11:45:38 -07002345 if (low_ram_device) {
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08002346 /* For Go devices kill only one task */
Suren Baghdasaryanf81b5f42018-10-26 11:32:15 -07002347 if (find_and_kill_process(level_oomadj[level]) == 0) {
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08002348 if (debug_process_killing) {
2349 ALOGI("Nothing to kill");
2350 }
Suren Baghdasaryan282ad1a2018-07-26 16:34:27 -07002351 } else {
2352 meminfo_log(&mi);
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08002353 }
2354 } else {
Suren Baghdasaryanffdc4dd2018-04-13 13:53:43 -07002355 int pages_freed;
Suren Baghdasaryan36934412018-09-05 15:46:32 -07002356 static struct timespec last_report_tm;
2357 static unsigned long report_skip_count = 0;
Suren Baghdasaryanffdc4dd2018-04-13 13:53:43 -07002358
2359 if (!use_minfree_levels) {
Suren Baghdasaryanffdc4dd2018-04-13 13:53:43 -07002360 /* Free up enough memory to downgrate the memory pressure to low level */
Suren Baghdasaryanf81b5f42018-10-26 11:32:15 -07002361 if (mi.field.nr_free_pages >= low_pressure_mem.max_nr_free_pages) {
Suren Baghdasaryanffdc4dd2018-04-13 13:53:43 -07002362 if (debug_process_killing) {
2363 ALOGI("Ignoring pressure since more memory is "
2364 "available (%" PRId64 ") than watermark (%" PRId64 ")",
2365 mi.field.nr_free_pages, low_pressure_mem.max_nr_free_pages);
2366 }
2367 return;
2368 }
2369 min_score_adj = level_oomadj[level];
Suren Baghdasaryan65f54a22018-01-17 17:17:44 -08002370 }
2371
Suren Baghdasaryanf81b5f42018-10-26 11:32:15 -07002372 pages_freed = find_and_kill_process(min_score_adj);
Suren Baghdasaryanda88b242018-05-10 16:10:56 -07002373
Suren Baghdasaryan36934412018-09-05 15:46:32 -07002374 if (pages_freed == 0) {
2375 /* Rate limit kill reports when nothing was reclaimed */
2376 if (get_time_diff_ms(&last_report_tm, &curr_tm) < FAIL_REPORT_RLIMIT_MS) {
2377 report_skip_count++;
Suren Baghdasaryan314a5052018-07-24 17:13:06 -07002378 return;
2379 }
Tim Murraye7853f62018-10-25 17:05:41 -07002380 } else {
2381 /* If we killed anything, update the last killed timestamp. */
2382 last_kill_tm = curr_tm;
Robert Beneacaeaa652017-08-11 16:03:20 -07002383 }
Suren Baghdasaryan36934412018-09-05 15:46:32 -07002384
2385 /* Log meminfo whenever we kill or when report rate limit allows */
2386 meminfo_log(&mi);
Suren Baghdasaryan36934412018-09-05 15:46:32 -07002387
2388 if (use_minfree_levels) {
Suren Baghdasaryanf81b5f42018-10-26 11:32:15 -07002389 ALOGI("Reclaimed %ldkB, cache(%ldkB) and "
Suren Baghdasaryan36934412018-09-05 15:46:32 -07002390 "free(%" PRId64 "kB)-reserved(%" PRId64 "kB) below min(%ldkB) for oom_adj %d",
Suren Baghdasaryanf81b5f42018-10-26 11:32:15 -07002391 pages_freed * page_k,
Suren Baghdasaryan36934412018-09-05 15:46:32 -07002392 other_file * page_k, mi.field.nr_free_pages * page_k,
Suren Baghdasaryan94ce3dd2019-07-15 13:54:20 -07002393 zi.totalreserve_pages * page_k,
Suren Baghdasaryan36934412018-09-05 15:46:32 -07002394 minfree * page_k, min_score_adj);
2395 } else {
Suren Baghdasaryanf81b5f42018-10-26 11:32:15 -07002396 ALOGI("Reclaimed %ldkB at oom_adj %d",
2397 pages_freed * page_k, min_score_adj);
Suren Baghdasaryan36934412018-09-05 15:46:32 -07002398 }
2399
2400 if (report_skip_count > 0) {
2401 ALOGI("Suppressed %lu failed kill reports", report_skip_count);
2402 report_skip_count = 0;
2403 }
2404
2405 last_report_tm = curr_tm;
Colin Crossf8857cc2014-07-11 17:16:56 -07002406 }
Todd Poynor3948f802013-07-09 19:35:14 -07002407}
2408
Suren Baghdasaryan77122e52019-01-08 12:54:48 -08002409static bool init_mp_psi(enum vmpressure_level level) {
2410 int fd = init_psi_monitor(psi_thresholds[level].stall_type,
2411 psi_thresholds[level].threshold_ms * US_PER_MS,
2412 PSI_WINDOW_SIZE_MS * US_PER_MS);
2413
2414 if (fd < 0) {
2415 return false;
2416 }
2417
2418 vmpressure_hinfo[level].handler = mp_event_common;
2419 vmpressure_hinfo[level].data = level;
2420 if (register_psi_monitor(epollfd, fd, &vmpressure_hinfo[level]) < 0) {
2421 destroy_psi_monitor(fd);
2422 return false;
2423 }
2424 maxevents++;
2425 mpevfd[level] = fd;
2426
2427 return true;
2428}
2429
2430static void destroy_mp_psi(enum vmpressure_level level) {
2431 int fd = mpevfd[level];
2432
2433 if (unregister_psi_monitor(epollfd, fd) < 0) {
2434 ALOGE("Failed to unregister psi monitor for %s memory pressure; errno=%d",
2435 level_name[level], errno);
2436 }
2437 destroy_psi_monitor(fd);
2438 mpevfd[level] = -1;
2439}
2440
2441static bool init_psi_monitors() {
2442 if (!init_mp_psi(VMPRESS_LEVEL_LOW)) {
2443 return false;
2444 }
2445 if (!init_mp_psi(VMPRESS_LEVEL_MEDIUM)) {
2446 destroy_mp_psi(VMPRESS_LEVEL_LOW);
2447 return false;
2448 }
2449 if (!init_mp_psi(VMPRESS_LEVEL_CRITICAL)) {
2450 destroy_mp_psi(VMPRESS_LEVEL_MEDIUM);
2451 destroy_mp_psi(VMPRESS_LEVEL_LOW);
2452 return false;
2453 }
2454 return true;
2455}
2456
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08002457static bool init_mp_common(enum vmpressure_level level) {
Todd Poynor3948f802013-07-09 19:35:14 -07002458 int mpfd;
2459 int evfd;
2460 int evctlfd;
2461 char buf[256];
2462 struct epoll_event epev;
2463 int ret;
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08002464 int level_idx = (int)level;
2465 const char *levelstr = level_name[level_idx];
Suren Baghdasaryan96bf3a62017-12-08 12:58:52 -08002466
Mark Salyzyn64d97d82018-04-09 09:50:32 -07002467 /* gid containing AID_SYSTEM required */
Nick Kralevichc68c8862015-12-18 20:52:37 -08002468 mpfd = open(MEMCG_SYSFS_PATH "memory.pressure_level", O_RDONLY | O_CLOEXEC);
Todd Poynor3948f802013-07-09 19:35:14 -07002469 if (mpfd < 0) {
2470 ALOGI("No kernel memory.pressure_level support (errno=%d)", errno);
2471 goto err_open_mpfd;
2472 }
2473
Nick Kralevichc68c8862015-12-18 20:52:37 -08002474 evctlfd = open(MEMCG_SYSFS_PATH "cgroup.event_control", O_WRONLY | O_CLOEXEC);
Todd Poynor3948f802013-07-09 19:35:14 -07002475 if (evctlfd < 0) {
2476 ALOGI("No kernel memory cgroup event control (errno=%d)", errno);
2477 goto err_open_evctlfd;
2478 }
2479
Nick Kralevichc68c8862015-12-18 20:52:37 -08002480 evfd = eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC);
Todd Poynor3948f802013-07-09 19:35:14 -07002481 if (evfd < 0) {
2482 ALOGE("eventfd failed for level %s; errno=%d", levelstr, errno);
2483 goto err_eventfd;
2484 }
2485
2486 ret = snprintf(buf, sizeof(buf), "%d %d %s", evfd, mpfd, levelstr);
2487 if (ret >= (ssize_t)sizeof(buf)) {
2488 ALOGE("cgroup.event_control line overflow for level %s", levelstr);
2489 goto err;
2490 }
2491
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08002492 ret = TEMP_FAILURE_RETRY(write(evctlfd, buf, strlen(buf) + 1));
Todd Poynor3948f802013-07-09 19:35:14 -07002493 if (ret == -1) {
2494 ALOGE("cgroup.event_control write failed for level %s; errno=%d",
2495 levelstr, errno);
2496 goto err;
2497 }
2498
2499 epev.events = EPOLLIN;
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08002500 /* use data to store event level */
2501 vmpressure_hinfo[level_idx].data = level_idx;
2502 vmpressure_hinfo[level_idx].handler = mp_event_common;
2503 epev.data.ptr = (void *)&vmpressure_hinfo[level_idx];
Todd Poynor3948f802013-07-09 19:35:14 -07002504 ret = epoll_ctl(epollfd, EPOLL_CTL_ADD, evfd, &epev);
2505 if (ret == -1) {
2506 ALOGE("epoll_ctl for level %s failed; errno=%d", levelstr, errno);
2507 goto err;
2508 }
2509 maxevents++;
Suren Baghdasaryan96bf3a62017-12-08 12:58:52 -08002510 mpevfd[level] = evfd;
Suren Baghdasaryan1bd2fc42018-01-04 08:54:53 -08002511 close(evctlfd);
Suren Baghdasaryan96bf3a62017-12-08 12:58:52 -08002512 return true;
Todd Poynor3948f802013-07-09 19:35:14 -07002513
2514err:
2515 close(evfd);
2516err_eventfd:
2517 close(evctlfd);
2518err_open_evctlfd:
2519 close(mpfd);
2520err_open_mpfd:
Suren Baghdasaryan96bf3a62017-12-08 12:58:52 -08002521 return false;
Robert Benea673e2762017-06-01 16:32:31 -07002522}
2523
Jim Blackler3947c932019-04-26 11:18:29 +01002524#ifdef LMKD_LOG_STATS
2525static int kernel_poll_fd = -1;
Jim Blackler3947c932019-04-26 11:18:29 +01002526static void poll_kernel() {
2527 if (kernel_poll_fd == -1) {
2528 // not waiting
2529 return;
2530 }
2531
2532 while (1) {
2533 char rd_buf[256];
2534 int bytes_read =
2535 TEMP_FAILURE_RETRY(pread(kernel_poll_fd, (void*)rd_buf, sizeof(rd_buf), 0));
2536 if (bytes_read <= 0) break;
2537 rd_buf[bytes_read] = '\0';
2538
2539 int64_t pid;
2540 int64_t uid;
2541 int64_t group_leader_pid;
2542 int64_t min_flt;
2543 int64_t maj_flt;
2544 int64_t rss_in_pages;
2545 int16_t oom_score_adj;
2546 int16_t min_score_adj;
2547 int64_t starttime;
2548 char* taskname = 0;
2549 int fields_read = sscanf(rd_buf,
2550 "%" SCNd64 " %" SCNd64 " %" SCNd64 " %" SCNd64 " %" SCNd64
2551 " %" SCNd64 " %" SCNd16 " %" SCNd16 " %" SCNd64 "\n%m[^\n]",
2552 &pid, &uid, &group_leader_pid, &min_flt, &maj_flt, &rss_in_pages,
2553 &oom_score_adj, &min_score_adj, &starttime, &taskname);
2554
2555 /* only the death of the group leader process is logged */
2556 if (fields_read == 10 && group_leader_pid == pid) {
2557 int64_t process_start_time_ns = starttime * (NS_PER_SEC / sysconf(_SC_CLK_TCK));
Jim Blacklerd2da8142019-09-10 15:30:05 +01002558 stats_write_lmk_kill_occurred_pid(log_ctx, LMK_KILL_OCCURRED, uid, pid, oom_score_adj,
2559 min_flt, maj_flt, rss_in_pages * PAGE_SIZE, 0, 0,
2560 process_start_time_ns, min_score_adj);
Jim Blackler3947c932019-04-26 11:18:29 +01002561 }
2562
2563 free(taskname);
2564 }
2565}
2566
2567static struct event_handler_info kernel_poll_hinfo = {0, poll_kernel};
2568
2569static void init_poll_kernel() {
2570 struct epoll_event epev;
2571 kernel_poll_fd =
2572 TEMP_FAILURE_RETRY(open("/proc/lowmemorykiller", O_RDONLY | O_NONBLOCK | O_CLOEXEC));
2573
2574 if (kernel_poll_fd < 0) {
2575 ALOGE("kernel lmk event file could not be opened; errno=%d", kernel_poll_fd);
2576 return;
2577 }
2578
2579 epev.events = EPOLLIN;
2580 epev.data.ptr = (void*)&kernel_poll_hinfo;
2581 if (epoll_ctl(epollfd, EPOLL_CTL_ADD, kernel_poll_fd, &epev) != 0) {
2582 ALOGE("epoll_ctl for lmk events failed; errno=%d", errno);
2583 close(kernel_poll_fd);
2584 kernel_poll_fd = -1;
2585 } else {
2586 maxevents++;
2587 }
2588}
2589#endif
2590
Todd Poynor3948f802013-07-09 19:35:14 -07002591static int init(void) {
Suren Baghdasaryana77b3272019-07-15 13:35:04 -07002592 struct reread_data file_data = {
2593 .filename = ZONEINFO_PATH,
2594 .fd = -1,
2595 };
Todd Poynor3948f802013-07-09 19:35:14 -07002596 struct epoll_event epev;
2597 int i;
2598 int ret;
2599
2600 page_k = sysconf(_SC_PAGESIZE);
2601 if (page_k == -1)
2602 page_k = PAGE_SIZE;
2603 page_k /= 1024;
2604
2605 epollfd = epoll_create(MAX_EPOLL_EVENTS);
2606 if (epollfd == -1) {
2607 ALOGE("epoll_create failed (errno=%d)", errno);
2608 return -1;
2609 }
2610
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08002611 // mark data connections as not connected
2612 for (int i = 0; i < MAX_DATA_CONN; i++) {
2613 data_sock[i].sock = -1;
2614 }
2615
2616 ctrl_sock.sock = android_get_control_socket("lmkd");
2617 if (ctrl_sock.sock < 0) {
Todd Poynor3948f802013-07-09 19:35:14 -07002618 ALOGE("get lmkd control socket failed");
2619 return -1;
2620 }
2621
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08002622 ret = listen(ctrl_sock.sock, MAX_DATA_CONN);
Todd Poynor3948f802013-07-09 19:35:14 -07002623 if (ret < 0) {
2624 ALOGE("lmkd control socket listen failed (errno=%d)", errno);
2625 return -1;
2626 }
2627
2628 epev.events = EPOLLIN;
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08002629 ctrl_sock.handler_info.handler = ctrl_connect_handler;
2630 epev.data.ptr = (void *)&(ctrl_sock.handler_info);
2631 if (epoll_ctl(epollfd, EPOLL_CTL_ADD, ctrl_sock.sock, &epev) == -1) {
Todd Poynor3948f802013-07-09 19:35:14 -07002632 ALOGE("epoll_ctl for lmkd control socket failed (errno=%d)", errno);
2633 return -1;
2634 }
2635 maxevents++;
2636
Robert Benea164baeb2017-09-11 16:53:28 -07002637 has_inkernel_module = !access(INKERNEL_MINFREE_PATH, W_OK);
Suren Baghdasaryan979591b2018-01-18 17:27:30 -08002638 use_inkernel_interface = has_inkernel_module;
Todd Poynor3948f802013-07-09 19:35:14 -07002639
2640 if (use_inkernel_interface) {
2641 ALOGI("Using in-kernel low memory killer interface");
Jim Blackler3947c932019-04-26 11:18:29 +01002642#ifdef LMKD_LOG_STATS
2643 if (enable_stats_log) {
2644 init_poll_kernel();
2645 }
2646#endif
Todd Poynor3948f802013-07-09 19:35:14 -07002647 } else {
Suren Baghdasaryan77122e52019-01-08 12:54:48 -08002648 /* Try to use psi monitor first if kernel has it */
2649 use_psi_monitors = property_get_bool("ro.lmk.use_psi", true) &&
2650 init_psi_monitors();
2651 /* Fall back to vmpressure */
2652 if (!use_psi_monitors &&
2653 (!init_mp_common(VMPRESS_LEVEL_LOW) ||
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08002654 !init_mp_common(VMPRESS_LEVEL_MEDIUM) ||
Suren Baghdasaryan77122e52019-01-08 12:54:48 -08002655 !init_mp_common(VMPRESS_LEVEL_CRITICAL))) {
Todd Poynor3948f802013-07-09 19:35:14 -07002656 ALOGE("Kernel does not support memory pressure events or in-kernel low memory killer");
Suren Baghdasaryan96bf3a62017-12-08 12:58:52 -08002657 return -1;
2658 }
Suren Baghdasaryan77122e52019-01-08 12:54:48 -08002659 if (use_psi_monitors) {
2660 ALOGI("Using psi monitors for memory pressure detection");
2661 } else {
2662 ALOGI("Using vmpressure for memory pressure detection");
2663 }
Todd Poynor3948f802013-07-09 19:35:14 -07002664 }
2665
Chong Zhang0a4acdf2015-10-14 16:19:53 -07002666 for (i = 0; i <= ADJTOSLOT(OOM_SCORE_ADJ_MAX); i++) {
Todd Poynor3948f802013-07-09 19:35:14 -07002667 procadjslot_list[i].next = &procadjslot_list[i];
2668 procadjslot_list[i].prev = &procadjslot_list[i];
2669 }
2670
Suren Baghdasaryand4a29902018-10-12 11:07:40 -07002671 memset(killcnt_idx, KILLCNT_INVALID_IDX, sizeof(killcnt_idx));
2672
Suren Baghdasaryana77b3272019-07-15 13:35:04 -07002673 /*
2674 * Read zoneinfo as the biggest file we read to create and size the initial
2675 * read buffer and avoid memory re-allocations during memory pressure
2676 */
2677 if (reread_file(&file_data) == NULL) {
2678 ALOGE("Failed to read %s: %s", file_data.filename, strerror(errno));
2679 }
2680
Todd Poynor3948f802013-07-09 19:35:14 -07002681 return 0;
2682}
2683
2684static void mainloop(void) {
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08002685 struct event_handler_info* handler_info;
Suren Baghdasaryanef3650f2019-07-15 14:50:49 -07002686 struct polling_params poll_params;
2687 struct timespec curr_tm;
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08002688 struct epoll_event *evt;
Suren Baghdasaryan77122e52019-01-08 12:54:48 -08002689 long delay = -1;
Suren Baghdasaryanef3650f2019-07-15 14:50:49 -07002690
2691 poll_params.poll_handler = NULL;
2692 poll_params.update = POLLING_DO_NOT_CHANGE;
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08002693
Todd Poynor3948f802013-07-09 19:35:14 -07002694 while (1) {
2695 struct epoll_event events[maxevents];
2696 int nevents;
2697 int i;
2698
Suren Baghdasaryanef3650f2019-07-15 14:50:49 -07002699 if (poll_params.poll_handler) {
Suren Baghdasaryan77122e52019-01-08 12:54:48 -08002700 /* Calculate next timeout */
2701 clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm);
Suren Baghdasaryanef3650f2019-07-15 14:50:49 -07002702 delay = get_time_diff_ms(&poll_params.last_poll_tm, &curr_tm);
2703 delay = (delay < poll_params.polling_interval_ms) ?
2704 poll_params.polling_interval_ms - delay : poll_params.polling_interval_ms;
Suren Baghdasaryan77122e52019-01-08 12:54:48 -08002705
2706 /* Wait for events until the next polling timeout */
2707 nevents = epoll_wait(epollfd, events, maxevents, delay);
2708
2709 clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm);
Suren Baghdasaryanef3650f2019-07-15 14:50:49 -07002710 if (get_time_diff_ms(&poll_params.last_poll_tm, &curr_tm) >=
2711 poll_params.polling_interval_ms) {
2712 /* Set input params for the call */
2713 poll_params.poll_handler->handler(poll_params.poll_handler->data, 0, &poll_params);
2714 poll_params.last_poll_tm = curr_tm;
2715
2716 if (poll_params.update != POLLING_DO_NOT_CHANGE) {
2717 switch (poll_params.update) {
2718 case POLLING_START:
2719 poll_params.poll_start_tm = curr_tm;
2720 break;
2721 case POLLING_STOP:
2722 poll_params.poll_handler = NULL;
2723 break;
2724 default:
2725 break;
2726 }
2727 poll_params.update = POLLING_DO_NOT_CHANGE;
2728 } else {
2729 if (get_time_diff_ms(&poll_params.poll_start_tm, &curr_tm) >
2730 PSI_WINDOW_SIZE_MS) {
2731 /* Polled for the duration of PSI window, time to stop */
2732 poll_params.poll_handler = NULL;
2733 }
2734 }
Suren Baghdasaryan77122e52019-01-08 12:54:48 -08002735 }
2736 } else {
2737 /* Wait for events with no timeout */
2738 nevents = epoll_wait(epollfd, events, maxevents, -1);
2739 }
Todd Poynor3948f802013-07-09 19:35:14 -07002740
2741 if (nevents == -1) {
2742 if (errno == EINTR)
2743 continue;
2744 ALOGE("epoll_wait failed (errno=%d)", errno);
2745 continue;
2746 }
2747
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08002748 /*
2749 * First pass to see if any data socket connections were dropped.
2750 * Dropped connection should be handled before any other events
2751 * to deallocate data connection and correctly handle cases when
2752 * connection gets dropped and reestablished in the same epoll cycle.
2753 * In such cases it's essential to handle connection closures first.
2754 */
2755 for (i = 0, evt = &events[0]; i < nevents; ++i, evt++) {
2756 if ((evt->events & EPOLLHUP) && evt->data.ptr) {
2757 ALOGI("lmkd data connection dropped");
2758 handler_info = (struct event_handler_info*)evt->data.ptr;
2759 ctrl_data_close(handler_info->data);
2760 }
2761 }
2762
2763 /* Second pass to handle all other events */
2764 for (i = 0, evt = &events[0]; i < nevents; ++i, evt++) {
Suren Baghdasaryanef3650f2019-07-15 14:50:49 -07002765 if (evt->events & EPOLLERR) {
Todd Poynor3948f802013-07-09 19:35:14 -07002766 ALOGD("EPOLLERR on event #%d", i);
Suren Baghdasaryanef3650f2019-07-15 14:50:49 -07002767 }
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08002768 if (evt->events & EPOLLHUP) {
2769 /* This case was handled in the first pass */
2770 continue;
2771 }
2772 if (evt->data.ptr) {
2773 handler_info = (struct event_handler_info*)evt->data.ptr;
Suren Baghdasaryanef3650f2019-07-15 14:50:49 -07002774 /* Set input params for the call */
2775 handler_info->handler(handler_info->data, evt->events, &poll_params);
Suren Baghdasaryan77122e52019-01-08 12:54:48 -08002776
Suren Baghdasaryanef3650f2019-07-15 14:50:49 -07002777 if (poll_params.update != POLLING_DO_NOT_CHANGE) {
2778 switch (poll_params.update) {
2779 case POLLING_START:
2780 /*
2781 * Poll for the duration of PSI_WINDOW_SIZE_MS after the
2782 * initial PSI event because psi events are rate-limited
2783 * at one per sec.
2784 */
2785 clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm);
2786 poll_params.poll_start_tm = poll_params.last_poll_tm = curr_tm;
2787 poll_params.poll_handler = handler_info;
2788 break;
2789 case POLLING_STOP:
2790 poll_params.poll_handler = NULL;
2791 break;
2792 default:
2793 break;
2794 }
2795 poll_params.update = POLLING_DO_NOT_CHANGE;
Suren Baghdasaryan77122e52019-01-08 12:54:48 -08002796 }
Suren Baghdasaryan3cfb2c82018-01-26 12:51:19 -08002797 }
Todd Poynor3948f802013-07-09 19:35:14 -07002798 }
2799 }
2800}
2801
Mark Salyzyne6ed68b2014-04-30 13:36:35 -07002802int main(int argc __unused, char **argv __unused) {
Colin Cross1a0d9be2014-07-14 14:31:15 -07002803 struct sched_param param = {
2804 .sched_priority = 1,
2805 };
2806
Suren Baghdasaryan96bf3a62017-12-08 12:58:52 -08002807 /* By default disable low level vmpressure events */
2808 level_oomadj[VMPRESS_LEVEL_LOW] =
2809 property_get_int32("ro.lmk.low", OOM_SCORE_ADJ_MAX + 1);
2810 level_oomadj[VMPRESS_LEVEL_MEDIUM] =
2811 property_get_int32("ro.lmk.medium", 800);
2812 level_oomadj[VMPRESS_LEVEL_CRITICAL] =
2813 property_get_int32("ro.lmk.critical", 0);
Robert Beneacaeaa652017-08-11 16:03:20 -07002814 debug_process_killing = property_get_bool("ro.lmk.debug", false);
Suren Baghdasaryanad2fd912017-12-08 13:08:41 -08002815
2816 /* By default disable upgrade/downgrade logic */
2817 enable_pressure_upgrade =
2818 property_get_bool("ro.lmk.critical_upgrade", false);
2819 upgrade_pressure =
2820 (int64_t)property_get_int32("ro.lmk.upgrade_pressure", 100);
2821 downgrade_pressure =
2822 (int64_t)property_get_int32("ro.lmk.downgrade_pressure", 100);
Suren Baghdasaryan662492a2017-12-08 13:17:06 -08002823 kill_heaviest_task =
Suren Baghdasaryan818b59b2018-04-13 11:49:54 -07002824 property_get_bool("ro.lmk.kill_heaviest_task", false);
Suren Baghdasaryanff61afb2018-04-13 11:45:38 -07002825 low_ram_device = property_get_bool("ro.config.low_ram", false);
Suren Baghdasaryancaa2dc52018-01-17 17:28:01 -08002826 kill_timeout_ms =
2827 (unsigned long)property_get_int32("ro.lmk.kill_timeout_ms", 0);
Suren Baghdasaryanffdc4dd2018-04-13 13:53:43 -07002828 use_minfree_levels =
2829 property_get_bool("ro.lmk.use_minfree_levels", false);
Suren Baghdasaryance13cb52018-06-19 18:38:12 -07002830 per_app_memcg =
2831 property_get_bool("ro.config.per_app_memcg", low_ram_device);
Suren Baghdasaryan561cfd92019-07-15 15:35:44 -07002832 swap_free_low_percentage = clamp(0, 100, property_get_int32("ro.lmk.swap_free_low_percentage",
2833 low_ram_device ? DEF_LOW_SWAP_LOWRAM : DEF_LOW_SWAP));
2834 thrashing_limit_pct = max(0, property_get_int32("ro.lmk.thrashing_limit",
2835 low_ram_device ? DEF_THRASHING_LOWRAM : DEF_THRASHING));
2836 thrashing_limit_decay_pct = clamp(0, 100, property_get_int32("ro.lmk.thrashing_limit_decay",
2837 low_ram_device ? DEF_THRASHING_DECAY_LOWRAM : DEF_THRASHING_DECAY));
Robert Benea58891d52017-07-31 17:15:20 -07002838
Suren Baghdasaryan282ad1a2018-07-26 16:34:27 -07002839 ctx = create_android_logger(MEMINFO_LOG_TAG);
2840
Rajeev Kumar70450032018-01-31 17:54:56 -08002841#ifdef LMKD_LOG_STATS
Rajeev Kumar1c669f72018-03-09 15:20:56 -08002842 statslog_init(&log_ctx, &enable_stats_log);
Rajeev Kumar70450032018-01-31 17:54:56 -08002843#endif
2844
Mark Salyzyn721d7c72018-03-21 12:24:58 -07002845 if (!init()) {
2846 if (!use_inkernel_interface) {
2847 /*
2848 * MCL_ONFAULT pins pages as they fault instead of loading
2849 * everything immediately all at once. (Which would be bad,
2850 * because as of this writing, we have a lot of mapped pages we
2851 * never use.) Old kernels will see MCL_ONFAULT and fail with
2852 * EINVAL; we ignore this failure.
2853 *
2854 * N.B. read the man page for mlockall. MCL_CURRENT | MCL_ONFAULT
2855 * pins ⊆ MCL_CURRENT, converging to just MCL_CURRENT as we fault
2856 * in pages.
2857 */
Mark Salyzyn64d97d82018-04-09 09:50:32 -07002858 /* CAP_IPC_LOCK required */
Mark Salyzyn721d7c72018-03-21 12:24:58 -07002859 if (mlockall(MCL_CURRENT | MCL_FUTURE | MCL_ONFAULT) && (errno != EINVAL)) {
2860 ALOGW("mlockall failed %s", strerror(errno));
2861 }
Daniel Colascione4dd5d002018-01-03 12:01:02 -08002862
Mark Salyzyn64d97d82018-04-09 09:50:32 -07002863 /* CAP_NICE required */
2864 if (sched_setscheduler(0, SCHED_FIFO, &param)) {
2865 ALOGW("set SCHED_FIFO failed %s", strerror(errno));
2866 }
Mark Salyzyn721d7c72018-03-21 12:24:58 -07002867 }
2868
Todd Poynor3948f802013-07-09 19:35:14 -07002869 mainloop();
Mark Salyzyn721d7c72018-03-21 12:24:58 -07002870 }
Todd Poynor3948f802013-07-09 19:35:14 -07002871
Rajeev Kumar70450032018-01-31 17:54:56 -08002872#ifdef LMKD_LOG_STATS
Rajeev Kumar1c669f72018-03-09 15:20:56 -08002873 statslog_destroy(&log_ctx);
Rajeev Kumar70450032018-01-31 17:54:56 -08002874#endif
2875
Suren Baghdasaryan282ad1a2018-07-26 16:34:27 -07002876 android_log_destroy(&ctx);
2877
Todd Poynor3948f802013-07-09 19:35:14 -07002878 ALOGI("exiting");
2879 return 0;
2880}