oom_kill.c 31 KB

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