oom_kill.c 30 KB

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