blob: 02a9601f97f4197f69e823114aba90543c30a048 [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
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>
Colin Crossfef95222014-06-11 14:53:41 -070037#include <processgroup/processgroup.h>
Mark Salyzyne6ed68b2014-04-30 13:36:35 -070038
39#ifndef __unused
40#define __unused __attribute__((__unused__))
41#endif
Todd Poynor3948f802013-07-09 19:35:14 -070042
43#define MEMCG_SYSFS_PATH "/dev/memcg/"
Robert Benea673e2762017-06-01 16:32:31 -070044#define MEMPRESSURE_WATCH_MEDIUM_LEVEL "medium"
45#define MEMPRESSURE_WATCH_CRITICAL_LEVEL "critical"
Todd Poynor3948f802013-07-09 19:35:14 -070046#define ZONEINFO_PATH "/proc/zoneinfo"
47#define LINE_MAX 128
48
49#define INKERNEL_MINFREE_PATH "/sys/module/lowmemorykiller/parameters/minfree"
50#define INKERNEL_ADJ_PATH "/sys/module/lowmemorykiller/parameters/adj"
51
52#define ARRAY_SIZE(x) (sizeof(x) / sizeof(*(x)))
Robert Benea673e2762017-06-01 16:32:31 -070053#define EIGHT_MEGA (1 << 23)
Todd Poynor3948f802013-07-09 19:35:14 -070054
55enum lmk_cmd {
56 LMK_TARGET,
57 LMK_PROCPRIO,
58 LMK_PROCREMOVE,
59};
60
61#define MAX_TARGETS 6
62/*
63 * longest is LMK_TARGET followed by MAX_TARGETS each minfree and minkillprio
64 * values
65 */
66#define CTRL_PACKET_MAX (sizeof(int) * (MAX_TARGETS * 2 + 1))
67
68/* default to old in-kernel interface if no memory pressure events */
69static int use_inkernel_interface = 1;
70
71/* memory pressure level medium event */
Robert Benea673e2762017-06-01 16:32:31 -070072static int mpevfd[2];
73#define CRITICAL_INDEX 1
74#define MEDIUM_INDEX 0
Todd Poynor3948f802013-07-09 19:35:14 -070075
Robert Benea58891d52017-07-31 17:15:20 -070076static int medium_oomadj;
77static int critical_oomadj;
Robert Beneacaeaa652017-08-11 16:03:20 -070078static int debug_process_killing;
Robert Benea58891d52017-07-31 17:15:20 -070079
Todd Poynor3948f802013-07-09 19:35:14 -070080/* control socket listen and data */
81static int ctrl_lfd;
82static int ctrl_dfd = -1;
83static int ctrl_dfd_reopened; /* did we reopen ctrl conn on this loop? */
84
Robert Benea673e2762017-06-01 16:32:31 -070085/* 2 memory pressure levels, 1 ctrl listen socket, 1 ctrl data socket */
86#define MAX_EPOLL_EVENTS 4
Todd Poynor3948f802013-07-09 19:35:14 -070087static int epollfd;
88static int maxevents;
89
Chong Zhang0a4acdf2015-10-14 16:19:53 -070090/* OOM score values used by both kernel and framework */
Todd Poynor16b60992013-09-16 19:26:47 -070091#define OOM_SCORE_ADJ_MIN (-1000)
92#define OOM_SCORE_ADJ_MAX 1000
93
Todd Poynor3948f802013-07-09 19:35:14 -070094static int lowmem_adj[MAX_TARGETS];
95static int lowmem_minfree[MAX_TARGETS];
96static int lowmem_targets_size;
97
98struct sysmeminfo {
99 int nr_free_pages;
100 int nr_file_pages;
101 int nr_shmem;
102 int totalreserve_pages;
103};
104
105struct adjslot_list {
106 struct adjslot_list *next;
107 struct adjslot_list *prev;
108};
109
110struct proc {
111 struct adjslot_list asl;
112 int pid;
Colin Crossfbb78c62014-06-13 14:52:43 -0700113 uid_t uid;
Todd Poynor3948f802013-07-09 19:35:14 -0700114 int oomadj;
115 struct proc *pidhash_next;
116};
117
118#define PIDHASH_SZ 1024
119static struct proc *pidhash[PIDHASH_SZ];
120#define pid_hashfn(x) ((((x) >> 8) ^ (x)) & (PIDHASH_SZ - 1))
121
Chih-Hung Hsiehdaa13ea2016-05-19 16:02:22 -0700122#define ADJTOSLOT(adj) ((adj) + -OOM_SCORE_ADJ_MIN)
Chong Zhang0a4acdf2015-10-14 16:19:53 -0700123static struct adjslot_list procadjslot_list[ADJTOSLOT(OOM_SCORE_ADJ_MAX) + 1];
Todd Poynor3948f802013-07-09 19:35:14 -0700124
Todd Poynor3948f802013-07-09 19:35:14 -0700125/* PAGE_SIZE / 1024 */
126static long page_k;
127
Colin Crossce85d952014-07-11 17:53:27 -0700128static ssize_t read_all(int fd, char *buf, size_t max_len)
129{
130 ssize_t ret = 0;
131
132 while (max_len > 0) {
133 ssize_t r = read(fd, buf, max_len);
134 if (r == 0) {
135 break;
136 }
137 if (r == -1) {
138 return -1;
139 }
140 ret += r;
141 buf += r;
142 max_len -= r;
143 }
144
145 return ret;
146}
147
Todd Poynor3948f802013-07-09 19:35:14 -0700148static struct proc *pid_lookup(int pid) {
149 struct proc *procp;
150
151 for (procp = pidhash[pid_hashfn(pid)]; procp && procp->pid != pid;
152 procp = procp->pidhash_next)
153 ;
154
155 return procp;
156}
157
158static void adjslot_insert(struct adjslot_list *head, struct adjslot_list *new)
159{
160 struct adjslot_list *next = head->next;
161 new->prev = head;
162 new->next = next;
163 next->prev = new;
164 head->next = new;
165}
166
167static void adjslot_remove(struct adjslot_list *old)
168{
169 struct adjslot_list *prev = old->prev;
170 struct adjslot_list *next = old->next;
171 next->prev = prev;
172 prev->next = next;
173}
174
175static struct adjslot_list *adjslot_tail(struct adjslot_list *head) {
176 struct adjslot_list *asl = head->prev;
177
178 return asl == head ? NULL : asl;
179}
180
181static void proc_slot(struct proc *procp) {
182 int adjslot = ADJTOSLOT(procp->oomadj);
183
184 adjslot_insert(&procadjslot_list[adjslot], &procp->asl);
185}
186
187static void proc_unslot(struct proc *procp) {
188 adjslot_remove(&procp->asl);
189}
190
191static void proc_insert(struct proc *procp) {
192 int hval = pid_hashfn(procp->pid);
193
194 procp->pidhash_next = pidhash[hval];
195 pidhash[hval] = procp;
196 proc_slot(procp);
197}
198
199static int pid_remove(int pid) {
200 int hval = pid_hashfn(pid);
201 struct proc *procp;
202 struct proc *prevp;
203
204 for (procp = pidhash[hval], prevp = NULL; procp && procp->pid != pid;
205 procp = procp->pidhash_next)
206 prevp = procp;
207
208 if (!procp)
209 return -1;
210
211 if (!prevp)
212 pidhash[hval] = procp->pidhash_next;
213 else
214 prevp->pidhash_next = procp->pidhash_next;
215
216 proc_unslot(procp);
217 free(procp);
218 return 0;
219}
220
221static void writefilestring(char *path, char *s) {
Nick Kralevichc68c8862015-12-18 20:52:37 -0800222 int fd = open(path, O_WRONLY | O_CLOEXEC);
Todd Poynor3948f802013-07-09 19:35:14 -0700223 int len = strlen(s);
224 int ret;
225
226 if (fd < 0) {
227 ALOGE("Error opening %s; errno=%d", path, errno);
228 return;
229 }
230
231 ret = write(fd, s, len);
232 if (ret < 0) {
233 ALOGE("Error writing %s; errno=%d", path, errno);
234 } else if (ret < len) {
235 ALOGE("Short write on %s; length=%d", path, ret);
236 }
237
238 close(fd);
239}
240
Colin Crossfbb78c62014-06-13 14:52:43 -0700241static void cmd_procprio(int pid, int uid, int oomadj) {
Todd Poynor3948f802013-07-09 19:35:14 -0700242 struct proc *procp;
243 char path[80];
244 char val[20];
Robert Benea673e2762017-06-01 16:32:31 -0700245 int soft_limit_mult;
Todd Poynor3948f802013-07-09 19:35:14 -0700246
Chong Zhang0a4acdf2015-10-14 16:19:53 -0700247 if (oomadj < OOM_SCORE_ADJ_MIN || oomadj > OOM_SCORE_ADJ_MAX) {
Todd Poynor3948f802013-07-09 19:35:14 -0700248 ALOGE("Invalid PROCPRIO oomadj argument %d", oomadj);
249 return;
250 }
251
Todd Poynor16b60992013-09-16 19:26:47 -0700252 snprintf(path, sizeof(path), "/proc/%d/oom_score_adj", pid);
Chong Zhang0a4acdf2015-10-14 16:19:53 -0700253 snprintf(val, sizeof(val), "%d", oomadj);
Todd Poynor3948f802013-07-09 19:35:14 -0700254 writefilestring(path, val);
255
256 if (use_inkernel_interface)
257 return;
258
Robert Benea673e2762017-06-01 16:32:31 -0700259 if (oomadj >= 900) {
260 soft_limit_mult = 0;
261 } else if (oomadj >= 800) {
262 soft_limit_mult = 0;
263 } else if (oomadj >= 700) {
264 soft_limit_mult = 0;
265 } else if (oomadj >= 600) {
Robert Beneacaeaa652017-08-11 16:03:20 -0700266 // Launcher should be perceptible, don't kill it.
267 oomadj = 200;
268 soft_limit_mult = 1;
Robert Benea673e2762017-06-01 16:32:31 -0700269 } else if (oomadj >= 500) {
270 soft_limit_mult = 0;
271 } else if (oomadj >= 400) {
272 soft_limit_mult = 0;
273 } else if (oomadj >= 300) {
274 soft_limit_mult = 1;
275 } else if (oomadj >= 200) {
276 soft_limit_mult = 2;
277 } else if (oomadj >= 100) {
278 soft_limit_mult = 10;
279 } else if (oomadj >= 0) {
280 soft_limit_mult = 20;
281 } else {
282 // Persistent processes will have a large
283 // soft limit 512MB.
284 soft_limit_mult = 64;
285 }
286
287 snprintf(path, sizeof(path), "/dev/memcg/apps/uid_%d/pid_%d/memory.soft_limit_in_bytes", uid, pid);
288 snprintf(val, sizeof(val), "%d", soft_limit_mult * EIGHT_MEGA);
289 writefilestring(path, val);
290
Todd Poynor3948f802013-07-09 19:35:14 -0700291 procp = pid_lookup(pid);
292 if (!procp) {
293 procp = malloc(sizeof(struct proc));
294 if (!procp) {
295 // Oh, the irony. May need to rebuild our state.
296 return;
297 }
298
299 procp->pid = pid;
Colin Crossfbb78c62014-06-13 14:52:43 -0700300 procp->uid = uid;
Todd Poynor3948f802013-07-09 19:35:14 -0700301 procp->oomadj = oomadj;
302 proc_insert(procp);
303 } else {
304 proc_unslot(procp);
305 procp->oomadj = oomadj;
306 proc_slot(procp);
307 }
308}
309
310static void cmd_procremove(int pid) {
Todd Poynor3948f802013-07-09 19:35:14 -0700311 if (use_inkernel_interface)
312 return;
313
314 pid_remove(pid);
Todd Poynor3948f802013-07-09 19:35:14 -0700315}
316
317static void cmd_target(int ntargets, int *params) {
318 int i;
319
320 if (ntargets > (int)ARRAY_SIZE(lowmem_adj))
321 return;
322
323 for (i = 0; i < ntargets; i++) {
324 lowmem_minfree[i] = ntohl(*params++);
325 lowmem_adj[i] = ntohl(*params++);
326 }
327
328 lowmem_targets_size = ntargets;
329
330 if (use_inkernel_interface) {
331 char minfreestr[128];
332 char killpriostr[128];
333
334 minfreestr[0] = '\0';
335 killpriostr[0] = '\0';
336
337 for (i = 0; i < lowmem_targets_size; i++) {
338 char val[40];
339
340 if (i) {
341 strlcat(minfreestr, ",", sizeof(minfreestr));
342 strlcat(killpriostr, ",", sizeof(killpriostr));
343 }
344
345 snprintf(val, sizeof(val), "%d", lowmem_minfree[i]);
346 strlcat(minfreestr, val, sizeof(minfreestr));
347 snprintf(val, sizeof(val), "%d", lowmem_adj[i]);
348 strlcat(killpriostr, val, sizeof(killpriostr));
349 }
350
351 writefilestring(INKERNEL_MINFREE_PATH, minfreestr);
352 writefilestring(INKERNEL_ADJ_PATH, killpriostr);
353 }
354}
355
356static void ctrl_data_close(void) {
357 ALOGI("Closing Activity Manager data connection");
358 close(ctrl_dfd);
359 ctrl_dfd = -1;
360 maxevents--;
361}
362
363static int ctrl_data_read(char *buf, size_t bufsz) {
364 int ret = 0;
365
366 ret = read(ctrl_dfd, buf, bufsz);
367
368 if (ret == -1) {
369 ALOGE("control data socket read failed; errno=%d", errno);
370 } else if (ret == 0) {
371 ALOGE("Got EOF on control data socket");
372 ret = -1;
373 }
374
375 return ret;
376}
377
378static void ctrl_command_handler(void) {
379 int ibuf[CTRL_PACKET_MAX / sizeof(int)];
380 int len;
381 int cmd = -1;
382 int nargs;
383 int targets;
384
385 len = ctrl_data_read((char *)ibuf, CTRL_PACKET_MAX);
386 if (len <= 0)
387 return;
388
389 nargs = len / sizeof(int) - 1;
390 if (nargs < 0)
391 goto wronglen;
392
393 cmd = ntohl(ibuf[0]);
394
395 switch(cmd) {
396 case LMK_TARGET:
397 targets = nargs / 2;
398 if (nargs & 0x1 || targets > (int)ARRAY_SIZE(lowmem_adj))
399 goto wronglen;
400 cmd_target(targets, &ibuf[1]);
401 break;
402 case LMK_PROCPRIO:
Colin Crossfbb78c62014-06-13 14:52:43 -0700403 if (nargs != 3)
Todd Poynor3948f802013-07-09 19:35:14 -0700404 goto wronglen;
Colin Crossfbb78c62014-06-13 14:52:43 -0700405 cmd_procprio(ntohl(ibuf[1]), ntohl(ibuf[2]), ntohl(ibuf[3]));
Todd Poynor3948f802013-07-09 19:35:14 -0700406 break;
407 case LMK_PROCREMOVE:
408 if (nargs != 1)
409 goto wronglen;
410 cmd_procremove(ntohl(ibuf[1]));
411 break;
412 default:
413 ALOGE("Received unknown command code %d", cmd);
414 return;
415 }
416
417 return;
418
419wronglen:
420 ALOGE("Wrong control socket read length cmd=%d len=%d", cmd, len);
421}
422
423static void ctrl_data_handler(uint32_t events) {
424 if (events & EPOLLHUP) {
425 ALOGI("ActivityManager disconnected");
426 if (!ctrl_dfd_reopened)
427 ctrl_data_close();
428 } else if (events & EPOLLIN) {
429 ctrl_command_handler();
430 }
431}
432
Mark Salyzyne6ed68b2014-04-30 13:36:35 -0700433static void ctrl_connect_handler(uint32_t events __unused) {
Todd Poynor3948f802013-07-09 19:35:14 -0700434 struct epoll_event epev;
435
436 if (ctrl_dfd >= 0) {
437 ctrl_data_close();
438 ctrl_dfd_reopened = 1;
439 }
440
Elliott Hughes3dcfa3f2016-08-23 12:50:00 -0700441 ctrl_dfd = accept(ctrl_lfd, NULL, NULL);
Todd Poynor3948f802013-07-09 19:35:14 -0700442
443 if (ctrl_dfd < 0) {
444 ALOGE("lmkd control socket accept failed; errno=%d", errno);
445 return;
446 }
447
448 ALOGI("ActivityManager connected");
449 maxevents++;
450 epev.events = EPOLLIN;
451 epev.data.ptr = (void *)ctrl_data_handler;
452 if (epoll_ctl(epollfd, EPOLL_CTL_ADD, ctrl_dfd, &epev) == -1) {
453 ALOGE("epoll_ctl for data connection socket failed; errno=%d", errno);
454 ctrl_data_close();
455 return;
456 }
457}
458
459static int zoneinfo_parse_protection(char *cp) {
460 int max = 0;
461 int zoneval;
Colin Crossce85d952014-07-11 17:53:27 -0700462 char *save_ptr;
Todd Poynor3948f802013-07-09 19:35:14 -0700463
Colin Crossce85d952014-07-11 17:53:27 -0700464 for (cp = strtok_r(cp, "(), ", &save_ptr); cp; cp = strtok_r(NULL, "), ", &save_ptr)) {
Todd Poynor3948f802013-07-09 19:35:14 -0700465 zoneval = strtol(cp, &cp, 0);
Todd Poynor3948f802013-07-09 19:35:14 -0700466 if (zoneval > max)
467 max = zoneval;
Colin Crossce85d952014-07-11 17:53:27 -0700468 }
Todd Poynor3948f802013-07-09 19:35:14 -0700469
470 return max;
471}
472
473static void zoneinfo_parse_line(char *line, struct sysmeminfo *mip) {
474 char *cp = line;
475 char *ap;
Colin Crossce85d952014-07-11 17:53:27 -0700476 char *save_ptr;
Todd Poynor3948f802013-07-09 19:35:14 -0700477
Colin Crossce85d952014-07-11 17:53:27 -0700478 cp = strtok_r(line, " ", &save_ptr);
Todd Poynor3948f802013-07-09 19:35:14 -0700479 if (!cp)
480 return;
481
Colin Crossce85d952014-07-11 17:53:27 -0700482 ap = strtok_r(NULL, " ", &save_ptr);
Todd Poynor3948f802013-07-09 19:35:14 -0700483 if (!ap)
484 return;
485
486 if (!strcmp(cp, "nr_free_pages"))
487 mip->nr_free_pages += strtol(ap, NULL, 0);
488 else if (!strcmp(cp, "nr_file_pages"))
489 mip->nr_file_pages += strtol(ap, NULL, 0);
490 else if (!strcmp(cp, "nr_shmem"))
491 mip->nr_shmem += strtol(ap, NULL, 0);
492 else if (!strcmp(cp, "high"))
493 mip->totalreserve_pages += strtol(ap, NULL, 0);
494 else if (!strcmp(cp, "protection:"))
495 mip->totalreserve_pages += zoneinfo_parse_protection(ap);
496}
497
498static int zoneinfo_parse(struct sysmeminfo *mip) {
Colin Crossce85d952014-07-11 17:53:27 -0700499 int fd;
500 ssize_t size;
501 char buf[PAGE_SIZE];
502 char *save_ptr;
503 char *line;
Todd Poynor3948f802013-07-09 19:35:14 -0700504
505 memset(mip, 0, sizeof(struct sysmeminfo));
Colin Crossce85d952014-07-11 17:53:27 -0700506
Nick Kralevichc68c8862015-12-18 20:52:37 -0800507 fd = open(ZONEINFO_PATH, O_RDONLY | O_CLOEXEC);
Colin Crossce85d952014-07-11 17:53:27 -0700508 if (fd == -1) {
Todd Poynor3948f802013-07-09 19:35:14 -0700509 ALOGE("%s open: errno=%d", ZONEINFO_PATH, errno);
510 return -1;
511 }
512
Colin Crossce85d952014-07-11 17:53:27 -0700513 size = read_all(fd, buf, sizeof(buf) - 1);
514 if (size < 0) {
515 ALOGE("%s read: errno=%d", ZONEINFO_PATH, errno);
516 close(fd);
517 return -1;
518 }
519 ALOG_ASSERT((size_t)size < sizeof(buf) - 1, "/proc/zoneinfo too large");
520 buf[size] = 0;
521
522 for (line = strtok_r(buf, "\n", &save_ptr); line; line = strtok_r(NULL, "\n", &save_ptr))
Todd Poynor3948f802013-07-09 19:35:14 -0700523 zoneinfo_parse_line(line, mip);
524
Colin Crossce85d952014-07-11 17:53:27 -0700525 close(fd);
Todd Poynor3948f802013-07-09 19:35:14 -0700526 return 0;
527}
528
529static int proc_get_size(int pid) {
530 char path[PATH_MAX];
531 char line[LINE_MAX];
Colin Crossce85d952014-07-11 17:53:27 -0700532 int fd;
Todd Poynor3948f802013-07-09 19:35:14 -0700533 int rss = 0;
534 int total;
Colin Crossce85d952014-07-11 17:53:27 -0700535 ssize_t ret;
Todd Poynor3948f802013-07-09 19:35:14 -0700536
537 snprintf(path, PATH_MAX, "/proc/%d/statm", pid);
Nick Kralevichc68c8862015-12-18 20:52:37 -0800538 fd = open(path, O_RDONLY | O_CLOEXEC);
Colin Crossce85d952014-07-11 17:53:27 -0700539 if (fd == -1)
Todd Poynor3948f802013-07-09 19:35:14 -0700540 return -1;
Colin Crossce85d952014-07-11 17:53:27 -0700541
542 ret = read_all(fd, line, sizeof(line) - 1);
543 if (ret < 0) {
544 close(fd);
Todd Poynor3948f802013-07-09 19:35:14 -0700545 return -1;
546 }
547
548 sscanf(line, "%d %d ", &total, &rss);
Colin Crossce85d952014-07-11 17:53:27 -0700549 close(fd);
Todd Poynor3948f802013-07-09 19:35:14 -0700550 return rss;
551}
552
553static char *proc_get_name(int pid) {
554 char path[PATH_MAX];
555 static char line[LINE_MAX];
Colin Crossce85d952014-07-11 17:53:27 -0700556 int fd;
Todd Poynor3948f802013-07-09 19:35:14 -0700557 char *cp;
Colin Crossce85d952014-07-11 17:53:27 -0700558 ssize_t ret;
Todd Poynor3948f802013-07-09 19:35:14 -0700559
560 snprintf(path, PATH_MAX, "/proc/%d/cmdline", pid);
Nick Kralevichc68c8862015-12-18 20:52:37 -0800561 fd = open(path, O_RDONLY | O_CLOEXEC);
Colin Crossce85d952014-07-11 17:53:27 -0700562 if (fd == -1)
Todd Poynor3948f802013-07-09 19:35:14 -0700563 return NULL;
Colin Crossce85d952014-07-11 17:53:27 -0700564 ret = read_all(fd, line, sizeof(line) - 1);
565 close(fd);
566 if (ret < 0) {
Todd Poynor3948f802013-07-09 19:35:14 -0700567 return NULL;
568 }
569
570 cp = strchr(line, ' ');
571 if (cp)
572 *cp = '\0';
573
574 return line;
575}
576
577static struct proc *proc_adj_lru(int oomadj) {
578 return (struct proc *)adjslot_tail(&procadjslot_list[ADJTOSLOT(oomadj)]);
579}
580
Colin Cross16b09462014-07-14 12:39:56 -0700581/* Kill one process specified by procp. Returns the size of the process killed */
Robert Beneacaeaa652017-08-11 16:03:20 -0700582static int kill_one_process(struct proc* procp, int min_score_adj, bool is_critical) {
Colin Cross16b09462014-07-14 12:39:56 -0700583 int pid = procp->pid;
584 uid_t uid = procp->uid;
585 char *taskname;
586 int tasksize;
587 int r;
588
589 taskname = proc_get_name(pid);
590 if (!taskname) {
591 pid_remove(pid);
592 return -1;
593 }
594
595 tasksize = proc_get_size(pid);
596 if (tasksize <= 0) {
597 pid_remove(pid);
598 return -1;
599 }
600
Robert Beneacaeaa652017-08-11 16:03:20 -0700601 ALOGI(
602 "Killing '%s' (%d), uid %d, adj %d\n"
603 " to free %ldkB because system is under %s memory pressure oom_adj %d\n",
604 taskname, pid, uid, procp->oomadj, tasksize * page_k, is_critical ? "critical" : "medium",
605 min_score_adj);
Colin Cross16b09462014-07-14 12:39:56 -0700606 r = kill(pid, SIGKILL);
Colin Cross16b09462014-07-14 12:39:56 -0700607 pid_remove(pid);
608
609 if (r) {
610 ALOGE("kill(%d): errno=%d", procp->pid, errno);
611 return -1;
612 } else {
613 return tasksize;
614 }
615}
616
617/*
618 * Find a process to kill based on the current (possibly estimated) free memory
619 * and cached memory sizes. Returns the size of the killed processes.
620 */
Robert Beneacaeaa652017-08-11 16:03:20 -0700621static int find_and_kill_process(int min_score_adj, bool is_critical) {
Colin Cross16b09462014-07-14 12:39:56 -0700622 int i;
Colin Cross16b09462014-07-14 12:39:56 -0700623 int killed_size = 0;
624
Chong Zhang0a4acdf2015-10-14 16:19:53 -0700625 for (i = OOM_SCORE_ADJ_MAX; i >= min_score_adj; i--) {
Colin Cross16b09462014-07-14 12:39:56 -0700626 struct proc *procp;
627
628retry:
629 procp = proc_adj_lru(i);
630
631 if (procp) {
Robert Beneacaeaa652017-08-11 16:03:20 -0700632 killed_size = kill_one_process(procp, min_score_adj, is_critical);
Colin Cross16b09462014-07-14 12:39:56 -0700633 if (killed_size < 0) {
634 goto retry;
635 } else {
636 return killed_size;
637 }
638 }
639 }
640
641 return 0;
642}
643
Robert Benea673e2762017-06-01 16:32:31 -0700644static void mp_event_common(bool is_critical) {
Todd Poynor3948f802013-07-09 19:35:14 -0700645 int ret;
646 unsigned long long evcount;
Robert Benea58891d52017-07-31 17:15:20 -0700647 int min_adj_score = is_critical ? critical_oomadj : medium_oomadj;
Robert Benea673e2762017-06-01 16:32:31 -0700648 int index = is_critical ? CRITICAL_INDEX : MEDIUM_INDEX;
Todd Poynor3948f802013-07-09 19:35:14 -0700649
Robert Benea673e2762017-06-01 16:32:31 -0700650 ret = read(mpevfd[index], &evcount, sizeof(evcount));
Todd Poynor3948f802013-07-09 19:35:14 -0700651 if (ret < 0)
652 ALOGE("Error reading memory pressure event fd; errno=%d",
653 errno);
654
Robert Beneacaeaa652017-08-11 16:03:20 -0700655 if (find_and_kill_process(min_adj_score, is_critical) == 0) {
656 if (debug_process_killing) {
657 ALOGI("Nothing to kill");
658 }
Colin Crossf8857cc2014-07-11 17:16:56 -0700659 }
Todd Poynor3948f802013-07-09 19:35:14 -0700660}
661
Robert Benea673e2762017-06-01 16:32:31 -0700662static void mp_event(uint32_t events __unused) {
663 mp_event_common(false);
664}
665
666static void mp_event_critical(uint32_t events __unused) {
Robert Benea673e2762017-06-01 16:32:31 -0700667 mp_event_common(true);
668}
669
670static int init_mp_common(char *levelstr, void *event_handler, bool is_critical)
Todd Poynor3948f802013-07-09 19:35:14 -0700671{
672 int mpfd;
673 int evfd;
674 int evctlfd;
675 char buf[256];
676 struct epoll_event epev;
677 int ret;
Robert Benea673e2762017-06-01 16:32:31 -0700678 int mpevfd_index = is_critical ? CRITICAL_INDEX : MEDIUM_INDEX;
Todd Poynor3948f802013-07-09 19:35:14 -0700679
Nick Kralevichc68c8862015-12-18 20:52:37 -0800680 mpfd = open(MEMCG_SYSFS_PATH "memory.pressure_level", O_RDONLY | O_CLOEXEC);
Todd Poynor3948f802013-07-09 19:35:14 -0700681 if (mpfd < 0) {
682 ALOGI("No kernel memory.pressure_level support (errno=%d)", errno);
683 goto err_open_mpfd;
684 }
685
Nick Kralevichc68c8862015-12-18 20:52:37 -0800686 evctlfd = open(MEMCG_SYSFS_PATH "cgroup.event_control", O_WRONLY | O_CLOEXEC);
Todd Poynor3948f802013-07-09 19:35:14 -0700687 if (evctlfd < 0) {
688 ALOGI("No kernel memory cgroup event control (errno=%d)", errno);
689 goto err_open_evctlfd;
690 }
691
Nick Kralevichc68c8862015-12-18 20:52:37 -0800692 evfd = eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC);
Todd Poynor3948f802013-07-09 19:35:14 -0700693 if (evfd < 0) {
694 ALOGE("eventfd failed for level %s; errno=%d", levelstr, errno);
695 goto err_eventfd;
696 }
697
698 ret = snprintf(buf, sizeof(buf), "%d %d %s", evfd, mpfd, levelstr);
699 if (ret >= (ssize_t)sizeof(buf)) {
700 ALOGE("cgroup.event_control line overflow for level %s", levelstr);
701 goto err;
702 }
703
704 ret = write(evctlfd, buf, strlen(buf) + 1);
705 if (ret == -1) {
706 ALOGE("cgroup.event_control write failed for level %s; errno=%d",
707 levelstr, errno);
708 goto err;
709 }
710
711 epev.events = EPOLLIN;
712 epev.data.ptr = event_handler;
713 ret = epoll_ctl(epollfd, EPOLL_CTL_ADD, evfd, &epev);
714 if (ret == -1) {
715 ALOGE("epoll_ctl for level %s failed; errno=%d", levelstr, errno);
716 goto err;
717 }
718 maxevents++;
Robert Benea673e2762017-06-01 16:32:31 -0700719 mpevfd[mpevfd_index] = evfd;
Todd Poynor3948f802013-07-09 19:35:14 -0700720 return 0;
721
722err:
723 close(evfd);
724err_eventfd:
725 close(evctlfd);
726err_open_evctlfd:
727 close(mpfd);
728err_open_mpfd:
729 return -1;
730}
731
Robert Benea673e2762017-06-01 16:32:31 -0700732static int init_mp_medium()
733{
734 return init_mp_common(MEMPRESSURE_WATCH_MEDIUM_LEVEL, (void *)&mp_event, false);
735}
736
737static int init_mp_critical()
738{
739 return init_mp_common(MEMPRESSURE_WATCH_CRITICAL_LEVEL, (void *)&mp_event_critical, true);
740}
741
Todd Poynor3948f802013-07-09 19:35:14 -0700742static int init(void) {
743 struct epoll_event epev;
744 int i;
745 int ret;
746
747 page_k = sysconf(_SC_PAGESIZE);
748 if (page_k == -1)
749 page_k = PAGE_SIZE;
750 page_k /= 1024;
751
752 epollfd = epoll_create(MAX_EPOLL_EVENTS);
753 if (epollfd == -1) {
754 ALOGE("epoll_create failed (errno=%d)", errno);
755 return -1;
756 }
757
758 ctrl_lfd = android_get_control_socket("lmkd");
759 if (ctrl_lfd < 0) {
760 ALOGE("get lmkd control socket failed");
761 return -1;
762 }
763
764 ret = listen(ctrl_lfd, 1);
765 if (ret < 0) {
766 ALOGE("lmkd control socket listen failed (errno=%d)", errno);
767 return -1;
768 }
769
770 epev.events = EPOLLIN;
771 epev.data.ptr = (void *)ctrl_connect_handler;
772 if (epoll_ctl(epollfd, EPOLL_CTL_ADD, ctrl_lfd, &epev) == -1) {
773 ALOGE("epoll_ctl for lmkd control socket failed (errno=%d)", errno);
774 return -1;
775 }
776 maxevents++;
777
778 use_inkernel_interface = !access(INKERNEL_MINFREE_PATH, W_OK);
779
780 if (use_inkernel_interface) {
781 ALOGI("Using in-kernel low memory killer interface");
782 } else {
Robert Benea673e2762017-06-01 16:32:31 -0700783 ret = init_mp_medium();
784 ret |= init_mp_critical();
Todd Poynor3948f802013-07-09 19:35:14 -0700785 if (ret)
786 ALOGE("Kernel does not support memory pressure events or in-kernel low memory killer");
787 }
788
Chong Zhang0a4acdf2015-10-14 16:19:53 -0700789 for (i = 0; i <= ADJTOSLOT(OOM_SCORE_ADJ_MAX); i++) {
Todd Poynor3948f802013-07-09 19:35:14 -0700790 procadjslot_list[i].next = &procadjslot_list[i];
791 procadjslot_list[i].prev = &procadjslot_list[i];
792 }
793
794 return 0;
795}
796
797static void mainloop(void) {
798 while (1) {
799 struct epoll_event events[maxevents];
800 int nevents;
801 int i;
802
803 ctrl_dfd_reopened = 0;
804 nevents = epoll_wait(epollfd, events, maxevents, -1);
805
806 if (nevents == -1) {
807 if (errno == EINTR)
808 continue;
809 ALOGE("epoll_wait failed (errno=%d)", errno);
810 continue;
811 }
812
813 for (i = 0; i < nevents; ++i) {
814 if (events[i].events & EPOLLERR)
815 ALOGD("EPOLLERR on event #%d", i);
816 if (events[i].data.ptr)
817 (*(void (*)(uint32_t))events[i].data.ptr)(events[i].events);
818 }
819 }
820}
821
Mark Salyzyne6ed68b2014-04-30 13:36:35 -0700822int main(int argc __unused, char **argv __unused) {
Colin Cross1a0d9be2014-07-14 14:31:15 -0700823 struct sched_param param = {
824 .sched_priority = 1,
825 };
826
Robert Benea58891d52017-07-31 17:15:20 -0700827 medium_oomadj = property_get_int32("ro.lmk.medium", 800);
828 critical_oomadj = property_get_int32("ro.lmk.critical", 0);
Robert Beneacaeaa652017-08-11 16:03:20 -0700829 debug_process_killing = property_get_bool("ro.lmk.debug", false);
Robert Benea58891d52017-07-31 17:15:20 -0700830
Colin Crossb28ff912014-07-11 17:15:44 -0700831 mlockall(MCL_FUTURE);
Colin Cross1a0d9be2014-07-14 14:31:15 -0700832 sched_setscheduler(0, SCHED_FIFO, &param);
Todd Poynor3948f802013-07-09 19:35:14 -0700833 if (!init())
834 mainloop();
835
836 ALOGI("exiting");
837 return 0;
838}