当前位置:   article > 正文

OOM探究:XNU内存状态管理, Jetsam原理_xnu开源吗

xnu开源吗

OOM 其实是Out Of Memory的简称,指的是在 iOS 设备上当前应用因为内存占用过高而被操作系统强制终止,在用户侧的感知就是 App 一瞬间的闪退,与普通的 Crash 没有明显差异。但是当我们在调试阶段遇到这种崩溃的时候,从系统 设置- 隐私-分析与改进中是找不到普通类型的崩溃日志,只能够找到Jetsam开头的日志,这种形式的日志其实就是 OOM 崩溃之后系统生成的一种专门反映内存异常问题的日志。OOM是一种操作系统管理内存的机制。因为手机的内存是有限的,不可能无限制的使用,当内存不够时,需要将低优先级的进程kill,腾出内存以便高优先级的进程使用。

那OOM的触发机制到底是怎么样的呢?目前市上的资料说的都比较模糊,没有一个很清晰的介绍, 找了很多文章, 尝试总结一下

源码探究

xnu这块代码是开源的,在opensource.apple.com里可以下到整个 xnu 内核的代码。内存状态管理相关的代码主要是在kern_memorystatus.c(.h)文件中

优先级队列

首先系统对进程是分优先级的,整个系统会有一个优先级队列。

  1. #define MEMSTAT_BUCKET_COUNT (JETSAM_PRIORITY_MAX + 1)
  2. typedef struct memstat_bucket {
  3. TAILQ_HEAD(, proc) list;
  4. int count;
  5. } memstat_bucket_t;
  6. memstat_bucket_t memstat_bucket[MEMSTAT_BUCKET_COUNT];

kern_memorystatus.c中定义了一个memstat_bucket_t的结构体。结构体很简单,count 表示这个优先级下有多少个进程,list是一个链表,用来存放各个进程。(使用链表是为了插入和删除方便。)

memstat_bucket_t结构体之后,系统定义了一个memstat_bucket_t结构体的数组,用来存放系统进程的优先级队列。每个优先级对应一个memstat_bucket_t结构体,结构体中存放着这个优先级下的所有进程。

kern_memorystatus.h中定义了优先级有哪些:

  1. #define JETSAM_PRIORITY_REVISION 2
  2. #define JETSAM_PRIORITY_IDLE_HEAD -2
  3. /* The value -1 is an alias to JETSAM_PRIORITY_DEFAULT */
  4. #define JETSAM_PRIORITY_IDLE 0
  5. #define JETSAM_PRIORITY_IDLE_DEFERRED 1 /* Keeping this around till all xnu_quick_tests can be moved away from it.*/
  6. #define JETSAM_PRIORITY_AGING_BAND1 JETSAM_PRIORITY_IDLE_DEFERRED
  7. #define JETSAM_PRIORITY_BACKGROUND_OPPORTUNISTIC 2
  8. #define JETSAM_PRIORITY_AGING_BAND2 JETSAM_PRIORITY_BACKGROUND_OPPORTUNISTIC
  9. #define JETSAM_PRIORITY_BACKGROUND 3
  10. #define JETSAM_PRIORITY_ELEVATED_INACTIVE JETSAM_PRIORITY_BACKGROUND
  11. #define JETSAM_PRIORITY_MAIL 4
  12. #define JETSAM_PRIORITY_PHONE 5
  13. #define JETSAM_PRIORITY_UI_SUPPORT 8
  14. #define JETSAM_PRIORITY_FOREGROUND_SUPPORT 9
  15. #define JETSAM_PRIORITY_FOREGROUND 10
  16. #define JETSAM_PRIORITY_AUDIO_AND_ACCESSORY 12
  17. #define JETSAM_PRIORITY_CONDUCTOR 13
  18. #define JETSAM_PRIORITY_HOME 16
  19. #define JETSAM_PRIORITY_EXECUTIVE 17
  20. #define JETSAM_PRIORITY_IMPORTANT 18
  21. #define JETSAM_PRIORITY_CRITICAL 19
  22. #define JETSAM_PRIORITY_MAX 21
  23. /* TODO - tune. This should probably be lower priority */
  24. #define JETSAM_PRIORITY_DEFAULT 18
  25. #define JETSAM_PRIORITY_TELEPHONY 19

可以看到foreground是10,background 是3,当内存紧张的时候,后台的进程会优先被干掉,正常当foreground前面优先级的进程全被kill后,依然内存紧张,才会kill foreground进程

优先级规则是:内核进程优先级 > 操作系统优先级 > App 优先级。且前台 App 优先级高于后台运行的 App;当进程的优先级相同时, CPU 占用多的进程的优先级会被降低。

用户态的应用程序的线程不可能高于操作系统和内核。iOS 上应用程序优先级最高的是 SpringBoard;此外线程的优先级不是一成不变的。Mach 会根据线程的利用率和系统整体负载动态调整线程优先级。如果耗费 CPU 太多就降低线程优先级,如果线程过度挨饿,则会提升线程优先级。但是无论怎么变,程序都不能超过其所在线程的优先级区间范围。

OOM 类型

目前 OOM 主要分为11种类型:

  1. /* Cause */
  2. enum {
  3. kMemorystatusInvalid = JETSAM_REASON_INVALID,
  4. kMemorystatusKilled = JETSAM_REASON_GENERIC,
  5. kMemorystatusKilledHiwat = JETSAM_REASON_MEMORY_HIGHWATER, //high water
  6. kMemorystatusKilledVnodes = JETSAM_REASON_VNODE, // vnode
  7. kMemorystatusKilledVMPageShortage = JETSAM_REASON_MEMORY_VMPAGESHORTAGE, //vm page shortager
  8. kMemorystatusKilledVMThrashing = JETSAM_REASON_MEMORY_VMTHRASHING, // vm thrashing
  9. kMemorystatusKilledFCThrashing = JETSAM_REASON_MEMORY_FCTHRASHING, // fc thrashing
  10. kMemorystatusKilledPerProcessLimit = JETSAM_REASON_MEMORY_PERPROCESSLIMIT, // per process limit
  11. kMemorystatusKilledDiagnostic = JETSAM_REASON_MEMORY_DIAGNOSTIC, // diagnostic
  12. kMemorystatusKilledIdleExit = JETSAM_REASON_MEMORY_IDLE_EXIT, // idle exit
  13. kMemorystatusKilledZoneMapExhaustion = JETSAM_REASON_ZONE_MAP_EXHAUSTION // map exhaustion
  14. };

对应每种类型,输出日志时会有相应的字符串,输出到 log 中

  1. /* For logging clarity */
  2. static const char *memorystatus_kill_cause_name[] = {
  3. "" ,
  4. "jettisoned" , /* kMemorystatusKilled */
  5. "highwater" , /* kMemorystatusKilledHiwat */
  6. "vnode-limit" , /* kMemorystatusKilledVnodes */
  7. "vm-pageshortage" , /* kMemorystatusKilledVMPageShortage */
  8. "vm-thrashing" , /* kMemorystatusKilledVMThrashing */
  9. "fc-thrashing" , /* kMemorystatusKilledFCThrashing */
  10. "per-process-limit" , /* kMemorystatusKilledPerProcessLimit */
  11. "diagnostic" , /* kMemorystatusKilledDiagnostic */
  12. "idle-exit" , /* kMemorystatusKilledIdleExit */
  13. "zone-map-exhaustion" , /* kMemorystatusKilledZoneMapExhaustion */
  14. };

当我们的 App 触发 OOM 时,系统会有相应的日志写到手机的设置->隐私->分析->分析数据->jstsamEvent-xxx文件中。打开文件,可以看到reason一栏会标明 OOM 的类型

这是我手机里的一个jstsamEvent文件

  1. ...
  2. "largestProcess" : "Boom",
  3. "genCounter" : 23,
  4. "processes" : [
  5. {
  6. "uuid" : "ebd916c8-96e7-3b8f-985d-027098a13fd6",
  7. "states" : [
  8. "daemon",
  9. "idle"
  10. ],
  11. "killDelta" : 1887,
  12. "genCount" : 0,
  13. "age" : 200706725,
  14. "purgeable" : 0,
  15. "fds" : 50,
  16. "coalition" : 268,
  17. "rpages" : 34,
  18. "reason" : "vm-pageshortage",
  19. "pid" : 2205,
  20. "cpuTime" : 0.0030500000000000002,
  21. "name" : "xpcproxy",
  22. "lifetimeMax" : 79
  23. },
  24. ...

在这里我们可以看到占用内存最大的进程是 boom,OOM 的类型是vm-pageshortage

  • pageSize:指的是当前设备物理内存页的大小,当前设备是iPhoneXs Max,大小是 16KB,苹果 A7 芯片之前的设备物理内存页大小则是 4KB。

  • states:当前应用的运行状态,对于Heimdallr-Example这个应用而言是正在前台运行的状态,这类崩溃我们称之为FOOM(Foreground Out Of Memory);与此相对应的也有应用程序在后台发生的 OOM 崩溃,这类崩溃我们称之为BOOM(Background Out Of Memory)。

  • rpages:是resident pages的缩写,表明进程当前占用的内存页数量,Heimdallr-Example 这个应用占用的内存页数量是 92800,基于 pageSize 和 rpages 可以计算出应用崩溃时占用的内存大小:16384 * 92800 / 1024 /1024 = 1.4GB。

  • reason:表明进程被终止的的原因,Heimdallr-Example这个应用被终止的原因是超过了操作系统允许的单个进程物理内存占用的上限。

Jetsam机制清理策略可以总结为下面两点:

  1. 单个 App 物理内存占用超过上限

  2. 整个设备物理内存占用收到压力按照下面优先级完成清理:

    1. 用户应用>系统应用

    2. 内存占用高的应用>内存占用低的应用

    3. 后台应用>前台应用

stackoverflow上有一份数据,整理了单个App的 OOM 临界值

device

crash amount:MB

total amount:MB

percentage of total

iPad1

127

256

49%

iPad2

275

512

53%

iPad3

645

1024

62%

iPad4(iOS 8.1)

585

1024

57%

Pad Mini 1st Generation

297

512

58%

iPad Mini retina(iOS 7.1)

696

1024

68%

iPad Air

697

1024

68%

iPad Air 2(iOS 10.2.1)

1383

2048

68%

iPad Pro 9.7"(iOS 10.0.2 (14A456))

1395

1971

71%

iPad Pro 10.5”(iOS 11 beta4)

3057

4000

76%

iPad Pro 12.9” (2015)(iOS 11.2.1)

3058

3999

76%

iPad 10.2(iOS 13.2.3)

1844

2998

62%

iPod touch 4th gen(iOS 6.1.1)

130

256

51%

iPod touch 5th gen

286

512

56%

iPhone4

325

512

63%

iPhone4s

286

512

56%

iPhone5

645

1024

62%

iPhone5s

646

1024

63%

iPhone6(iOS 8.x)

645

1024

62%

iPhone6 Plus(iOS 8.x)

645

1024

62%

iPhone6s(iOS 9.2)

1396

2048

68%

iPhone6s Plus(iOS 10.2.1)

1396

2048

68%

iPhoneSE(iOS 9.3)

1395

2048

68%

iPhone7(iOS 10.2)

1395

2048

68%

iPhone7 Plus(iOS 10.2.1)

2040

3072

66%

iPhone8(iOS 12.1)

1364

1990

70%

iPhoneX(iOS 11.2.1)

1392

2785

50%

iPhoneXS(iOS 12.1)

2040

3754

54%

iPhoneXS Max(iOS 12.1)

2039

3735

55%

iPhoneXR(iOS 12.1)

1792

2813

63%

iPhone11(iOS 13.1.3)

2068

3844

54%

iPhone11 Pro Max(iOS 13.2.3)

2067

3740

55%

OOM 的触发方式

正常 OOM 的触发方式有2种,一种是同步触发,一种是异步触发。比如 VMPageShortage类型的 OOM 触发方式:

  1. boolean_t memorystatus_kill_on_VM_page_shortage(boolean_t async) {
  2. if (async) {
  3. return memorystatus_kill_process_async(-1, kMemorystatusKilledVMPageShortage);
  4. } else {
  5. os_reason_t jetsam_reason = os_reason_create(OS_REASON_JETSAM, JETSAM_REASON_MEMORY_VMPAGESHORTAGE);
  6. if (jetsam_reason == OS_REASON_NULL) {
  7. printf("memorystatus_kill_on_VM_page_shortage -- sync: failed to allocate jetsam reason\n");
  8. }
  9. return memorystatus_kill_process_sync(-1, kMemorystatusKilledVMPageShortage, jetsam_reason);
  10. }
  11. }

同步触发比较简单粗暴,直接根据pid,kill 掉相应的进程。如果 pid 传的是-1,就 kill 掉优先级队列里面优先级最低的那个进程。(如果多个进程同一个优先级,系统会根据占用内存大小排序,kill 掉内存占用最大的进程)

  1. static boolean_t
  2. memorystatus_kill_process_sync(pid_t victim_pid, uint32_t cause, os_reason_t jetsam_reason) {
  3. boolean_t res;
  4. uint32_t errors = 0;
  5. if (victim_pid == -1) {
  6. /* No pid, so kill first process */
  7. res = memorystatus_kill_top_process(TRUE, TRUE, cause, jetsam_reason, NULL, &errors);
  8. } else {
  9. res = memorystatus_kill_specific_process(victim_pid, cause, jetsam_reason);
  10. }
  11. if (errors) {
  12. memorystatus_clear_errors();
  13. }
  14. return res;
  15. }

而异步触发实际是通过设置一个内存标志位,标志当前内存已经有问题了,然后唤醒专门的内存管理线程去管理内存状态,触发 OOM,kill 部分进程,回收内存。

  1. static boolean_t
  2. memorystatus_kill_process_async(pid_t victim_pid, uint32_t cause) {
  3. /*
  4. * TODO: allow a general async path
  5. *
  6. * NOTE: If a new async kill cause is added, make sure to update memorystatus_thread() to
  7. * add the appropriate exit reason code mapping.
  8. */
  9. if ((victim_pid != -1) || (cause != kMemorystatusKilledVMPageShortage && cause != kMemorystatusKilledVMThrashing &&
  10. cause != kMemorystatusKilledFCThrashing && cause != kMemorystatusKilledZoneMapExhaustion)) {
  11. return FALSE;
  12. }
  13. kill_under_pressure_cause = cause;
  14. memorystatus_thread_wake();
  15. return TRUE;
  16. }

内存状态管理线程

系统中专门有一个线程用来管理内存状态,当内存状态出现问题或者内存压力过大时,将会通过一定的策略,干掉一些 App 回收内存。

将部分无关代码删除后,内存状态管理线程代码是这样的

  1. static void
  2. memorystatus_thread(void *param __unused, wait_result_t wr __unused)
  3. {
  4. static boolean_t is_vm_privileged = FALSE;
  5. boolean_t post_snapshot = FALSE;
  6. uint32_t errors = 0;
  7. uint32_t hwm_kill = 0;
  8. boolean_t sort_flag = TRUE;
  9. boolean_t corpse_list_purged = FALSE;
  10. int jld_idle_kills = 0;
  11. if (is_vm_privileged == FALSE) {
  12. /* 一些初始化工作 */
  13. thread_wire(host_priv_self(), current_thread(), TRUE);
  14. is_vm_privileged = TRUE;
  15. if (vm_restricted_to_single_processor == TRUE)
  16. thread_vm_bind_group_add();
  17. thread_set_thread_name(current_thread(), "VM_memorystatus");
  18. memorystatus_thread_block(0, memorystatus_thread);
  19. }
  20. // 真正的内存管理的循环
  21. while (memorystatus_action_needed()) {
  22. boolean_t killed;
  23. int32_t priority;
  24. uint32_t cause;
  25. uint64_t jetsam_reason_code = JETSAM_REASON_INVALID;
  26. os_reason_t jetsam_reason = OS_REASON_NULL;
  27. cause = kill_under_pressure_cause;
  28. switch (cause) {
  29. case kMemorystatusKilledFCThrashing:
  30. jetsam_reason_code = JETSAM_REASON_MEMORY_FCTHRASHING;
  31. break;
  32. case kMemorystatusKilledVMThrashing:
  33. jetsam_reason_code = JETSAM_REASON_MEMORY_VMTHRASHING;
  34. break;
  35. case kMemorystatusKilledZoneMapExhaustion:
  36. jetsam_reason_code = JETSAM_REASON_ZONE_MAP_EXHAUSTION;
  37. break;
  38. case kMemorystatusKilledVMPageShortage:
  39. /* falls through */
  40. default:
  41. jetsam_reason_code = JETSAM_REASON_MEMORY_VMPAGESHORTAGE;
  42. cause = kMemorystatusKilledVMPageShortage;
  43. break;
  44. }
  45. /* HIGHWATER类型的 OOM 触发 */
  46. boolean_t is_critical = TRUE;
  47. if (memorystatus_act_on_hiwat_processes(&errors, &hwm_kill, &post_snapshot, &is_critical)) {
  48. if (is_critical == FALSE) {
  49. /*
  50. * For now, don't kill any other processes.
  51. */
  52. break;
  53. } else {
  54. goto done;
  55. }
  56. }
  57. jetsam_reason = os_reason_create(OS_REASON_JETSAM, jetsam_reason_code);
  58. if (jetsam_reason == OS_REASON_NULL) {
  59. printf("memorystatus_thread: failed to allocate jetsam reason\n");
  60. }
  61. // 核心的 OOM 触发机制
  62. if (memorystatus_act_aggressive(cause, jetsam_reason, &jld_idle_kills, &corpse_list_purged, &post_snapshot)) {
  63. goto done;
  64. }
  65. os_reason_ref(jetsam_reason);
  66. /* LRU,干掉优先级最低的一个进程 */
  67. killed = memorystatus_kill_top_process(TRUE, sort_flag, cause, jetsam_reason, &priority, &errors);
  68. sort_flag = FALSE;
  69. if (killed) {
  70. /* Jetsam Loop Detection */
  71. if (memorystatus_jld_enabled == TRUE) {
  72. if ((priority == JETSAM_PRIORITY_IDLE) || (priority == system_procs_aging_band) || (priority == applications_aging_band)) {
  73. jld_idle_kills++;
  74. }
  75. }
  76. if ((priority >= JETSAM_PRIORITY_UI_SUPPORT) && (total_corpses_count() > 0) && (corpse_list_purged == FALSE)) {
  77. task_purge_all_corpses();
  78. corpse_list_purged = TRUE;
  79. }
  80. goto done;
  81. }
  82. if (memorystatus_avail_pages_below_critical()) {
  83. /*
  84. * Still under pressure and unable to kill a process - purge corpse memory
  85. */
  86. if (total_corpses_count() > 0) {
  87. task_purge_all_corpses();
  88. corpse_list_purged = TRUE;
  89. }
  90. if (memorystatus_avail_pages_below_critical()) {
  91. /*
  92. * Still under pressure and unable to kill a process - panic
  93. */
  94. panic("memorystatus_jetsam_thread: no victim! available pages:%llu\n", (uint64_t)memorystatus_available_pages);
  95. }
  96. }
  97. done:
  98. /*
  99. * We do not want to over-kill when thrashing has been detected.
  100. * To avoid that, we reset the flag here and notify the
  101. * compressor.
  102. */
  103. if (is_reason_thrashing(kill_under_pressure_cause)) {
  104. kill_under_pressure_cause = 0;
  105. #if CONFIG_JETSAM
  106. vm_thrashing_jetsam_done();
  107. #endif /* CONFIG_JETSAM */
  108. } else if (is_reason_zone_map_exhaustion(kill_under_pressure_cause)) {
  109. kill_under_pressure_cause = 0;
  110. }
  111. os_reason_free(jetsam_reason);
  112. }
  113. kill_under_pressure_cause = 0;
  114. if (errors) {
  115. memorystatus_clear_errors();
  116. }
  117. }

代码比较多,我们来慢慢解析

准入条件

我们可以看到真正核心的代码在while (memorystatus_action_needed())的循环里面,memorystatus_action_needed是触发 OOM 的核心判断条件

  1. /* Does cause indicate vm or fc thrashing? */
  2. static boolean_t
  3. is_reason_thrashing(unsigned cause)
  4. {
  5. switch (cause) {
  6. case kMemorystatusKilledVMThrashing:
  7. case kMemorystatusKilledFCThrashing:
  8. return TRUE;
  9. default:
  10. return FALSE;
  11. }
  12. }
  13. /* Is the zone map almost full? */
  14. static boolean_t
  15. is_reason_zone_map_exhaustion(unsigned cause)
  16. {
  17. if (cause == kMemorystatusKilledZoneMapExhaustion)
  18. return TRUE;
  19. return FALSE;
  20. }
  21. static boolean_t
  22. memorystatus_action_needed(void)
  23. {
  24. return (is_reason_thrashing(kill_under_pressure_cause) ||
  25. is_reason_zone_map_exhaustion(kill_under_pressure_cause) ||
  26. memorystatus_available_pages <= memorystatus_available_pages_pressure);
  27. }

kill_under_pressure_cause值为kMemorystatusKilledVMThrashing,kMemorystatusKilledFCThrashing,kMemorystatusKilledZoneMapExhaustion时,或者当前可用内存 memorystatus_available_pages 小于阈值memorystatus_available_pages_pressure时,会走进去触发 OOM。

high-water

进入循环之后,首先走到memorystatus_act_on_hiwat_processes

  1. /* HIGHWATER类型的 OOM 触发 */
  2. boolean_t is_critical = TRUE;
  3. if (memorystatus_act_on_hiwat_processes(&errors, &hwm_kill, &post_snapshot, &is_critical)) {
  4. if (is_critical == FALSE) {
  5. /*
  6. * For now, don't kill any other processes.
  7. */
  8. break;
  9. } else {
  10. goto done;
  11. }
  12. }

这是触发HIGHWATER类型 OOM 的关键方法

  1. static boolean_t
  2. memorystatus_act_on_hiwat_processes(uint32_t *errors, uint32_t *hwm_kill, boolean_t *post_snapshot, __unused boolean_t *is_critical)
  3. {
  4. boolean_t killed = memorystatus_kill_hiwat_proc(errors);
  5. if (killed) {
  6. *hwm_kill = *hwm_kill + 1;
  7. *post_snapshot = TRUE;
  8. return TRUE;
  9. } else {
  10. memorystatus_hwm_candidates = FALSE;
  11. }
  12. return FALSE;
  13. }

memorystatus_act_on_hiwat_processes会直接调用memorystatus_kill_hiwat_proc,核心代码都在memorystatus_kill_hiwat_proc中。

  1. static boolean_t
  2. memorystatus_kill_hiwat_proc(uint32_t *errors)
  3. {
  4. pid_t aPid = 0;
  5. proc_t p = PROC_NULL, next_p = PROC_NULL;
  6. boolean_t new_snapshot = FALSE, killed = FALSE;
  7. int kill_count = 0;
  8. unsigned int i = 0;
  9. uint32_t aPid_ep;
  10. uint64_t killtime = 0;
  11. clock_sec_t tv_sec;
  12. clock_usec_t tv_usec;
  13. uint32_t tv_msec;
  14. os_reason_t jetsam_reason = OS_REASON_NULL;
  15. jetsam_reason = os_reason_create(OS_REASON_JETSAM, JETSAM_REASON_MEMORY_HIGHWATER);
  16. proc_list_lock();
  17. next_p = memorystatus_get_first_proc_locked(&i, TRUE);
  18. while (next_p) {
  19. uint64_t footprint_in_bytes = 0;
  20. uint64_t memlimit_in_bytes = 0;
  21. boolean_t skip = 0;
  22. p = next_p;
  23. next_p = memorystatus_get_next_proc_locked(&i, p, TRUE);
  24. aPid = p->p_pid;
  25. aPid_ep = p->p_memstat_effectivepriority;
  26. if (p->p_memstat_state & (P_MEMSTAT_ERROR | P_MEMSTAT_TERMINATED)) {
  27. continue;
  28. }
  29. /* skip if no limit set */
  30. if (p->p_memstat_memlimit <= 0) {
  31. continue;
  32. }
  33. footprint_in_bytes = get_task_phys_footprint(p->task);
  34. memlimit_in_bytes = (((uint64_t)p->p_memstat_memlimit) * 1024ULL * 1024ULL); /* convert MB to bytes */
  35. skip = (footprint_in_bytes <= memlimit_in_bytes);
  36. #if CONFIG_FREEZE
  37. if (!skip) {
  38. if (p->p_memstat_state & P_MEMSTAT_LOCKED) {
  39. skip = TRUE;
  40. } else {
  41. skip = FALSE;
  42. }
  43. }
  44. #endif
  45. if (skip) {
  46. continue;
  47. } else {
  48. if (memorystatus_jetsam_snapshot_count == 0) {
  49. p->p_memstat_state |= P_MEMSTAT_TERMINATED;
  50. killtime = mach_absolute_time();
  51. absolutetime_to_microtime(killtime, &tv_sec, &tv_usec);
  52. tv_msec = tv_usec / 1000;
  53. {
  54. memorystatus_update_jetsam_snapshot_entry_locked(p, kMemorystatusKilledHiwat, killtime);
  55. if (proc_ref_locked(p) == p) {
  56. proc_list_unlock();
  57. /*
  58. * memorystatus_do_kill drops a reference, so take another one so we can
  59. * continue to use this exit reason even after memorystatus_do_kill()
  60. * returns
  61. */
  62. os_reason_ref(jetsam_reason);
  63. killed = memorystatus_do_kill(p, kMemorystatusKilledHiwat, jetsam_reason);
  64. /* Success? */
  65. if (killed) {
  66. proc_rele(p);
  67. kill_count++;
  68. goto exit;
  69. }
  70. proc_list_lock();
  71. proc_rele_locked(p);
  72. p->p_memstat_state &= ~P_MEMSTAT_TERMINATED;
  73. p->p_memstat_state |= P_MEMSTAT_ERROR;
  74. *errors += 1;
  75. }
  76. i = 0;
  77. next_p = memorystatus_get_first_proc_locked(&i, TRUE);
  78. }
  79. }
  80. }
  81. proc_list_unlock();
  82. exit:
  83. os_reason_free(jetsam_reason);
  84. return killed;
  85. }

首先通过memorystatus_get_first_proc_locked(&i, TRUE)去优先级队列里面取出优先级最低的进程。如果这个进程内存小于阈值(footprint_in_bytes <= memlimit_in_bytes),则跳过然后取下一个进程memorystatus_get_next_proc_locked,如果内存超过阈值,将通过memorystatus_do_kill干掉这个进程,并结束循环。

我们可以看到这里计算内存的口径主要用的是phys_footprint,不过目前观察我自己手机上的 OOM 类型,从未见过high-water 类型的 OOM,猜测可能high-water的阈值比较高,比较难触发,大家也可以看看自己手机里的 OOM 类型,如果有 high-water 类型的 OOM,可以告诉我

normal kill

如果没有high-water的进程,程序继续往下执行,走到memorystatus_act_aggressive方法里,这个方法是通常oom的触发方法,大部分OOM都在这里面触发。

  1. static boolean_t
  2. memorystatus_act_aggressive(uint32_t cause, os_reason_t jetsam_reason, int *jld_idle_kills, boolean_t *corpse_list_purged, boolean_t *post_snapshot)
  3. {
  4. if (memorystatus_jld_enabled == TRUE) {
  5. boolean_t killed;
  6. uint32_t errors = 0;
  7. /* Jetsam Loop Detection - locals */
  8. memstat_bucket_t *bucket;
  9. int jld_bucket_count = 0;
  10. struct timeval jld_now_tstamp = {0,0};
  11. uint64_t jld_now_msecs = 0;
  12. int elevated_bucket_count = 0;
  13. /* Jetsam Loop Detection - statics */
  14. static uint64_t jld_timestamp_msecs = 0;
  15. static int jld_idle_kill_candidates = 0; /* Number of available processes in band 0,1 at start */
  16. static int jld_eval_aggressive_count = 0; /* Bumps the max priority in aggressive loop */
  17. static int32_t jld_priority_band_max = JETSAM_PRIORITY_UI_SUPPORT;
  18. microuptime(&jld_now_tstamp);
  19. jld_now_msecs = (jld_now_tstamp.tv_sec * 1000);
  20. proc_list_lock();
  21. switch (jetsam_aging_policy) {
  22. case kJetsamAgingPolicyLegacy:
  23. bucket = &memstat_bucket[JETSAM_PRIORITY_IDLE];
  24. jld_bucket_count = bucket->count;
  25. bucket = &memstat_bucket[JETSAM_PRIORITY_AGING_BAND1];
  26. jld_bucket_count += bucket->count;
  27. break;
  28. case kJetsamAgingPolicySysProcsReclaimedFirst:
  29. case kJetsamAgingPolicyAppsReclaimedFirst:
  30. bucket = &memstat_bucket[JETSAM_PRIORITY_IDLE];
  31. jld_bucket_count = bucket->count;
  32. bucket = &memstat_bucket[system_procs_aging_band];
  33. jld_bucket_count += bucket->count;
  34. bucket = &memstat_bucket[applications_aging_band];
  35. jld_bucket_count += bucket->count;
  36. break;
  37. case kJetsamAgingPolicyNone:
  38. default:
  39. bucket = &memstat_bucket[JETSAM_PRIORITY_IDLE];
  40. jld_bucket_count = bucket->count;
  41. break;
  42. }
  43. bucket = &memstat_bucket[JETSAM_PRIORITY_ELEVATED_INACTIVE];
  44. elevated_bucket_count = bucket->count;
  45. proc_list_unlock();
  46. if ( (jld_bucket_count == 0) ||
  47. (jld_now_msecs > (jld_timestamp_msecs + memorystatus_jld_eval_period_msecs))) {
  48. jld_timestamp_msecs = jld_now_msecs;
  49. // 先回收优先级特别低的进程:JETSAM_PRIORITY_IDLE,system_procs_aging_band,applications_aging_band,这些进程回收后jld_bucket_count将等于0
  50. jld_idle_kill_candidates = jld_bucket_count;
  51. *jld_idle_kills = 0;
  52. jld_eval_aggressive_count = 0;
  53. jld_priority_band_max = JETSAM_PRIORITY_UI_SUPPORT;
  54. }
  55. // 正常状态下先回收一些随时可以回收的线程:JETSAM_PRIORITY_IDLE,system_procs_aging_band,applications_aging_band,这些进程回收后才能走进这个判断里面
  56. if (*jld_idle_kills > jld_idle_kill_candidates) {
  57. jld_eval_aggressive_count++;
  58. if ((jld_eval_aggressive_count == memorystatus_jld_eval_aggressive_count) &&
  59. (total_corpses_count() > 0) && (*corpse_list_purged == FALSE)) {
  60. task_purge_all_corpses();
  61. *corpse_list_purged = TRUE;
  62. }
  63. else if (jld_eval_aggressive_count > memorystatus_jld_eval_aggressive_count) {
  64. if ((memorystatus_jld_eval_aggressive_priority_band_max < 0) ||
  65. (memorystatus_jld_eval_aggressive_priority_band_max >= MEMSTAT_BUCKET_COUNT)) {
  66. } else {
  67. jld_priority_band_max = memorystatus_jld_eval_aggressive_priority_band_max;
  68. }
  69. }
  70. // 先干掉后台线程
  71. /* Visit elevated processes first */
  72. while (elevated_bucket_count) {
  73. elevated_bucket_count--;
  74. os_reason_ref(jetsam_reason);
  75. killed = memorystatus_kill_elevated_process(
  76. cause,
  77. jetsam_reason,
  78. jld_eval_aggressive_count,
  79. &errors);
  80. if (killed) {
  81. *post_snapshot = TRUE;
  82. // 如果还是有压力,就继续杀App
  83. if (memorystatus_avail_pages_below_pressure()) {
  84. /*
  85. * Still under pressure.
  86. * Find another pinned processes.
  87. */
  88. continue;
  89. } else {
  90. return TRUE;
  91. }
  92. } else {
  93. break;
  94. }
  95. }
  96. // 干掉前台线程
  97. killed = memorystatus_kill_top_process_aggressive(
  98. kMemorystatusKilledVMThrashing,
  99. jld_eval_aggressive_count,
  100. jld_priority_band_max,
  101. &errors);
  102. if (killed) {
  103. /* Always generate logs after aggressive kill */
  104. *post_snapshot = TRUE;
  105. *jld_idle_kills = 0;
  106. return TRUE;
  107. }
  108. }
  109. return FALSE;
  110. }
  111. return FALSE;
  112. }

这里的逻辑比较多,我们慢慢解释。

首先有一个jld_bucket_count,这里面包含可以直接干掉的低优先级进程数量。

  1. switch (jetsam_aging_policy) {
  2. case kJetsamAgingPolicyLegacy:
  3. bucket = &memstat_bucket[JETSAM_PRIORITY_IDLE];
  4. jld_bucket_count = bucket->count;
  5. bucket = &memstat_bucket[JETSAM_PRIORITY_AGING_BAND1];
  6. jld_bucket_count += bucket->count;
  7. break;
  8. case kJetsamAgingPolicySysProcsReclaimedFirst:
  9. case kJetsamAgingPolicyAppsReclaimedFirst:
  10. bucket = &memstat_bucket[JETSAM_PRIORITY_IDLE];
  11. jld_bucket_count = bucket->count;
  12. bucket = &memstat_bucket[system_procs_aging_band];
  13. jld_bucket_count += bucket->count;
  14. bucket = &memstat_bucket[applications_aging_band];
  15. jld_bucket_count += bucket->count;
  16. break;
  17. case kJetsamAgingPolicyNone:
  18. default:
  19. bucket = &memstat_bucket[JETSAM_PRIORITY_IDLE];
  20. jld_bucket_count = bucket->count;
  21. break;
  22. }
  23. if ( (jld_bucket_count == 0) ||
  24. (jld_now_msecs > (jld_timestamp_msecs + memorystatus_jld_eval_period_msecs))) {
  25. jld_timestamp_msecs = jld_now_msecs;
  26. // 先回收优先级特别低的进程:JETSAM_PRIORITY_IDLE,system_procs_aging_band,applications_aging_band,这些进程回收后jld_bucket_count将等于0
  27. jld_idle_kill_candidates = jld_bucket_count;
  28. *jld_idle_kills = 0;
  29. jld_eval_aggressive_count = 0;
  30. jld_priority_band_max = JETSAM_PRIORITY_UI_SUPPORT;
  31. }
  32. // 正常状态下先回收一些随时可以回收的线程:JETSAM_PRIORITY_IDLE,system_procs_aging_band,applications_aging_band,这些进程回收后才能走进这个判断里面
  33. if (*jld_idle_kills > jld_idle_kill_candidates) {
  34. // 这里面是我们App经常触发OOM的地方
  35. }
  36. killed = memorystatus_kill_top_process(TRUE, sort_flag, cause, jetsam_reason, &priority, &errors);
  37. if (killed) {
  38. jld_idle_kills++;
  39. }

根据jetsam_aging_policy确定哪些优先级类型的进程需要被直接干掉。正常走到kJetsamAgingPolicyAppsReclaimedFirst或者kJetsamAgingPolicySysProcsReclaimedFirstjld_bucket_count = JETSAM_PRIORITY_IDLE + system_procs_aging_band + applications_aging_band

*jld_idle_kills表示已经kill掉的低优先级进程,每次kill掉一个低优先级进程jld_idle_kills++jld_idle_kill_candidates = jld_bucket_count;,在if (*jld_idle_kills > jld_idle_kill_candidates)的判断条件里,只有前面提到的jld_bucket_count的低优先级进程全部被干掉了,才会走到判断条件里面。

所以当内存不够的时候,系统会先回收JETSAM_PRIORITY_IDLE ``system_procs_aging_band ``applications_aging_band优先级的进程。

我们再来看判断条件里面

  1. if (*jld_idle_kills > jld_idle_kill_candidates) {
  2. jld_eval_aggressive_count++;
  3. if ((jld_eval_aggressive_count == memorystatus_jld_eval_aggressive_count) &&
  4. (total_corpses_count() > 0) && (*corpse_list_purged == FALSE)) {
  5. task_purge_all_corpses();
  6. *corpse_list_purged = TRUE;
  7. }
  8. else if (jld_eval_aggressive_count > memorystatus_jld_eval_aggressive_count) {
  9. if ((memorystatus_jld_eval_aggressive_priority_band_max < 0) ||
  10. (memorystatus_jld_eval_aggressive_priority_band_max >= MEMSTAT_BUCKET_COUNT)) {
  11. } else {
  12. jld_priority_band_max = memorystatus_jld_eval_aggressive_priority_band_max;
  13. }
  14. }
  15. // 先干掉后台线程
  16. /* Visit elevated processes first */
  17. while (elevated_bucket_count) {
  18. elevated_bucket_count--;
  19. os_reason_ref(jetsam_reason);
  20. killed = memorystatus_kill_elevated_process(
  21. cause,
  22. jetsam_reason,
  23. jld_eval_aggressive_count,
  24. &errors);
  25. if (killed) {
  26. *post_snapshot = TRUE;
  27. // 如果还是有压力,就继续杀App
  28. if (memorystatus_avail_pages_below_pressure()) {
  29. /*
  30. * Still under pressure.
  31. * Find another pinned processes.
  32. */
  33. continue;
  34. } else {
  35. return TRUE;
  36. }
  37. } else {
  38. break;
  39. }
  40. }
  41. // 干掉前台线程
  42. killed = memorystatus_kill_top_process_aggressive(
  43. kMemorystatusKilledVMThrashing,
  44. jld_eval_aggressive_count,
  45. jld_priority_band_max,
  46. &errors);
  47. if (killed) {
  48. /* Always generate logs after aggressive kill */
  49. *post_snapshot = TRUE;
  50. *jld_idle_kills = 0;
  51. return TRUE;
  52. }
  53. }

他会先通过memorystatus_kill_elevated_process干掉后台的进程,每干掉一个进程,检测一下内存压力,检测内存压力还是通过memorystatus_available_pages

  1. static boolean_t memorystatus_avail_pages_below_pressure(void) {
  2. return (memorystatus_available_pages <= memorystatus_available_pages_pressure);
  3. }

如果memorystatus_available_pages还是小于阈值,则继续kill下一个进程。当所有后台进程都被kill后。如果还有内存压力,再通过memorystatus_kill_top_process_aggressivekill掉优先级最低的进程。这里是触发FOOM的关键,如果foreground已经是最低优先级的进程了,那就会发生FOOM,kill掉前台的App

memorystatus_available_pages计算

是否触发FOOM,主要还是根据memorystatus_available_pages是否小于阈值。那memorystatus_available_pages怎么计算呢?

查阅源码,可以找到

  1. #define VM_CHECK_MEMORYSTATUS do { \
  2. memorystatus_pages_update( \
  3. vm_page_pageable_external_count + \
  4. vm_page_free_count + \
  5. (VM_DYNAMIC_PAGING_ENABLED() ? 0 : vm_page_purgeable_count) \
  6. ); \
  7. } while(0)
  8. void memorystatus_pages_update(unsigned int pages_avail)
  9. {
  10. memorystatus_available_pages = pages_avail;
  11. ...
  12. }

可以看到memorystatus_available_pages = vm_page_pageable_external_count + vm_page_free_count + vm_page_purgeable_count

  • vm_page_pageable_external_count: iOS里表示已经备份的page count,内存不够时,可以使用
  • vm_page_free_count: 表示未使用的page count
  • vm_page_purgeable_count: 表示可清理的page count

另外memorystatus_available_pages_pressure实际等于手机最大内存的15%。也就是说当可用内存小于系统内存的15%时,就会触发OOM了

逻辑汇总

纵观memorystatus_thread代码,逻辑如下:

  1. 判断 kill_under_pressure_cause值为
    kMemorystatusKilledVMThrashing,
    kMemorystatusKilledFCThrashing,
    kMemorystatusKilledZoneMapExhaustion时,
    或者当前可用内存 memorystatus_available_pages 小于阈值memorystatus_available_pages_pressure,进入OOM逻辑
  2. 遍历每个进程,跟据phys_footprint,判断每个进程是否高于阈值,如果高于阈值,以high-water类型kill进程,触发OOM
  3. 如果JETSAM_PRIORITY_IDLE,
    JETSAM_PRIORITY_AGING_BAND1,
    JETSAM_PRIORITY_IDLE优先级队列中还存在进程,则kill一个最低优先级的进程,再次走1的判断逻辑
  4. 当所有低优先级进程被kill掉后,如果memorystatus_available_pages仍然小于阈值,先kill掉后台进程,每kill一个进程,判断一下memorystatus_available_pages是否还小于阈值,如果已经小于阈值,则结束流程,走到1
  5. 当所有后台优先级进程都被kill后,调用memorystatus_kill_top_process_aggressive,kill掉前台的进程。再次回到1

总结

根据源码,触发前台OOM的可能性有3个:

  1. 直接触发同步kill,比如kMemorystatusKilledPerProcessLimit类型的OOM,这个解释起来还需要一篇文章,暂时不在本文的讨论范围之类
  2. footprint_in_bytes > memlimit_in_bytes,触发high-water类型的OOM,目前我在自己手机上,暂时没有看到这个类型的OOM
  3. 当后台线程都被kill后,依然memorystatus_available_pages <= memorystatus_available_pages_pressure,进而系统kill掉我们的App



参考文章: OOM探究:XNU 内存状态管理 - 简书

带你打造一套 APM 监控系统 之 OOM 问题

iOS性能优化实践:头条抖音如何实现OOM崩溃率下降50%

iOS内存abort(Jetsam) 原理探究

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/891353
推荐阅读
相关标签
  

闽ICP备14008679号