1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3 * linux/mm/oom_kill.c
4 *
5 * Copyright (C) 1998,2000 Rik van Riel
6 * Thanks go out to Claus Fischer for some serious inspiration and
7 * for goading me into coding this file...
8 * Copyright (C) 2010 Google, Inc.
9 * Rewritten by David Rientjes
10 *
11 * The routines in this file are used to kill a process when
12 * we're seriously out of memory. This gets called from __alloc_pages()
13 * in mm/page_alloc.c when we really run out of memory.
14 *
15 * Since we won't call these routines often (on a well-configured
16 * machine) this file will double as a 'coding guide' and a signpost
17 * for newbie kernel hackers. It features several pointers to major
18 * kernel subsystems and hints as to where to find out what things do.
19 */
20
21 #include <linux/oom.h>
22 #include <linux/mm.h>
23 #include <linux/err.h>
24 #include <linux/gfp.h>
25 #include <linux/sched.h>
26 #include <linux/sched/mm.h>
27 #include <linux/sched/coredump.h>
28 #include <linux/sched/task.h>
29 #include <linux/sched/debug.h>
30 #include <linux/swap.h>
31 #include <linux/syscalls.h>
32 #include <linux/timex.h>
33 #include <linux/jiffies.h>
34 #include <linux/cpuset.h>
35 #include <linux/export.h>
36 #include <linux/notifier.h>
37 #include <linux/memcontrol.h>
38 #include <linux/mempolicy.h>
39 #include <linux/security.h>
40 #include <linux/ptrace.h>
41 #include <linux/freezer.h>
42 #include <linux/ftrace.h>
43 #include <linux/ratelimit.h>
44 #include <linux/kthread.h>
45 #include <linux/init.h>
46 #include <linux/mmu_notifier.h>
47 #include <linux/cred.h>
48
49 #include <asm/tlb.h>
50 #include "internal.h"
51 #include "slab.h"
52
53 #define CREATE_TRACE_POINTS
54 #include <trace/events/oom.h>
55
56 #undef CREATE_TRACE_POINTS
57 #include <trace/hooks/mm.h>
58
59 int sysctl_panic_on_oom;
60 int sysctl_oom_kill_allocating_task;
61 int sysctl_oom_dump_tasks = 1;
62
63 /*
64 * Serializes oom killer invocations (out_of_memory()) from all contexts to
65 * prevent from over eager oom killing (e.g. when the oom killer is invoked
66 * from different domains).
67 *
68 * oom_killer_disable() relies on this lock to stabilize oom_killer_disabled
69 * and mark_oom_victim
70 */
71 DEFINE_MUTEX(oom_lock);
72 /* Serializes oom_score_adj and oom_score_adj_min updates */
73 DEFINE_MUTEX(oom_adj_mutex);
74
is_memcg_oom(struct oom_control * oc)75 static inline bool is_memcg_oom(struct oom_control *oc)
76 {
77 return oc->memcg != NULL;
78 }
79
80 #ifdef CONFIG_NUMA
81 /**
82 * oom_cpuset_eligible() - check task eligiblity for kill
83 * @start: task struct of which task to consider
84 * @oc: pointer to struct oom_control
85 *
86 * Task eligibility is determined by whether or not a candidate task, @tsk,
87 * shares the same mempolicy nodes as current if it is bound by such a policy
88 * and whether or not it has the same set of allowed cpuset nodes.
89 *
90 * This function is assuming oom-killer context and 'current' has triggered
91 * the oom-killer.
92 */
oom_cpuset_eligible(struct task_struct * start,struct oom_control * oc)93 static bool oom_cpuset_eligible(struct task_struct *start,
94 struct oom_control *oc)
95 {
96 struct task_struct *tsk;
97 bool ret = false;
98 const nodemask_t *mask = oc->nodemask;
99
100 if (is_memcg_oom(oc))
101 return true;
102
103 rcu_read_lock();
104 for_each_thread(start, tsk) {
105 if (mask) {
106 /*
107 * If this is a mempolicy constrained oom, tsk's
108 * cpuset is irrelevant. Only return true if its
109 * mempolicy intersects current, otherwise it may be
110 * needlessly killed.
111 */
112 ret = mempolicy_nodemask_intersects(tsk, mask);
113 } else {
114 /*
115 * This is not a mempolicy constrained oom, so only
116 * check the mems of tsk's cpuset.
117 */
118 ret = cpuset_mems_allowed_intersects(current, tsk);
119 }
120 if (ret)
121 break;
122 }
123 rcu_read_unlock();
124
125 return ret;
126 }
127 #else
oom_cpuset_eligible(struct task_struct * tsk,struct oom_control * oc)128 static bool oom_cpuset_eligible(struct task_struct *tsk, struct oom_control *oc)
129 {
130 return true;
131 }
132 #endif /* CONFIG_NUMA */
133
134 /*
135 * The process p may have detached its own ->mm while exiting or through
136 * kthread_use_mm(), but one or more of its subthreads may still have a valid
137 * pointer. Return p, or any of its subthreads with a valid ->mm, with
138 * task_lock() held.
139 */
find_lock_task_mm(struct task_struct * p)140 struct task_struct *find_lock_task_mm(struct task_struct *p)
141 {
142 struct task_struct *t;
143
144 rcu_read_lock();
145
146 for_each_thread(p, t) {
147 task_lock(t);
148 if (likely(t->mm))
149 goto found;
150 task_unlock(t);
151 }
152 t = NULL;
153 found:
154 rcu_read_unlock();
155
156 return t;
157 }
158
159 /*
160 * order == -1 means the oom kill is required by sysrq, otherwise only
161 * for display purposes.
162 */
is_sysrq_oom(struct oom_control * oc)163 static inline bool is_sysrq_oom(struct oom_control *oc)
164 {
165 return oc->order == -1;
166 }
167
168 /* return true if the task is not adequate as candidate victim task. */
oom_unkillable_task(struct task_struct * p)169 static bool oom_unkillable_task(struct task_struct *p)
170 {
171 if (is_global_init(p))
172 return true;
173 if (p->flags & PF_KTHREAD)
174 return true;
175 return false;
176 }
177
178 /*
179 * Print out unreclaimble slabs info when unreclaimable slabs amount is greater
180 * than all user memory (LRU pages)
181 */
is_dump_unreclaim_slabs(void)182 static bool is_dump_unreclaim_slabs(void)
183 {
184 unsigned long nr_lru;
185
186 nr_lru = global_node_page_state(NR_ACTIVE_ANON) +
187 global_node_page_state(NR_INACTIVE_ANON) +
188 global_node_page_state(NR_ACTIVE_FILE) +
189 global_node_page_state(NR_INACTIVE_FILE) +
190 global_node_page_state(NR_ISOLATED_ANON) +
191 global_node_page_state(NR_ISOLATED_FILE) +
192 global_node_page_state(NR_UNEVICTABLE);
193
194 return (global_node_page_state_pages(NR_SLAB_UNRECLAIMABLE_B) > nr_lru);
195 }
196
197 /**
198 * oom_badness - heuristic function to determine which candidate task to kill
199 * @p: task struct of which task we should calculate
200 * @totalpages: total present RAM allowed for page allocation
201 *
202 * The heuristic for determining which task to kill is made to be as simple and
203 * predictable as possible. The goal is to return the highest value for the
204 * task consuming the most memory to avoid subsequent oom failures.
205 */
oom_badness(struct task_struct * p,unsigned long totalpages)206 long oom_badness(struct task_struct *p, unsigned long totalpages)
207 {
208 long points;
209 long adj;
210
211 if (oom_unkillable_task(p))
212 return LONG_MIN;
213
214 p = find_lock_task_mm(p);
215 if (!p)
216 return LONG_MIN;
217
218 /*
219 * Do not even consider tasks which are explicitly marked oom
220 * unkillable or have been already oom reaped or the are in
221 * the middle of vfork
222 */
223 adj = (long)p->signal->oom_score_adj;
224 if (adj == OOM_SCORE_ADJ_MIN ||
225 test_bit(MMF_OOM_SKIP, &p->mm->flags) ||
226 in_vfork(p)) {
227 task_unlock(p);
228 return LONG_MIN;
229 }
230
231 /*
232 * The baseline for the badness score is the proportion of RAM that each
233 * task's rss, pagetable and swap space use.
234 */
235 points = get_mm_rss(p->mm) + get_mm_counter(p->mm, MM_SWAPENTS) +
236 mm_pgtables_bytes(p->mm) / PAGE_SIZE;
237 task_unlock(p);
238
239 /* Normalize to oom_score_adj units */
240 adj *= totalpages / 1000;
241 points += adj;
242
243 return points;
244 }
245
246 static const char * const oom_constraint_text[] = {
247 [CONSTRAINT_NONE] = "CONSTRAINT_NONE",
248 [CONSTRAINT_CPUSET] = "CONSTRAINT_CPUSET",
249 [CONSTRAINT_MEMORY_POLICY] = "CONSTRAINT_MEMORY_POLICY",
250 [CONSTRAINT_MEMCG] = "CONSTRAINT_MEMCG",
251 };
252
253 /*
254 * Determine the type of allocation constraint.
255 */
constrained_alloc(struct oom_control * oc)256 static enum oom_constraint constrained_alloc(struct oom_control *oc)
257 {
258 struct zone *zone;
259 struct zoneref *z;
260 enum zone_type highest_zoneidx = gfp_zone(oc->gfp_mask);
261 bool cpuset_limited = false;
262 int nid;
263
264 if (is_memcg_oom(oc)) {
265 oc->totalpages = mem_cgroup_get_max(oc->memcg) ?: 1;
266 return CONSTRAINT_MEMCG;
267 }
268
269 /* Default to all available memory */
270 oc->totalpages = totalram_pages() + total_swap_pages;
271
272 if (!IS_ENABLED(CONFIG_NUMA))
273 return CONSTRAINT_NONE;
274
275 if (!oc->zonelist)
276 return CONSTRAINT_NONE;
277 /*
278 * Reach here only when __GFP_NOFAIL is used. So, we should avoid
279 * to kill current.We have to random task kill in this case.
280 * Hopefully, CONSTRAINT_THISNODE...but no way to handle it, now.
281 */
282 if (oc->gfp_mask & __GFP_THISNODE)
283 return CONSTRAINT_NONE;
284
285 /*
286 * This is not a __GFP_THISNODE allocation, so a truncated nodemask in
287 * the page allocator means a mempolicy is in effect. Cpuset policy
288 * is enforced in get_page_from_freelist().
289 */
290 if (oc->nodemask &&
291 !nodes_subset(node_states[N_MEMORY], *oc->nodemask)) {
292 oc->totalpages = total_swap_pages;
293 for_each_node_mask(nid, *oc->nodemask)
294 oc->totalpages += node_present_pages(nid);
295 return CONSTRAINT_MEMORY_POLICY;
296 }
297
298 /* Check this allocation failure is caused by cpuset's wall function */
299 for_each_zone_zonelist_nodemask(zone, z, oc->zonelist,
300 highest_zoneidx, oc->nodemask)
301 if (!cpuset_zone_allowed(zone, oc->gfp_mask))
302 cpuset_limited = true;
303
304 if (cpuset_limited) {
305 oc->totalpages = total_swap_pages;
306 for_each_node_mask(nid, cpuset_current_mems_allowed)
307 oc->totalpages += node_present_pages(nid);
308 return CONSTRAINT_CPUSET;
309 }
310 return CONSTRAINT_NONE;
311 }
312
oom_evaluate_task(struct task_struct * task,void * arg)313 static int oom_evaluate_task(struct task_struct *task, void *arg)
314 {
315 struct oom_control *oc = arg;
316 long points;
317
318 if (oom_unkillable_task(task))
319 goto next;
320
321 /* p may not have freeable memory in nodemask */
322 if (!is_memcg_oom(oc) && !oom_cpuset_eligible(task, oc))
323 goto next;
324
325 /*
326 * This task already has access to memory reserves and is being killed.
327 * Don't allow any other task to have access to the reserves unless
328 * the task has MMF_OOM_SKIP because chances that it would release
329 * any memory is quite low.
330 */
331 if (!is_sysrq_oom(oc) && tsk_is_oom_victim(task)) {
332 if (test_bit(MMF_OOM_SKIP, &task->signal->oom_mm->flags))
333 goto next;
334 goto abort;
335 }
336
337 /*
338 * If task is allocating a lot of memory and has been marked to be
339 * killed first if it triggers an oom, then select it.
340 */
341 if (oom_task_origin(task)) {
342 points = LONG_MAX;
343 goto select;
344 }
345
346 points = oom_badness(task, oc->totalpages);
347
348 if (points == LONG_MIN)
349 goto next;
350
351 /*
352 * Check to see if this is the worst task with a non-negative
353 * ADJ score seen so far
354 */
355 if (task->signal->oom_score_adj >= 0 &&
356 points > oc->chosen_non_negative_adj_points) {
357 if (oc->chosen_non_negative_adj)
358 put_task_struct(oc->chosen_non_negative_adj);
359 get_task_struct(task);
360 oc->chosen_non_negative_adj = task;
361 oc->chosen_non_negative_adj_points = points;
362 }
363
364 if (points < oc->chosen_points)
365 goto next;
366
367 select:
368 if (oc->chosen)
369 put_task_struct(oc->chosen);
370 get_task_struct(task);
371 oc->chosen = task;
372 oc->chosen_points = points;
373 next:
374 return 0;
375 abort:
376 if (oc->chosen_non_negative_adj)
377 put_task_struct(oc->chosen_non_negative_adj);
378 if (oc->chosen)
379 put_task_struct(oc->chosen);
380 oc->chosen_non_negative_adj = NULL;
381 oc->chosen = (void *)-1UL;
382 return 1;
383 }
384
385 /*
386 * Simple selection loop. We choose the process with the highest number of
387 * 'points'. In case scan was aborted, oc->chosen is set to -1.
388 */
select_bad_process(struct oom_control * oc)389 static void select_bad_process(struct oom_control *oc)
390 {
391 oc->chosen_points = LONG_MIN;
392 oc->chosen_non_negative_adj_points = LONG_MIN;
393 oc->chosen_non_negative_adj = NULL;
394
395 if (is_memcg_oom(oc))
396 mem_cgroup_scan_tasks(oc->memcg, oom_evaluate_task, oc);
397 else {
398 struct task_struct *p;
399
400 rcu_read_lock();
401 for_each_process(p)
402 if (oom_evaluate_task(p, oc))
403 break;
404 rcu_read_unlock();
405 }
406
407 if (oc->chosen_non_negative_adj) {
408 /*
409 * If oc->chosen has a negative ADJ, and we found a task with
410 * a postive ADJ to kill, kill the task with the positive ADJ
411 * instead.
412 */
413 if (oc->chosen && oc->chosen->signal->oom_score_adj < 0) {
414 put_task_struct(oc->chosen);
415 oc->chosen = oc->chosen_non_negative_adj;
416 oc->chosen_points = oc->chosen_non_negative_adj_points;
417 } else
418 put_task_struct(oc->chosen_non_negative_adj);
419 }
420 }
421
dump_task(struct task_struct * p,void * arg)422 static int dump_task(struct task_struct *p, void *arg)
423 {
424 struct oom_control *oc = arg;
425 struct task_struct *task;
426
427 if (oom_unkillable_task(p))
428 return 0;
429
430 /* p may not have freeable memory in nodemask */
431 if (!is_memcg_oom(oc) && !oom_cpuset_eligible(p, oc))
432 return 0;
433
434 task = find_lock_task_mm(p);
435 if (!task) {
436 /*
437 * This is a kthread or all of p's threads have already
438 * detached their mm's. There's no need to report
439 * them; they can't be oom killed anyway.
440 */
441 return 0;
442 }
443
444 pr_info("[%7d] %5d %5d %8lu %8lu %8ld %8lu %5hd %s\n",
445 task->pid, from_kuid(&init_user_ns, task_uid(task)),
446 task->tgid, task->mm->total_vm, get_mm_rss(task->mm),
447 mm_pgtables_bytes(task->mm),
448 get_mm_counter(task->mm, MM_SWAPENTS),
449 task->signal->oom_score_adj, task->comm);
450 task_unlock(task);
451
452 return 0;
453 }
454
455 /**
456 * dump_tasks - dump current memory state of all system tasks
457 * @oc: pointer to struct oom_control
458 *
459 * Dumps the current memory state of all eligible tasks. Tasks not in the same
460 * memcg, not in the same cpuset, or bound to a disjoint set of mempolicy nodes
461 * are not shown.
462 * State information includes task's pid, uid, tgid, vm size, rss,
463 * pgtables_bytes, swapents, oom_score_adj value, and name.
464 */
dump_tasks(struct oom_control * oc)465 static void dump_tasks(struct oom_control *oc)
466 {
467 pr_info("Tasks state (memory values in pages):\n");
468 pr_info("[ pid ] uid tgid total_vm rss pgtables_bytes swapents oom_score_adj name\n");
469
470 if (is_memcg_oom(oc))
471 mem_cgroup_scan_tasks(oc->memcg, dump_task, oc);
472 else {
473 struct task_struct *p;
474
475 rcu_read_lock();
476 for_each_process(p)
477 dump_task(p, oc);
478 rcu_read_unlock();
479 }
480 }
481
dump_oom_summary(struct oom_control * oc,struct task_struct * victim)482 static void dump_oom_summary(struct oom_control *oc, struct task_struct *victim)
483 {
484 /* one line summary of the oom killer context. */
485 pr_info("oom-kill:constraint=%s,nodemask=%*pbl",
486 oom_constraint_text[oc->constraint],
487 nodemask_pr_args(oc->nodemask));
488 cpuset_print_current_mems_allowed();
489 mem_cgroup_print_oom_context(oc->memcg, victim);
490 pr_cont(",task=%s,pid=%d,uid=%d\n", victim->comm, victim->pid,
491 from_kuid(&init_user_ns, task_uid(victim)));
492 }
493
dump_header(struct oom_control * oc,struct task_struct * p)494 static void dump_header(struct oom_control *oc, struct task_struct *p)
495 {
496 pr_warn("%s invoked oom-killer: gfp_mask=%#x(%pGg), order=%d, oom_score_adj=%hd\n",
497 current->comm, oc->gfp_mask, &oc->gfp_mask, oc->order,
498 current->signal->oom_score_adj);
499 if (!IS_ENABLED(CONFIG_COMPACTION) && oc->order)
500 pr_warn("COMPACTION is disabled!!!\n");
501
502 dump_stack();
503 if (is_memcg_oom(oc))
504 mem_cgroup_print_oom_meminfo(oc->memcg);
505 else {
506 show_mem(SHOW_MEM_FILTER_NODES, oc->nodemask);
507 if (is_dump_unreclaim_slabs())
508 dump_unreclaimable_slab();
509 }
510 if (sysctl_oom_dump_tasks)
511 dump_tasks(oc);
512 if (p)
513 dump_oom_summary(oc, p);
514 }
515
516 /*
517 * Number of OOM victims in flight
518 */
519 static atomic_t oom_victims = ATOMIC_INIT(0);
520 static DECLARE_WAIT_QUEUE_HEAD(oom_victims_wait);
521
522 static bool oom_killer_disabled __read_mostly;
523
524 #define K(x) ((x) << (PAGE_SHIFT-10))
525
526 /*
527 * task->mm can be NULL if the task is the exited group leader. So to
528 * determine whether the task is using a particular mm, we examine all the
529 * task's threads: if one of those is using this mm then this task was also
530 * using it.
531 */
process_shares_mm(struct task_struct * p,struct mm_struct * mm)532 bool process_shares_mm(struct task_struct *p, struct mm_struct *mm)
533 {
534 struct task_struct *t;
535
536 for_each_thread(p, t) {
537 struct mm_struct *t_mm = READ_ONCE(t->mm);
538 if (t_mm)
539 return t_mm == mm;
540 }
541 return false;
542 }
543
544 #ifdef CONFIG_MMU
545 /*
546 * OOM Reaper kernel thread which tries to reap the memory used by the OOM
547 * victim (if that is possible) to help the OOM killer to move on.
548 */
549 static struct task_struct *oom_reaper_th;
550 static DECLARE_WAIT_QUEUE_HEAD(oom_reaper_wait);
551 static struct task_struct *oom_reaper_list;
552 static DEFINE_SPINLOCK(oom_reaper_lock);
553
__oom_reap_task_mm(struct mm_struct * mm)554 bool __oom_reap_task_mm(struct mm_struct *mm)
555 {
556 struct vm_area_struct *vma;
557 bool ret = true;
558
559 /*
560 * Tell all users of get_user/copy_from_user etc... that the content
561 * is no longer stable. No barriers really needed because unmapping
562 * should imply barriers already and the reader would hit a page fault
563 * if it stumbled over a reaped memory.
564 */
565 set_bit(MMF_UNSTABLE, &mm->flags);
566
567 for (vma = mm->mmap ; vma; vma = vma->vm_next) {
568 if (!can_madv_lru_vma(vma))
569 continue;
570
571 /*
572 * Only anonymous pages have a good chance to be dropped
573 * without additional steps which we cannot afford as we
574 * are OOM already.
575 *
576 * We do not even care about fs backed pages because all
577 * which are reclaimable have already been reclaimed and
578 * we do not want to block exit_mmap by keeping mm ref
579 * count elevated without a good reason.
580 */
581 if (vma_is_anonymous(vma) || !(vma->vm_flags & VM_SHARED)) {
582 struct mmu_notifier_range range;
583 struct mmu_gather tlb;
584
585 mmu_notifier_range_init(&range, MMU_NOTIFY_UNMAP, 0,
586 vma, mm, vma->vm_start,
587 vma->vm_end);
588 tlb_gather_mmu(&tlb, mm, range.start, range.end);
589 if (mmu_notifier_invalidate_range_start_nonblock(&range)) {
590 tlb_finish_mmu(&tlb, range.start, range.end);
591 ret = false;
592 continue;
593 }
594 unmap_page_range(&tlb, vma, range.start, range.end, NULL);
595 mmu_notifier_invalidate_range_end(&range);
596 tlb_finish_mmu(&tlb, range.start, range.end);
597 }
598 }
599
600 return ret;
601 }
602
603 /*
604 * Reaps the address space of the give task.
605 *
606 * Returns true on success and false if none or part of the address space
607 * has been reclaimed and the caller should retry later.
608 */
oom_reap_task_mm(struct task_struct * tsk,struct mm_struct * mm)609 static bool oom_reap_task_mm(struct task_struct *tsk, struct mm_struct *mm)
610 {
611 bool ret = true;
612
613 if (!mmap_read_trylock(mm)) {
614 trace_skip_task_reaping(tsk->pid);
615 return false;
616 }
617
618 /*
619 * MMF_OOM_SKIP is set by exit_mmap when the OOM reaper can't
620 * work on the mm anymore. The check for MMF_OOM_SKIP must run
621 * under mmap_lock for reading because it serializes against the
622 * mmap_write_lock();mmap_write_unlock() cycle in exit_mmap().
623 */
624 if (test_bit(MMF_OOM_SKIP, &mm->flags)) {
625 trace_skip_task_reaping(tsk->pid);
626 goto out_unlock;
627 }
628
629 trace_start_task_reaping(tsk->pid);
630
631 /* failed to reap part of the address space. Try again later */
632 ret = __oom_reap_task_mm(mm);
633 if (!ret)
634 goto out_finish;
635
636 pr_info("oom_reaper: reaped process %d (%s), now anon-rss:%lukB, file-rss:%lukB, shmem-rss:%lukB\n",
637 task_pid_nr(tsk), tsk->comm,
638 K(get_mm_counter(mm, MM_ANONPAGES)),
639 K(get_mm_counter(mm, MM_FILEPAGES)),
640 K(get_mm_counter(mm, MM_SHMEMPAGES)));
641 out_finish:
642 trace_finish_task_reaping(tsk->pid);
643 out_unlock:
644 mmap_read_unlock(mm);
645
646 return ret;
647 }
648
649 #define MAX_OOM_REAP_RETRIES 10
oom_reap_task(struct task_struct * tsk)650 static void oom_reap_task(struct task_struct *tsk)
651 {
652 int attempts = 0;
653 struct mm_struct *mm = tsk->signal->oom_mm;
654
655 /* Retry the mmap_read_trylock(mm) a few times */
656 while (attempts++ < MAX_OOM_REAP_RETRIES && !oom_reap_task_mm(tsk, mm))
657 schedule_timeout_idle(HZ/10);
658
659 if (attempts <= MAX_OOM_REAP_RETRIES ||
660 test_bit(MMF_OOM_SKIP, &mm->flags))
661 goto done;
662
663 pr_info("oom_reaper: unable to reap pid:%d (%s)\n",
664 task_pid_nr(tsk), tsk->comm);
665 sched_show_task(tsk);
666 debug_show_all_locks();
667
668 done:
669 tsk->oom_reaper_list = NULL;
670
671 /*
672 * Hide this mm from OOM killer because it has been either reaped or
673 * somebody can't call mmap_write_unlock(mm).
674 */
675 set_bit(MMF_OOM_SKIP, &mm->flags);
676
677 /* Drop a reference taken by wake_oom_reaper */
678 put_task_struct(tsk);
679 }
680
oom_reaper(void * unused)681 static int oom_reaper(void *unused)
682 {
683 while (true) {
684 struct task_struct *tsk = NULL;
685
686 wait_event_freezable(oom_reaper_wait, oom_reaper_list != NULL);
687 spin_lock(&oom_reaper_lock);
688 if (oom_reaper_list != NULL) {
689 tsk = oom_reaper_list;
690 oom_reaper_list = tsk->oom_reaper_list;
691 }
692 spin_unlock(&oom_reaper_lock);
693
694 if (tsk)
695 oom_reap_task(tsk);
696 }
697
698 return 0;
699 }
700
wake_oom_reaper(struct task_struct * tsk)701 static void wake_oom_reaper(struct task_struct *tsk)
702 {
703 /* mm is already queued? */
704 if (test_and_set_bit(MMF_OOM_REAP_QUEUED, &tsk->signal->oom_mm->flags))
705 return;
706
707 get_task_struct(tsk);
708
709 spin_lock(&oom_reaper_lock);
710 tsk->oom_reaper_list = oom_reaper_list;
711 oom_reaper_list = tsk;
712 spin_unlock(&oom_reaper_lock);
713 trace_wake_reaper(tsk->pid);
714 wake_up(&oom_reaper_wait);
715 }
716
oom_init(void)717 static int __init oom_init(void)
718 {
719 oom_reaper_th = kthread_run(oom_reaper, NULL, "oom_reaper");
720 return 0;
721 }
subsys_initcall(oom_init)722 subsys_initcall(oom_init)
723 #else
724 static inline void wake_oom_reaper(struct task_struct *tsk)
725 {
726 }
727 #endif /* CONFIG_MMU */
728
729 /**
730 * tsk->mm has to be non NULL and caller has to guarantee it is stable (either
731 * under task_lock or operate on the current).
732 */
733 static void __mark_oom_victim(struct task_struct *tsk)
734 {
735 struct mm_struct *mm = tsk->mm;
736
737 if (!cmpxchg(&tsk->signal->oom_mm, NULL, mm)) {
738 mmgrab(tsk->signal->oom_mm);
739 set_bit(MMF_OOM_VICTIM, &mm->flags);
740 }
741 }
742
743 /**
744 * mark_oom_victim - mark the given task as OOM victim
745 * @tsk: task to mark
746 *
747 * Has to be called with oom_lock held and never after
748 * oom has been disabled already.
749 *
750 * tsk->mm has to be non NULL and caller has to guarantee it is stable (either
751 * under task_lock or operate on the current).
752 */
mark_oom_victim(struct task_struct * tsk)753 static void mark_oom_victim(struct task_struct *tsk)
754 {
755 const struct cred *cred;
756
757 WARN_ON(oom_killer_disabled);
758 /* OOM killer might race with memcg OOM */
759 if (test_and_set_tsk_thread_flag(tsk, TIF_MEMDIE))
760 return;
761
762 /* oom_mm is bound to the signal struct life time. */
763 __mark_oom_victim(tsk);
764
765 /*
766 * Make sure that the task is woken up from uninterruptible sleep
767 * if it is frozen because OOM killer wouldn't be able to free
768 * any memory and livelock. freezing_slow_path will tell the freezer
769 * that TIF_MEMDIE tasks should be ignored.
770 */
771 __thaw_task(tsk);
772 atomic_inc(&oom_victims);
773 cred = get_task_cred(tsk);
774 trace_mark_victim(tsk, cred->uid.val);
775 put_cred(cred);
776 }
777
778 /**
779 * exit_oom_victim - note the exit of an OOM victim
780 */
exit_oom_victim(void)781 void exit_oom_victim(void)
782 {
783 clear_thread_flag(TIF_MEMDIE);
784
785 if (!atomic_dec_return(&oom_victims))
786 wake_up_all(&oom_victims_wait);
787 }
788
789 /**
790 * oom_killer_enable - enable OOM killer
791 */
oom_killer_enable(void)792 void oom_killer_enable(void)
793 {
794 oom_killer_disabled = false;
795 pr_info("OOM killer enabled.\n");
796 }
797
798 /**
799 * oom_killer_disable - disable OOM killer
800 * @timeout: maximum timeout to wait for oom victims in jiffies
801 *
802 * Forces all page allocations to fail rather than trigger OOM killer.
803 * Will block and wait until all OOM victims are killed or the given
804 * timeout expires.
805 *
806 * The function cannot be called when there are runnable user tasks because
807 * the userspace would see unexpected allocation failures as a result. Any
808 * new usage of this function should be consulted with MM people.
809 *
810 * Returns true if successful and false if the OOM killer cannot be
811 * disabled.
812 */
oom_killer_disable(signed long timeout)813 bool oom_killer_disable(signed long timeout)
814 {
815 signed long ret;
816
817 /*
818 * Make sure to not race with an ongoing OOM killer. Check that the
819 * current is not killed (possibly due to sharing the victim's memory).
820 */
821 if (mutex_lock_killable(&oom_lock))
822 return false;
823 oom_killer_disabled = true;
824 mutex_unlock(&oom_lock);
825
826 ret = wait_event_interruptible_timeout(oom_victims_wait,
827 !atomic_read(&oom_victims), timeout);
828 if (ret <= 0) {
829 oom_killer_enable();
830 return false;
831 }
832 pr_info("OOM killer disabled.\n");
833
834 return true;
835 }
836
__task_will_free_mem(struct task_struct * task)837 static inline bool __task_will_free_mem(struct task_struct *task)
838 {
839 struct signal_struct *sig = task->signal;
840
841 /*
842 * A coredumping process may sleep for an extended period in exit_mm(),
843 * so the oom killer cannot assume that the process will promptly exit
844 * and release memory.
845 */
846 if (sig->flags & SIGNAL_GROUP_COREDUMP)
847 return false;
848
849 if (sig->flags & SIGNAL_GROUP_EXIT)
850 return true;
851
852 if (thread_group_empty(task) && (task->flags & PF_EXITING))
853 return true;
854
855 return false;
856 }
857
858 /*
859 * Checks whether the given task is dying or exiting and likely to
860 * release its address space. This means that all threads and processes
861 * sharing the same mm have to be killed or exiting.
862 * Caller has to make sure that task->mm is stable (hold task_lock or
863 * it operates on the current).
864 */
task_will_free_mem(struct task_struct * task)865 static bool task_will_free_mem(struct task_struct *task)
866 {
867 struct mm_struct *mm = task->mm;
868 struct task_struct *p;
869 bool ret = true;
870
871 /*
872 * Skip tasks without mm because it might have passed its exit_mm and
873 * exit_oom_victim. oom_reaper could have rescued that but do not rely
874 * on that for now. We can consider find_lock_task_mm in future.
875 */
876 if (!mm)
877 return false;
878
879 if (!__task_will_free_mem(task))
880 return false;
881
882 /*
883 * This task has already been drained by the oom reaper so there are
884 * only small chances it will free some more
885 */
886 if (test_bit(MMF_OOM_SKIP, &mm->flags))
887 return false;
888
889 if (atomic_read(&mm->mm_users) <= 1)
890 return true;
891
892 /*
893 * Make sure that all tasks which share the mm with the given tasks
894 * are dying as well to make sure that a) nobody pins its mm and
895 * b) the task is also reapable by the oom reaper.
896 */
897 rcu_read_lock();
898 for_each_process(p) {
899 if (!process_shares_mm(p, mm))
900 continue;
901 if (same_thread_group(task, p))
902 continue;
903 ret = __task_will_free_mem(p);
904 if (!ret)
905 break;
906 }
907 rcu_read_unlock();
908
909 return ret;
910 }
911
__oom_kill_process(struct task_struct * victim,const char * message)912 static void __oom_kill_process(struct task_struct *victim, const char *message)
913 {
914 struct task_struct *p;
915 struct mm_struct *mm;
916 bool can_oom_reap = true;
917
918 p = find_lock_task_mm(victim);
919 if (!p) {
920 pr_info("%s: OOM victim %d (%s) is already exiting. Skip killing the task\n",
921 message, task_pid_nr(victim), victim->comm);
922 put_task_struct(victim);
923 return;
924 } else if (victim != p) {
925 get_task_struct(p);
926 put_task_struct(victim);
927 victim = p;
928 }
929
930 /* Get a reference to safely compare mm after task_unlock(victim) */
931 mm = victim->mm;
932 mmgrab(mm);
933
934 /* Raise event before sending signal: task reaper must see this */
935 count_vm_event(OOM_KILL);
936 memcg_memory_event_mm(mm, MEMCG_OOM_KILL);
937
938 /*
939 * We should send SIGKILL before granting access to memory reserves
940 * in order to prevent the OOM victim from depleting the memory
941 * reserves from the user space under its control.
942 */
943 do_send_sig_info(SIGKILL, SEND_SIG_PRIV, victim, PIDTYPE_TGID);
944 mark_oom_victim(victim);
945 pr_err("%s: Killed process %d (%s) total-vm:%lukB, anon-rss:%lukB, file-rss:%lukB, shmem-rss:%lukB, UID:%u pgtables:%lukB oom_score_adj:%hd\n",
946 message, task_pid_nr(victim), victim->comm, K(mm->total_vm),
947 K(get_mm_counter(mm, MM_ANONPAGES)),
948 K(get_mm_counter(mm, MM_FILEPAGES)),
949 K(get_mm_counter(mm, MM_SHMEMPAGES)),
950 from_kuid(&init_user_ns, task_uid(victim)),
951 mm_pgtables_bytes(mm) >> 10, victim->signal->oom_score_adj);
952 task_unlock(victim);
953
954 /*
955 * Kill all user processes sharing victim->mm in other thread groups, if
956 * any. They don't get access to memory reserves, though, to avoid
957 * depletion of all memory. This prevents mm->mmap_lock livelock when an
958 * oom killed thread cannot exit because it requires the semaphore and
959 * its contended by another thread trying to allocate memory itself.
960 * That thread will now get access to memory reserves since it has a
961 * pending fatal signal.
962 */
963 rcu_read_lock();
964 for_each_process(p) {
965 if (!process_shares_mm(p, mm))
966 continue;
967 if (same_thread_group(p, victim))
968 continue;
969 if (is_global_init(p)) {
970 can_oom_reap = false;
971 set_bit(MMF_OOM_SKIP, &mm->flags);
972 pr_info("oom killer %d (%s) has mm pinned by %d (%s)\n",
973 task_pid_nr(victim), victim->comm,
974 task_pid_nr(p), p->comm);
975 continue;
976 }
977 /*
978 * No kthead_use_mm() user needs to read from the userspace so
979 * we are ok to reap it.
980 */
981 if (unlikely(p->flags & PF_KTHREAD))
982 continue;
983 do_send_sig_info(SIGKILL, SEND_SIG_PRIV, p, PIDTYPE_TGID);
984 }
985 rcu_read_unlock();
986
987 if (can_oom_reap)
988 wake_oom_reaper(victim);
989
990 mmdrop(mm);
991 put_task_struct(victim);
992 }
993 #undef K
994
995 /*
996 * Kill provided task unless it's secured by setting
997 * oom_score_adj to OOM_SCORE_ADJ_MIN.
998 */
oom_kill_memcg_member(struct task_struct * task,void * message)999 static int oom_kill_memcg_member(struct task_struct *task, void *message)
1000 {
1001 if (task->signal->oom_score_adj != OOM_SCORE_ADJ_MIN &&
1002 !is_global_init(task)) {
1003 get_task_struct(task);
1004 __oom_kill_process(task, message);
1005 }
1006 return 0;
1007 }
1008
oom_kill_process(struct oom_control * oc,const char * message)1009 static void oom_kill_process(struct oom_control *oc, const char *message)
1010 {
1011 struct task_struct *victim = oc->chosen;
1012 struct mem_cgroup *oom_group;
1013 static DEFINE_RATELIMIT_STATE(oom_rs, DEFAULT_RATELIMIT_INTERVAL,
1014 DEFAULT_RATELIMIT_BURST);
1015
1016 /*
1017 * If the task is already exiting, don't alarm the sysadmin or kill
1018 * its children or threads, just give it access to memory reserves
1019 * so it can die quickly
1020 */
1021 task_lock(victim);
1022 if (task_will_free_mem(victim)) {
1023 mark_oom_victim(victim);
1024 wake_oom_reaper(victim);
1025 task_unlock(victim);
1026 put_task_struct(victim);
1027 return;
1028 }
1029 task_unlock(victim);
1030
1031 if (__ratelimit(&oom_rs))
1032 dump_header(oc, victim);
1033
1034 /*
1035 * Do we need to kill the entire memory cgroup?
1036 * Or even one of the ancestor memory cgroups?
1037 * Check this out before killing the victim task.
1038 */
1039 oom_group = mem_cgroup_get_oom_group(victim, oc->memcg);
1040
1041 __oom_kill_process(victim, message);
1042
1043 /*
1044 * If necessary, kill all tasks in the selected memory cgroup.
1045 */
1046 if (oom_group) {
1047 mem_cgroup_print_oom_group(oom_group);
1048 mem_cgroup_scan_tasks(oom_group, oom_kill_memcg_member,
1049 (void*)message);
1050 mem_cgroup_put(oom_group);
1051 }
1052 }
1053
1054 /*
1055 * Determines whether the kernel must panic because of the panic_on_oom sysctl.
1056 */
check_panic_on_oom(struct oom_control * oc)1057 static void check_panic_on_oom(struct oom_control *oc)
1058 {
1059 if (likely(!sysctl_panic_on_oom))
1060 return;
1061 if (sysctl_panic_on_oom != 2) {
1062 /*
1063 * panic_on_oom == 1 only affects CONSTRAINT_NONE, the kernel
1064 * does not panic for cpuset, mempolicy, or memcg allocation
1065 * failures.
1066 */
1067 if (oc->constraint != CONSTRAINT_NONE)
1068 return;
1069 }
1070 /* Do not panic for oom kills triggered by sysrq */
1071 if (is_sysrq_oom(oc))
1072 return;
1073 dump_header(oc, NULL);
1074 panic("Out of memory: %s panic_on_oom is enabled\n",
1075 sysctl_panic_on_oom == 2 ? "compulsory" : "system-wide");
1076 }
1077
1078 static BLOCKING_NOTIFIER_HEAD(oom_notify_list);
1079
register_oom_notifier(struct notifier_block * nb)1080 int register_oom_notifier(struct notifier_block *nb)
1081 {
1082 return blocking_notifier_chain_register(&oom_notify_list, nb);
1083 }
1084 EXPORT_SYMBOL_GPL(register_oom_notifier);
1085
unregister_oom_notifier(struct notifier_block * nb)1086 int unregister_oom_notifier(struct notifier_block *nb)
1087 {
1088 return blocking_notifier_chain_unregister(&oom_notify_list, nb);
1089 }
1090 EXPORT_SYMBOL_GPL(unregister_oom_notifier);
1091
1092 /**
1093 * out_of_memory - kill the "best" process when we run out of memory
1094 * @oc: pointer to struct oom_control
1095 *
1096 * If we run out of memory, we have the choice between either
1097 * killing a random task (bad), letting the system crash (worse)
1098 * OR try to be smart about which process to kill. Note that we
1099 * don't have to be perfect here, we just have to be good.
1100 */
out_of_memory(struct oom_control * oc)1101 bool out_of_memory(struct oom_control *oc)
1102 {
1103 unsigned long freed = 0;
1104
1105 if (oom_killer_disabled)
1106 return false;
1107
1108 if (!is_memcg_oom(oc)) {
1109 blocking_notifier_call_chain(&oom_notify_list, 0, &freed);
1110 if (freed > 0)
1111 /* Got some memory back in the last second. */
1112 return true;
1113 }
1114
1115 /*
1116 * If current has a pending SIGKILL or is exiting, then automatically
1117 * select it. The goal is to allow it to allocate so that it may
1118 * quickly exit and free its memory.
1119 */
1120 if (task_will_free_mem(current)) {
1121 mark_oom_victim(current);
1122 wake_oom_reaper(current);
1123 return true;
1124 }
1125
1126 /*
1127 * The OOM killer does not compensate for IO-less reclaim.
1128 * pagefault_out_of_memory lost its gfp context so we have to
1129 * make sure exclude 0 mask - all other users should have at least
1130 * ___GFP_DIRECT_RECLAIM to get here. But mem_cgroup_oom() has to
1131 * invoke the OOM killer even if it is a GFP_NOFS allocation.
1132 */
1133 if (oc->gfp_mask && !(oc->gfp_mask & __GFP_FS) && !is_memcg_oom(oc))
1134 return true;
1135
1136 /*
1137 * Check if there were limitations on the allocation (only relevant for
1138 * NUMA and memcg) that may require different handling.
1139 */
1140 oc->constraint = constrained_alloc(oc);
1141 if (oc->constraint != CONSTRAINT_MEMORY_POLICY)
1142 oc->nodemask = NULL;
1143 check_panic_on_oom(oc);
1144
1145 if (!is_memcg_oom(oc) && sysctl_oom_kill_allocating_task &&
1146 current->mm && !oom_unkillable_task(current) &&
1147 oom_cpuset_eligible(current, oc) &&
1148 current->signal->oom_score_adj != OOM_SCORE_ADJ_MIN) {
1149 get_task_struct(current);
1150 oc->chosen = current;
1151 oom_kill_process(oc, "Out of memory (oom_kill_allocating_task)");
1152 return true;
1153 }
1154
1155 select_bad_process(oc);
1156 /* Found nothing?!?! */
1157 if (!oc->chosen) {
1158 int ret = false;
1159
1160 trace_android_vh_oom_check_panic(oc, &ret);
1161 if (ret)
1162 return true;
1163
1164 dump_header(oc, NULL);
1165 pr_warn("Out of memory and no killable processes...\n");
1166 /*
1167 * If we got here due to an actual allocation at the
1168 * system level, we cannot survive this and will enter
1169 * an endless loop in the allocator. Bail out now.
1170 */
1171 if (!is_sysrq_oom(oc) && !is_memcg_oom(oc))
1172 panic("System is deadlocked on memory\n");
1173 }
1174 if (oc->chosen && oc->chosen != (void *)-1UL)
1175 oom_kill_process(oc, !is_memcg_oom(oc) ? "Out of memory" :
1176 "Memory cgroup out of memory");
1177 return !!oc->chosen;
1178 }
1179
1180 /*
1181 * The pagefault handler calls here because some allocation has failed. We have
1182 * to take care of the memcg OOM here because this is the only safe context without
1183 * any locks held but let the oom killer triggered from the allocation context care
1184 * about the global OOM.
1185 */
pagefault_out_of_memory(void)1186 void pagefault_out_of_memory(void)
1187 {
1188 static DEFINE_RATELIMIT_STATE(pfoom_rs, DEFAULT_RATELIMIT_INTERVAL,
1189 DEFAULT_RATELIMIT_BURST);
1190
1191 if (mem_cgroup_oom_synchronize(true))
1192 return;
1193
1194 if (fatal_signal_pending(current))
1195 return;
1196
1197 if (__ratelimit(&pfoom_rs))
1198 pr_warn("Huh VM_FAULT_OOM leaked out to the #PF handler. Retrying PF\n");
1199 }
1200
SYSCALL_DEFINE2(process_mrelease,int,pidfd,unsigned int,flags)1201 SYSCALL_DEFINE2(process_mrelease, int, pidfd, unsigned int, flags)
1202 {
1203 #ifdef CONFIG_MMU
1204 struct mm_struct *mm = NULL;
1205 struct task_struct *task;
1206 struct task_struct *p;
1207 unsigned int f_flags;
1208 bool reap = false;
1209 struct pid *pid;
1210 long ret = 0;
1211
1212 if (flags)
1213 return -EINVAL;
1214
1215 pid = pidfd_get_pid(pidfd, &f_flags);
1216 if (IS_ERR(pid))
1217 return PTR_ERR(pid);
1218
1219 task = get_pid_task(pid, PIDTYPE_TGID);
1220 if (!task) {
1221 ret = -ESRCH;
1222 goto put_pid;
1223 }
1224
1225 /*
1226 * Make sure to choose a thread which still has a reference to mm
1227 * during the group exit
1228 */
1229 p = find_lock_task_mm(task);
1230 if (!p) {
1231 ret = -ESRCH;
1232 goto put_task;
1233 }
1234
1235 mm = p->mm;
1236 mmgrab(mm);
1237
1238 /*
1239 * If we are too late and exit_mmap already checked mm_is_oom_victim
1240 * then will block on mmap_read_lock until exit_mmap releases mmap_lock
1241 */
1242 set_bit(MMF_OOM_VICTIM, &mm->flags);
1243
1244 if (task_will_free_mem(p))
1245 reap = true;
1246 else {
1247 /* Error only if the work has not been done already */
1248 if (!test_bit(MMF_OOM_SKIP, &mm->flags))
1249 ret = -EINVAL;
1250 }
1251 task_unlock(p);
1252
1253 if (!reap)
1254 goto drop_mm;
1255
1256 if (mmap_read_lock_killable(mm)) {
1257 ret = -EINTR;
1258 goto drop_mm;
1259 }
1260 /*
1261 * Check MMF_OOM_SKIP again under mmap_read_lock protection to ensure
1262 * possible change in exit_mmap is seen
1263 */
1264 if (!test_bit(MMF_OOM_SKIP, &mm->flags) && !__oom_reap_task_mm(mm))
1265 ret = -EAGAIN;
1266 mmap_read_unlock(mm);
1267
1268 drop_mm:
1269 mmdrop(mm);
1270 put_task:
1271 put_task_struct(task);
1272 put_pid:
1273 put_pid(pid);
1274 return ret;
1275 #else
1276 return -ENOSYS;
1277 #endif /* CONFIG_MMU */
1278 }
1279
add_to_oom_reaper(struct task_struct * p)1280 void add_to_oom_reaper(struct task_struct *p)
1281 {
1282 p = find_lock_task_mm(p);
1283 if (!p)
1284 return;
1285
1286 get_task_struct(p);
1287 if (task_will_free_mem(p)) {
1288 __mark_oom_victim(p);
1289 wake_oom_reaper(p);
1290 }
1291 task_unlock(p);
1292 put_task_struct(p);
1293 }
1294