blob: 8a6168cd3929d354f71c8ef95c1fcc6e16c4c4fd [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>
Mark Salyzyncfd5b082016-10-17 14:28:00 -070021#include <sched.h>
Todd Poynor3948f802013-07-09 19:35:14 -070022#include <signal.h>
Todd Poynor3948f802013-07-09 19:35:14 -070023#include <stdlib.h>
24#include <string.h>
25#include <time.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
Todd Poynor3948f802013-07-09 19:35:14 -070034#include <cutils/sockets.h>
Mark Salyzyn30f991f2017-01-10 13:19:54 -080035#include <log/log.h>
Colin Crossfef95222014-06-11 14:53:41 -070036#include <processgroup/processgroup.h>
Mark Salyzyne6ed68b2014-04-30 13:36:35 -070037
38#ifndef __unused
39#define __unused __attribute__((__unused__))
40#endif
Todd Poynor3948f802013-07-09 19:35:14 -070041
42#define MEMCG_SYSFS_PATH "/dev/memcg/"
Martijn Coenen9010a232016-02-09 11:25:18 +010043#define MEMPRESSURE_WATCH_LEVEL "low"
Todd Poynor3948f802013-07-09 19:35:14 -070044#define ZONEINFO_PATH "/proc/zoneinfo"
45#define LINE_MAX 128
46
47#define INKERNEL_MINFREE_PATH "/sys/module/lowmemorykiller/parameters/minfree"
48#define INKERNEL_ADJ_PATH "/sys/module/lowmemorykiller/parameters/adj"
49
50#define ARRAY_SIZE(x) (sizeof(x) / sizeof(*(x)))
51
52enum lmk_cmd {
53 LMK_TARGET,
54 LMK_PROCPRIO,
55 LMK_PROCREMOVE,
56};
57
58#define MAX_TARGETS 6
59/*
60 * longest is LMK_TARGET followed by MAX_TARGETS each minfree and minkillprio
61 * values
62 */
63#define CTRL_PACKET_MAX (sizeof(int) * (MAX_TARGETS * 2 + 1))
64
65/* default to old in-kernel interface if no memory pressure events */
66static int use_inkernel_interface = 1;
67
68/* memory pressure level medium event */
69static int mpevfd;
70
71/* control socket listen and data */
72static int ctrl_lfd;
73static int ctrl_dfd = -1;
74static int ctrl_dfd_reopened; /* did we reopen ctrl conn on this loop? */
75
76/* 1 memory pressure level, 1 ctrl listen socket, 1 ctrl data socket */
77#define MAX_EPOLL_EVENTS 3
78static int epollfd;
79static int maxevents;
80
Chong Zhang0a4acdf2015-10-14 16:19:53 -070081/* OOM score values used by both kernel and framework */
Todd Poynor16b60992013-09-16 19:26:47 -070082#define OOM_SCORE_ADJ_MIN (-1000)
83#define OOM_SCORE_ADJ_MAX 1000
84
Todd Poynor3948f802013-07-09 19:35:14 -070085static int lowmem_adj[MAX_TARGETS];
86static int lowmem_minfree[MAX_TARGETS];
87static int lowmem_targets_size;
88
89struct sysmeminfo {
90 int nr_free_pages;
91 int nr_file_pages;
92 int nr_shmem;
93 int totalreserve_pages;
94};
95
96struct adjslot_list {
97 struct adjslot_list *next;
98 struct adjslot_list *prev;
99};
100
101struct proc {
102 struct adjslot_list asl;
103 int pid;
Colin Crossfbb78c62014-06-13 14:52:43 -0700104 uid_t uid;
Todd Poynor3948f802013-07-09 19:35:14 -0700105 int oomadj;
106 struct proc *pidhash_next;
107};
108
109#define PIDHASH_SZ 1024
110static struct proc *pidhash[PIDHASH_SZ];
111#define pid_hashfn(x) ((((x) >> 8) ^ (x)) & (PIDHASH_SZ - 1))
112
Chih-Hung Hsiehdaa13ea2016-05-19 16:02:22 -0700113#define ADJTOSLOT(adj) ((adj) + -OOM_SCORE_ADJ_MIN)
Chong Zhang0a4acdf2015-10-14 16:19:53 -0700114static struct adjslot_list procadjslot_list[ADJTOSLOT(OOM_SCORE_ADJ_MAX) + 1];
Todd Poynor3948f802013-07-09 19:35:14 -0700115
116/*
117 * Wait 1-2 seconds for the death report of a killed process prior to
118 * considering killing more processes.
119 */
120#define KILL_TIMEOUT 2
121/* Time of last process kill we initiated, stop me before I kill again */
122static time_t kill_lasttime;
123
124/* PAGE_SIZE / 1024 */
125static long page_k;
126
Colin Crossce85d952014-07-11 17:53:27 -0700127static ssize_t read_all(int fd, char *buf, size_t max_len)
128{
129 ssize_t ret = 0;
130
131 while (max_len > 0) {
132 ssize_t r = read(fd, buf, max_len);
133 if (r == 0) {
134 break;
135 }
136 if (r == -1) {
137 return -1;
138 }
139 ret += r;
140 buf += r;
141 max_len -= r;
142 }
143
144 return ret;
145}
146
Todd Poynor3948f802013-07-09 19:35:14 -0700147static struct proc *pid_lookup(int pid) {
148 struct proc *procp;
149
150 for (procp = pidhash[pid_hashfn(pid)]; procp && procp->pid != pid;
151 procp = procp->pidhash_next)
152 ;
153
154 return procp;
155}
156
157static void adjslot_insert(struct adjslot_list *head, struct adjslot_list *new)
158{
159 struct adjslot_list *next = head->next;
160 new->prev = head;
161 new->next = next;
162 next->prev = new;
163 head->next = new;
164}
165
166static void adjslot_remove(struct adjslot_list *old)
167{
168 struct adjslot_list *prev = old->prev;
169 struct adjslot_list *next = old->next;
170 next->prev = prev;
171 prev->next = next;
172}
173
174static struct adjslot_list *adjslot_tail(struct adjslot_list *head) {
175 struct adjslot_list *asl = head->prev;
176
177 return asl == head ? NULL : asl;
178}
179
180static void proc_slot(struct proc *procp) {
181 int adjslot = ADJTOSLOT(procp->oomadj);
182
183 adjslot_insert(&procadjslot_list[adjslot], &procp->asl);
184}
185
186static void proc_unslot(struct proc *procp) {
187 adjslot_remove(&procp->asl);
188}
189
190static void proc_insert(struct proc *procp) {
191 int hval = pid_hashfn(procp->pid);
192
193 procp->pidhash_next = pidhash[hval];
194 pidhash[hval] = procp;
195 proc_slot(procp);
196}
197
198static int pid_remove(int pid) {
199 int hval = pid_hashfn(pid);
200 struct proc *procp;
201 struct proc *prevp;
202
203 for (procp = pidhash[hval], prevp = NULL; procp && procp->pid != pid;
204 procp = procp->pidhash_next)
205 prevp = procp;
206
207 if (!procp)
208 return -1;
209
210 if (!prevp)
211 pidhash[hval] = procp->pidhash_next;
212 else
213 prevp->pidhash_next = procp->pidhash_next;
214
215 proc_unslot(procp);
216 free(procp);
217 return 0;
218}
219
220static void writefilestring(char *path, char *s) {
Nick Kralevichc68c8862015-12-18 20:52:37 -0800221 int fd = open(path, O_WRONLY | O_CLOEXEC);
Todd Poynor3948f802013-07-09 19:35:14 -0700222 int len = strlen(s);
223 int ret;
224
225 if (fd < 0) {
226 ALOGE("Error opening %s; errno=%d", path, errno);
227 return;
228 }
229
230 ret = write(fd, s, len);
231 if (ret < 0) {
232 ALOGE("Error writing %s; errno=%d", path, errno);
233 } else if (ret < len) {
234 ALOGE("Short write on %s; length=%d", path, ret);
235 }
236
237 close(fd);
238}
239
Colin Crossfbb78c62014-06-13 14:52:43 -0700240static void cmd_procprio(int pid, int uid, int oomadj) {
Todd Poynor3948f802013-07-09 19:35:14 -0700241 struct proc *procp;
242 char path[80];
243 char val[20];
244
Chong Zhang0a4acdf2015-10-14 16:19:53 -0700245 if (oomadj < OOM_SCORE_ADJ_MIN || oomadj > OOM_SCORE_ADJ_MAX) {
Todd Poynor3948f802013-07-09 19:35:14 -0700246 ALOGE("Invalid PROCPRIO oomadj argument %d", oomadj);
247 return;
248 }
249
Todd Poynor16b60992013-09-16 19:26:47 -0700250 snprintf(path, sizeof(path), "/proc/%d/oom_score_adj", pid);
Chong Zhang0a4acdf2015-10-14 16:19:53 -0700251 snprintf(val, sizeof(val), "%d", oomadj);
Todd Poynor3948f802013-07-09 19:35:14 -0700252 writefilestring(path, val);
253
254 if (use_inkernel_interface)
255 return;
256
257 procp = pid_lookup(pid);
258 if (!procp) {
259 procp = malloc(sizeof(struct proc));
260 if (!procp) {
261 // Oh, the irony. May need to rebuild our state.
262 return;
263 }
264
265 procp->pid = pid;
Colin Crossfbb78c62014-06-13 14:52:43 -0700266 procp->uid = uid;
Todd Poynor3948f802013-07-09 19:35:14 -0700267 procp->oomadj = oomadj;
268 proc_insert(procp);
269 } else {
270 proc_unslot(procp);
271 procp->oomadj = oomadj;
272 proc_slot(procp);
273 }
274}
275
276static void cmd_procremove(int pid) {
Todd Poynor3948f802013-07-09 19:35:14 -0700277 if (use_inkernel_interface)
278 return;
279
280 pid_remove(pid);
281 kill_lasttime = 0;
282}
283
284static void cmd_target(int ntargets, int *params) {
285 int i;
286
287 if (ntargets > (int)ARRAY_SIZE(lowmem_adj))
288 return;
289
290 for (i = 0; i < ntargets; i++) {
291 lowmem_minfree[i] = ntohl(*params++);
292 lowmem_adj[i] = ntohl(*params++);
293 }
294
295 lowmem_targets_size = ntargets;
296
297 if (use_inkernel_interface) {
298 char minfreestr[128];
299 char killpriostr[128];
300
301 minfreestr[0] = '\0';
302 killpriostr[0] = '\0';
303
304 for (i = 0; i < lowmem_targets_size; i++) {
305 char val[40];
306
307 if (i) {
308 strlcat(minfreestr, ",", sizeof(minfreestr));
309 strlcat(killpriostr, ",", sizeof(killpriostr));
310 }
311
312 snprintf(val, sizeof(val), "%d", lowmem_minfree[i]);
313 strlcat(minfreestr, val, sizeof(minfreestr));
314 snprintf(val, sizeof(val), "%d", lowmem_adj[i]);
315 strlcat(killpriostr, val, sizeof(killpriostr));
316 }
317
318 writefilestring(INKERNEL_MINFREE_PATH, minfreestr);
319 writefilestring(INKERNEL_ADJ_PATH, killpriostr);
320 }
321}
322
323static void ctrl_data_close(void) {
324 ALOGI("Closing Activity Manager data connection");
325 close(ctrl_dfd);
326 ctrl_dfd = -1;
327 maxevents--;
328}
329
330static int ctrl_data_read(char *buf, size_t bufsz) {
331 int ret = 0;
332
333 ret = read(ctrl_dfd, buf, bufsz);
334
335 if (ret == -1) {
336 ALOGE("control data socket read failed; errno=%d", errno);
337 } else if (ret == 0) {
338 ALOGE("Got EOF on control data socket");
339 ret = -1;
340 }
341
342 return ret;
343}
344
345static void ctrl_command_handler(void) {
346 int ibuf[CTRL_PACKET_MAX / sizeof(int)];
347 int len;
348 int cmd = -1;
349 int nargs;
350 int targets;
351
352 len = ctrl_data_read((char *)ibuf, CTRL_PACKET_MAX);
353 if (len <= 0)
354 return;
355
356 nargs = len / sizeof(int) - 1;
357 if (nargs < 0)
358 goto wronglen;
359
360 cmd = ntohl(ibuf[0]);
361
362 switch(cmd) {
363 case LMK_TARGET:
364 targets = nargs / 2;
365 if (nargs & 0x1 || targets > (int)ARRAY_SIZE(lowmem_adj))
366 goto wronglen;
367 cmd_target(targets, &ibuf[1]);
368 break;
369 case LMK_PROCPRIO:
Colin Crossfbb78c62014-06-13 14:52:43 -0700370 if (nargs != 3)
Todd Poynor3948f802013-07-09 19:35:14 -0700371 goto wronglen;
Colin Crossfbb78c62014-06-13 14:52:43 -0700372 cmd_procprio(ntohl(ibuf[1]), ntohl(ibuf[2]), ntohl(ibuf[3]));
Todd Poynor3948f802013-07-09 19:35:14 -0700373 break;
374 case LMK_PROCREMOVE:
375 if (nargs != 1)
376 goto wronglen;
377 cmd_procremove(ntohl(ibuf[1]));
378 break;
379 default:
380 ALOGE("Received unknown command code %d", cmd);
381 return;
382 }
383
384 return;
385
386wronglen:
387 ALOGE("Wrong control socket read length cmd=%d len=%d", cmd, len);
388}
389
390static void ctrl_data_handler(uint32_t events) {
391 if (events & EPOLLHUP) {
392 ALOGI("ActivityManager disconnected");
393 if (!ctrl_dfd_reopened)
394 ctrl_data_close();
395 } else if (events & EPOLLIN) {
396 ctrl_command_handler();
397 }
398}
399
Mark Salyzyne6ed68b2014-04-30 13:36:35 -0700400static void ctrl_connect_handler(uint32_t events __unused) {
Todd Poynor3948f802013-07-09 19:35:14 -0700401 struct epoll_event epev;
402
403 if (ctrl_dfd >= 0) {
404 ctrl_data_close();
405 ctrl_dfd_reopened = 1;
406 }
407
Elliott Hughes3dcfa3f2016-08-23 12:50:00 -0700408 ctrl_dfd = accept(ctrl_lfd, NULL, NULL);
Todd Poynor3948f802013-07-09 19:35:14 -0700409
410 if (ctrl_dfd < 0) {
411 ALOGE("lmkd control socket accept failed; errno=%d", errno);
412 return;
413 }
414
415 ALOGI("ActivityManager connected");
416 maxevents++;
417 epev.events = EPOLLIN;
418 epev.data.ptr = (void *)ctrl_data_handler;
419 if (epoll_ctl(epollfd, EPOLL_CTL_ADD, ctrl_dfd, &epev) == -1) {
420 ALOGE("epoll_ctl for data connection socket failed; errno=%d", errno);
421 ctrl_data_close();
422 return;
423 }
424}
425
426static int zoneinfo_parse_protection(char *cp) {
427 int max = 0;
428 int zoneval;
Colin Crossce85d952014-07-11 17:53:27 -0700429 char *save_ptr;
Todd Poynor3948f802013-07-09 19:35:14 -0700430
Colin Crossce85d952014-07-11 17:53:27 -0700431 for (cp = strtok_r(cp, "(), ", &save_ptr); cp; cp = strtok_r(NULL, "), ", &save_ptr)) {
Todd Poynor3948f802013-07-09 19:35:14 -0700432 zoneval = strtol(cp, &cp, 0);
Todd Poynor3948f802013-07-09 19:35:14 -0700433 if (zoneval > max)
434 max = zoneval;
Colin Crossce85d952014-07-11 17:53:27 -0700435 }
Todd Poynor3948f802013-07-09 19:35:14 -0700436
437 return max;
438}
439
440static void zoneinfo_parse_line(char *line, struct sysmeminfo *mip) {
441 char *cp = line;
442 char *ap;
Colin Crossce85d952014-07-11 17:53:27 -0700443 char *save_ptr;
Todd Poynor3948f802013-07-09 19:35:14 -0700444
Colin Crossce85d952014-07-11 17:53:27 -0700445 cp = strtok_r(line, " ", &save_ptr);
Todd Poynor3948f802013-07-09 19:35:14 -0700446 if (!cp)
447 return;
448
Colin Crossce85d952014-07-11 17:53:27 -0700449 ap = strtok_r(NULL, " ", &save_ptr);
Todd Poynor3948f802013-07-09 19:35:14 -0700450 if (!ap)
451 return;
452
453 if (!strcmp(cp, "nr_free_pages"))
454 mip->nr_free_pages += strtol(ap, NULL, 0);
455 else if (!strcmp(cp, "nr_file_pages"))
456 mip->nr_file_pages += strtol(ap, NULL, 0);
457 else if (!strcmp(cp, "nr_shmem"))
458 mip->nr_shmem += strtol(ap, NULL, 0);
459 else if (!strcmp(cp, "high"))
460 mip->totalreserve_pages += strtol(ap, NULL, 0);
461 else if (!strcmp(cp, "protection:"))
462 mip->totalreserve_pages += zoneinfo_parse_protection(ap);
463}
464
465static int zoneinfo_parse(struct sysmeminfo *mip) {
Colin Crossce85d952014-07-11 17:53:27 -0700466 int fd;
467 ssize_t size;
468 char buf[PAGE_SIZE];
469 char *save_ptr;
470 char *line;
Todd Poynor3948f802013-07-09 19:35:14 -0700471
472 memset(mip, 0, sizeof(struct sysmeminfo));
Colin Crossce85d952014-07-11 17:53:27 -0700473
Nick Kralevichc68c8862015-12-18 20:52:37 -0800474 fd = open(ZONEINFO_PATH, O_RDONLY | O_CLOEXEC);
Colin Crossce85d952014-07-11 17:53:27 -0700475 if (fd == -1) {
Todd Poynor3948f802013-07-09 19:35:14 -0700476 ALOGE("%s open: errno=%d", ZONEINFO_PATH, errno);
477 return -1;
478 }
479
Colin Crossce85d952014-07-11 17:53:27 -0700480 size = read_all(fd, buf, sizeof(buf) - 1);
481 if (size < 0) {
482 ALOGE("%s read: errno=%d", ZONEINFO_PATH, errno);
483 close(fd);
484 return -1;
485 }
486 ALOG_ASSERT((size_t)size < sizeof(buf) - 1, "/proc/zoneinfo too large");
487 buf[size] = 0;
488
489 for (line = strtok_r(buf, "\n", &save_ptr); line; line = strtok_r(NULL, "\n", &save_ptr))
Todd Poynor3948f802013-07-09 19:35:14 -0700490 zoneinfo_parse_line(line, mip);
491
Colin Crossce85d952014-07-11 17:53:27 -0700492 close(fd);
Todd Poynor3948f802013-07-09 19:35:14 -0700493 return 0;
494}
495
496static int proc_get_size(int pid) {
497 char path[PATH_MAX];
498 char line[LINE_MAX];
Colin Crossce85d952014-07-11 17:53:27 -0700499 int fd;
Todd Poynor3948f802013-07-09 19:35:14 -0700500 int rss = 0;
501 int total;
Colin Crossce85d952014-07-11 17:53:27 -0700502 ssize_t ret;
Todd Poynor3948f802013-07-09 19:35:14 -0700503
504 snprintf(path, PATH_MAX, "/proc/%d/statm", pid);
Nick Kralevichc68c8862015-12-18 20:52:37 -0800505 fd = open(path, O_RDONLY | O_CLOEXEC);
Colin Crossce85d952014-07-11 17:53:27 -0700506 if (fd == -1)
Todd Poynor3948f802013-07-09 19:35:14 -0700507 return -1;
Colin Crossce85d952014-07-11 17:53:27 -0700508
509 ret = read_all(fd, line, sizeof(line) - 1);
510 if (ret < 0) {
511 close(fd);
Todd Poynor3948f802013-07-09 19:35:14 -0700512 return -1;
513 }
514
515 sscanf(line, "%d %d ", &total, &rss);
Colin Crossce85d952014-07-11 17:53:27 -0700516 close(fd);
Todd Poynor3948f802013-07-09 19:35:14 -0700517 return rss;
518}
519
520static char *proc_get_name(int pid) {
521 char path[PATH_MAX];
522 static char line[LINE_MAX];
Colin Crossce85d952014-07-11 17:53:27 -0700523 int fd;
Todd Poynor3948f802013-07-09 19:35:14 -0700524 char *cp;
Colin Crossce85d952014-07-11 17:53:27 -0700525 ssize_t ret;
Todd Poynor3948f802013-07-09 19:35:14 -0700526
527 snprintf(path, PATH_MAX, "/proc/%d/cmdline", pid);
Nick Kralevichc68c8862015-12-18 20:52:37 -0800528 fd = open(path, O_RDONLY | O_CLOEXEC);
Colin Crossce85d952014-07-11 17:53:27 -0700529 if (fd == -1)
Todd Poynor3948f802013-07-09 19:35:14 -0700530 return NULL;
Colin Crossce85d952014-07-11 17:53:27 -0700531 ret = read_all(fd, line, sizeof(line) - 1);
532 close(fd);
533 if (ret < 0) {
Todd Poynor3948f802013-07-09 19:35:14 -0700534 return NULL;
535 }
536
537 cp = strchr(line, ' ');
538 if (cp)
539 *cp = '\0';
540
541 return line;
542}
543
544static struct proc *proc_adj_lru(int oomadj) {
545 return (struct proc *)adjslot_tail(&procadjslot_list[ADJTOSLOT(oomadj)]);
546}
547
Colin Cross16b09462014-07-14 12:39:56 -0700548/* Kill one process specified by procp. Returns the size of the process killed */
549static int kill_one_process(struct proc *procp, int other_free, int other_file,
550 int minfree, int min_score_adj, bool first)
551{
552 int pid = procp->pid;
553 uid_t uid = procp->uid;
554 char *taskname;
555 int tasksize;
556 int r;
557
558 taskname = proc_get_name(pid);
559 if (!taskname) {
560 pid_remove(pid);
561 return -1;
562 }
563
564 tasksize = proc_get_size(pid);
565 if (tasksize <= 0) {
566 pid_remove(pid);
567 return -1;
568 }
569
570 ALOGI("Killing '%s' (%d), uid %d, adj %d\n"
571 " to free %ldkB because cache %s%ldkB is below limit %ldkB for oom_adj %d\n"
572 " Free memory is %s%ldkB %s reserved",
573 taskname, pid, uid, procp->oomadj, tasksize * page_k,
574 first ? "" : "~", other_file * page_k, minfree * page_k, min_score_adj,
575 first ? "" : "~", other_free * page_k, other_free >= 0 ? "above" : "below");
576 r = kill(pid, SIGKILL);
577 killProcessGroup(uid, pid, SIGKILL);
578 pid_remove(pid);
579
580 if (r) {
581 ALOGE("kill(%d): errno=%d", procp->pid, errno);
582 return -1;
583 } else {
584 return tasksize;
585 }
586}
587
588/*
589 * Find a process to kill based on the current (possibly estimated) free memory
590 * and cached memory sizes. Returns the size of the killed processes.
591 */
592static int find_and_kill_process(int other_free, int other_file, bool first)
593{
594 int i;
Chong Zhang0a4acdf2015-10-14 16:19:53 -0700595 int min_score_adj = OOM_SCORE_ADJ_MAX + 1;
Colin Cross16b09462014-07-14 12:39:56 -0700596 int minfree = 0;
597 int killed_size = 0;
598
599 for (i = 0; i < lowmem_targets_size; i++) {
600 minfree = lowmem_minfree[i];
601 if (other_free < minfree && other_file < minfree) {
602 min_score_adj = lowmem_adj[i];
603 break;
604 }
605 }
606
Chong Zhang0a4acdf2015-10-14 16:19:53 -0700607 if (min_score_adj == OOM_SCORE_ADJ_MAX + 1)
Colin Cross16b09462014-07-14 12:39:56 -0700608 return 0;
609
Chong Zhang0a4acdf2015-10-14 16:19:53 -0700610 for (i = OOM_SCORE_ADJ_MAX; i >= min_score_adj; i--) {
Colin Cross16b09462014-07-14 12:39:56 -0700611 struct proc *procp;
612
613retry:
614 procp = proc_adj_lru(i);
615
616 if (procp) {
617 killed_size = kill_one_process(procp, other_free, other_file, minfree, min_score_adj, first);
618 if (killed_size < 0) {
619 goto retry;
620 } else {
621 return killed_size;
622 }
623 }
624 }
625
626 return 0;
627}
628
Mark Salyzyne6ed68b2014-04-30 13:36:35 -0700629static void mp_event(uint32_t events __unused) {
Todd Poynor3948f802013-07-09 19:35:14 -0700630 int ret;
631 unsigned long long evcount;
632 struct sysmeminfo mi;
633 int other_free;
634 int other_file;
Colin Cross16b09462014-07-14 12:39:56 -0700635 int killed_size;
636 bool first = true;
Todd Poynor3948f802013-07-09 19:35:14 -0700637
638 ret = read(mpevfd, &evcount, sizeof(evcount));
639 if (ret < 0)
640 ALOGE("Error reading memory pressure event fd; errno=%d",
641 errno);
642
643 if (time(NULL) - kill_lasttime < KILL_TIMEOUT)
644 return;
645
Colin Crossf8857cc2014-07-11 17:16:56 -0700646 while (zoneinfo_parse(&mi) < 0) {
647 // Failed to read /proc/zoneinfo, assume ENOMEM and kill something
648 find_and_kill_process(0, 0, true);
649 }
Todd Poynor3948f802013-07-09 19:35:14 -0700650
651 other_free = mi.nr_free_pages - mi.totalreserve_pages;
652 other_file = mi.nr_file_pages - mi.nr_shmem;
653
Colin Cross16b09462014-07-14 12:39:56 -0700654 do {
655 killed_size = find_and_kill_process(other_free, other_file, first);
656 if (killed_size > 0) {
657 first = false;
658 other_free += killed_size;
659 other_file += killed_size;
Todd Poynor3948f802013-07-09 19:35:14 -0700660 }
Colin Cross16b09462014-07-14 12:39:56 -0700661 } while (killed_size > 0);
Todd Poynor3948f802013-07-09 19:35:14 -0700662}
663
664static int init_mp(char *levelstr, void *event_handler)
665{
666 int mpfd;
667 int evfd;
668 int evctlfd;
669 char buf[256];
670 struct epoll_event epev;
671 int ret;
672
Nick Kralevichc68c8862015-12-18 20:52:37 -0800673 mpfd = open(MEMCG_SYSFS_PATH "memory.pressure_level", O_RDONLY | O_CLOEXEC);
Todd Poynor3948f802013-07-09 19:35:14 -0700674 if (mpfd < 0) {
675 ALOGI("No kernel memory.pressure_level support (errno=%d)", errno);
676 goto err_open_mpfd;
677 }
678
Nick Kralevichc68c8862015-12-18 20:52:37 -0800679 evctlfd = open(MEMCG_SYSFS_PATH "cgroup.event_control", O_WRONLY | O_CLOEXEC);
Todd Poynor3948f802013-07-09 19:35:14 -0700680 if (evctlfd < 0) {
681 ALOGI("No kernel memory cgroup event control (errno=%d)", errno);
682 goto err_open_evctlfd;
683 }
684
Nick Kralevichc68c8862015-12-18 20:52:37 -0800685 evfd = eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC);
Todd Poynor3948f802013-07-09 19:35:14 -0700686 if (evfd < 0) {
687 ALOGE("eventfd failed for level %s; errno=%d", levelstr, errno);
688 goto err_eventfd;
689 }
690
691 ret = snprintf(buf, sizeof(buf), "%d %d %s", evfd, mpfd, levelstr);
692 if (ret >= (ssize_t)sizeof(buf)) {
693 ALOGE("cgroup.event_control line overflow for level %s", levelstr);
694 goto err;
695 }
696
697 ret = write(evctlfd, buf, strlen(buf) + 1);
698 if (ret == -1) {
699 ALOGE("cgroup.event_control write failed for level %s; errno=%d",
700 levelstr, errno);
701 goto err;
702 }
703
704 epev.events = EPOLLIN;
705 epev.data.ptr = event_handler;
706 ret = epoll_ctl(epollfd, EPOLL_CTL_ADD, evfd, &epev);
707 if (ret == -1) {
708 ALOGE("epoll_ctl for level %s failed; errno=%d", levelstr, errno);
709 goto err;
710 }
711 maxevents++;
712 mpevfd = evfd;
713 return 0;
714
715err:
716 close(evfd);
717err_eventfd:
718 close(evctlfd);
719err_open_evctlfd:
720 close(mpfd);
721err_open_mpfd:
722 return -1;
723}
724
725static int init(void) {
726 struct epoll_event epev;
727 int i;
728 int ret;
729
730 page_k = sysconf(_SC_PAGESIZE);
731 if (page_k == -1)
732 page_k = PAGE_SIZE;
733 page_k /= 1024;
734
735 epollfd = epoll_create(MAX_EPOLL_EVENTS);
736 if (epollfd == -1) {
737 ALOGE("epoll_create failed (errno=%d)", errno);
738 return -1;
739 }
740
741 ctrl_lfd = android_get_control_socket("lmkd");
742 if (ctrl_lfd < 0) {
743 ALOGE("get lmkd control socket failed");
744 return -1;
745 }
746
747 ret = listen(ctrl_lfd, 1);
748 if (ret < 0) {
749 ALOGE("lmkd control socket listen failed (errno=%d)", errno);
750 return -1;
751 }
752
753 epev.events = EPOLLIN;
754 epev.data.ptr = (void *)ctrl_connect_handler;
755 if (epoll_ctl(epollfd, EPOLL_CTL_ADD, ctrl_lfd, &epev) == -1) {
756 ALOGE("epoll_ctl for lmkd control socket failed (errno=%d)", errno);
757 return -1;
758 }
759 maxevents++;
760
761 use_inkernel_interface = !access(INKERNEL_MINFREE_PATH, W_OK);
762
763 if (use_inkernel_interface) {
764 ALOGI("Using in-kernel low memory killer interface");
765 } else {
766 ret = init_mp(MEMPRESSURE_WATCH_LEVEL, (void *)&mp_event);
767 if (ret)
768 ALOGE("Kernel does not support memory pressure events or in-kernel low memory killer");
769 }
770
Chong Zhang0a4acdf2015-10-14 16:19:53 -0700771 for (i = 0; i <= ADJTOSLOT(OOM_SCORE_ADJ_MAX); i++) {
Todd Poynor3948f802013-07-09 19:35:14 -0700772 procadjslot_list[i].next = &procadjslot_list[i];
773 procadjslot_list[i].prev = &procadjslot_list[i];
774 }
775
776 return 0;
777}
778
779static void mainloop(void) {
780 while (1) {
781 struct epoll_event events[maxevents];
782 int nevents;
783 int i;
784
785 ctrl_dfd_reopened = 0;
786 nevents = epoll_wait(epollfd, events, maxevents, -1);
787
788 if (nevents == -1) {
789 if (errno == EINTR)
790 continue;
791 ALOGE("epoll_wait failed (errno=%d)", errno);
792 continue;
793 }
794
795 for (i = 0; i < nevents; ++i) {
796 if (events[i].events & EPOLLERR)
797 ALOGD("EPOLLERR on event #%d", i);
798 if (events[i].data.ptr)
799 (*(void (*)(uint32_t))events[i].data.ptr)(events[i].events);
800 }
801 }
802}
803
Mark Salyzyne6ed68b2014-04-30 13:36:35 -0700804int main(int argc __unused, char **argv __unused) {
Colin Cross1a0d9be2014-07-14 14:31:15 -0700805 struct sched_param param = {
806 .sched_priority = 1,
807 };
808
Colin Crossb28ff912014-07-11 17:15:44 -0700809 mlockall(MCL_FUTURE);
Colin Cross1a0d9be2014-07-14 14:31:15 -0700810 sched_setscheduler(0, SCHED_FIFO, &param);
Todd Poynor3948f802013-07-09 19:35:14 -0700811 if (!init())
812 mainloop();
813
814 ALOGI("exiting");
815 return 0;
816}