blob: 6b40d3ffb55323f951862c68a672d15af9247fd4 [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
Mark Salyzyne6ed68b2014-04-30 13:36:35 -070019#include <arpa/inet.h>
Todd Poynor3948f802013-07-09 19:35:14 -070020#include <errno.h>
Robert Beneac47f2992017-08-21 15:18:31 -070021#include <inttypes.h>
Mark Salyzyncfd5b082016-10-17 14:28:00 -070022#include <sched.h>
Todd Poynor3948f802013-07-09 19:35:14 -070023#include <signal.h>
Todd Poynor3948f802013-07-09 19:35:14 -070024#include <stdlib.h>
25#include <string.h>
Mark Salyzyne6ed68b2014-04-30 13:36:35 -070026#include <sys/cdefs.h>
Todd Poynor3948f802013-07-09 19:35:14 -070027#include <sys/epoll.h>
28#include <sys/eventfd.h>
Colin Crossb28ff912014-07-11 17:15:44 -070029#include <sys/mman.h>
Todd Poynor3948f802013-07-09 19:35:14 -070030#include <sys/socket.h>
31#include <sys/types.h>
Mark Salyzyne6ed68b2014-04-30 13:36:35 -070032#include <unistd.h>
33
Robert Benea58891d52017-07-31 17:15:20 -070034#include <cutils/properties.h>
Todd Poynor3948f802013-07-09 19:35:14 -070035#include <cutils/sockets.h>
Mark Salyzyn30f991f2017-01-10 13:19:54 -080036#include <log/log.h>
Mark Salyzyne6ed68b2014-04-30 13:36:35 -070037
Suren Baghdasaryane1217c02018-01-04 10:43:58 -080038/*
39 * Define LMKD_TRACE_KILLS to record lmkd kills in kernel traces
40 * to profile and correlate with OOM kills
41 */
42#ifdef LMKD_TRACE_KILLS
43
44#define ATRACE_TAG ATRACE_TAG_ALWAYS
45#include <cutils/trace.h>
46
47#define TRACE_KILL_START(pid) ATRACE_INT(__FUNCTION__, pid);
48#define TRACE_KILL_END() ATRACE_INT(__FUNCTION__, 0);
49
50#else /* LMKD_TRACE_KILLS */
51
52#define TRACE_KILL_START(pid)
53#define TRACE_KILL_END()
54
55#endif /* LMKD_TRACE_KILLS */
56
Mark Salyzyne6ed68b2014-04-30 13:36:35 -070057#ifndef __unused
58#define __unused __attribute__((__unused__))
59#endif
Todd Poynor3948f802013-07-09 19:35:14 -070060
61#define MEMCG_SYSFS_PATH "/dev/memcg/"
Robert Beneac47f2992017-08-21 15:18:31 -070062#define MEMCG_MEMORY_USAGE "/dev/memcg/memory.usage_in_bytes"
63#define MEMCG_MEMORYSW_USAGE "/dev/memcg/memory.memsw.usage_in_bytes"
Todd Poynor3948f802013-07-09 19:35:14 -070064#define ZONEINFO_PATH "/proc/zoneinfo"
65#define LINE_MAX 128
66
67#define INKERNEL_MINFREE_PATH "/sys/module/lowmemorykiller/parameters/minfree"
68#define INKERNEL_ADJ_PATH "/sys/module/lowmemorykiller/parameters/adj"
69
70#define ARRAY_SIZE(x) (sizeof(x) / sizeof(*(x)))
Robert Benea673e2762017-06-01 16:32:31 -070071#define EIGHT_MEGA (1 << 23)
Todd Poynor3948f802013-07-09 19:35:14 -070072
73enum lmk_cmd {
74 LMK_TARGET,
75 LMK_PROCPRIO,
76 LMK_PROCREMOVE,
77};
78
79#define MAX_TARGETS 6
80/*
81 * longest is LMK_TARGET followed by MAX_TARGETS each minfree and minkillprio
82 * values
83 */
84#define CTRL_PACKET_MAX (sizeof(int) * (MAX_TARGETS * 2 + 1))
85
86/* default to old in-kernel interface if no memory pressure events */
87static int use_inkernel_interface = 1;
Robert Benea164baeb2017-09-11 16:53:28 -070088static bool has_inkernel_module;
Todd Poynor3948f802013-07-09 19:35:14 -070089
Suren Baghdasaryancd7ad2f2017-12-08 12:58:52 -080090/* memory pressure levels */
91enum vmpressure_level {
92 VMPRESS_LEVEL_LOW = 0,
93 VMPRESS_LEVEL_MEDIUM,
94 VMPRESS_LEVEL_CRITICAL,
95 VMPRESS_LEVEL_COUNT
96};
Todd Poynor3948f802013-07-09 19:35:14 -070097
Suren Baghdasaryancd7ad2f2017-12-08 12:58:52 -080098static const char *level_name[] = {
99 "low",
100 "medium",
101 "critical"
102};
103
104static int level_oomadj[VMPRESS_LEVEL_COUNT];
Suren Baghdasaryan1a2589e2018-01-04 09:16:21 -0800105static int mpevfd[VMPRESS_LEVEL_COUNT] = { -1, -1, -1 };
Robert Beneac47f2992017-08-21 15:18:31 -0700106static bool debug_process_killing;
107static bool enable_pressure_upgrade;
108static int64_t upgrade_pressure;
Robert Benea6e8e7102017-09-13 15:20:30 -0700109static int64_t downgrade_pressure;
Robert Benea164baeb2017-09-11 16:53:28 -0700110static bool is_go_device;
Suren Baghdasaryanb93764d2017-12-08 13:17:06 -0800111static bool kill_heaviest_task;
Robert Benea58891d52017-07-31 17:15:20 -0700112
Todd Poynor3948f802013-07-09 19:35:14 -0700113/* control socket listen and data */
114static int ctrl_lfd;
115static int ctrl_dfd = -1;
116static int ctrl_dfd_reopened; /* did we reopen ctrl conn on this loop? */
117
Suren Baghdasaryancd7ad2f2017-12-08 12:58:52 -0800118/* 3 memory pressure levels, 1 ctrl listen socket, 1 ctrl data socket */
119#define MAX_EPOLL_EVENTS 5
Todd Poynor3948f802013-07-09 19:35:14 -0700120static int epollfd;
121static int maxevents;
122
Chong Zhang0a4acdf2015-10-14 16:19:53 -0700123/* OOM score values used by both kernel and framework */
Todd Poynor16b60992013-09-16 19:26:47 -0700124#define OOM_SCORE_ADJ_MIN (-1000)
125#define OOM_SCORE_ADJ_MAX 1000
126
Todd Poynor3948f802013-07-09 19:35:14 -0700127static int lowmem_adj[MAX_TARGETS];
128static int lowmem_minfree[MAX_TARGETS];
129static int lowmem_targets_size;
130
131struct sysmeminfo {
132 int nr_free_pages;
133 int nr_file_pages;
134 int nr_shmem;
135 int totalreserve_pages;
136};
137
138struct adjslot_list {
139 struct adjslot_list *next;
140 struct adjslot_list *prev;
141};
142
143struct proc {
144 struct adjslot_list asl;
145 int pid;
Colin Crossfbb78c62014-06-13 14:52:43 -0700146 uid_t uid;
Todd Poynor3948f802013-07-09 19:35:14 -0700147 int oomadj;
148 struct proc *pidhash_next;
149};
150
151#define PIDHASH_SZ 1024
152static struct proc *pidhash[PIDHASH_SZ];
153#define pid_hashfn(x) ((((x) >> 8) ^ (x)) & (PIDHASH_SZ - 1))
154
Chih-Hung Hsiehdaa13ea2016-05-19 16:02:22 -0700155#define ADJTOSLOT(adj) ((adj) + -OOM_SCORE_ADJ_MIN)
Chong Zhang0a4acdf2015-10-14 16:19:53 -0700156static struct adjslot_list procadjslot_list[ADJTOSLOT(OOM_SCORE_ADJ_MAX) + 1];
Todd Poynor3948f802013-07-09 19:35:14 -0700157
Todd Poynor3948f802013-07-09 19:35:14 -0700158/* PAGE_SIZE / 1024 */
159static long page_k;
160
Colin Crossce85d952014-07-11 17:53:27 -0700161static ssize_t read_all(int fd, char *buf, size_t max_len)
162{
163 ssize_t ret = 0;
164
165 while (max_len > 0) {
166 ssize_t r = read(fd, buf, max_len);
167 if (r == 0) {
168 break;
169 }
170 if (r == -1) {
171 return -1;
172 }
173 ret += r;
174 buf += r;
175 max_len -= r;
176 }
177
178 return ret;
179}
180
Todd Poynor3948f802013-07-09 19:35:14 -0700181static struct proc *pid_lookup(int pid) {
182 struct proc *procp;
183
184 for (procp = pidhash[pid_hashfn(pid)]; procp && procp->pid != pid;
185 procp = procp->pidhash_next)
186 ;
187
188 return procp;
189}
190
191static void adjslot_insert(struct adjslot_list *head, struct adjslot_list *new)
192{
193 struct adjslot_list *next = head->next;
194 new->prev = head;
195 new->next = next;
196 next->prev = new;
197 head->next = new;
198}
199
200static void adjslot_remove(struct adjslot_list *old)
201{
202 struct adjslot_list *prev = old->prev;
203 struct adjslot_list *next = old->next;
204 next->prev = prev;
205 prev->next = next;
206}
207
208static struct adjslot_list *adjslot_tail(struct adjslot_list *head) {
209 struct adjslot_list *asl = head->prev;
210
211 return asl == head ? NULL : asl;
212}
213
214static void proc_slot(struct proc *procp) {
215 int adjslot = ADJTOSLOT(procp->oomadj);
216
217 adjslot_insert(&procadjslot_list[adjslot], &procp->asl);
218}
219
220static void proc_unslot(struct proc *procp) {
221 adjslot_remove(&procp->asl);
222}
223
224static void proc_insert(struct proc *procp) {
225 int hval = pid_hashfn(procp->pid);
226
227 procp->pidhash_next = pidhash[hval];
228 pidhash[hval] = procp;
229 proc_slot(procp);
230}
231
232static int pid_remove(int pid) {
233 int hval = pid_hashfn(pid);
234 struct proc *procp;
235 struct proc *prevp;
236
237 for (procp = pidhash[hval], prevp = NULL; procp && procp->pid != pid;
238 procp = procp->pidhash_next)
239 prevp = procp;
240
241 if (!procp)
242 return -1;
243
244 if (!prevp)
245 pidhash[hval] = procp->pidhash_next;
246 else
247 prevp->pidhash_next = procp->pidhash_next;
248
249 proc_unslot(procp);
250 free(procp);
251 return 0;
252}
253
Suren Baghdasaryancd7ad2f2017-12-08 12:58:52 -0800254static void writefilestring(const char *path, char *s) {
Nick Kralevichc68c8862015-12-18 20:52:37 -0800255 int fd = open(path, O_WRONLY | O_CLOEXEC);
Todd Poynor3948f802013-07-09 19:35:14 -0700256 int len = strlen(s);
257 int ret;
258
259 if (fd < 0) {
260 ALOGE("Error opening %s; errno=%d", path, errno);
261 return;
262 }
263
264 ret = write(fd, s, len);
265 if (ret < 0) {
266 ALOGE("Error writing %s; errno=%d", path, errno);
267 } else if (ret < len) {
268 ALOGE("Short write on %s; length=%d", path, ret);
269 }
270
271 close(fd);
272}
273
Colin Crossfbb78c62014-06-13 14:52:43 -0700274static void cmd_procprio(int pid, int uid, int oomadj) {
Todd Poynor3948f802013-07-09 19:35:14 -0700275 struct proc *procp;
276 char path[80];
277 char val[20];
Robert Benea673e2762017-06-01 16:32:31 -0700278 int soft_limit_mult;
Todd Poynor3948f802013-07-09 19:35:14 -0700279
Chong Zhang0a4acdf2015-10-14 16:19:53 -0700280 if (oomadj < OOM_SCORE_ADJ_MIN || oomadj > OOM_SCORE_ADJ_MAX) {
Todd Poynor3948f802013-07-09 19:35:14 -0700281 ALOGE("Invalid PROCPRIO oomadj argument %d", oomadj);
282 return;
283 }
284
Todd Poynor16b60992013-09-16 19:26:47 -0700285 snprintf(path, sizeof(path), "/proc/%d/oom_score_adj", pid);
Chong Zhang0a4acdf2015-10-14 16:19:53 -0700286 snprintf(val, sizeof(val), "%d", oomadj);
Todd Poynor3948f802013-07-09 19:35:14 -0700287 writefilestring(path, val);
288
289 if (use_inkernel_interface)
290 return;
291
Robert Benea673e2762017-06-01 16:32:31 -0700292 if (oomadj >= 900) {
293 soft_limit_mult = 0;
294 } else if (oomadj >= 800) {
295 soft_limit_mult = 0;
296 } else if (oomadj >= 700) {
297 soft_limit_mult = 0;
298 } else if (oomadj >= 600) {
Robert Beneacaeaa652017-08-11 16:03:20 -0700299 // Launcher should be perceptible, don't kill it.
300 oomadj = 200;
301 soft_limit_mult = 1;
Robert Benea673e2762017-06-01 16:32:31 -0700302 } else if (oomadj >= 500) {
303 soft_limit_mult = 0;
304 } else if (oomadj >= 400) {
305 soft_limit_mult = 0;
306 } else if (oomadj >= 300) {
307 soft_limit_mult = 1;
308 } else if (oomadj >= 200) {
309 soft_limit_mult = 2;
310 } else if (oomadj >= 100) {
311 soft_limit_mult = 10;
312 } else if (oomadj >= 0) {
313 soft_limit_mult = 20;
314 } else {
315 // Persistent processes will have a large
316 // soft limit 512MB.
317 soft_limit_mult = 64;
318 }
319
320 snprintf(path, sizeof(path), "/dev/memcg/apps/uid_%d/pid_%d/memory.soft_limit_in_bytes", uid, pid);
321 snprintf(val, sizeof(val), "%d", soft_limit_mult * EIGHT_MEGA);
322 writefilestring(path, val);
323
Todd Poynor3948f802013-07-09 19:35:14 -0700324 procp = pid_lookup(pid);
325 if (!procp) {
326 procp = malloc(sizeof(struct proc));
327 if (!procp) {
328 // Oh, the irony. May need to rebuild our state.
329 return;
330 }
331
332 procp->pid = pid;
Colin Crossfbb78c62014-06-13 14:52:43 -0700333 procp->uid = uid;
Todd Poynor3948f802013-07-09 19:35:14 -0700334 procp->oomadj = oomadj;
335 proc_insert(procp);
336 } else {
337 proc_unslot(procp);
338 procp->oomadj = oomadj;
339 proc_slot(procp);
340 }
341}
342
343static void cmd_procremove(int pid) {
Todd Poynor3948f802013-07-09 19:35:14 -0700344 if (use_inkernel_interface)
345 return;
346
347 pid_remove(pid);
Todd Poynor3948f802013-07-09 19:35:14 -0700348}
349
350static void cmd_target(int ntargets, int *params) {
351 int i;
352
353 if (ntargets > (int)ARRAY_SIZE(lowmem_adj))
354 return;
355
356 for (i = 0; i < ntargets; i++) {
357 lowmem_minfree[i] = ntohl(*params++);
358 lowmem_adj[i] = ntohl(*params++);
359 }
360
361 lowmem_targets_size = ntargets;
362
Robert Benea164baeb2017-09-11 16:53:28 -0700363 if (has_inkernel_module) {
Todd Poynor3948f802013-07-09 19:35:14 -0700364 char minfreestr[128];
365 char killpriostr[128];
366
367 minfreestr[0] = '\0';
368 killpriostr[0] = '\0';
369
370 for (i = 0; i < lowmem_targets_size; i++) {
371 char val[40];
372
373 if (i) {
374 strlcat(minfreestr, ",", sizeof(minfreestr));
375 strlcat(killpriostr, ",", sizeof(killpriostr));
376 }
377
Robert Benea164baeb2017-09-11 16:53:28 -0700378 snprintf(val, sizeof(val), "%d", use_inkernel_interface ? lowmem_minfree[i] : 0);
Todd Poynor3948f802013-07-09 19:35:14 -0700379 strlcat(minfreestr, val, sizeof(minfreestr));
Robert Benea164baeb2017-09-11 16:53:28 -0700380 snprintf(val, sizeof(val), "%d", use_inkernel_interface ? lowmem_adj[i] : 0);
Todd Poynor3948f802013-07-09 19:35:14 -0700381 strlcat(killpriostr, val, sizeof(killpriostr));
382 }
383
384 writefilestring(INKERNEL_MINFREE_PATH, minfreestr);
385 writefilestring(INKERNEL_ADJ_PATH, killpriostr);
386 }
387}
388
389static void ctrl_data_close(void) {
390 ALOGI("Closing Activity Manager data connection");
391 close(ctrl_dfd);
392 ctrl_dfd = -1;
393 maxevents--;
394}
395
396static int ctrl_data_read(char *buf, size_t bufsz) {
397 int ret = 0;
398
399 ret = read(ctrl_dfd, buf, bufsz);
400
401 if (ret == -1) {
402 ALOGE("control data socket read failed; errno=%d", errno);
403 } else if (ret == 0) {
404 ALOGE("Got EOF on control data socket");
405 ret = -1;
406 }
407
408 return ret;
409}
410
411static void ctrl_command_handler(void) {
412 int ibuf[CTRL_PACKET_MAX / sizeof(int)];
413 int len;
414 int cmd = -1;
415 int nargs;
416 int targets;
417
418 len = ctrl_data_read((char *)ibuf, CTRL_PACKET_MAX);
419 if (len <= 0)
420 return;
421
422 nargs = len / sizeof(int) - 1;
423 if (nargs < 0)
424 goto wronglen;
425
426 cmd = ntohl(ibuf[0]);
427
428 switch(cmd) {
429 case LMK_TARGET:
430 targets = nargs / 2;
431 if (nargs & 0x1 || targets > (int)ARRAY_SIZE(lowmem_adj))
432 goto wronglen;
433 cmd_target(targets, &ibuf[1]);
434 break;
435 case LMK_PROCPRIO:
Colin Crossfbb78c62014-06-13 14:52:43 -0700436 if (nargs != 3)
Todd Poynor3948f802013-07-09 19:35:14 -0700437 goto wronglen;
Colin Crossfbb78c62014-06-13 14:52:43 -0700438 cmd_procprio(ntohl(ibuf[1]), ntohl(ibuf[2]), ntohl(ibuf[3]));
Todd Poynor3948f802013-07-09 19:35:14 -0700439 break;
440 case LMK_PROCREMOVE:
441 if (nargs != 1)
442 goto wronglen;
443 cmd_procremove(ntohl(ibuf[1]));
444 break;
445 default:
446 ALOGE("Received unknown command code %d", cmd);
447 return;
448 }
449
450 return;
451
452wronglen:
453 ALOGE("Wrong control socket read length cmd=%d len=%d", cmd, len);
454}
455
456static void ctrl_data_handler(uint32_t events) {
457 if (events & EPOLLHUP) {
458 ALOGI("ActivityManager disconnected");
459 if (!ctrl_dfd_reopened)
460 ctrl_data_close();
461 } else if (events & EPOLLIN) {
462 ctrl_command_handler();
463 }
464}
465
Mark Salyzyne6ed68b2014-04-30 13:36:35 -0700466static void ctrl_connect_handler(uint32_t events __unused) {
Todd Poynor3948f802013-07-09 19:35:14 -0700467 struct epoll_event epev;
468
469 if (ctrl_dfd >= 0) {
470 ctrl_data_close();
471 ctrl_dfd_reopened = 1;
472 }
473
Elliott Hughes3dcfa3f2016-08-23 12:50:00 -0700474 ctrl_dfd = accept(ctrl_lfd, NULL, NULL);
Todd Poynor3948f802013-07-09 19:35:14 -0700475
476 if (ctrl_dfd < 0) {
477 ALOGE("lmkd control socket accept failed; errno=%d", errno);
478 return;
479 }
480
481 ALOGI("ActivityManager connected");
482 maxevents++;
483 epev.events = EPOLLIN;
484 epev.data.ptr = (void *)ctrl_data_handler;
485 if (epoll_ctl(epollfd, EPOLL_CTL_ADD, ctrl_dfd, &epev) == -1) {
486 ALOGE("epoll_ctl for data connection socket failed; errno=%d", errno);
487 ctrl_data_close();
488 return;
489 }
490}
491
492static int zoneinfo_parse_protection(char *cp) {
493 int max = 0;
494 int zoneval;
Colin Crossce85d952014-07-11 17:53:27 -0700495 char *save_ptr;
Todd Poynor3948f802013-07-09 19:35:14 -0700496
Colin Crossce85d952014-07-11 17:53:27 -0700497 for (cp = strtok_r(cp, "(), ", &save_ptr); cp; cp = strtok_r(NULL, "), ", &save_ptr)) {
Todd Poynor3948f802013-07-09 19:35:14 -0700498 zoneval = strtol(cp, &cp, 0);
Todd Poynor3948f802013-07-09 19:35:14 -0700499 if (zoneval > max)
500 max = zoneval;
Colin Crossce85d952014-07-11 17:53:27 -0700501 }
Todd Poynor3948f802013-07-09 19:35:14 -0700502
503 return max;
504}
505
506static void zoneinfo_parse_line(char *line, struct sysmeminfo *mip) {
507 char *cp = line;
508 char *ap;
Colin Crossce85d952014-07-11 17:53:27 -0700509 char *save_ptr;
Todd Poynor3948f802013-07-09 19:35:14 -0700510
Colin Crossce85d952014-07-11 17:53:27 -0700511 cp = strtok_r(line, " ", &save_ptr);
Todd Poynor3948f802013-07-09 19:35:14 -0700512 if (!cp)
513 return;
514
Colin Crossce85d952014-07-11 17:53:27 -0700515 ap = strtok_r(NULL, " ", &save_ptr);
Todd Poynor3948f802013-07-09 19:35:14 -0700516 if (!ap)
517 return;
518
519 if (!strcmp(cp, "nr_free_pages"))
520 mip->nr_free_pages += strtol(ap, NULL, 0);
521 else if (!strcmp(cp, "nr_file_pages"))
522 mip->nr_file_pages += strtol(ap, NULL, 0);
523 else if (!strcmp(cp, "nr_shmem"))
524 mip->nr_shmem += strtol(ap, NULL, 0);
525 else if (!strcmp(cp, "high"))
526 mip->totalreserve_pages += strtol(ap, NULL, 0);
527 else if (!strcmp(cp, "protection:"))
528 mip->totalreserve_pages += zoneinfo_parse_protection(ap);
529}
530
531static int zoneinfo_parse(struct sysmeminfo *mip) {
Colin Crossce85d952014-07-11 17:53:27 -0700532 int fd;
533 ssize_t size;
534 char buf[PAGE_SIZE];
535 char *save_ptr;
536 char *line;
Todd Poynor3948f802013-07-09 19:35:14 -0700537
538 memset(mip, 0, sizeof(struct sysmeminfo));
Colin Crossce85d952014-07-11 17:53:27 -0700539
Nick Kralevichc68c8862015-12-18 20:52:37 -0800540 fd = open(ZONEINFO_PATH, O_RDONLY | O_CLOEXEC);
Colin Crossce85d952014-07-11 17:53:27 -0700541 if (fd == -1) {
Todd Poynor3948f802013-07-09 19:35:14 -0700542 ALOGE("%s open: errno=%d", ZONEINFO_PATH, errno);
543 return -1;
544 }
545
Colin Crossce85d952014-07-11 17:53:27 -0700546 size = read_all(fd, buf, sizeof(buf) - 1);
547 if (size < 0) {
548 ALOGE("%s read: errno=%d", ZONEINFO_PATH, errno);
549 close(fd);
550 return -1;
551 }
552 ALOG_ASSERT((size_t)size < sizeof(buf) - 1, "/proc/zoneinfo too large");
553 buf[size] = 0;
554
555 for (line = strtok_r(buf, "\n", &save_ptr); line; line = strtok_r(NULL, "\n", &save_ptr))
Todd Poynor3948f802013-07-09 19:35:14 -0700556 zoneinfo_parse_line(line, mip);
557
Colin Crossce85d952014-07-11 17:53:27 -0700558 close(fd);
Todd Poynor3948f802013-07-09 19:35:14 -0700559 return 0;
560}
561
562static int proc_get_size(int pid) {
563 char path[PATH_MAX];
564 char line[LINE_MAX];
Colin Crossce85d952014-07-11 17:53:27 -0700565 int fd;
Todd Poynor3948f802013-07-09 19:35:14 -0700566 int rss = 0;
567 int total;
Colin Crossce85d952014-07-11 17:53:27 -0700568 ssize_t ret;
Todd Poynor3948f802013-07-09 19:35:14 -0700569
570 snprintf(path, PATH_MAX, "/proc/%d/statm", pid);
Nick Kralevichc68c8862015-12-18 20:52:37 -0800571 fd = open(path, O_RDONLY | O_CLOEXEC);
Colin Crossce85d952014-07-11 17:53:27 -0700572 if (fd == -1)
Todd Poynor3948f802013-07-09 19:35:14 -0700573 return -1;
Colin Crossce85d952014-07-11 17:53:27 -0700574
575 ret = read_all(fd, line, sizeof(line) - 1);
576 if (ret < 0) {
577 close(fd);
Todd Poynor3948f802013-07-09 19:35:14 -0700578 return -1;
579 }
580
581 sscanf(line, "%d %d ", &total, &rss);
Colin Crossce85d952014-07-11 17:53:27 -0700582 close(fd);
Todd Poynor3948f802013-07-09 19:35:14 -0700583 return rss;
584}
585
586static char *proc_get_name(int pid) {
587 char path[PATH_MAX];
588 static char line[LINE_MAX];
Colin Crossce85d952014-07-11 17:53:27 -0700589 int fd;
Todd Poynor3948f802013-07-09 19:35:14 -0700590 char *cp;
Colin Crossce85d952014-07-11 17:53:27 -0700591 ssize_t ret;
Todd Poynor3948f802013-07-09 19:35:14 -0700592
593 snprintf(path, PATH_MAX, "/proc/%d/cmdline", pid);
Nick Kralevichc68c8862015-12-18 20:52:37 -0800594 fd = open(path, O_RDONLY | O_CLOEXEC);
Colin Crossce85d952014-07-11 17:53:27 -0700595 if (fd == -1)
Todd Poynor3948f802013-07-09 19:35:14 -0700596 return NULL;
Colin Crossce85d952014-07-11 17:53:27 -0700597 ret = read_all(fd, line, sizeof(line) - 1);
598 close(fd);
599 if (ret < 0) {
Todd Poynor3948f802013-07-09 19:35:14 -0700600 return NULL;
601 }
602
603 cp = strchr(line, ' ');
604 if (cp)
605 *cp = '\0';
606
607 return line;
608}
609
610static struct proc *proc_adj_lru(int oomadj) {
611 return (struct proc *)adjslot_tail(&procadjslot_list[ADJTOSLOT(oomadj)]);
612}
613
Suren Baghdasaryanb93764d2017-12-08 13:17:06 -0800614static struct proc *proc_get_heaviest(int oomadj) {
615 struct adjslot_list *head = &procadjslot_list[ADJTOSLOT(oomadj)];
616 struct adjslot_list *curr = head->next;
617 struct proc *maxprocp = NULL;
618 int maxsize = 0;
619 while (curr != head) {
620 int pid = ((struct proc *)curr)->pid;
621 int tasksize = proc_get_size(pid);
622 if (tasksize <= 0) {
623 struct adjslot_list *next = curr->next;
624 pid_remove(pid);
625 curr = next;
626 } else {
627 if (tasksize > maxsize) {
628 maxsize = tasksize;
629 maxprocp = (struct proc *)curr;
630 }
631 curr = curr->next;
632 }
633 }
634 return maxprocp;
635}
636
Colin Cross16b09462014-07-14 12:39:56 -0700637/* Kill one process specified by procp. Returns the size of the process killed */
Suren Baghdasaryancd7ad2f2017-12-08 12:58:52 -0800638static int kill_one_process(struct proc* procp, int min_score_adj,
639 enum vmpressure_level level) {
Colin Cross16b09462014-07-14 12:39:56 -0700640 int pid = procp->pid;
641 uid_t uid = procp->uid;
642 char *taskname;
643 int tasksize;
644 int r;
645
646 taskname = proc_get_name(pid);
647 if (!taskname) {
648 pid_remove(pid);
649 return -1;
650 }
651
652 tasksize = proc_get_size(pid);
653 if (tasksize <= 0) {
654 pid_remove(pid);
655 return -1;
656 }
657
Suren Baghdasaryane1217c02018-01-04 10:43:58 -0800658 TRACE_KILL_START(pid);
659
Suren Baghdasaryancd7ad2f2017-12-08 12:58:52 -0800660 r = kill(pid, SIGKILL);
Robert Beneacaeaa652017-08-11 16:03:20 -0700661 ALOGI(
662 "Killing '%s' (%d), uid %d, adj %d\n"
663 " to free %ldkB because system is under %s memory pressure oom_adj %d\n",
Suren Baghdasaryancd7ad2f2017-12-08 12:58:52 -0800664 taskname, pid, uid, procp->oomadj, tasksize * page_k,
665 level_name[level], min_score_adj);
Colin Cross16b09462014-07-14 12:39:56 -0700666 pid_remove(pid);
667
Suren Baghdasaryane1217c02018-01-04 10:43:58 -0800668 TRACE_KILL_END();
669
Colin Cross16b09462014-07-14 12:39:56 -0700670 if (r) {
Mark Salyzyn919f5382018-02-04 15:27:23 -0800671 ALOGE("kill(%d): errno=%d", pid, errno);
Colin Cross16b09462014-07-14 12:39:56 -0700672 return -1;
Colin Cross16b09462014-07-14 12:39:56 -0700673 }
Mark Salyzyn919f5382018-02-04 15:27:23 -0800674
675 return tasksize;
Colin Cross16b09462014-07-14 12:39:56 -0700676}
677
678/*
679 * Find a process to kill based on the current (possibly estimated) free memory
680 * and cached memory sizes. Returns the size of the killed processes.
681 */
Suren Baghdasaryancd7ad2f2017-12-08 12:58:52 -0800682static int find_and_kill_process(enum vmpressure_level level) {
Colin Cross16b09462014-07-14 12:39:56 -0700683 int i;
Colin Cross16b09462014-07-14 12:39:56 -0700684 int killed_size = 0;
Suren Baghdasaryancd7ad2f2017-12-08 12:58:52 -0800685 int min_score_adj = level_oomadj[level];
Colin Cross16b09462014-07-14 12:39:56 -0700686
Chong Zhang0a4acdf2015-10-14 16:19:53 -0700687 for (i = OOM_SCORE_ADJ_MAX; i >= min_score_adj; i--) {
Colin Cross16b09462014-07-14 12:39:56 -0700688 struct proc *procp;
689
690retry:
Suren Baghdasaryanb93764d2017-12-08 13:17:06 -0800691 if (kill_heaviest_task)
692 procp = proc_get_heaviest(i);
693 else
694 procp = proc_adj_lru(i);
Colin Cross16b09462014-07-14 12:39:56 -0700695
696 if (procp) {
Suren Baghdasaryancd7ad2f2017-12-08 12:58:52 -0800697 killed_size = kill_one_process(procp, min_score_adj, level);
Colin Cross16b09462014-07-14 12:39:56 -0700698 if (killed_size < 0) {
699 goto retry;
700 } else {
701 return killed_size;
702 }
703 }
704 }
705
706 return 0;
707}
708
Robert Beneac47f2992017-08-21 15:18:31 -0700709static int64_t get_memory_usage(const char* path) {
710 int ret;
711 int64_t mem_usage;
712 char buf[32];
713 int fd = open(path, O_RDONLY | O_CLOEXEC);
714 if (fd == -1) {
715 ALOGE("%s open: errno=%d", path, errno);
716 return -1;
717 }
718
719 ret = read_all(fd, buf, sizeof(buf) - 1);
720 close(fd);
721 if (ret < 0) {
722 ALOGE("%s error: errno=%d", path, errno);
723 return -1;
724 }
725 sscanf(buf, "%" SCNd64, &mem_usage);
726 if (mem_usage == 0) {
727 ALOGE("No memory!");
728 return -1;
729 }
730 return mem_usage;
731}
732
Suren Baghdasaryancd7ad2f2017-12-08 12:58:52 -0800733enum vmpressure_level upgrade_level(enum vmpressure_level level) {
734 return (enum vmpressure_level)((level < VMPRESS_LEVEL_CRITICAL) ?
735 level + 1 : level);
736}
737
738enum vmpressure_level downgrade_level(enum vmpressure_level level) {
739 return (enum vmpressure_level)((level > VMPRESS_LEVEL_LOW) ?
740 level - 1 : level);
741}
742
743static void mp_event_common(enum vmpressure_level level) {
Todd Poynor3948f802013-07-09 19:35:14 -0700744 int ret;
745 unsigned long long evcount;
Robert Beneac47f2992017-08-21 15:18:31 -0700746 int64_t mem_usage, memsw_usage;
Robert Benea6e8e7102017-09-13 15:20:30 -0700747 int64_t mem_pressure;
Suren Baghdasaryan1a2589e2018-01-04 09:16:21 -0800748 enum vmpressure_level lvl;
Todd Poynor3948f802013-07-09 19:35:14 -0700749
Suren Baghdasaryan1a2589e2018-01-04 09:16:21 -0800750 /*
751 * Check all event counters from low to critical
752 * and upgrade to the highest priority one. By reading
753 * eventfd we also reset the event counters.
754 */
755 for (lvl = VMPRESS_LEVEL_LOW; lvl < VMPRESS_LEVEL_COUNT; lvl++) {
756 if (mpevfd[lvl] != -1 &&
757 read(mpevfd[lvl], &evcount, sizeof(evcount)) > 0 &&
758 evcount > 0 && lvl > level) {
759 level = lvl;
760 }
761 }
Todd Poynor3948f802013-07-09 19:35:14 -0700762
Robert Benea6e8e7102017-09-13 15:20:30 -0700763 mem_usage = get_memory_usage(MEMCG_MEMORY_USAGE);
764 memsw_usage = get_memory_usage(MEMCG_MEMORYSW_USAGE);
765 if (memsw_usage < 0 || mem_usage < 0) {
Suren Baghdasaryancd7ad2f2017-12-08 12:58:52 -0800766 goto do_kill;
Robert Benea6e8e7102017-09-13 15:20:30 -0700767 }
Robert Beneac47f2992017-08-21 15:18:31 -0700768
Robert Benea6e8e7102017-09-13 15:20:30 -0700769 // Calculate percent for swappinness.
770 mem_pressure = (mem_usage * 100) / memsw_usage;
771
Suren Baghdasaryancd7ad2f2017-12-08 12:58:52 -0800772 if (enable_pressure_upgrade && level != VMPRESS_LEVEL_CRITICAL) {
Robert Benea6e8e7102017-09-13 15:20:30 -0700773 // We are swapping too much.
774 if (mem_pressure < upgrade_pressure) {
Suren Baghdasaryancd7ad2f2017-12-08 12:58:52 -0800775 level = upgrade_level(level);
776 if (debug_process_killing) {
777 ALOGI("Event upgraded to %s", level_name[level]);
778 }
Robert Beneac47f2992017-08-21 15:18:31 -0700779 }
780 }
781
Robert Benea6e8e7102017-09-13 15:20:30 -0700782 // If the pressure is larger than downgrade_pressure lmk will not
783 // kill any process, since enough memory is available.
784 if (mem_pressure > downgrade_pressure) {
785 if (debug_process_killing) {
Suren Baghdasaryancd7ad2f2017-12-08 12:58:52 -0800786 ALOGI("Ignore %s memory pressure", level_name[level]);
Robert Benea6e8e7102017-09-13 15:20:30 -0700787 }
788 return;
Suren Baghdasaryancd7ad2f2017-12-08 12:58:52 -0800789 } else if (level == VMPRESS_LEVEL_CRITICAL &&
790 mem_pressure > upgrade_pressure) {
Robert Benea6e8e7102017-09-13 15:20:30 -0700791 if (debug_process_killing) {
792 ALOGI("Downgrade critical memory pressure");
793 }
Suren Baghdasaryancd7ad2f2017-12-08 12:58:52 -0800794 // Downgrade event, since enough memory available.
795 level = downgrade_level(level);
Robert Benea6e8e7102017-09-13 15:20:30 -0700796 }
797
Suren Baghdasaryancd7ad2f2017-12-08 12:58:52 -0800798do_kill:
799 if (find_and_kill_process(level) == 0) {
Robert Beneacaeaa652017-08-11 16:03:20 -0700800 if (debug_process_killing) {
801 ALOGI("Nothing to kill");
802 }
Colin Crossf8857cc2014-07-11 17:16:56 -0700803 }
Todd Poynor3948f802013-07-09 19:35:14 -0700804}
805
Suren Baghdasaryancd7ad2f2017-12-08 12:58:52 -0800806static void mp_event_low(uint32_t events __unused) {
807 mp_event_common(VMPRESS_LEVEL_LOW);
808}
809
810static void mp_event_medium(uint32_t events __unused) {
811 mp_event_common(VMPRESS_LEVEL_MEDIUM);
Robert Benea673e2762017-06-01 16:32:31 -0700812}
813
814static void mp_event_critical(uint32_t events __unused) {
Suren Baghdasaryancd7ad2f2017-12-08 12:58:52 -0800815 mp_event_common(VMPRESS_LEVEL_CRITICAL);
Robert Benea673e2762017-06-01 16:32:31 -0700816}
817
Suren Baghdasaryancd7ad2f2017-12-08 12:58:52 -0800818static bool init_mp_common(void *event_handler, enum vmpressure_level level) {
Todd Poynor3948f802013-07-09 19:35:14 -0700819 int mpfd;
820 int evfd;
821 int evctlfd;
822 char buf[256];
823 struct epoll_event epev;
824 int ret;
Suren Baghdasaryancd7ad2f2017-12-08 12:58:52 -0800825 const char *levelstr = level_name[level];
826
827 if (level_oomadj[level] > OOM_SCORE_ADJ_MAX) {
828 ALOGI("%s pressure events are disabled", levelstr);
829 return true;
830 }
Todd Poynor3948f802013-07-09 19:35:14 -0700831
Nick Kralevichc68c8862015-12-18 20:52:37 -0800832 mpfd = open(MEMCG_SYSFS_PATH "memory.pressure_level", O_RDONLY | O_CLOEXEC);
Todd Poynor3948f802013-07-09 19:35:14 -0700833 if (mpfd < 0) {
834 ALOGI("No kernel memory.pressure_level support (errno=%d)", errno);
835 goto err_open_mpfd;
836 }
837
Nick Kralevichc68c8862015-12-18 20:52:37 -0800838 evctlfd = open(MEMCG_SYSFS_PATH "cgroup.event_control", O_WRONLY | O_CLOEXEC);
Todd Poynor3948f802013-07-09 19:35:14 -0700839 if (evctlfd < 0) {
840 ALOGI("No kernel memory cgroup event control (errno=%d)", errno);
841 goto err_open_evctlfd;
842 }
843
Nick Kralevichc68c8862015-12-18 20:52:37 -0800844 evfd = eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC);
Todd Poynor3948f802013-07-09 19:35:14 -0700845 if (evfd < 0) {
846 ALOGE("eventfd failed for level %s; errno=%d", levelstr, errno);
847 goto err_eventfd;
848 }
849
850 ret = snprintf(buf, sizeof(buf), "%d %d %s", evfd, mpfd, levelstr);
851 if (ret >= (ssize_t)sizeof(buf)) {
852 ALOGE("cgroup.event_control line overflow for level %s", levelstr);
853 goto err;
854 }
855
856 ret = write(evctlfd, buf, strlen(buf) + 1);
857 if (ret == -1) {
858 ALOGE("cgroup.event_control write failed for level %s; errno=%d",
859 levelstr, errno);
860 goto err;
861 }
862
863 epev.events = EPOLLIN;
864 epev.data.ptr = event_handler;
865 ret = epoll_ctl(epollfd, EPOLL_CTL_ADD, evfd, &epev);
866 if (ret == -1) {
867 ALOGE("epoll_ctl for level %s failed; errno=%d", levelstr, errno);
868 goto err;
869 }
870 maxevents++;
Suren Baghdasaryancd7ad2f2017-12-08 12:58:52 -0800871 mpevfd[level] = evfd;
Suren Baghdasaryanab05d672018-01-04 08:54:53 -0800872 close(evctlfd);
Suren Baghdasaryancd7ad2f2017-12-08 12:58:52 -0800873 return true;
Todd Poynor3948f802013-07-09 19:35:14 -0700874
875err:
876 close(evfd);
877err_eventfd:
878 close(evctlfd);
879err_open_evctlfd:
880 close(mpfd);
881err_open_mpfd:
Suren Baghdasaryancd7ad2f2017-12-08 12:58:52 -0800882 return false;
Robert Benea673e2762017-06-01 16:32:31 -0700883}
884
Todd Poynor3948f802013-07-09 19:35:14 -0700885static int init(void) {
886 struct epoll_event epev;
887 int i;
888 int ret;
889
890 page_k = sysconf(_SC_PAGESIZE);
891 if (page_k == -1)
892 page_k = PAGE_SIZE;
893 page_k /= 1024;
894
895 epollfd = epoll_create(MAX_EPOLL_EVENTS);
896 if (epollfd == -1) {
897 ALOGE("epoll_create failed (errno=%d)", errno);
898 return -1;
899 }
900
901 ctrl_lfd = android_get_control_socket("lmkd");
902 if (ctrl_lfd < 0) {
903 ALOGE("get lmkd control socket failed");
904 return -1;
905 }
906
907 ret = listen(ctrl_lfd, 1);
908 if (ret < 0) {
909 ALOGE("lmkd control socket listen failed (errno=%d)", errno);
910 return -1;
911 }
912
913 epev.events = EPOLLIN;
914 epev.data.ptr = (void *)ctrl_connect_handler;
915 if (epoll_ctl(epollfd, EPOLL_CTL_ADD, ctrl_lfd, &epev) == -1) {
916 ALOGE("epoll_ctl for lmkd control socket failed (errno=%d)", errno);
917 return -1;
918 }
919 maxevents++;
920
Robert Benea164baeb2017-09-11 16:53:28 -0700921 has_inkernel_module = !access(INKERNEL_MINFREE_PATH, W_OK);
922 use_inkernel_interface = has_inkernel_module && !is_go_device;
Todd Poynor3948f802013-07-09 19:35:14 -0700923
924 if (use_inkernel_interface) {
925 ALOGI("Using in-kernel low memory killer interface");
926 } else {
Suren Baghdasaryancd7ad2f2017-12-08 12:58:52 -0800927 if (!init_mp_common((void *)&mp_event_low, VMPRESS_LEVEL_LOW) ||
928 !init_mp_common((void *)&mp_event_medium, VMPRESS_LEVEL_MEDIUM) ||
929 !init_mp_common((void *)&mp_event_critical,
930 VMPRESS_LEVEL_CRITICAL)) {
Todd Poynor3948f802013-07-09 19:35:14 -0700931 ALOGE("Kernel does not support memory pressure events or in-kernel low memory killer");
Suren Baghdasaryancd7ad2f2017-12-08 12:58:52 -0800932 return -1;
933 }
Todd Poynor3948f802013-07-09 19:35:14 -0700934 }
935
Chong Zhang0a4acdf2015-10-14 16:19:53 -0700936 for (i = 0; i <= ADJTOSLOT(OOM_SCORE_ADJ_MAX); i++) {
Todd Poynor3948f802013-07-09 19:35:14 -0700937 procadjslot_list[i].next = &procadjslot_list[i];
938 procadjslot_list[i].prev = &procadjslot_list[i];
939 }
940
941 return 0;
942}
943
944static void mainloop(void) {
945 while (1) {
946 struct epoll_event events[maxevents];
947 int nevents;
948 int i;
949
950 ctrl_dfd_reopened = 0;
951 nevents = epoll_wait(epollfd, events, maxevents, -1);
952
953 if (nevents == -1) {
954 if (errno == EINTR)
955 continue;
956 ALOGE("epoll_wait failed (errno=%d)", errno);
957 continue;
958 }
959
960 for (i = 0; i < nevents; ++i) {
961 if (events[i].events & EPOLLERR)
962 ALOGD("EPOLLERR on event #%d", i);
963 if (events[i].data.ptr)
964 (*(void (*)(uint32_t))events[i].data.ptr)(events[i].events);
965 }
966 }
967}
968
Mark Salyzyne6ed68b2014-04-30 13:36:35 -0700969int main(int argc __unused, char **argv __unused) {
Colin Cross1a0d9be2014-07-14 14:31:15 -0700970 struct sched_param param = {
971 .sched_priority = 1,
972 };
973
Suren Baghdasaryancd7ad2f2017-12-08 12:58:52 -0800974 /* By default disable low level vmpressure events */
975 level_oomadj[VMPRESS_LEVEL_LOW] =
976 property_get_int32("ro.lmk.low", OOM_SCORE_ADJ_MAX + 1);
977 level_oomadj[VMPRESS_LEVEL_MEDIUM] =
978 property_get_int32("ro.lmk.medium", 800);
979 level_oomadj[VMPRESS_LEVEL_CRITICAL] =
980 property_get_int32("ro.lmk.critical", 0);
Robert Beneacaeaa652017-08-11 16:03:20 -0700981 debug_process_killing = property_get_bool("ro.lmk.debug", false);
Suren Baghdasaryane5c964312017-12-08 13:08:41 -0800982
983 /* By default disable upgrade/downgrade logic */
984 enable_pressure_upgrade =
985 property_get_bool("ro.lmk.critical_upgrade", false);
986 upgrade_pressure =
987 (int64_t)property_get_int32("ro.lmk.upgrade_pressure", 100);
988 downgrade_pressure =
989 (int64_t)property_get_int32("ro.lmk.downgrade_pressure", 100);
Suren Baghdasaryanb93764d2017-12-08 13:17:06 -0800990 kill_heaviest_task =
991 property_get_bool("ro.lmk.kill_heaviest_task", true);
Robert Benea164baeb2017-09-11 16:53:28 -0700992 is_go_device = property_get_bool("ro.config.low_ram", false);
Robert Benea58891d52017-07-31 17:15:20 -0700993
Daniel Colascioned39adf22018-01-05 14:59:55 -0800994 // MCL_ONFAULT pins pages as they fault instead of loading
995 // everything immediately all at once. (Which would be bad,
996 // because as of this writing, we have a lot of mapped pages we
997 // never use.) Old kernels will see MCL_ONFAULT and fail with
998 // EINVAL; we ignore this failure.
999 //
1000 // N.B. read the man page for mlockall. MCL_CURRENT | MCL_ONFAULT
1001 // pins ⊆ MCL_CURRENT, converging to just MCL_CURRENT as we fault
1002 // in pages.
1003 if (mlockall(MCL_CURRENT | MCL_FUTURE | MCL_ONFAULT) && errno != EINVAL)
Daniel Colascione4dd5d002018-01-03 12:01:02 -08001004 ALOGW("mlockall failed: errno=%d", errno);
1005
Colin Cross1a0d9be2014-07-14 14:31:15 -07001006 sched_setscheduler(0, SCHED_FIFO, &param);
Todd Poynor3948f802013-07-09 19:35:14 -07001007 if (!init())
1008 mainloop();
1009
1010 ALOGI("exiting");
1011 return 0;
1012}