oom_kill.c 28 KB

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