oom_kill.c 31 KB

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