---
title: "linux内核OOM源码分析"
author: "nuistcc"
date: "2018-05-12T21:17:56Z"
tags: []
categories: ["编程语言"]
slug: "linux-oom"
draft: false
lastmod: "2018-05-12T21:17:56Z"
id: 2422620
url: "https://nuistcc.iteye.com/blog/2422620"
---

Out Of Memory(OOM)，即内存耗尽，当系统中内存耗尽时，如果不做处理，将处于崩溃的边缘，因为无内核资源可用，而系统运行时刻都可能需要申请内存。这时，内核需要采取一定的措施来防止系统崩溃，这就是我们熟知的OOM流程，其实就是要回收一些内存，而走到OOM流程，已经基本说明其它的回收内存的手段都已经尝试过了(比如回收cache)，这里通常只能通过kill进程来回收内存了，而选择被kill进程的标准就比较简单直接了，总体就是：谁用的多，就kill谁。  
OOM处理的基本流程简单描述如下：  
1、检查是否配置了/proc/sys/kernel/panic\_on\_oom，如果是则直接触发panic。  
2、检查是否配置了oom\_kill\_allocating\_task，即是否需要kill current进程来回收内存，如果是，且current进程是killable的，则kill current进程。  
3、根据既定策略选择需要kill的process，基本策略为：通过进程的内存占用情况计算“点数”，点数最高者被选中。  
4、如果没有选出来可kill的进程，那么直接panic(通常不会走到这个流程，但也有例外，比如，当被选中的进程处于D状态，或者正在被kill)  
5、kill掉被选中的进程，以释放内存。  
代码注释如下：

点击(此处)折叠或打开

01. /*
02. * OOM处理的主流程，上面的注释应该比较清楚了。
03. \*/
04. void out\_of\_memory(struct zonelist \*zonelist, gfp\_t gfp\_mask,
05. int order, nodemask\_t \*nodemask, bool force\_kill)
06. {
07. const nodemask\_t \*mpol\_mask;
08. struct task\_struct \*p;
09. unsigned long totalpages;
10. unsigned long freed = 0;
11. unsigned int uninitialized\_var(points);
12. enum oom\_constraint constraint = CONSTRAINT\_NONE;
13. int killed = 0;
14. // 调用block通知链oom\_nofify\_list中的函数
15. blocking\_notifier\_call\_chain(&oom\_notify\_list, 0, &freed);
16. if (freed &gt; 0)
17. /* Got some memory back in the last second. \*/
18. return;
19. /*
20. * If current has a pending SIGKILL or is exiting, then automatically
21. * select it. The goal is to allow it to allocate so that it may
22. * quickly exit and free its memory.
23. \*/
24. /*
25. * 如果当前进程有pending的SIGKILL(9)信号，或者正在退出，则选择当前进程来kill,
26. * 这样可以最快的达到释放内存的目的。
27. \*/
28. if (fatal\_signal\_pending(current) || current-&gt;flags & PF\_EXITING) {
29. set\_thread\_flag(TIF\_MEMDIE);
30. return;
31. }
32. /*
33. * Check if there were limitations on the allocation (only relevant for
34. * NUMA) that may require different handling.
35. \*/
36. /*
37. * 检查是否有限制，有几种不同的限制策略，仅用于NUMA场景
38. \*/
39. constraint = constrained\_alloc(zonelist, gfp\_mask, nodemask,
40. &totalpages);
41. mpol\_mask = (constraint == CONSTRAINT\_MEMORY\_POLICY) ? nodemask : NULL;
42. // 检查是否配置了/proc/sys/kernel/panic\_on\_oom，如果是则直接触发panic
43. check\_panic\_on\_oom(constraint, gfp\_mask, order, mpol\_mask);
44. /*
45. * 检查是否配置了oom\_kill\_allocating\_task，即是否需要kill current进程来
46. * 回收内存，如果是，且current进程是killable的，则kill current进程。
47. \*/
48. if (sysctl\_oom\_kill\_allocating\_task && current-&gt;mm &&
49. !oom\_unkillable\_task(current, NULL, nodemask) &&
50. current-&gt;signal-&gt;oom\_score\_adj != OOM\_SCORE\_ADJ\_MIN) {
51. get\_task\_struct(current);
52. // kill被选中的进程。
53. oom\_kill\_process(current, gfp\_mask, order, 0, totalpages, NULL,
54. nodemask,
55. "Out of memory (oom\_kill\_allocating\_task)");
56. goto out;
57. }
58. // 根据既定策略选择需要kill的process。
59. p = select\_bad\_process(&points, totalpages, mpol\_mask, force\_kill);
60. /* Found nothing?!?! Either we hang forever, or we panic. \*/
61. /*
62. * 如果没有选出来，即没有可kill的进程，那么直接panic
63. * 通常不会走到这个流程，但也有例外，比如，当被选中的进程处于D状态，或者正在被kill
64. \*/
65. if (!p) {
66. dump\_header(NULL, gfp\_mask, order, NULL, mpol\_mask);
67. panic("Out of memory and no killable processes...\\n");
68. }
69. // kill掉被选中的进程，以释放内存。
70. if (PTR\_ERR(p) != -1UL) {
71. oom\_kill\_process(p, gfp\_mask, order, points, totalpages, NULL,
72. nodemask, "Out of memory");
73. killed = 1;
74. }
75. out:
76. /*
77. * Give the killed threads a good chance of exiting before trying to
78. * allocate memory again.
79. \*/
80. /*
81. * 在重新分配内存之前，给被kill的进程1s的时间完成exit相关处理，通常情况
82. * 下，1s应该够了。
83. \*/
84. if (killed)
85. schedule\_timeout\_killable(1);
86. }

out\_of\_memory-&gt;select\_bad\_process  
通过select\_bad\_process函数选择被kill的进程，其基本流程为：  
1、遍历系统中的所有进程，进行"点数"计算  
2、进行一些特殊情况的处理，比如: 优先选择触发OOM的进程、不处理正在exit的进程等。  
3、计算"点数"，选择点数最大的进程。通过函数oom\_badness()  
代码注释和分析如下：

点击(此处)折叠或打开

01. /*
02. * OOM流程中，用来选择被kill的进程的函数
03. * @ppoints:点数，用来计算每个进程被"选中"可能性，点数越高，越可能被"选中"
04. \*/
05. static struct task\_struct \*select\_bad\_process(unsigned int \*ppoints,
06. unsigned long totalpages, const nodemask\_t \*nodemask,
07. bool force\_kill)
08. {
09. struct task\_struct \*g, \*p;
10. struct task\_struct \*chosen = NULL;
11. unsigned long chosen\_points = 0;
12. rcu\_read\_lock();
13. // 遍历系统中的所有进程，进行"点数"计算
14. do\_each\_thread(g, p) {
15. unsigned int points;
16. /*
17. * 进行一些特殊情况的处理，比如: 优先选择触发OOM的进程、不处理
18. * 正在exit的进程等。
19. \*/
20. switch (oom\_scan\_process\_thread(p, totalpages, nodemask,
21. force\_kill)) {
22. case OOM\_SCAN\_SELECT:
23. chosen = p;
24. chosen\_points = ULONG\_MAX;
25. /* fall through \*/
26. case OOM\_SCAN\_CONTINUE:
27. continue;
28. case OOM\_SCAN\_ABORT:
29. rcu\_read\_unlock();
30. return ERR\_PTR(-1UL);
31. case OOM\_SCAN\_OK:
32. break;
33. };
34. // 计算"点数"，选择点数最大的进程。
35. points = oom\_badness(p, NULL, nodemask, totalpages);
36. if (points &gt; chosen\_points) {
37. chosen = p;
38. chosen\_points = points;
39. }
40. } while\_each\_thread(g, p);
41. if (chosen)
42. get\_task\_struct(chosen);
43. rcu\_read\_unlock();
44. \*ppoints = chosen\_points * 1000 / totalpages;
45. return chosen;
46. }

out\_of\_memory-&gt;select\_bad\_process-&gt;oom\_scan\_process\_thread  
oom\_scan\_process\_thread函数的分析和注释如下：

点击(此处)折叠或打开

01. enum oom\_scan\_t oom\_scan\_process\_thread(struct task\_struct \*task,
02. unsigned long totalpages, const nodemask\_t \*nodemask,
03. bool force\_kill)
04. {
05. // 如果进程正在exit
06. if (task-&gt;exit\_state)
07. return OOM\_SCAN\_CONTINUE;
08. /*
09. * 如果进程不能被kill，比如: init进程或进程在nodemask对应的节点上，
10. * 没有可以释放的内存。
11. \*/
12. if (oom\_unkillable\_task(task, NULL, nodemask))
13. return OOM\_SCAN\_CONTINUE;
14. /*
15. * This task already has access to memory reserves and is being killed.
16. * Don't allow any other task to have access to the reserves.
17. \*/
18. /*
19. * 如果有进程正在被OOM流程kill，那么应该有内存可以释放了，就不需要再kill
20. * 其它进程了，此时返回abort，结束oom kill流程。
21. \*/
22. if (test\_tsk\_thread\_flag(task, TIF\_MEMDIE)) {
23. if (unlikely(frozen(task)))
24. \_\_thaw\_task(task);
25. if (!force\_kill)
26. return OOM\_SCAN\_ABORT;
27. }
28. // 如果不存在mm了(可能进程刚退出了)
29. if (!task-&gt;mm)
30. return OOM\_SCAN\_CONTINUE;
31. /*
32. * If task is allocating a lot of memory and has been marked to be
33. * killed first if it triggers an oom, then select it.
34. \*/
35. // 优先选择触发OOM的进程。
36. if (oom\_task\_origin(task))
37. return OOM\_SCAN\_SELECT;
38. if (task-&gt;flags & PF\_EXITING && !force\_kill) {
39. /*
40. * If this task is not being ptraced on exit, then wait for it
41. * to finish before killing some other task unnecessarily.
42. \*/
43. if (!(task-&gt;group\_leader-&gt;ptrace & PT\_TRACE\_EXIT))
44. return OOM\_SCAN\_ABORT;
45. }
46. return OOM\_SCAN\_OK;
47. }

out\_of\_memory-&gt;select\_bad\_process-&gt;oom\_badness  
oom\_badness用于计算进程的“点数”，点数最高者被选中，代码注释和分析如下：

点击(此处)折叠或打开

01. /*
02. * 计算进程"点数"(代表进程被选中的可能性)的函数，点数根据进程占用的物理内存来计算
03. * 物理内存占用越多，被选中的可能性越大。root processes有3%的bonus。
04. \*/
05. unsigned long oom\_badness(struct task\_struct \*p, struct mem\_cgroup \*memcg,
06. const nodemask\_t \*nodemask, unsigned long totalpages)
07. {
08. long points;
09. long adj;
10. if (oom\_unkillable\_task(p, memcg, nodemask))
11. return 0;
12. // 确认进程是否还存在
13. p = find\_lock\_task\_mm(p);
14. if (!p)
15. return 0;
16. adj = (long)p-&gt;signal-&gt;oom\_score\_adj;
17. if (adj == OOM\_SCORE\_ADJ\_MIN) {
18. task\_unlock(p);
19. return 0;
20. }
21. /*
22. * The baseline for the badness score is the proportion of RAM that each
23. * task's rss, pagetable and swap space use.
24. \*/
25. // 点数=rss(驻留内存/占用物理内存)+pte数+交换分区用量
26. points = get\_mm\_rss(p-&gt;mm) + p-&gt;mm-&gt;nr\_ptes +
27. get\_mm\_counter(p-&gt;mm, MM\_SWAPENTS);
28. task\_unlock(p);
29. /*
30. * Root processes get 3% bonus, just like the \_\_vm\_enough\_memory()
31. * implementation used by LSMs.
32. \*/
33. /*
34. * root用户启动的进程，有总 内存\*3% 的bonus，就是说可以使用比其它进程多3%的内存
35. * 3%=30/1000
36. \*/
37. if (has\_capability\_noaudit(p, CAP\_SYS\_ADMIN))
38. adj -= 30;
39. /* Normalize to oom\_score\_adj units \*/
40. // 归一化"点数"单位
41. adj \*= totalpages / 1000;
42. points += adj;
43. /*
44. * Never return 0 for an eligible task regardless of the root bonus and
45. * oom\_score\_adj (oom\_score\_adj can't be OOM\_SCORE\_ADJ\_MIN here).
46. \*/
47. return points &gt; 0 ? points : 1;
48. }

out\_of\_memory-&gt;oom\_kill\_process  
oom\_kill\_process()函数用于：kill被选中的进程，其实就是给指定进程发送SIGKILL信号，待被选中进程返回用户态时，进行信号处理。  
相关代码注释和分析如下：

点击(此处)折叠或打开

001. /*
002. * kill被选中的进程，在OOM流程中被调用
003. \*/
004. void oom\_kill\_process(struct task\_struct \*p, gfp\_t gfp\_mask, int order,
005. unsigned int points, unsigned long totalpages,
006. struct mem\_cgroup \*memcg, nodemask\_t \*nodemask,
007. const char \*message)
008. {
009. struct task\_struct \*victim = p;
010. struct task\_struct \*child;
011. struct task\_struct \*t = p;
012. struct mm\_struct \*mm;
013. unsigned int victim\_points = 0;
014. static DEFINE\_RATELIMIT\_STATE(oom\_rs, DEFAULT\_RATELIMIT\_INTERVAL,
015. DEFAULT\_RATELIMIT\_BURST);
016. /*
017. * If the task is already exiting, don't alarm the sysadmin or kill
018. * its children or threads, just set TIF\_MEMDIE so it can die quickly
019. \*/
020. /*
021. * 如果进程正在exiting，就没有必要再kill它了，直接设置TIF\_MEMDIE，然后返回。
022. \*/
023. if (p-&gt;flags & PF\_EXITING) {
024. set\_tsk\_thread\_flag(p, TIF\_MEMDIE);
025. put\_task\_struct(p);
026. return;
027. }
028. if (\_\_ratelimit(&oom\_rs))
029. dump\_header(p, gfp\_mask, order, memcg, nodemask);
030. task\_lock(p);
031. pr\_err("%s: Kill process %d (%s) score %d or sacrifice child\\n",
032. message, task\_pid\_nr(p), p-&gt;comm, points);
033. task\_unlock(p);
034. /*
035. * If any of p's children has a different mm and is eligible for kill,
036. * the one with the highest oom\_badness() score is sacrificed for its
037. * parent. This attempts to lose the minimal amount of work done while
038. * still freeing memory.
039. \*/
040. /*
041. * 如果被选中的进程的子进程，不跟其共享mm(通常是这样)，且膐om\_badness的
042. * 得分更高，那么重新选择该子进程为被kill的进程。
043. \*/
044. read\_lock(&tasklist\_lock);
045. do {
046. // 遍历被选中进程的所有子进程
047. list\_for\_each\_entry(child, &t-&gt;children, sibling) {
048. unsigned int child\_points;
049. // 如果不共享mm
050. if (child-&gt;mm == p-&gt;mm)
051. continue;
052. /*
053. * oom\_badness() returns 0 if the thread is unkillable
054. \*/
055. // 计算child?om\_badness得分
056. child\_points = oom\_badness(child, memcg, nodemask,
057. totalpages);
058. // 如果child得分更高，则将被选中进程换成child
059. if (child\_points &gt; victim\_points) {
060. put\_task\_struct(victim);
061. victim = child;
062. victim\_points = child\_points;
063. get\_task\_struct(victim);
064. }
065. }
066. } while\_each\_thread(p, t);
067. read\_unlock(&tasklist\_lock);
068. rcu\_read\_lock();
069. /*
070. * 遍历确认被选中进程的线程组，判断是否还存在task\_struct-&gt;mm，如果不存在
071. * (有可能这个时候进程退出了，或释放了mm),就没必要再kill了。
072. * 如果存在则选择线程组中的进程。
073. \*/
074. p = find\_lock\_task\_mm(victim);
075. if (!p) {
076. rcu\_read\_unlock();
077. put\_task\_struct(victim);
078. return;
079. // 如果新选择的进程跟之前的不是同一个，那么更新victim。
080. } else if (victim != p) {
081. get\_task\_struct(p);
082. put\_task\_struct(victim);
083. victim = p;
084. }
085. /* mm cannot safely be dereferenced after task\_unlock(victim) \*/
086. mm = victim-&gt;mm;
087. pr\_err("Killed process %d (%s) total-vm:%lukB, anon-rss:%lukB, file-rss:%lukB\\n",
088. task\_pid\_nr(victim), victim-&gt;comm, K(victim-&gt;mm-&gt;total\_vm),
089. K(get\_mm\_counter(victim-&gt;mm, MM\_ANONPAGES)),
090. K(get\_mm\_counter(victim-&gt;mm, MM\_FILEPAGES)));
091. task\_unlock(victim);
092. /*
093. * Kill all user processes sharing victim-&gt;mm in other thread groups, if
094. * any. They don't get access to memory reserves, though, to avoid
095. * depletion of all memory. This prevents mm-&gt;mmap\_sem livelock when an
096. * oom killed thread cannot exit because it requires the semaphore and
097. * its contended by another thread trying to allocate memory itself.
098. * That thread will now get access to memory reserves since it has a
099. * pending fatal signal.
100. \*/
101. /*
102. * 遍历系统中的所有进程，寻找在其它线程组中，跟被选中进程(victim)共享mm结构
103. * 的进程(内核线程除外)，共享mm结构即共享进程地址空间，比如fork后exec之前，
104. * 父子进程是共享mm的，回收内存必须要将共享mm的所有进程都kill掉。
105. \*/
106. for\_each\_process(p)
107. if (p-&gt;mm == mm && !same\_thread\_group(p, victim) &&
108. !(p-&gt;flags & PF\_KTHREAD)) {
109. if (p-&gt;signal-&gt;oom\_score\_adj == OOM\_SCORE\_ADJ\_MIN)
110. continue;
111. // 进行task\_struct相关操作时，通常需要获取该锁。
112. task\_lock(p);    /* Protect -&gt;comm from prctl() \*/
113. pr\_err("Kill process %d (%s) sharing same memory\\n",
114. task\_pid\_nr(p), p-&gt;comm);
115. task\_unlock(p);
116. // 通过向被选中的进程发送kill信号，来kill进程。
117. do\_send\_sig\_info(SIGKILL, SEND\_SIG\_FORCED, p, true);
118. }
119. rcu\_read\_unlock();
120. // 进程设置TIF\_MEMDIE标记，表示进程正在被oom killer终止中。
121. set\_tsk\_thread\_flag(victim, TIF\_MEMDIE);
122. /*
123. * 最终通过向被选中的进程发送kill信号，来kill进程，被kill的进程在从内核态
124. * 返回用户态时，进行信号处理。
125. * 被选中的进程可以是自己(current)，则current进程会在oom流程执行完成后，返回
126. * 用户态时，处理信号。
127. \*/
128. do\_send\_sig\_info(SIGKILL, SEND\_SIG\_FORCED, victim, true);
129. put\_task\_struct(victim);
130. }