oom_kill.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641
  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. *
  8. * The routines in this file are used to kill a process when
  9. * we're seriously out of memory. This gets called from __alloc_pages()
  10. * in mm/page_alloc.c when we really run out of memory.
  11. *
  12. * Since we won't call these routines often (on a well-configured
  13. * machine) this file will double as a 'coding guide' and a signpost
  14. * for newbie kernel hackers. It features several pointers to major
  15. * kernel subsystems and hints as to where to find out what things do.
  16. */
  17. #include <linux/oom.h>
  18. #include <linux/mm.h>
  19. #include <linux/err.h>
  20. #include <linux/sched.h>
  21. #include <linux/swap.h>
  22. #include <linux/timex.h>
  23. #include <linux/jiffies.h>
  24. #include <linux/cpuset.h>
  25. #include <linux/module.h>
  26. #include <linux/notifier.h>
  27. #include <linux/memcontrol.h>
  28. #include <linux/security.h>
  29. int sysctl_panic_on_oom;
  30. int sysctl_oom_kill_allocating_task;
  31. int sysctl_oom_dump_tasks;
  32. static DEFINE_SPINLOCK(zone_scan_lock);
  33. /* #define DEBUG */
  34. /**
  35. * badness - calculate a numeric value for how bad this task has been
  36. * @p: task struct of which task we should calculate
  37. * @uptime: current uptime in seconds
  38. *
  39. * The formula used is relatively simple and documented inline in the
  40. * function. The main rationale is that we want to select a good task
  41. * to kill when we run out of memory.
  42. *
  43. * Good in this context means that:
  44. * 1) we lose the minimum amount of work done
  45. * 2) we recover a large amount of memory
  46. * 3) we don't kill anything innocent of eating tons of memory
  47. * 4) we want to kill the minimum amount of processes (one)
  48. * 5) we try to kill the process the user expects us to kill, this
  49. * algorithm has been meticulously tuned to meet the principle
  50. * of least surprise ... (be careful when you change it)
  51. */
  52. unsigned long badness(struct task_struct *p, unsigned long uptime)
  53. {
  54. unsigned long points, cpu_time, run_time;
  55. struct mm_struct *mm;
  56. struct task_struct *child;
  57. task_lock(p);
  58. mm = p->mm;
  59. if (!mm) {
  60. task_unlock(p);
  61. return 0;
  62. }
  63. /*
  64. * The memory size of the process is the basis for the badness.
  65. */
  66. points = mm->total_vm;
  67. /*
  68. * After this unlock we can no longer dereference local variable `mm'
  69. */
  70. task_unlock(p);
  71. /*
  72. * swapoff can easily use up all memory, so kill those first.
  73. */
  74. if (p->flags & PF_SWAPOFF)
  75. return ULONG_MAX;
  76. /*
  77. * Processes which fork a lot of child processes are likely
  78. * a good choice. We add half the vmsize of the children if they
  79. * have an own mm. This prevents forking servers to flood the
  80. * machine with an endless amount of children. In case a single
  81. * child is eating the vast majority of memory, adding only half
  82. * to the parents will make the child our kill candidate of choice.
  83. */
  84. list_for_each_entry(child, &p->children, sibling) {
  85. task_lock(child);
  86. if (child->mm != mm && child->mm)
  87. points += child->mm->total_vm/2 + 1;
  88. task_unlock(child);
  89. }
  90. /*
  91. * CPU time is in tens of seconds and run time is in thousands
  92. * of seconds. There is no particular reason for this other than
  93. * that it turned out to work very well in practice.
  94. */
  95. cpu_time = (cputime_to_jiffies(p->utime) + cputime_to_jiffies(p->stime))
  96. >> (SHIFT_HZ + 3);
  97. if (uptime >= p->start_time.tv_sec)
  98. run_time = (uptime - p->start_time.tv_sec) >> 10;
  99. else
  100. run_time = 0;
  101. if (cpu_time)
  102. points /= int_sqrt(cpu_time);
  103. if (run_time)
  104. points /= int_sqrt(int_sqrt(run_time));
  105. /*
  106. * Niced processes are most likely less important, so double
  107. * their badness points.
  108. */
  109. if (task_nice(p) > 0)
  110. points *= 2;
  111. /*
  112. * Superuser processes are usually more important, so we make it
  113. * less likely that we kill those.
  114. */
  115. if (has_capability_noaudit(p, CAP_SYS_ADMIN) ||
  116. has_capability_noaudit(p, CAP_SYS_RESOURCE))
  117. points /= 4;
  118. /*
  119. * We don't want to kill a process with direct hardware access.
  120. * Not only could that mess up the hardware, but usually users
  121. * tend to only have this flag set on applications they think
  122. * of as important.
  123. */
  124. if (has_capability_noaudit(p, CAP_SYS_RAWIO))
  125. points /= 4;
  126. /*
  127. * If p's nodes don't overlap ours, it may still help to kill p
  128. * because p may have allocated or otherwise mapped memory on
  129. * this node before. However it will be less likely.
  130. */
  131. if (!cpuset_mems_allowed_intersects(current, p))
  132. points /= 8;
  133. /*
  134. * Adjust the score by oomkilladj.
  135. */
  136. if (p->oomkilladj) {
  137. if (p->oomkilladj > 0) {
  138. if (!points)
  139. points = 1;
  140. points <<= p->oomkilladj;
  141. } else
  142. points >>= -(p->oomkilladj);
  143. }
  144. #ifdef DEBUG
  145. printk(KERN_DEBUG "OOMkill: task %d (%s) got %lu points\n",
  146. p->pid, p->comm, points);
  147. #endif
  148. return points;
  149. }
  150. /*
  151. * Determine the type of allocation constraint.
  152. */
  153. static inline enum oom_constraint constrained_alloc(struct zonelist *zonelist,
  154. gfp_t gfp_mask)
  155. {
  156. #ifdef CONFIG_NUMA
  157. struct zone *zone;
  158. struct zoneref *z;
  159. enum zone_type high_zoneidx = gfp_zone(gfp_mask);
  160. nodemask_t nodes = node_states[N_HIGH_MEMORY];
  161. for_each_zone_zonelist(zone, z, zonelist, high_zoneidx)
  162. if (cpuset_zone_allowed_softwall(zone, gfp_mask))
  163. node_clear(zone_to_nid(zone), nodes);
  164. else
  165. return CONSTRAINT_CPUSET;
  166. if (!nodes_empty(nodes))
  167. return CONSTRAINT_MEMORY_POLICY;
  168. #endif
  169. return CONSTRAINT_NONE;
  170. }
  171. /*
  172. * Simple selection loop. We chose the process with the highest
  173. * number of 'points'. We expect the caller will lock the tasklist.
  174. *
  175. * (not docbooked, we don't want this one cluttering up the manual)
  176. */
  177. static struct task_struct *select_bad_process(unsigned long *ppoints,
  178. struct mem_cgroup *mem)
  179. {
  180. struct task_struct *g, *p;
  181. struct task_struct *chosen = NULL;
  182. struct timespec uptime;
  183. *ppoints = 0;
  184. do_posix_clock_monotonic_gettime(&uptime);
  185. do_each_thread(g, p) {
  186. unsigned long points;
  187. /*
  188. * skip kernel threads and tasks which have already released
  189. * their mm.
  190. */
  191. if (!p->mm)
  192. continue;
  193. /* skip the init task */
  194. if (is_global_init(p))
  195. continue;
  196. if (mem && !task_in_mem_cgroup(p, mem))
  197. continue;
  198. /*
  199. * This task already has access to memory reserves and is
  200. * being killed. Don't allow any other task access to the
  201. * memory reserve.
  202. *
  203. * Note: this may have a chance of deadlock if it gets
  204. * blocked waiting for another task which itself is waiting
  205. * for memory. Is there a better alternative?
  206. */
  207. if (test_tsk_thread_flag(p, TIF_MEMDIE))
  208. return ERR_PTR(-1UL);
  209. /*
  210. * This is in the process of releasing memory so wait for it
  211. * to finish before killing some other task by mistake.
  212. *
  213. * However, if p is the current task, we allow the 'kill' to
  214. * go ahead if it is exiting: this will simply set TIF_MEMDIE,
  215. * which will allow it to gain access to memory reserves in
  216. * the process of exiting and releasing its resources.
  217. * Otherwise we could get an easy OOM deadlock.
  218. */
  219. if (p->flags & PF_EXITING) {
  220. if (p != current)
  221. return ERR_PTR(-1UL);
  222. chosen = p;
  223. *ppoints = ULONG_MAX;
  224. }
  225. if (p->oomkilladj == OOM_DISABLE)
  226. continue;
  227. points = badness(p, uptime.tv_sec);
  228. if (points > *ppoints || !chosen) {
  229. chosen = p;
  230. *ppoints = points;
  231. }
  232. } while_each_thread(g, p);
  233. return chosen;
  234. }
  235. /**
  236. * dump_tasks - dump current memory state of all system tasks
  237. * @mem: target memory controller
  238. *
  239. * Dumps the current memory state of all system tasks, excluding kernel threads.
  240. * State information includes task's pid, uid, tgid, vm size, rss, cpu, oom_adj
  241. * score, and name.
  242. *
  243. * If the actual is non-NULL, only tasks that are a member of the mem_cgroup are
  244. * shown.
  245. *
  246. * Call with tasklist_lock read-locked.
  247. */
  248. static void dump_tasks(const struct mem_cgroup *mem)
  249. {
  250. struct task_struct *g, *p;
  251. printk(KERN_INFO "[ pid ] uid tgid total_vm rss cpu oom_adj "
  252. "name\n");
  253. do_each_thread(g, p) {
  254. struct mm_struct *mm;
  255. if (mem && !task_in_mem_cgroup(p, mem))
  256. continue;
  257. if (!thread_group_leader(p))
  258. continue;
  259. task_lock(p);
  260. mm = p->mm;
  261. if (!mm) {
  262. /*
  263. * total_vm and rss sizes do not exist for tasks with no
  264. * mm so there's no need to report them; they can't be
  265. * oom killed anyway.
  266. */
  267. task_unlock(p);
  268. continue;
  269. }
  270. printk(KERN_INFO "[%5d] %5d %5d %8lu %8lu %3d %3d %s\n",
  271. p->pid, __task_cred(p)->uid, p->tgid, mm->total_vm,
  272. get_mm_rss(mm), (int)task_cpu(p), p->oomkilladj,
  273. p->comm);
  274. task_unlock(p);
  275. } while_each_thread(g, p);
  276. }
  277. /*
  278. * Send SIGKILL to the selected process irrespective of CAP_SYS_RAW_IO
  279. * flag though it's unlikely that we select a process with CAP_SYS_RAW_IO
  280. * set.
  281. */
  282. static void __oom_kill_task(struct task_struct *p, int verbose)
  283. {
  284. if (is_global_init(p)) {
  285. WARN_ON(1);
  286. printk(KERN_WARNING "tried to kill init!\n");
  287. return;
  288. }
  289. if (!p->mm) {
  290. WARN_ON(1);
  291. printk(KERN_WARNING "tried to kill an mm-less task!\n");
  292. return;
  293. }
  294. if (verbose)
  295. printk(KERN_ERR "Killed process %d (%s)\n",
  296. task_pid_nr(p), p->comm);
  297. /*
  298. * We give our sacrificial lamb high priority and access to
  299. * all the memory it needs. That way it should be able to
  300. * exit() and clear out its resources quickly...
  301. */
  302. p->rt.time_slice = HZ;
  303. set_tsk_thread_flag(p, TIF_MEMDIE);
  304. force_sig(SIGKILL, p);
  305. }
  306. static int oom_kill_task(struct task_struct *p)
  307. {
  308. struct mm_struct *mm;
  309. struct task_struct *g, *q;
  310. mm = p->mm;
  311. /* WARNING: mm may not be dereferenced since we did not obtain its
  312. * value from get_task_mm(p). This is OK since all we need to do is
  313. * compare mm to q->mm below.
  314. *
  315. * Furthermore, even if mm contains a non-NULL value, p->mm may
  316. * change to NULL at any time since we do not hold task_lock(p).
  317. * However, this is of no concern to us.
  318. */
  319. if (mm == NULL)
  320. return 1;
  321. /*
  322. * Don't kill the process if any threads are set to OOM_DISABLE
  323. */
  324. do_each_thread(g, q) {
  325. if (q->mm == mm && q->oomkilladj == OOM_DISABLE)
  326. return 1;
  327. } while_each_thread(g, q);
  328. __oom_kill_task(p, 1);
  329. /*
  330. * kill all processes that share the ->mm (i.e. all threads),
  331. * but are in a different thread group. Don't let them have access
  332. * to memory reserves though, otherwise we might deplete all memory.
  333. */
  334. do_each_thread(g, q) {
  335. if (q->mm == mm && !same_thread_group(q, p))
  336. force_sig(SIGKILL, q);
  337. } while_each_thread(g, q);
  338. return 0;
  339. }
  340. static int oom_kill_process(struct task_struct *p, gfp_t gfp_mask, int order,
  341. unsigned long points, struct mem_cgroup *mem,
  342. const char *message)
  343. {
  344. struct task_struct *c;
  345. if (printk_ratelimit()) {
  346. printk(KERN_WARNING "%s invoked oom-killer: "
  347. "gfp_mask=0x%x, order=%d, oomkilladj=%d\n",
  348. current->comm, gfp_mask, order, current->oomkilladj);
  349. task_lock(current);
  350. cpuset_print_task_mems_allowed(current);
  351. task_unlock(current);
  352. dump_stack();
  353. mem_cgroup_print_oom_info(mem, current);
  354. show_mem();
  355. if (sysctl_oom_dump_tasks)
  356. dump_tasks(mem);
  357. }
  358. /*
  359. * If the task is already exiting, don't alarm the sysadmin or kill
  360. * its children or threads, just set TIF_MEMDIE so it can die quickly
  361. */
  362. if (p->flags & PF_EXITING) {
  363. __oom_kill_task(p, 0);
  364. return 0;
  365. }
  366. printk(KERN_ERR "%s: kill process %d (%s) score %li or a child\n",
  367. message, task_pid_nr(p), p->comm, points);
  368. /* Try to kill a child first */
  369. list_for_each_entry(c, &p->children, sibling) {
  370. if (c->mm == p->mm)
  371. continue;
  372. if (!oom_kill_task(c))
  373. return 0;
  374. }
  375. return oom_kill_task(p);
  376. }
  377. #ifdef CONFIG_CGROUP_MEM_RES_CTLR
  378. void mem_cgroup_out_of_memory(struct mem_cgroup *mem, gfp_t gfp_mask)
  379. {
  380. unsigned long points = 0;
  381. struct task_struct *p;
  382. read_lock(&tasklist_lock);
  383. retry:
  384. p = select_bad_process(&points, mem);
  385. if (PTR_ERR(p) == -1UL)
  386. goto out;
  387. if (!p)
  388. p = current;
  389. if (oom_kill_process(p, gfp_mask, 0, points, mem,
  390. "Memory cgroup out of memory"))
  391. goto retry;
  392. out:
  393. read_unlock(&tasklist_lock);
  394. }
  395. #endif
  396. static BLOCKING_NOTIFIER_HEAD(oom_notify_list);
  397. int register_oom_notifier(struct notifier_block *nb)
  398. {
  399. return blocking_notifier_chain_register(&oom_notify_list, nb);
  400. }
  401. EXPORT_SYMBOL_GPL(register_oom_notifier);
  402. int unregister_oom_notifier(struct notifier_block *nb)
  403. {
  404. return blocking_notifier_chain_unregister(&oom_notify_list, nb);
  405. }
  406. EXPORT_SYMBOL_GPL(unregister_oom_notifier);
  407. /*
  408. * Try to acquire the OOM killer lock for the zones in zonelist. Returns zero
  409. * if a parallel OOM killing is already taking place that includes a zone in
  410. * the zonelist. Otherwise, locks all zones in the zonelist and returns 1.
  411. */
  412. int try_set_zone_oom(struct zonelist *zonelist, gfp_t gfp_mask)
  413. {
  414. struct zoneref *z;
  415. struct zone *zone;
  416. int ret = 1;
  417. spin_lock(&zone_scan_lock);
  418. for_each_zone_zonelist(zone, z, zonelist, gfp_zone(gfp_mask)) {
  419. if (zone_is_oom_locked(zone)) {
  420. ret = 0;
  421. goto out;
  422. }
  423. }
  424. for_each_zone_zonelist(zone, z, zonelist, gfp_zone(gfp_mask)) {
  425. /*
  426. * Lock each zone in the zonelist under zone_scan_lock so a
  427. * parallel invocation of try_set_zone_oom() doesn't succeed
  428. * when it shouldn't.
  429. */
  430. zone_set_flag(zone, ZONE_OOM_LOCKED);
  431. }
  432. out:
  433. spin_unlock(&zone_scan_lock);
  434. return ret;
  435. }
  436. /*
  437. * Clears the ZONE_OOM_LOCKED flag for all zones in the zonelist so that failed
  438. * allocation attempts with zonelists containing them may now recall the OOM
  439. * killer, if necessary.
  440. */
  441. void clear_zonelist_oom(struct zonelist *zonelist, gfp_t gfp_mask)
  442. {
  443. struct zoneref *z;
  444. struct zone *zone;
  445. spin_lock(&zone_scan_lock);
  446. for_each_zone_zonelist(zone, z, zonelist, gfp_zone(gfp_mask)) {
  447. zone_clear_flag(zone, ZONE_OOM_LOCKED);
  448. }
  449. spin_unlock(&zone_scan_lock);
  450. }
  451. /*
  452. * Must be called with tasklist_lock held for read.
  453. */
  454. static void __out_of_memory(gfp_t gfp_mask, int order)
  455. {
  456. struct task_struct *p;
  457. unsigned long points;
  458. if (sysctl_oom_kill_allocating_task)
  459. if (!oom_kill_process(current, gfp_mask, order, 0, NULL,
  460. "Out of memory (oom_kill_allocating_task)"))
  461. return;
  462. retry:
  463. /*
  464. * Rambo mode: Shoot down a process and hope it solves whatever
  465. * issues we may have.
  466. */
  467. p = select_bad_process(&points, NULL);
  468. if (PTR_ERR(p) == -1UL)
  469. return;
  470. /* Found nothing?!?! Either we hang forever, or we panic. */
  471. if (!p) {
  472. read_unlock(&tasklist_lock);
  473. panic("Out of memory and no killable processes...\n");
  474. }
  475. if (oom_kill_process(p, gfp_mask, order, points, NULL,
  476. "Out of memory"))
  477. goto retry;
  478. }
  479. /*
  480. * pagefault handler calls into here because it is out of memory but
  481. * doesn't know exactly how or why.
  482. */
  483. void pagefault_out_of_memory(void)
  484. {
  485. unsigned long freed = 0;
  486. blocking_notifier_call_chain(&oom_notify_list, 0, &freed);
  487. if (freed > 0)
  488. /* Got some memory back in the last second. */
  489. return;
  490. /*
  491. * If this is from memcg, oom-killer is already invoked.
  492. * and not worth to go system-wide-oom.
  493. */
  494. if (mem_cgroup_oom_called(current))
  495. goto rest_and_return;
  496. if (sysctl_panic_on_oom)
  497. panic("out of memory from page fault. panic_on_oom is selected.\n");
  498. read_lock(&tasklist_lock);
  499. __out_of_memory(0, 0); /* unknown gfp_mask and order */
  500. read_unlock(&tasklist_lock);
  501. /*
  502. * Give "p" a good chance of killing itself before we
  503. * retry to allocate memory.
  504. */
  505. rest_and_return:
  506. if (!test_thread_flag(TIF_MEMDIE))
  507. schedule_timeout_uninterruptible(1);
  508. }
  509. /**
  510. * out_of_memory - kill the "best" process when we run out of memory
  511. * @zonelist: zonelist pointer
  512. * @gfp_mask: memory allocation flags
  513. * @order: amount of memory being requested as a power of 2
  514. *
  515. * If we run out of memory, we have the choice between either
  516. * killing a random task (bad), letting the system crash (worse)
  517. * OR try to be smart about which process to kill. Note that we
  518. * don't have to be perfect here, we just have to be good.
  519. */
  520. void out_of_memory(struct zonelist *zonelist, gfp_t gfp_mask, int order)
  521. {
  522. unsigned long freed = 0;
  523. enum oom_constraint constraint;
  524. blocking_notifier_call_chain(&oom_notify_list, 0, &freed);
  525. if (freed > 0)
  526. /* Got some memory back in the last second. */
  527. return;
  528. if (sysctl_panic_on_oom == 2)
  529. panic("out of memory. Compulsory panic_on_oom is selected.\n");
  530. /*
  531. * Check if there were limitations on the allocation (only relevant for
  532. * NUMA) that may require different handling.
  533. */
  534. constraint = constrained_alloc(zonelist, gfp_mask);
  535. read_lock(&tasklist_lock);
  536. switch (constraint) {
  537. case CONSTRAINT_MEMORY_POLICY:
  538. oom_kill_process(current, gfp_mask, order, 0, NULL,
  539. "No available memory (MPOL_BIND)");
  540. break;
  541. case CONSTRAINT_NONE:
  542. if (sysctl_panic_on_oom)
  543. panic("out of memory. panic_on_oom is selected\n");
  544. /* Fall-through */
  545. case CONSTRAINT_CPUSET:
  546. __out_of_memory(gfp_mask, order);
  547. break;
  548. }
  549. read_unlock(&tasklist_lock);
  550. /*
  551. * Give "p" a good chance of killing itself before we
  552. * retry to allocate memory unless "p" is current
  553. */
  554. if (!test_thread_flag(TIF_MEMDIE))
  555. schedule_timeout_uninterruptible(1);
  556. }