blob: 7bbc81119514c0ade2d540d082e008d78e6f22b3 [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>
21#include <signal.h>
Todd Poynor3948f802013-07-09 19:35:14 -070022#include <stdlib.h>
23#include <string.h>
24#include <time.h>
Mark Salyzyne6ed68b2014-04-30 13:36:35 -070025#include <sys/cdefs.h>
Todd Poynor3948f802013-07-09 19:35:14 -070026#include <sys/epoll.h>
27#include <sys/eventfd.h>
Colin Crossb28ff912014-07-11 17:15:44 -070028#include <sys/mman.h>
Todd Poynor3948f802013-07-09 19:35:14 -070029#include <sys/socket.h>
30#include <sys/types.h>
Mark Salyzyne6ed68b2014-04-30 13:36:35 -070031#include <unistd.h>
32
Todd Poynor3948f802013-07-09 19:35:14 -070033#include <cutils/sockets.h>
Mark Salyzyne6ed68b2014-04-30 13:36:35 -070034#include <log/log.h>
Colin Crossfef95222014-06-11 14:53:41 -070035#include <processgroup/processgroup.h>
Mark Salyzyne6ed68b2014-04-30 13:36:35 -070036
37#ifndef __unused
38#define __unused __attribute__((__unused__))
39#endif
Todd Poynor3948f802013-07-09 19:35:14 -070040
41#define MEMCG_SYSFS_PATH "/dev/memcg/"
42#define MEMPRESSURE_WATCH_LEVEL "medium"
43#define ZONEINFO_PATH "/proc/zoneinfo"
44#define LINE_MAX 128
45
46#define INKERNEL_MINFREE_PATH "/sys/module/lowmemorykiller/parameters/minfree"
47#define INKERNEL_ADJ_PATH "/sys/module/lowmemorykiller/parameters/adj"
48
49#define ARRAY_SIZE(x) (sizeof(x) / sizeof(*(x)))
50
51enum lmk_cmd {
52 LMK_TARGET,
53 LMK_PROCPRIO,
54 LMK_PROCREMOVE,
55};
56
57#define MAX_TARGETS 6
58/*
59 * longest is LMK_TARGET followed by MAX_TARGETS each minfree and minkillprio
60 * values
61 */
62#define CTRL_PACKET_MAX (sizeof(int) * (MAX_TARGETS * 2 + 1))
63
64/* default to old in-kernel interface if no memory pressure events */
65static int use_inkernel_interface = 1;
66
67/* memory pressure level medium event */
68static int mpevfd;
69
70/* control socket listen and data */
71static int ctrl_lfd;
72static int ctrl_dfd = -1;
73static int ctrl_dfd_reopened; /* did we reopen ctrl conn on this loop? */
74
75/* 1 memory pressure level, 1 ctrl listen socket, 1 ctrl data socket */
76#define MAX_EPOLL_EVENTS 3
77static int epollfd;
78static int maxevents;
79
80#define OOM_DISABLE (-17)
81/* inclusive */
82#define OOM_ADJUST_MIN (-16)
83#define OOM_ADJUST_MAX 15
84
Todd Poynor16b60992013-09-16 19:26:47 -070085/* kernel OOM score values */
86#define OOM_SCORE_ADJ_MIN (-1000)
87#define OOM_SCORE_ADJ_MAX 1000
88
Todd Poynor3948f802013-07-09 19:35:14 -070089static int lowmem_adj[MAX_TARGETS];
90static int lowmem_minfree[MAX_TARGETS];
91static int lowmem_targets_size;
92
93struct sysmeminfo {
94 int nr_free_pages;
95 int nr_file_pages;
96 int nr_shmem;
97 int totalreserve_pages;
98};
99
100struct adjslot_list {
101 struct adjslot_list *next;
102 struct adjslot_list *prev;
103};
104
105struct proc {
106 struct adjslot_list asl;
107 int pid;
Colin Crossfbb78c62014-06-13 14:52:43 -0700108 uid_t uid;
Todd Poynor3948f802013-07-09 19:35:14 -0700109 int oomadj;
110 struct proc *pidhash_next;
111};
112
113#define PIDHASH_SZ 1024
114static struct proc *pidhash[PIDHASH_SZ];
115#define pid_hashfn(x) ((((x) >> 8) ^ (x)) & (PIDHASH_SZ - 1))
116
117#define ADJTOSLOT(adj) (adj + -OOM_ADJUST_MIN)
118static struct adjslot_list procadjslot_list[ADJTOSLOT(OOM_ADJUST_MAX) + 1];
119
120/*
121 * Wait 1-2 seconds for the death report of a killed process prior to
122 * considering killing more processes.
123 */
124#define KILL_TIMEOUT 2
125/* Time of last process kill we initiated, stop me before I kill again */
126static time_t kill_lasttime;
127
128/* PAGE_SIZE / 1024 */
129static long page_k;
130
Colin Crossce85d952014-07-11 17:53:27 -0700131static ssize_t read_all(int fd, char *buf, size_t max_len)
132{
133 ssize_t ret = 0;
134
135 while (max_len > 0) {
136 ssize_t r = read(fd, buf, max_len);
137 if (r == 0) {
138 break;
139 }
140 if (r == -1) {
141 return -1;
142 }
143 ret += r;
144 buf += r;
145 max_len -= r;
146 }
147
148 return ret;
149}
150
Todd Poynor16b60992013-09-16 19:26:47 -0700151static int lowmem_oom_adj_to_oom_score_adj(int oom_adj)
152{
153 if (oom_adj == OOM_ADJUST_MAX)
154 return OOM_SCORE_ADJ_MAX;
155 else
156 return (oom_adj * OOM_SCORE_ADJ_MAX) / -OOM_DISABLE;
157}
158
Todd Poynor3948f802013-07-09 19:35:14 -0700159static struct proc *pid_lookup(int pid) {
160 struct proc *procp;
161
162 for (procp = pidhash[pid_hashfn(pid)]; procp && procp->pid != pid;
163 procp = procp->pidhash_next)
164 ;
165
166 return procp;
167}
168
169static void adjslot_insert(struct adjslot_list *head, struct adjslot_list *new)
170{
171 struct adjslot_list *next = head->next;
172 new->prev = head;
173 new->next = next;
174 next->prev = new;
175 head->next = new;
176}
177
178static void adjslot_remove(struct adjslot_list *old)
179{
180 struct adjslot_list *prev = old->prev;
181 struct adjslot_list *next = old->next;
182 next->prev = prev;
183 prev->next = next;
184}
185
186static struct adjslot_list *adjslot_tail(struct adjslot_list *head) {
187 struct adjslot_list *asl = head->prev;
188
189 return asl == head ? NULL : asl;
190}
191
192static void proc_slot(struct proc *procp) {
193 int adjslot = ADJTOSLOT(procp->oomadj);
194
195 adjslot_insert(&procadjslot_list[adjslot], &procp->asl);
196}
197
198static void proc_unslot(struct proc *procp) {
199 adjslot_remove(&procp->asl);
200}
201
202static void proc_insert(struct proc *procp) {
203 int hval = pid_hashfn(procp->pid);
204
205 procp->pidhash_next = pidhash[hval];
206 pidhash[hval] = procp;
207 proc_slot(procp);
208}
209
210static int pid_remove(int pid) {
211 int hval = pid_hashfn(pid);
212 struct proc *procp;
213 struct proc *prevp;
214
215 for (procp = pidhash[hval], prevp = NULL; procp && procp->pid != pid;
216 procp = procp->pidhash_next)
217 prevp = procp;
218
219 if (!procp)
220 return -1;
221
222 if (!prevp)
223 pidhash[hval] = procp->pidhash_next;
224 else
225 prevp->pidhash_next = procp->pidhash_next;
226
227 proc_unslot(procp);
228 free(procp);
229 return 0;
230}
231
232static void writefilestring(char *path, char *s) {
233 int fd = open(path, O_WRONLY);
234 int len = strlen(s);
235 int ret;
236
237 if (fd < 0) {
238 ALOGE("Error opening %s; errno=%d", path, errno);
239 return;
240 }
241
242 ret = write(fd, s, len);
243 if (ret < 0) {
244 ALOGE("Error writing %s; errno=%d", path, errno);
245 } else if (ret < len) {
246 ALOGE("Short write on %s; length=%d", path, ret);
247 }
248
249 close(fd);
250}
251
Colin Crossfbb78c62014-06-13 14:52:43 -0700252static void cmd_procprio(int pid, int uid, int oomadj) {
Todd Poynor3948f802013-07-09 19:35:14 -0700253 struct proc *procp;
254 char path[80];
255 char val[20];
256
257 if (oomadj < OOM_DISABLE || oomadj > OOM_ADJUST_MAX) {
258 ALOGE("Invalid PROCPRIO oomadj argument %d", oomadj);
259 return;
260 }
261
Todd Poynor16b60992013-09-16 19:26:47 -0700262 snprintf(path, sizeof(path), "/proc/%d/oom_score_adj", pid);
263 snprintf(val, sizeof(val), "%d", lowmem_oom_adj_to_oom_score_adj(oomadj));
Todd Poynor3948f802013-07-09 19:35:14 -0700264 writefilestring(path, val);
265
266 if (use_inkernel_interface)
267 return;
268
269 procp = pid_lookup(pid);
270 if (!procp) {
271 procp = malloc(sizeof(struct proc));
272 if (!procp) {
273 // Oh, the irony. May need to rebuild our state.
274 return;
275 }
276
277 procp->pid = pid;
Colin Crossfbb78c62014-06-13 14:52:43 -0700278 procp->uid = uid;
Todd Poynor3948f802013-07-09 19:35:14 -0700279 procp->oomadj = oomadj;
280 proc_insert(procp);
281 } else {
282 proc_unslot(procp);
283 procp->oomadj = oomadj;
284 proc_slot(procp);
285 }
286}
287
288static void cmd_procremove(int pid) {
Todd Poynor3948f802013-07-09 19:35:14 -0700289 if (use_inkernel_interface)
290 return;
291
292 pid_remove(pid);
293 kill_lasttime = 0;
294}
295
296static void cmd_target(int ntargets, int *params) {
297 int i;
298
299 if (ntargets > (int)ARRAY_SIZE(lowmem_adj))
300 return;
301
302 for (i = 0; i < ntargets; i++) {
303 lowmem_minfree[i] = ntohl(*params++);
304 lowmem_adj[i] = ntohl(*params++);
305 }
306
307 lowmem_targets_size = ntargets;
308
309 if (use_inkernel_interface) {
310 char minfreestr[128];
311 char killpriostr[128];
312
313 minfreestr[0] = '\0';
314 killpriostr[0] = '\0';
315
316 for (i = 0; i < lowmem_targets_size; i++) {
317 char val[40];
318
319 if (i) {
320 strlcat(minfreestr, ",", sizeof(minfreestr));
321 strlcat(killpriostr, ",", sizeof(killpriostr));
322 }
323
324 snprintf(val, sizeof(val), "%d", lowmem_minfree[i]);
325 strlcat(minfreestr, val, sizeof(minfreestr));
326 snprintf(val, sizeof(val), "%d", lowmem_adj[i]);
327 strlcat(killpriostr, val, sizeof(killpriostr));
328 }
329
330 writefilestring(INKERNEL_MINFREE_PATH, minfreestr);
331 writefilestring(INKERNEL_ADJ_PATH, killpriostr);
332 }
333}
334
335static void ctrl_data_close(void) {
336 ALOGI("Closing Activity Manager data connection");
337 close(ctrl_dfd);
338 ctrl_dfd = -1;
339 maxevents--;
340}
341
342static int ctrl_data_read(char *buf, size_t bufsz) {
343 int ret = 0;
344
345 ret = read(ctrl_dfd, buf, bufsz);
346
347 if (ret == -1) {
348 ALOGE("control data socket read failed; errno=%d", errno);
349 } else if (ret == 0) {
350 ALOGE("Got EOF on control data socket");
351 ret = -1;
352 }
353
354 return ret;
355}
356
357static void ctrl_command_handler(void) {
358 int ibuf[CTRL_PACKET_MAX / sizeof(int)];
359 int len;
360 int cmd = -1;
361 int nargs;
362 int targets;
363
364 len = ctrl_data_read((char *)ibuf, CTRL_PACKET_MAX);
365 if (len <= 0)
366 return;
367
368 nargs = len / sizeof(int) - 1;
369 if (nargs < 0)
370 goto wronglen;
371
372 cmd = ntohl(ibuf[0]);
373
374 switch(cmd) {
375 case LMK_TARGET:
376 targets = nargs / 2;
377 if (nargs & 0x1 || targets > (int)ARRAY_SIZE(lowmem_adj))
378 goto wronglen;
379 cmd_target(targets, &ibuf[1]);
380 break;
381 case LMK_PROCPRIO:
Colin Crossfbb78c62014-06-13 14:52:43 -0700382 if (nargs != 3)
Todd Poynor3948f802013-07-09 19:35:14 -0700383 goto wronglen;
Colin Crossfbb78c62014-06-13 14:52:43 -0700384 cmd_procprio(ntohl(ibuf[1]), ntohl(ibuf[2]), ntohl(ibuf[3]));
Todd Poynor3948f802013-07-09 19:35:14 -0700385 break;
386 case LMK_PROCREMOVE:
387 if (nargs != 1)
388 goto wronglen;
389 cmd_procremove(ntohl(ibuf[1]));
390 break;
391 default:
392 ALOGE("Received unknown command code %d", cmd);
393 return;
394 }
395
396 return;
397
398wronglen:
399 ALOGE("Wrong control socket read length cmd=%d len=%d", cmd, len);
400}
401
402static void ctrl_data_handler(uint32_t events) {
403 if (events & EPOLLHUP) {
404 ALOGI("ActivityManager disconnected");
405 if (!ctrl_dfd_reopened)
406 ctrl_data_close();
407 } else if (events & EPOLLIN) {
408 ctrl_command_handler();
409 }
410}
411
Mark Salyzyne6ed68b2014-04-30 13:36:35 -0700412static void ctrl_connect_handler(uint32_t events __unused) {
Todd Poynor3948f802013-07-09 19:35:14 -0700413 struct sockaddr addr;
414 socklen_t alen;
415 struct epoll_event epev;
416
417 if (ctrl_dfd >= 0) {
418 ctrl_data_close();
419 ctrl_dfd_reopened = 1;
420 }
421
422 alen = sizeof(addr);
423 ctrl_dfd = accept(ctrl_lfd, &addr, &alen);
424
425 if (ctrl_dfd < 0) {
426 ALOGE("lmkd control socket accept failed; errno=%d", errno);
427 return;
428 }
429
430 ALOGI("ActivityManager connected");
431 maxevents++;
432 epev.events = EPOLLIN;
433 epev.data.ptr = (void *)ctrl_data_handler;
434 if (epoll_ctl(epollfd, EPOLL_CTL_ADD, ctrl_dfd, &epev) == -1) {
435 ALOGE("epoll_ctl for data connection socket failed; errno=%d", errno);
436 ctrl_data_close();
437 return;
438 }
439}
440
441static int zoneinfo_parse_protection(char *cp) {
442 int max = 0;
443 int zoneval;
Colin Crossce85d952014-07-11 17:53:27 -0700444 char *save_ptr;
Todd Poynor3948f802013-07-09 19:35:14 -0700445
Colin Crossce85d952014-07-11 17:53:27 -0700446 for (cp = strtok_r(cp, "(), ", &save_ptr); cp; cp = strtok_r(NULL, "), ", &save_ptr)) {
Todd Poynor3948f802013-07-09 19:35:14 -0700447 zoneval = strtol(cp, &cp, 0);
Todd Poynor3948f802013-07-09 19:35:14 -0700448 if (zoneval > max)
449 max = zoneval;
Colin Crossce85d952014-07-11 17:53:27 -0700450 }
Todd Poynor3948f802013-07-09 19:35:14 -0700451
452 return max;
453}
454
455static void zoneinfo_parse_line(char *line, struct sysmeminfo *mip) {
456 char *cp = line;
457 char *ap;
Colin Crossce85d952014-07-11 17:53:27 -0700458 char *save_ptr;
Todd Poynor3948f802013-07-09 19:35:14 -0700459
Colin Crossce85d952014-07-11 17:53:27 -0700460 cp = strtok_r(line, " ", &save_ptr);
Todd Poynor3948f802013-07-09 19:35:14 -0700461 if (!cp)
462 return;
463
Colin Crossce85d952014-07-11 17:53:27 -0700464 ap = strtok_r(NULL, " ", &save_ptr);
Todd Poynor3948f802013-07-09 19:35:14 -0700465 if (!ap)
466 return;
467
468 if (!strcmp(cp, "nr_free_pages"))
469 mip->nr_free_pages += strtol(ap, NULL, 0);
470 else if (!strcmp(cp, "nr_file_pages"))
471 mip->nr_file_pages += strtol(ap, NULL, 0);
472 else if (!strcmp(cp, "nr_shmem"))
473 mip->nr_shmem += strtol(ap, NULL, 0);
474 else if (!strcmp(cp, "high"))
475 mip->totalreserve_pages += strtol(ap, NULL, 0);
476 else if (!strcmp(cp, "protection:"))
477 mip->totalreserve_pages += zoneinfo_parse_protection(ap);
478}
479
480static int zoneinfo_parse(struct sysmeminfo *mip) {
Colin Crossce85d952014-07-11 17:53:27 -0700481 int fd;
482 ssize_t size;
483 char buf[PAGE_SIZE];
484 char *save_ptr;
485 char *line;
Todd Poynor3948f802013-07-09 19:35:14 -0700486
487 memset(mip, 0, sizeof(struct sysmeminfo));
Colin Crossce85d952014-07-11 17:53:27 -0700488
489 fd = open(ZONEINFO_PATH, O_RDONLY);
490 if (fd == -1) {
Todd Poynor3948f802013-07-09 19:35:14 -0700491 ALOGE("%s open: errno=%d", ZONEINFO_PATH, errno);
492 return -1;
493 }
494
Colin Crossce85d952014-07-11 17:53:27 -0700495 size = read_all(fd, buf, sizeof(buf) - 1);
496 if (size < 0) {
497 ALOGE("%s read: errno=%d", ZONEINFO_PATH, errno);
498 close(fd);
499 return -1;
500 }
501 ALOG_ASSERT((size_t)size < sizeof(buf) - 1, "/proc/zoneinfo too large");
502 buf[size] = 0;
503
504 for (line = strtok_r(buf, "\n", &save_ptr); line; line = strtok_r(NULL, "\n", &save_ptr))
Todd Poynor3948f802013-07-09 19:35:14 -0700505 zoneinfo_parse_line(line, mip);
506
Colin Crossce85d952014-07-11 17:53:27 -0700507 close(fd);
Todd Poynor3948f802013-07-09 19:35:14 -0700508 return 0;
509}
510
511static int proc_get_size(int pid) {
512 char path[PATH_MAX];
513 char line[LINE_MAX];
Colin Crossce85d952014-07-11 17:53:27 -0700514 int fd;
Todd Poynor3948f802013-07-09 19:35:14 -0700515 int rss = 0;
516 int total;
Colin Crossce85d952014-07-11 17:53:27 -0700517 ssize_t ret;
Todd Poynor3948f802013-07-09 19:35:14 -0700518
519 snprintf(path, PATH_MAX, "/proc/%d/statm", pid);
Colin Crossce85d952014-07-11 17:53:27 -0700520 fd = open(path, O_RDONLY);
521 if (fd == -1)
Todd Poynor3948f802013-07-09 19:35:14 -0700522 return -1;
Colin Crossce85d952014-07-11 17:53:27 -0700523
524 ret = read_all(fd, line, sizeof(line) - 1);
525 if (ret < 0) {
526 close(fd);
Todd Poynor3948f802013-07-09 19:35:14 -0700527 return -1;
528 }
529
530 sscanf(line, "%d %d ", &total, &rss);
Colin Crossce85d952014-07-11 17:53:27 -0700531 close(fd);
Todd Poynor3948f802013-07-09 19:35:14 -0700532 return rss;
533}
534
535static char *proc_get_name(int pid) {
536 char path[PATH_MAX];
537 static char line[LINE_MAX];
Colin Crossce85d952014-07-11 17:53:27 -0700538 int fd;
Todd Poynor3948f802013-07-09 19:35:14 -0700539 char *cp;
Colin Crossce85d952014-07-11 17:53:27 -0700540 ssize_t ret;
Todd Poynor3948f802013-07-09 19:35:14 -0700541
542 snprintf(path, PATH_MAX, "/proc/%d/cmdline", pid);
Colin Crossce85d952014-07-11 17:53:27 -0700543 fd = open(path, O_RDONLY);
544 if (fd == -1)
Todd Poynor3948f802013-07-09 19:35:14 -0700545 return NULL;
Colin Crossce85d952014-07-11 17:53:27 -0700546 ret = read_all(fd, line, sizeof(line) - 1);
547 close(fd);
548 if (ret < 0) {
Todd Poynor3948f802013-07-09 19:35:14 -0700549 return NULL;
550 }
551
552 cp = strchr(line, ' ');
553 if (cp)
554 *cp = '\0';
555
556 return line;
557}
558
559static struct proc *proc_adj_lru(int oomadj) {
560 return (struct proc *)adjslot_tail(&procadjslot_list[ADJTOSLOT(oomadj)]);
561}
562
Colin Cross16b09462014-07-14 12:39:56 -0700563/* Kill one process specified by procp. Returns the size of the process killed */
564static int kill_one_process(struct proc *procp, int other_free, int other_file,
565 int minfree, int min_score_adj, bool first)
566{
567 int pid = procp->pid;
568 uid_t uid = procp->uid;
569 char *taskname;
570 int tasksize;
571 int r;
572
573 taskname = proc_get_name(pid);
574 if (!taskname) {
575 pid_remove(pid);
576 return -1;
577 }
578
579 tasksize = proc_get_size(pid);
580 if (tasksize <= 0) {
581 pid_remove(pid);
582 return -1;
583 }
584
585 ALOGI("Killing '%s' (%d), uid %d, adj %d\n"
586 " to free %ldkB because cache %s%ldkB is below limit %ldkB for oom_adj %d\n"
587 " Free memory is %s%ldkB %s reserved",
588 taskname, pid, uid, procp->oomadj, tasksize * page_k,
589 first ? "" : "~", other_file * page_k, minfree * page_k, min_score_adj,
590 first ? "" : "~", other_free * page_k, other_free >= 0 ? "above" : "below");
591 r = kill(pid, SIGKILL);
592 killProcessGroup(uid, pid, SIGKILL);
593 pid_remove(pid);
594
595 if (r) {
596 ALOGE("kill(%d): errno=%d", procp->pid, errno);
597 return -1;
598 } else {
599 return tasksize;
600 }
601}
602
603/*
604 * Find a process to kill based on the current (possibly estimated) free memory
605 * and cached memory sizes. Returns the size of the killed processes.
606 */
607static int find_and_kill_process(int other_free, int other_file, bool first)
608{
609 int i;
Colin Cross16b09462014-07-14 12:39:56 -0700610 int min_score_adj = OOM_ADJUST_MAX + 1;
611 int minfree = 0;
612 int killed_size = 0;
613
614 for (i = 0; i < lowmem_targets_size; i++) {
615 minfree = lowmem_minfree[i];
616 if (other_free < minfree && other_file < minfree) {
617 min_score_adj = lowmem_adj[i];
618 break;
619 }
620 }
621
622 if (min_score_adj == OOM_ADJUST_MAX + 1)
623 return 0;
624
625 for (i = OOM_ADJUST_MAX; i >= min_score_adj; i--) {
626 struct proc *procp;
627
628retry:
629 procp = proc_adj_lru(i);
630
631 if (procp) {
632 killed_size = kill_one_process(procp, other_free, other_file, minfree, min_score_adj, first);
633 if (killed_size < 0) {
634 goto retry;
635 } else {
636 return killed_size;
637 }
638 }
639 }
640
641 return 0;
642}
643
Mark Salyzyne6ed68b2014-04-30 13:36:35 -0700644static void mp_event(uint32_t events __unused) {
Todd Poynor3948f802013-07-09 19:35:14 -0700645 int ret;
646 unsigned long long evcount;
647 struct sysmeminfo mi;
648 int other_free;
649 int other_file;
Colin Cross16b09462014-07-14 12:39:56 -0700650 int killed_size;
651 bool first = true;
Todd Poynor3948f802013-07-09 19:35:14 -0700652
653 ret = read(mpevfd, &evcount, sizeof(evcount));
654 if (ret < 0)
655 ALOGE("Error reading memory pressure event fd; errno=%d",
656 errno);
657
658 if (time(NULL) - kill_lasttime < KILL_TIMEOUT)
659 return;
660
Colin Crossf8857cc2014-07-11 17:16:56 -0700661 while (zoneinfo_parse(&mi) < 0) {
662 // Failed to read /proc/zoneinfo, assume ENOMEM and kill something
663 find_and_kill_process(0, 0, true);
664 }
Todd Poynor3948f802013-07-09 19:35:14 -0700665
666 other_free = mi.nr_free_pages - mi.totalreserve_pages;
667 other_file = mi.nr_file_pages - mi.nr_shmem;
668
Colin Cross16b09462014-07-14 12:39:56 -0700669 do {
670 killed_size = find_and_kill_process(other_free, other_file, first);
671 if (killed_size > 0) {
672 first = false;
673 other_free += killed_size;
674 other_file += killed_size;
Todd Poynor3948f802013-07-09 19:35:14 -0700675 }
Colin Cross16b09462014-07-14 12:39:56 -0700676 } while (killed_size > 0);
Todd Poynor3948f802013-07-09 19:35:14 -0700677}
678
679static int init_mp(char *levelstr, void *event_handler)
680{
681 int mpfd;
682 int evfd;
683 int evctlfd;
684 char buf[256];
685 struct epoll_event epev;
686 int ret;
687
688 mpfd = open(MEMCG_SYSFS_PATH "memory.pressure_level", O_RDONLY);
689 if (mpfd < 0) {
690 ALOGI("No kernel memory.pressure_level support (errno=%d)", errno);
691 goto err_open_mpfd;
692 }
693
694 evctlfd = open(MEMCG_SYSFS_PATH "cgroup.event_control", O_WRONLY);
695 if (evctlfd < 0) {
696 ALOGI("No kernel memory cgroup event control (errno=%d)", errno);
697 goto err_open_evctlfd;
698 }
699
700 evfd = eventfd(0, EFD_NONBLOCK);
701 if (evfd < 0) {
702 ALOGE("eventfd failed for level %s; errno=%d", levelstr, errno);
703 goto err_eventfd;
704 }
705
706 ret = snprintf(buf, sizeof(buf), "%d %d %s", evfd, mpfd, levelstr);
707 if (ret >= (ssize_t)sizeof(buf)) {
708 ALOGE("cgroup.event_control line overflow for level %s", levelstr);
709 goto err;
710 }
711
712 ret = write(evctlfd, buf, strlen(buf) + 1);
713 if (ret == -1) {
714 ALOGE("cgroup.event_control write failed for level %s; errno=%d",
715 levelstr, errno);
716 goto err;
717 }
718
719 epev.events = EPOLLIN;
720 epev.data.ptr = event_handler;
721 ret = epoll_ctl(epollfd, EPOLL_CTL_ADD, evfd, &epev);
722 if (ret == -1) {
723 ALOGE("epoll_ctl for level %s failed; errno=%d", levelstr, errno);
724 goto err;
725 }
726 maxevents++;
727 mpevfd = evfd;
728 return 0;
729
730err:
731 close(evfd);
732err_eventfd:
733 close(evctlfd);
734err_open_evctlfd:
735 close(mpfd);
736err_open_mpfd:
737 return -1;
738}
739
740static int init(void) {
741 struct epoll_event epev;
742 int i;
743 int ret;
744
745 page_k = sysconf(_SC_PAGESIZE);
746 if (page_k == -1)
747 page_k = PAGE_SIZE;
748 page_k /= 1024;
749
750 epollfd = epoll_create(MAX_EPOLL_EVENTS);
751 if (epollfd == -1) {
752 ALOGE("epoll_create failed (errno=%d)", errno);
753 return -1;
754 }
755
756 ctrl_lfd = android_get_control_socket("lmkd");
757 if (ctrl_lfd < 0) {
758 ALOGE("get lmkd control socket failed");
759 return -1;
760 }
761
762 ret = listen(ctrl_lfd, 1);
763 if (ret < 0) {
764 ALOGE("lmkd control socket listen failed (errno=%d)", errno);
765 return -1;
766 }
767
768 epev.events = EPOLLIN;
769 epev.data.ptr = (void *)ctrl_connect_handler;
770 if (epoll_ctl(epollfd, EPOLL_CTL_ADD, ctrl_lfd, &epev) == -1) {
771 ALOGE("epoll_ctl for lmkd control socket failed (errno=%d)", errno);
772 return -1;
773 }
774 maxevents++;
775
776 use_inkernel_interface = !access(INKERNEL_MINFREE_PATH, W_OK);
777
778 if (use_inkernel_interface) {
779 ALOGI("Using in-kernel low memory killer interface");
780 } else {
781 ret = init_mp(MEMPRESSURE_WATCH_LEVEL, (void *)&mp_event);
782 if (ret)
783 ALOGE("Kernel does not support memory pressure events or in-kernel low memory killer");
784 }
785
786 for (i = 0; i <= ADJTOSLOT(OOM_ADJUST_MAX); i++) {
787 procadjslot_list[i].next = &procadjslot_list[i];
788 procadjslot_list[i].prev = &procadjslot_list[i];
789 }
790
791 return 0;
792}
793
794static void mainloop(void) {
795 while (1) {
796 struct epoll_event events[maxevents];
797 int nevents;
798 int i;
799
800 ctrl_dfd_reopened = 0;
801 nevents = epoll_wait(epollfd, events, maxevents, -1);
802
803 if (nevents == -1) {
804 if (errno == EINTR)
805 continue;
806 ALOGE("epoll_wait failed (errno=%d)", errno);
807 continue;
808 }
809
810 for (i = 0; i < nevents; ++i) {
811 if (events[i].events & EPOLLERR)
812 ALOGD("EPOLLERR on event #%d", i);
813 if (events[i].data.ptr)
814 (*(void (*)(uint32_t))events[i].data.ptr)(events[i].events);
815 }
816 }
817}
818
Mark Salyzyne6ed68b2014-04-30 13:36:35 -0700819int main(int argc __unused, char **argv __unused) {
Colin Cross1a0d9be2014-07-14 14:31:15 -0700820 struct sched_param param = {
821 .sched_priority = 1,
822 };
823
Colin Crossb28ff912014-07-11 17:15:44 -0700824 mlockall(MCL_FUTURE);
Colin Cross1a0d9be2014-07-14 14:31:15 -0700825 sched_setscheduler(0, SCHED_FIFO, &param);
Todd Poynor3948f802013-07-09 19:35:14 -0700826 if (!init())
827 mainloop();
828
829 ALOGI("exiting");
830 return 0;
831}