oom_kill.c 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158
  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. /* mm is already queued? */
  555. if (test_and_set_bit(MMF_OOM_REAP_QUEUED, &tsk->signal->oom_mm->flags))
  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_FORCED, 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_FORCED, 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. !is_global_init(task)) {
  802. get_task_struct(task);
  803. __oom_kill_process(task);
  804. }
  805. return 0;
  806. }
  807. static void oom_kill_process(struct oom_control *oc, const char *message)
  808. {
  809. struct task_struct *p = oc->chosen;
  810. unsigned int points = oc->chosen_points;
  811. struct task_struct *victim = p;
  812. struct task_struct *child;
  813. struct task_struct *t;
  814. struct mem_cgroup *oom_group;
  815. unsigned int victim_points = 0;
  816. static DEFINE_RATELIMIT_STATE(oom_rs, DEFAULT_RATELIMIT_INTERVAL,
  817. DEFAULT_RATELIMIT_BURST);
  818. /*
  819. * If the task is already exiting, don't alarm the sysadmin or kill
  820. * its children or threads, just give it access to memory reserves
  821. * so it can die quickly
  822. */
  823. task_lock(p);
  824. if (task_will_free_mem(p)) {
  825. mark_oom_victim(p);
  826. wake_oom_reaper(p);
  827. task_unlock(p);
  828. put_task_struct(p);
  829. return;
  830. }
  831. task_unlock(p);
  832. if (__ratelimit(&oom_rs))
  833. dump_header(oc, p);
  834. pr_err("%s: Kill process %d (%s) score %u or sacrifice child\n",
  835. message, task_pid_nr(p), p->comm, points);
  836. /*
  837. * If any of p's children has a different mm and is eligible for kill,
  838. * the one with the highest oom_badness() score is sacrificed for its
  839. * parent. This attempts to lose the minimal amount of work done while
  840. * still freeing memory.
  841. */
  842. read_lock(&tasklist_lock);
  843. /*
  844. * The task 'p' might have already exited before reaching here. The
  845. * put_task_struct() will free task_struct 'p' while the loop still try
  846. * to access the field of 'p', so, get an extra reference.
  847. */
  848. get_task_struct(p);
  849. for_each_thread(p, t) {
  850. list_for_each_entry(child, &t->children, sibling) {
  851. unsigned int child_points;
  852. if (process_shares_mm(child, p->mm))
  853. continue;
  854. /*
  855. * oom_badness() returns 0 if the thread is unkillable
  856. */
  857. child_points = oom_badness(child,
  858. oc->memcg, oc->nodemask, oc->totalpages);
  859. if (child_points > victim_points) {
  860. put_task_struct(victim);
  861. victim = child;
  862. victim_points = child_points;
  863. get_task_struct(victim);
  864. }
  865. }
  866. }
  867. put_task_struct(p);
  868. read_unlock(&tasklist_lock);
  869. /*
  870. * Do we need to kill the entire memory cgroup?
  871. * Or even one of the ancestor memory cgroups?
  872. * Check this out before killing the victim task.
  873. */
  874. oom_group = mem_cgroup_get_oom_group(victim, oc->memcg);
  875. __oom_kill_process(victim);
  876. /*
  877. * If necessary, kill all tasks in the selected memory cgroup.
  878. */
  879. if (oom_group) {
  880. mem_cgroup_print_oom_group(oom_group);
  881. mem_cgroup_scan_tasks(oom_group, oom_kill_memcg_member, NULL);
  882. mem_cgroup_put(oom_group);
  883. }
  884. }
  885. /*
  886. * Determines whether the kernel must panic because of the panic_on_oom sysctl.
  887. */
  888. static void check_panic_on_oom(struct oom_control *oc,
  889. enum oom_constraint constraint)
  890. {
  891. if (likely(!sysctl_panic_on_oom))
  892. return;
  893. if (sysctl_panic_on_oom != 2) {
  894. /*
  895. * panic_on_oom == 1 only affects CONSTRAINT_NONE, the kernel
  896. * does not panic for cpuset, mempolicy, or memcg allocation
  897. * failures.
  898. */
  899. if (constraint != CONSTRAINT_NONE)
  900. return;
  901. }
  902. /* Do not panic for oom kills triggered by sysrq */
  903. if (is_sysrq_oom(oc))
  904. return;
  905. dump_header(oc, NULL);
  906. panic("Out of memory: %s panic_on_oom is enabled\n",
  907. sysctl_panic_on_oom == 2 ? "compulsory" : "system-wide");
  908. }
  909. static BLOCKING_NOTIFIER_HEAD(oom_notify_list);
  910. int register_oom_notifier(struct notifier_block *nb)
  911. {
  912. return blocking_notifier_chain_register(&oom_notify_list, nb);
  913. }
  914. EXPORT_SYMBOL_GPL(register_oom_notifier);
  915. int unregister_oom_notifier(struct notifier_block *nb)
  916. {
  917. return blocking_notifier_chain_unregister(&oom_notify_list, nb);
  918. }
  919. EXPORT_SYMBOL_GPL(unregister_oom_notifier);
  920. /**
  921. * out_of_memory - kill the "best" process when we run out of memory
  922. * @oc: pointer to struct oom_control
  923. *
  924. * If we run out of memory, we have the choice between either
  925. * killing a random task (bad), letting the system crash (worse)
  926. * OR try to be smart about which process to kill. Note that we
  927. * don't have to be perfect here, we just have to be good.
  928. */
  929. bool out_of_memory(struct oom_control *oc)
  930. {
  931. unsigned long freed = 0;
  932. enum oom_constraint constraint = CONSTRAINT_NONE;
  933. if (oom_killer_disabled)
  934. return false;
  935. if (!is_memcg_oom(oc)) {
  936. blocking_notifier_call_chain(&oom_notify_list, 0, &freed);
  937. if (freed > 0)
  938. /* Got some memory back in the last second. */
  939. return true;
  940. }
  941. /*
  942. * If current has a pending SIGKILL or is exiting, then automatically
  943. * select it. The goal is to allow it to allocate so that it may
  944. * quickly exit and free its memory.
  945. */
  946. if (task_will_free_mem(current)) {
  947. mark_oom_victim(current);
  948. wake_oom_reaper(current);
  949. return true;
  950. }
  951. /*
  952. * The OOM killer does not compensate for IO-less reclaim.
  953. * pagefault_out_of_memory lost its gfp context so we have to
  954. * make sure exclude 0 mask - all other users should have at least
  955. * ___GFP_DIRECT_RECLAIM to get here. But mem_cgroup_oom() has to
  956. * invoke the OOM killer even if it is a GFP_NOFS allocation.
  957. */
  958. if (oc->gfp_mask && !(oc->gfp_mask & __GFP_FS) && !is_memcg_oom(oc))
  959. return true;
  960. /*
  961. * Check if there were limitations on the allocation (only relevant for
  962. * NUMA and memcg) that may require different handling.
  963. */
  964. constraint = constrained_alloc(oc);
  965. if (constraint != CONSTRAINT_MEMORY_POLICY)
  966. oc->nodemask = NULL;
  967. check_panic_on_oom(oc, constraint);
  968. if (!is_memcg_oom(oc) && sysctl_oom_kill_allocating_task &&
  969. current->mm && !oom_unkillable_task(current, NULL, oc->nodemask) &&
  970. current->signal->oom_score_adj != OOM_SCORE_ADJ_MIN) {
  971. get_task_struct(current);
  972. oc->chosen = current;
  973. oom_kill_process(oc, "Out of memory (oom_kill_allocating_task)");
  974. return true;
  975. }
  976. select_bad_process(oc);
  977. /* Found nothing?!?! */
  978. if (!oc->chosen) {
  979. dump_header(oc, NULL);
  980. pr_warn("Out of memory and no killable processes...\n");
  981. /*
  982. * If we got here due to an actual allocation at the
  983. * system level, we cannot survive this and will enter
  984. * an endless loop in the allocator. Bail out now.
  985. */
  986. if (!is_sysrq_oom(oc) && !is_memcg_oom(oc))
  987. panic("System is deadlocked on memory\n");
  988. }
  989. if (oc->chosen && oc->chosen != (void *)-1UL)
  990. oom_kill_process(oc, !is_memcg_oom(oc) ? "Out of memory" :
  991. "Memory cgroup out of memory");
  992. return !!oc->chosen;
  993. }
  994. /*
  995. * The pagefault handler calls here because it is out of memory, so kill a
  996. * memory-hogging task. If oom_lock is held by somebody else, a parallel oom
  997. * killing is already in progress so do nothing.
  998. */
  999. void pagefault_out_of_memory(void)
  1000. {
  1001. struct oom_control oc = {
  1002. .zonelist = NULL,
  1003. .nodemask = NULL,
  1004. .memcg = NULL,
  1005. .gfp_mask = 0,
  1006. .order = 0,
  1007. };
  1008. if (mem_cgroup_oom_synchronize(true))
  1009. return;
  1010. if (!mutex_trylock(&oom_lock))
  1011. return;
  1012. out_of_memory(&oc);
  1013. mutex_unlock(&oom_lock);
  1014. }