当前位置:   article > 正文

(转载)深入了解iOS中的OOM(低内存崩溃)_os_proc_available_memory

os_proc_available_memory

英文原文:https://programmer.ink/think/learn-more-about-oom-low-memory-crash-in-ios.html

中文翻译:https://www.taodudu.cc/news/show-5381.html

在iOS开发过程或者用户反馈中,可能会经常看到这样的情况,用着用着就崩溃了,而在后台查看崩溃栈的时候,找不到崩溃日志。其实这大多数的可能是系统产生了低内存崩溃,也就是OOM(还有一种可能是主线程卡死,导致watchdog杀掉了应用),而低内存崩溃的日志,往往都是以JetsamEvent开头的,日志中有内存页大小(pageSize),CPU时间(cpuTime)等字段。

什么是OOM

什么是OOM呢,它是out-of-memory的缩写,字面意思就是内存超过了限制。它是由于 iOS 的 Jetsam机制造成的一种“另类” Crash,它不同于常规的Crash,通过Signal捕获等Crash监控方案无法捕获到OOM事件。

当然还会有FOOM这样的词,代表的是Foreground-out-of-memory,是指App在前台因消耗内存过多引起系统强杀。这也就是本文要讨论的。后台出现OOM不一定都是app本身造成的,大多数是因为当前在前台的App占用内存过大,系统为了保证前台应用正常运行,把后台应用清理掉了。

什么是Jetsam机制

Jetsam机制可以理解为操作系统为了控制内存资源过度使用而采用的一种管理机制。Jetsam是一个独立运行的进程,每一个进程都有一个内存阈值,一旦超过这个阈值Jetsam就会立刻杀掉这个进程。

为什么要设计Jetsam机制

首先设备的内存是有限制的,并不是无限大的,所以内存资源非常重要。系统进程及用户使用的其他app的进程都会争抢这个资源。由于iOS不支持交换空间,一旦触发低内存事件,Jetsam就会尽可能多的释放应用占用的内存,这样在iOS系统上出现系统内存不足时,应用就会被系统终止。

交换空间

物理内存不够使用该怎么办呢?像一些桌面操作系统,会有内存交换空间,在window上称为虚拟内存。它的机制是,在需要时能将物理内存中的一部分交换到硬盘上去,利用硬盘空间扩展内存空间。

iOS不支持交换空间

但iOS并不支持交换空间,大多数移动设备都不支持交换空间。移动设备的大容量存储器通常是闪存,它的读写速度远远小于电脑所使用的硬盘,这就导致在移动设备上就算使用了交换空间,也并不能提升性能。其次,移动设备的容量本身就经常短缺、内存的读写寿命也有限,所以在这种情况下还拿闪存来做内存交换,就有点奢侈了。

需要注意的是,网上有少出文章说iOS没有虚拟内存机制,实际上指的是iOS没有交换空间机制。

典型app内存类型

当内存不足的时候,系统会按照一定策略来腾出更多空间供使用,比较常见的做法是将一部分低优先级的数据挪到磁盘上,这个操作称为Page Out。之后当再次访问到这块数据的时候,系统会负责将它重新搬回内存空间中,这个操作称为Page In

Clean Memory

Clean Memory是指那些可以用以Page Out的内存,只读的内存映射文件,或者是App所用到的frameworks。每个frameworks都有_DATA_CONST段,通常他们都是Clean的,但如果用runtime进行swizzling,那么他们就会变Dirty

Dirty Memory

Dirty Memory是指那些被App写入过数据的内存,包括所有堆区的对象、图像解码缓冲区,同时,类似Clean memory,也包括App所用到的frameworks。每个framework都会有_DATA段和_DATA_DIRTY段,它们的内存是Dirty的。

值得注意的是,在使用framework的过程中会产生Dirty Memory,使用单例或者全局初始化方法是减少Dirty Memory不错的方法,因为单例一旦创建就不会销毁,全局初始化方法会在类加载时执行。

Compressed Memory

由于闪存容量和读写寿命的限制,iOS 上没有交换空间机制,取而代之使用Compressed memory。

Compressed memory是在内存紧张时能够将最近使用过的内存占用压缩至原有大小的一半以下,并且能够在需要时解压复用。它在节省内存的同时提高了系统的响应速度,特点总结起来如下:

  • Shrinks memory usage 减少了不活跃内存占用
  • Improves power efficiency 改善电源效率,通过压缩减少磁盘IO带来的损耗
  • Minimizes CPU usage 压缩/解压十分迅速,能够尽可能减少 CPU 的时间开销
  • Is multicore aware 支持多核操作

例如,当我们使用Dictionary去缓存数据的时候,假设现在已经使用了3页内存,当不访问的时候可能会被压缩为1页,再次使用到时候又会解压成3页。

本质上,Compressed memory也是Dirty memory
因此, memory footprint = dirty size + compressed size ,这也就是我们需要并且能够尝试去减少的内存占用。

Memory Warning

相信对于MemoryWarning并不陌生,每一个UIViewController都会有一个didReceivedMemoryWarning的方法。

当使用的内存是一点点上涨时,而不是一下子直接把内存撑爆。在达到内存临界点之前,系统会给各个正在运行的应用发出内存警告,告知app去清理自己的内存。而内存警告,并不总是由于自身app导致的。

内存压缩技术使得释放内存变得复杂。内存压缩技术在操作系统层面实现,对进程无感知。有趣的是如果当前进程收到了内存警告,进程这时候准备释放大量的误用内存,如果访问到过多的压缩内存,再解压缩内存的时候反而会导致内存压力更大,然后出现OOM,被系统杀掉。

我们对数据进行缓存的目的是想减少 CPU 的压力,但是过多的缓存又会占用过大的内存。在一些需要缓存数据的场景下,可以考虑使用NSCache代替NSDictionaryNSCache分配的内存实际上是Purgeable Memory,可以由系统自动释放。这点在Effective Objective 2.0一书中也有推荐NSCacheNSPureableData的结合使用既能让系统根据情况回收内存,也可以在内存清理的同时移除相关对象。

出现OOM前一定会出现Memory Warning么? 答案是不一定,有可能瞬间申请了大量内存,而恰好此时主线程在忙于其他事情,导致可能没有经历过Memory Warning就发生了OOM。当然即便出现了多次Memory Warning后,也不见得会在最后一次Memory Warning的几秒钟后出现OOM。之前做extension开发的时候,就经常会出现Memory Warnning,但是不会出现OOM,再操作一两分钟后,才出现OOM,而在这一两分钟内,没有再出现过Memory Warning。

当然在内存警告时,处理内存,可以在一定程度上避免出现OOM。

如何确定OOM的阈值

有经验的同学,肯定知道不同设备OOM的阈值是不同的。那我们该如何知道OOM的阈值呢?

方法1

当我们的App被Jetsam机制杀死的时候,在手机中会生成系统日志,在手机系统设置-隐私-分析中,可以得到JetSamEvent开头的日志。这些日志中就可以获取到一些关于App的内存信息,例如我当前用的iPhone8(iOS11.4.1),在日志中的前部分看到了pageSize,而查找per-process-limit一项(并不是所有日志都有,可以找有的),用该项的rpages * pageSize即可得到OOM的阈值。

  1. {"bug_type":"298","timestamp":"2020-01-03 04:11:13.65 +0800","os_version":"iPhone OS 11.4.1 (15G77)","incident_id":"2723B2EA-7FB8-49A6-B2FC-49F10C748D8A"}
  2. {
  3. "crashReporterKey" : "a6ad027ba01b1e66d0b3d8446aaef5dbd75dd732",
  4. "kernel" : "Darwin Kernel Version 17.7.0: Mon Jun 11 19:06:27 PDT 2018; root:xnu-4570.70.24~3\/RELEASE_ARM64_T8015",
  5. "product" : "iPhone10,1",
  6. "incident" : "2723B2EA-7FB8-49A6-B2FC-49F10C748D8A",
  7. "date" : "2020-01-03 04:11:13.65 +0800",
  8. "build" : "iPhone OS 11.4.1 (15G77)",
  9. "timeDelta" : 4,
  10. "memoryStatus" : {
  11. "compressorSize" : 39010,
  12. "compressions" : 2282594,
  13. "decompressions" : 1071238,
  14. "zoneMapCap" : 402653184,
  15. "largestZone" : "APFS_4K_OBJS",
  16. "largestZoneSize" : 35962880,
  17. "pageSize" : 16384,
  18. "uncompressed" : 105360,
  19. "zoneMapSize" : 118865920,
  20. "memoryPages" : {
  21. "active" : 39800,
  22. "throttled" : 0,
  23. "fileBacked" : 28778,
  24. "wired" : 19947,
  25. "anonymous" : 32084,
  26. "purgeable" : 543,
  27. "inactive" : 19877,
  28. "free" : 2935,
  29. "speculative" : 1185
  30. }
  31. },
  32. ...
  33. {
  34. "uuid" : "a2f9f2db-a110-3896-a0ec-d82c156055ed",
  35. "states" : [
  36. "frontmost",
  37. "resume"
  38. ],
  39. "killDelta" : 11351,
  40. "genCount" : 0,
  41. "age" : 361742447,
  42. "purgeable" : 0,
  43. "fds" : 50,
  44. "coalition" : 2694,
  45. "rpages" : 89600,
  46. "reason" : "per-process-limit",
  47. "pid" : 2541,
  48. "cpuTime" : 1.65848,
  49. "name" : "MemoryTest",
  50. "lifetimeMax" : 24126
  51. },
  52. ...

那么当前这个MemoryTest的内存阈值就是16384 * 89600 / 1024 / 1024 = 1400MB

方法2

当前网络上已经有人很多人整理的OOM内存对应表,我这边根据实际情况比较倾向于该版本。

  1. I created one more list by sorting Jaspers list by device RAM (I made my own tests with Split's tool and fixed some results - check my comments in Jaspers thread).
  2. device RAM: percent range to crash
  3. 256MB: 49% - 51%
  4. 512MB: 53% - 63%
  5. 1024MB: 57% - 68%
  6. 2048MB: 68% - 69%
  7. 3072MB: 63% - 66%
  8. 4096MB: 77%
  9. 6144MB: 81%
  10. Special cases:
  11. iPhone X (3072MB): 50%
  12. iPhone XS/XS Max (4096MB): 55%
  13. iPhone XR (3072MB): 63%
  14. iPhone 11/11 Pro Max (4096MB): 54% - 55%
  15. Device RAM can be read easily:
  16. [NSProcessInfo processInfo].physicalMemory
  17. From my experience it is safe to use 45% for 1GB devices, 50% for 2/3GB devices and 55% for 4GB devices. Percent for macOS can be a bit bigger.

方法3

首先,我们可以通过方法得到当前应用程序占用的内存。代码如下

  1. - (int)usedSizeOfMemory {
  2. task_vm_info_data_t taskInfo;
  3. mach_msg_type_number_t infoCount = TASK_VM_INFO_COUNT;
  4. kern_return_t kernReturn = task_info(mach_task_self(), TASK_VM_INFO, (task_info_t)&taskInfo, &infoCount);
  5. if (kernReturn != KERN_SUCCESS) {
  6. return 0;
  7. }
  8. return (int)(taskInfo.phys_footprint / 1024 / 1024);
  9. }

也有其他一些代码使用过的是taskInfo.resident_size,但该值并不准确。我对比Xcode Debug,发现taskInfo.phys_footprint值基本上与Xcode Debug的值一致。而在XNU的task.c中,也找到了该值是如何计算的。

  1. /*
  2. * phys_footprint
  3. * Physical footprint: This is the sum of:
  4. * + (internal - alternate_accounting)
  5. * + (internal_compressed - alternate_accounting_compressed)
  6. * + iokit_mapped
  7. * + purgeable_nonvolatile
  8. * + purgeable_nonvolatile_compressed
  9. * + page_table
  10. */
  11. 本地测试了一下:
  12. iOS11上,phys_footprint值与Xcode DEBUG的值相差不到1M,
  13. 而在iOS13上,phys_footprint值与Xcode DEBUG值完全一致。
  14. 有强迫症的同学可以在iOS11上使用
  15. ((taskInfo.internal + taskInfo.compressed - taskInfo.purgeable_volatile_pmap))来代替phys_footprint。

那么我们可以得到这个值之后,就可以开一个线程,循环申请1MB的内存,直至到达第一次内存警告,以及OOM。

  1. #import "ViewController.h"
  2. #import <mach/mach.h>
  3. #define kOneMB 1048576
  4. @interface ViewController ()
  5. {
  6. NSTimer *timer;
  7. int allocatedMB;
  8. Byte *p[10000];
  9. int physicalMemorySizeMB;
  10. int memoryWarningSizeMB;
  11. int memoryLimitSizeMB;
  12. BOOL firstMemoryWarningReceived;
  13. }
  14. @end
  15. @implementation ViewController
  16. - (void)viewDidLoad {
  17. [super viewDidLoad];
  18. // Do any additional setup after loading the view.
  19. physicalMemorySizeMB = (int)([[NSProcessInfo processInfo] physicalMemory] / kOneMB);
  20. firstMemoryWarningReceived = YES;
  21. }
  22. - (void)didReceiveMemoryWarning {
  23. [super didReceiveMemoryWarning];
  24. if (firstMemoryWarningReceived == NO) {
  25. return ;
  26. }
  27. memoryWarningSizeMB = [self usedSizeOfMemory];
  28. firstMemoryWarningReceived = NO;
  29. }
  30. - (IBAction)startTest:(UIButton *)button {
  31. [timer invalidate];
  32. timer = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(allocateMemory) userInfo:nil repeats:YES];
  33. }
  34. - (void)allocateMemory {
  35. p[allocatedMB] = malloc(1048576);
  36. memset(p[allocatedMB], 0, 1048576);
  37. allocatedMB += 1;
  38. memoryLimitSizeMB = [self usedSizeOfMemory];
  39. if (memoryWarningSizeMB && memoryLimitSizeMB) {
  40. NSLog(@"----- memory warnning:%dMB, memory limit:%dMB", memoryWarningSizeMB, memoryLimitSizeMB);
  41. }
  42. }
  43. - (int)usedSizeOfMemory {
  44. task_vm_info_data_t taskInfo;
  45. mach_msg_type_number_t infoCount = TASK_VM_INFO_COUNT;
  46. kern_return_t kernReturn = task_info(mach_task_self(), TASK_VM_INFO, (task_info_t)&taskInfo, &infoCount);
  47. if (kernReturn != KERN_SUCCESS) {
  48. return 0;
  49. }
  50. return (int)(taskInfo.phys_footprint / kOneMB);
  51. }
  52. @end

这样我们debug,查看控制台最后一条log即可。

  1. 2020-01-03 11:52:26.353765+0800 MemoryTest[2561:599014] ----- memory warnning:1289MB, memory limit:1397MB
  2. 2020-01-03 11:52:26.363799+0800 MemoryTest[2561:599014] ----- memory warnning:1289MB, memory limit:1398MB
  3. 2020-01-03 11:52:26.373895+0800 MemoryTest[2561:599014] ----- memory warnning:1289MB, memory limit:1399MB

我们发现,内存警告是1289MB,我们有记录的OOM的log到1399MB,那么也说明OOM值为1400MB。

方法4(适用于iOS13系统)

iOS13系统os/proc.h中提供了新的API,可以查看当前可用内存

  1. #import <os/proc.h>
  2. extern size_t os_proc_available_memory(void);
  3. + (CGFloat)availableSizeOfMemory {
  4. if (@available(iOS 13.0, *)) {
  5. return os_proc_available_memory() / 1024.0 / 1024.0;
  6. }
  7. // ...
  8. }

有了这个值,我们就可以计算出当前应用的内存限制。用了一个iPhone Xs Max测试了一下。通过方法1获取到的内存限制值为134278 * 16384 / 1024 / 1024 = 2098M。通过方法3获取到的内存值为2098M。

  1. - (int)limitSizeOfMemory {
  2. if (@available(iOS 13.0, *)) {
  3. task_vm_info_data_t taskInfo;
  4. mach_msg_type_number_t infoCount = TASK_VM_INFO_COUNT;
  5. kern_return_t kernReturn = task_info(mach_task_self(), TASK_VM_INFO, (task_info_t)&taskInfo, &infoCount);
  6. if (kernReturn != KERN_SUCCESS) {
  7. return 0;
  8. }
  9. return (int)((taskInfo.phys_footprint + os_proc_available_memory()) / 1024.0 / 1024.0);
  10. }
  11. return 0;
  12. }

通过这个方法,得到的值也为2098M。

以上就是几种可以获取到不同应用OOM值的方法。无论是应用还是应用扩展,都可以通过以上几个方法测试。但应用扩展的内存限制十分严格,要远低于普通的应用程序。例如,iPhone XS Max的应用内存限制为2098M,而同设备的自定义键盘,内存限制为66M(少的太可怜了)。

源码探究

我们知道,iOS/MacOS的内核都是XNU,同时XNU是开源的。我们可以在开源的XNU内核源码中,窥探苹果Jetsam的具体实现。

XNU的内核内层为Mach层,Mach作为微内核,是仅提供基础服务的一个薄层,如处理器管理和调度及IPC(进程间通信)。XNU的第二个主要部分是BSD层。我们可以将其看成围绕mach层的一个外环,BSD为最终用户的应用程序提供变成接口,其职责包括进程管理,文件系统和网络。

内存管理中各种常见的JetSam时间也是由BSD产生的,所以,我们从bsd_init这个函数作为入口,来探究一下原理。

bsd_init中基本都是在初始化各种子系统,比如虚拟内存管理等等。

BSD初始化bsd_init

跟内存相关的包括如下几步:

  1. //1. 初始化BSD内存Zone,这个Zone是基于Mach内核的zone
  2. kmeminit();
  3. //2.iOS上独有的特性,内存和进程的休眠的常驻监控线程
  4. #if CONFIG_FREEZE
  5. #ifndef CONFIG_MEMORYSTATUS
  6. #error "CONFIG_FREEZE defined without matching CONFIG_MEMORYSTATUS"
  7. #endif
  8. /* Initialise background freezing */
  9. bsd_init_kprintf("calling memorystatus_freeze_init\n");
  10. memorystatus_freeze_init();
  11. #endif
  12. //3.iOS独有,JetSAM(即低内存事件的常驻监控线程)
  13. #if CONFIG_MEMORYSTATUS
  14. /* Initialize kernel memory status notifications */
  15. bsd_init_kprintf("calling memorystatus_init\n");
  16. memorystatus_init();
  17. #endif /* CONFIG_MEMORYSTATUS */

这里面的memorystatus_freeze_init()memorystatus_init()两个方法都是调用kern_memorystatus.c里面暴露的接口,主要的作用就是从内核中开启两个优先级最高的线程,来监控整个系统的内存情况。

CONFIG_FREEZE涉及到的功能,当启用这个宏时,内核会对进程进行冷冻而不是Kill。涉及到进程休眠相关的代码,暂时不在本文讨论范围内。

回到iOS的OOM崩溃话题上,我们只需要关注memorystatus_init()方法即可。

知识点介绍

  • 内核里面对于所有的进程都有一个优先级的分布,通过一个数组维护,数组的每一项是一个进程的列表。这个数组的大小则是JETSAM_PRIORITY_MAX + 1
  1. #define MEMSTAT_BUCKET_COUNT (JETSAM_PRIORITY_MAX + 1)
  2. typedef struct memstat_bucket {
  3. TAILQ_HEAD(, proc) list; // 一个TAILQ_HEAD的双向链表,用来存放这个优先级下面的进程
  4. int count; // 进程的个数
  5. } memstat_bucket_t;
  6. memstat_bucket_t memstat_bucket[MEMSTAT_BUCKET_COUNT];//优先级队列(里面包含不同优先级的结构)
  • kern_memorystatus.h中,我们可以找到JETSAM_PRIORITY_MAX值以及进程优先级相关的定义:
  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

其中数值越大,优先级越高。后台应用程序优先级JETSAM_PRIORITY_BACKGROUND是3,低于前台应用程序优先级JETSAM_PRIORITY_FOREGROUND10,而SpringBoard(桌面程序)位于JETSAM_PRIORITY_HOME16。

  • JetSam出现的原因:
  1. //kern_memorystatus.h
  2. /*
  3. * Jetsam exit reason definitions - related to memorystatus
  4. *
  5. * When adding new exit reasons also update:
  6. * JETSAM_REASON_MEMORYSTATUS_MAX
  7. * kMemorystatusKilled... Cause enum
  8. * memorystatus_kill_cause_name[]
  9. */
  10. #define JETSAM_REASON_INVALID 0
  11. #define JETSAM_REASON_GENERIC 1
  12. #define JETSAM_REASON_MEMORY_HIGHWATER 2
  13. #define JETSAM_REASON_VNODE 3
  14. #define JETSAM_REASON_MEMORY_VMPAGESHORTAGE 4
  15. #define JETSAM_REASON_MEMORY_PROCTHRASHING 5
  16. #define JETSAM_REASON_MEMORY_FCTHRASHING 6
  17. #define JETSAM_REASON_MEMORY_PERPROCESSLIMIT 7
  18. #define JETSAM_REASON_MEMORY_DISK_SPACE_SHORTAGE 8
  19. #define JETSAM_REASON_MEMORY_IDLE_EXIT 9
  20. #define JETSAM_REASON_ZONE_MAP_EXHAUSTION 10
  21. #define JETSAM_REASON_MEMORY_VMCOMPRESSOR_THRASHING 11
  22. #define JETSAM_REASON_MEMORY_VMCOMPRESSOR_SPACE_SHORTAGE 12
  23. #define JETSAM_REASON_MEMORYSTATUS_MAX JETSAM_REASON_MEMORY_VMCOMPRESSOR_SPACE_SHORTAGE
  24. /*
  25. * Jetsam exit reason definitions - not related to memorystatus
  26. */
  27. #define JETSAM_REASON_CPULIMIT 100
  28. /* Cause */
  29. enum {
  30. kMemorystatusInvalid = JETSAM_REASON_INVALID,
  31. kMemorystatusKilled = JETSAM_REASON_GENERIC,
  32. kMemorystatusKilledHiwat = JETSAM_REASON_MEMORY_HIGHWATER,
  33. kMemorystatusKilledVnodes = JETSAM_REASON_VNODE,
  34. kMemorystatusKilledVMPageShortage = JETSAM_REASON_MEMORY_VMPAGESHORTAGE,
  35. kMemorystatusKilledProcThrashing = JETSAM_REASON_MEMORY_PROCTHRASHING,
  36. kMemorystatusKilledFCThrashing = JETSAM_REASON_MEMORY_FCTHRASHING,
  37. kMemorystatusKilledPerProcessLimit = JETSAM_REASON_MEMORY_PERPROCESSLIMIT,
  38. kMemorystatusKilledDiskSpaceShortage = JETSAM_REASON_MEMORY_DISK_SPACE_SHORTAGE,
  39. kMemorystatusKilledIdleExit = JETSAM_REASON_MEMORY_IDLE_EXIT,
  40. kMemorystatusKilledZoneMapExhaustion = JETSAM_REASON_ZONE_MAP_EXHAUSTION,
  41. kMemorystatusKilledVMCompressorThrashing = JETSAM_REASON_MEMORY_VMCOMPRESSOR_THRASHING,
  42. kMemorystatusKilledVMCompressorSpaceShortage = JETSAM_REASON_MEMORY_VMCOMPRESSOR_SPACE_SHORTAGE,
  43. };
  44. //kern_memorystatus.m
  45. /* For logging clarity */
  46. static const char *memorystatus_kill_cause_name[] = {
  47. "" , /* kMemorystatusInvalid */
  48. "jettisoned" , /* kMemorystatusKilled */
  49. "highwater" , /* kMemorystatusKilledHiwat */
  50. "vnode-limit" , /* kMemorystatusKilledVnodes */
  51. "vm-pageshortage" , /* kMemorystatusKilledVMPageShortage */
  52. "proc-thrashing" , /* kMemorystatusKilledProcThrashing */
  53. "fc-thrashing" , /* kMemorystatusKilledFCThrashing */
  54. "per-process-limit" , /* kMemorystatusKilledPerProcessLimit */
  55. "disk-space-shortage" , /* kMemorystatusKilledDiskSpaceShortage */
  56. "idle-exit" , /* kMemorystatusKilledIdleExit */
  57. "zone-map-exhaustion" , /* kMemorystatusKilledZoneMapExhaustion */
  58. "vm-compressor-thrashing" , /* kMemorystatusKilledVMCompressorThrashing */
  59. "vm-compressor-space-shortage" , /* kMemorystatusKilledVMCompressorSpaceShortage */
  60. };

memorystatus_init 内存状态初始化

接下里让我们看一下memorystatus_init()函数中,初始化JETSAM线程的关键部分代码。

  1. __private_extern__ void
  2. memorystatus_init(void)
  3. {
  4. ...
  5. /* Initialize the jetsam_threads state array */
  6. jetsam_threads = kalloc(sizeof(struct jetsam_thread_state) * max_jetsam_threads);
  7. /* Initialize all the jetsam threads */
  8. for (i = 0; i < max_jetsam_threads; i++) {
  9. result = kernel_thread_start_priority(memorystatus_thread, NULL, 95 /* MAXPRI_KERNEL */, &jetsam_threads[i].thread);
  10. if (result == KERN_SUCCESS) {
  11. jetsam_threads[i].inited = FALSE;
  12. jetsam_threads[i].index = i;
  13. thread_deallocate(jetsam_threads[i].thread);
  14. } else {
  15. panic("Could not create memorystatus_thread %d", i);
  16. }
  17. }
  18. }

在这里会根据内核启动参数和设备性能,开启max_jetsam_threads个JetSam线程(性能差的设备为1个,其余为3个),这些线程的优先级是内核所能分配的最高级(95, MAXPRI_KERNEL)。并且为每个线程增加了次序(注意:前文的-2~19是进程优先级区间,而这里的95是线程优先级,XNU的线程优先级范围是0~127)。

memorystatus_thread 内存状态管理线程

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

继续看memorystatus_thread内存状态管理线程的代码:

  1. static void
  2. memorystatus_thread(void *param __unused, wait_result_t wr __unused)
  3. {
  4. boolean_t post_snapshot = FALSE;
  5. uint32_t errors = 0;
  6. uint32_t hwm_kill = 0;
  7. boolean_t sort_flag = TRUE;
  8. boolean_t corpse_list_purged = FALSE;
  9. int jld_idle_kills = 0;
  10. struct jetsam_thread_state *jetsam_thread = jetsam_current_thread();
  11. if (jetsam_thread->inited == FALSE) {
  12. /*
  13. * It's the first time the thread has run, so just mark the thread as privileged and block.
  14. * This avoids a spurious pass with unset variables, as set out in <rdar://problem/9609402>.
  15. */
  16. char name[32];
  17. thread_wire(host_priv_self(), current_thread(), TRUE);
  18. snprintf(name, 32, "VM_memorystatus_%d", jetsam_thread->index + 1);
  19. if (jetsam_thread->index == 0) {
  20. if (vm_pageout_state.vm_restricted_to_single_processor == TRUE) {
  21. thread_vm_bind_group_add();
  22. }
  23. }
  24. thread_set_thread_name(current_thread(), name);
  25. jetsam_thread->inited = TRUE;
  26. memorystatus_thread_block(0, memorystatus_thread);
  27. }
  28. KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT, BSD_MEMSTAT_SCAN) | DBG_FUNC_START,
  29. memorystatus_available_pages, memorystatus_jld_enabled, memorystatus_jld_eval_period_msecs, memorystatus_jld_eval_aggressive_count,0);
  30. /*
  31. * Jetsam aware version.
  32. *
  33. * The VM pressure notification thread is working it's way through clients in parallel.
  34. *
  35. * So, while the pressure notification thread is targeting processes in order of
  36. * increasing jetsam priority, we can hopefully reduce / stop it's work by killing
  37. * any processes that have exceeded their highwater mark.
  38. *
  39. * If we run out of HWM processes and our available pages drops below the critical threshold, then,
  40. * we target the least recently used process in order of increasing jetsam priority (exception: the FG band).
  41. */
  42. while (memorystatus_action_needed()) {
  43. boolean_t killed;
  44. int32_t priority;
  45. uint32_t cause;
  46. uint64_t jetsam_reason_code = JETSAM_REASON_INVALID;
  47. os_reason_t jetsam_reason = OS_REASON_NULL;
  48. cause = kill_under_pressure_cause;
  49. switch (cause) {
  50. case kMemorystatusKilledFCThrashing:
  51. jetsam_reason_code = JETSAM_REASON_MEMORY_FCTHRASHING;
  52. break;
  53. case kMemorystatusKilledVMCompressorThrashing:
  54. jetsam_reason_code = JETSAM_REASON_MEMORY_VMCOMPRESSOR_THRASHING;
  55. break;
  56. case kMemorystatusKilledVMCompressorSpaceShortage:
  57. jetsam_reason_code = JETSAM_REASON_MEMORY_VMCOMPRESSOR_SPACE_SHORTAGE;
  58. break;
  59. case kMemorystatusKilledZoneMapExhaustion:
  60. jetsam_reason_code = JETSAM_REASON_ZONE_MAP_EXHAUSTION;
  61. break;
  62. case kMemorystatusKilledVMPageShortage:
  63. /* falls through */
  64. default:
  65. jetsam_reason_code = JETSAM_REASON_MEMORY_VMPAGESHORTAGE;
  66. cause = kMemorystatusKilledVMPageShortage;
  67. break;
  68. }
  69. /* Highwater */
  70. boolean_t is_critical = TRUE;
  71. if (memorystatus_act_on_hiwat_processes(&errors, &hwm_kill, &post_snapshot, &is_critical)) {
  72. if (is_critical == FALSE) {
  73. /*
  74. * For now, don't kill any other processes.
  75. */
  76. break;
  77. } else {
  78. goto done;
  79. }
  80. }
  81. jetsam_reason = os_reason_create(OS_REASON_JETSAM, jetsam_reason_code);
  82. if (jetsam_reason == OS_REASON_NULL) {
  83. printf("memorystatus_thread: failed to allocate jetsam reason\n");
  84. }
  85. if (memorystatus_act_aggressive(cause, jetsam_reason, &jld_idle_kills, &corpse_list_purged, &post_snapshot)) {
  86. goto done;
  87. }
  88. /*
  89. * memorystatus_kill_top_process() drops a reference,
  90. * so take another one so we can continue to use this exit reason
  91. * even after it returns
  92. */
  93. os_reason_ref(jetsam_reason);
  94. /* LRU */
  95. killed = memorystatus_kill_top_process(TRUE, sort_flag, cause, jetsam_reason, &priority, &errors);
  96. sort_flag = FALSE;
  97. if (killed) {
  98. if (memorystatus_post_snapshot(priority, cause) == TRUE) {
  99. post_snapshot = TRUE;
  100. }
  101. /* Jetsam Loop Detection */
  102. if (memorystatus_jld_enabled == TRUE) {
  103. if ((priority == JETSAM_PRIORITY_IDLE) || (priority == system_procs_aging_band) || (priority == applications_aging_band)) {
  104. jld_idle_kills++;
  105. } else {
  106. /*
  107. * We've reached into bands beyond idle deferred.
  108. * We make no attempt to monitor them
  109. */
  110. }
  111. }
  112. if ((priority >= JETSAM_PRIORITY_UI_SUPPORT) && (total_corpses_count() > 0) && (corpse_list_purged == FALSE)) {
  113. /*
  114. * If we have jetsammed a process in or above JETSAM_PRIORITY_UI_SUPPORT
  115. * then we attempt to relieve pressure by purging corpse memory.
  116. */
  117. task_purge_all_corpses();
  118. corpse_list_purged = TRUE;
  119. }
  120. goto done;
  121. }
  122. if (memorystatus_avail_pages_below_critical()) {
  123. /*
  124. * Still under pressure and unable to kill a process - purge corpse memory
  125. */
  126. if (total_corpses_count() > 0) {
  127. task_purge_all_corpses();
  128. corpse_list_purged = TRUE;
  129. }
  130. if (memorystatus_avail_pages_below_critical()) {
  131. /*
  132. * Still under pressure and unable to kill a process - panic
  133. */
  134. panic("memorystatus_jetsam_thread: no victim! available pages:%llu\n", (uint64_t)memorystatus_available_pages);
  135. }
  136. }
  137. done:
  138. /*
  139. * We do not want to over-kill when thrashing has been detected.
  140. * To avoid that, we reset the flag here and notify the
  141. * compressor.
  142. */
  143. if (is_reason_thrashing(kill_under_pressure_cause)) {
  144. kill_under_pressure_cause = 0;
  145. #if CONFIG_JETSAM
  146. vm_thrashing_jetsam_done();
  147. #endif /* CONFIG_JETSAM */
  148. } else if (is_reason_zone_map_exhaustion(kill_under_pressure_cause)) {
  149. kill_under_pressure_cause = 0;
  150. }
  151. os_reason_free(jetsam_reason);
  152. }
  153. kill_under_pressure_cause = 0;
  154. if (errors) {
  155. memorystatus_clear_errors();
  156. }
  157. if (post_snapshot) {
  158. proc_list_lock();
  159. size_t snapshot_size = sizeof(memorystatus_jetsam_snapshot_t) +
  160. sizeof(memorystatus_jetsam_snapshot_entry_t) * (memorystatus_jetsam_snapshot_count);
  161. uint64_t timestamp_now = mach_absolute_time();
  162. memorystatus_jetsam_snapshot->notification_time = timestamp_now;
  163. memorystatus_jetsam_snapshot->js_gencount++;
  164. if (memorystatus_jetsam_snapshot_count > 0 && (memorystatus_jetsam_snapshot_last_timestamp == 0 ||
  165. timestamp_now > memorystatus_jetsam_snapshot_last_timestamp + memorystatus_jetsam_snapshot_timeout)) {
  166. proc_list_unlock();
  167. int ret = memorystatus_send_note(kMemorystatusSnapshotNote, &snapshot_size, sizeof(snapshot_size));
  168. if (!ret) {
  169. proc_list_lock();
  170. memorystatus_jetsam_snapshot_last_timestamp = timestamp_now;
  171. proc_list_unlock();
  172. }
  173. } else {
  174. proc_list_unlock();
  175. }
  176. }
  177. KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT, BSD_MEMSTAT_SCAN) | DBG_FUNC_END,
  178. memorystatus_available_pages, 0, 0, 0, 0);
  179. memorystatus_thread_block(0, memorystatus_thread);
  180. }

代码较多,我们来逐一分析。

判断条件

我们可以看到核心的代码在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 kMemorystatusKilledFCThrashing:
  7. case kMemorystatusKilledVMCompressorThrashing:
  8. case kMemorystatusKilledVMCompressorSpaceShortage:
  9. return TRUE;
  10. default:
  11. return FALSE;
  12. }
  13. }
  14. /* Is the zone map almost full? */
  15. static boolean_t
  16. is_reason_zone_map_exhaustion(unsigned cause)
  17. {
  18. if (cause == kMemorystatusKilledZoneMapExhaustion)
  19. return TRUE;
  20. return FALSE;
  21. }
  22. static boolean_t 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. }

这里通过接受vm_pageout守护程序(实际上是一个线程)发送的内存压力来判断当前内存资源是否紧张。内存紧张的情况可能为:操作系统的抖动(Thrashing,频繁的内存页面(page)换进换出占用CPU过度),虚拟内存耗尽(比如有人从硬盘向ZFS(动态文件系统)池中拷贝1TB的数据),或者内存可用页低于阈值memorystatus_available_pages_pressure

high-water

判断条件通过之后,也就是当前内存紧张,首先走到memorystatus_act_on_hiwat_processes逻辑中。

  1. /* Highwater */
  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. }

这是触发high-water类型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 purged = FALSE;
  5. boolean_t killed = memorystatus_kill_hiwat_proc(errors, &purged);
  6. if (killed) {
  7. *hwm_kill = *hwm_kill + 1;
  8. *post_snapshot = TRUE;
  9. return TRUE;
  10. } else {
  11. if (purged == FALSE) {
  12. /* couldn't purge and couldn't kill */
  13. memorystatus_hwm_candidates = FALSE;
  14. }
  15. }
  16. #if CONFIG_JETSAM
  17. /* No highwater processes to kill. Continue or stop for now? */
  18. if (!is_reason_thrashing(kill_under_pressure_cause) &&
  19. !is_reason_zone_map_exhaustion(kill_under_pressure_cause) &&
  20. (memorystatus_available_pages > memorystatus_available_pages_critical)) {
  21. /*
  22. * We are _not_ out of pressure but we are above the critical threshold and there's:
  23. * - no compressor thrashing
  24. * - enough zone memory
  25. * - no more HWM processes left.
  26. * For now, don't kill any other processes.
  27. */
  28. if (*hwm_kill == 0) {
  29. memorystatus_thread_wasted_wakeup++;
  30. }
  31. *is_critical = FALSE;
  32. return TRUE;
  33. }
  34. #endif /* CONFIG_JETSAM */
  35. return FALSE;
  36. }

memorystatus_act_on_hiwat_processes会直接调用memorystatus_kill_hiwat_proc

  1. static boolean_t
  2. memorystatus_kill_hiwat_proc(uint32_t *errors, boolean_t *purged)
  3. {
  4. pid_t aPid = 0;
  5. proc_t p = PROC_NULL, next_p = PROC_NULL;
  6. boolean_t new_snapshot = FALSE, killed = FALSE, freed_mem = FALSE;
  7. unsigned int i = 0;
  8. uint32_t aPid_ep;
  9. os_reason_t jetsam_reason = OS_REASON_NULL;
  10. KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT, BSD_MEMSTAT_JETSAM_HIWAT) | DBG_FUNC_START,
  11. memorystatus_available_pages, 0, 0, 0, 0);
  12. jetsam_reason = os_reason_create(OS_REASON_JETSAM, JETSAM_REASON_MEMORY_HIGHWATER);
  13. if (jetsam_reason == OS_REASON_NULL) {
  14. printf("memorystatus_kill_hiwat_proc: failed to allocate exit reason\n");
  15. }
  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_JETSAM && (DEVELOPMENT || DEBUG)
  37. if (!skip && (memorystatus_jetsam_policy & kPolicyDiagnoseActive)) {
  38. if (p->p_memstat_state & P_MEMSTAT_DIAG_SUSPENDED) {
  39. continue;
  40. }
  41. }
  42. #endif /* CONFIG_JETSAM && (DEVELOPMENT || DEBUG) */
  43. #if CONFIG_FREEZE
  44. if (!skip) {
  45. if (p->p_memstat_state & P_MEMSTAT_LOCKED) {
  46. skip = TRUE;
  47. } else {
  48. skip = FALSE;
  49. }
  50. }
  51. #endif
  52. if (skip) {
  53. continue;
  54. } else {
  55. if (memorystatus_jetsam_snapshot_count == 0) {
  56. memorystatus_init_jetsam_snapshot_locked(NULL,0);
  57. new_snapshot = TRUE;
  58. }
  59. if (proc_ref_locked(p) == p) {
  60. /*
  61. * Mark as terminated so that if exit1() indicates success, but the process (for example)
  62. * is blocked in task_exception_notify(), it'll be skipped if encountered again - see
  63. * <rdar://problem/13553476>. This is cheaper than examining P_LEXIT, which requires the
  64. * acquisition of the proc lock.
  65. */
  66. p->p_memstat_state |= P_MEMSTAT_TERMINATED;
  67. proc_list_unlock();
  68. } else {
  69. /*
  70. * We need to restart the search again because
  71. * proc_ref_locked _can_ drop the proc_list lock
  72. * and we could have lost our stored next_p via
  73. * an exit() on another core.
  74. */
  75. i = 0;
  76. next_p = memorystatus_get_first_proc_locked(&i, TRUE);
  77. continue;
  78. }
  79. freed_mem = memorystatus_kill_proc(p, kMemorystatusKilledHiwat, jetsam_reason, &killed); /* purged and/or killed 'p' */
  80. /* Success? */
  81. if (freed_mem) {
  82. if (killed == FALSE) {
  83. /* purged 'p'..don't reset HWM candidate count */
  84. *purged = TRUE;
  85. proc_list_lock();
  86. p->p_memstat_state &= ~P_MEMSTAT_TERMINATED;
  87. proc_list_unlock();
  88. }
  89. proc_rele(p);
  90. goto exit;
  91. }
  92. /*
  93. * Failure - first unwind the state,
  94. * then fall through to restart the search.
  95. */
  96. proc_list_lock();
  97. proc_rele_locked(p);
  98. p->p_memstat_state &= ~P_MEMSTAT_TERMINATED;
  99. p->p_memstat_state |= P_MEMSTAT_ERROR;
  100. *errors += 1;
  101. i = 0;
  102. next_p = memorystatus_get_first_proc_locked(&i, TRUE);
  103. }
  104. }
  105. proc_list_unlock();
  106. exit:
  107. os_reason_free(jetsam_reason);
  108. /* Clear snapshot if freshly captured and no target was found */
  109. if (new_snapshot && !killed) {
  110. proc_list_lock();
  111. memorystatus_jetsam_snapshot->entry_count = memorystatus_jetsam_snapshot_count = 0;
  112. proc_list_unlock();
  113. }
  114. KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT, BSD_MEMSTAT_JETSAM_HIWAT) | DBG_FUNC_END,
  115. memorystatus_available_pages, killed ? aPid : 0, 0, 0, 0);
  116. return killed;
  117. }

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

normal kill

不过high-water的阈值较高,一般不容易触发。如果通过high-water相关代码不能结束任何进程,将走到memorystatus_act_aggressive()函数中,也就是大部分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. /*
  19. * Jetsam Loop Detection: attempt to detect
  20. * rapid daemon relaunches in the lower bands.
  21. */
  22. microuptime(&jld_now_tstamp);
  23. /*
  24. * Ignore usecs in this calculation.
  25. * msecs granularity is close enough.
  26. */
  27. jld_now_msecs = (jld_now_tstamp.tv_sec * 1000);
  28. proc_list_lock();
  29. switch (jetsam_aging_policy) {
  30. case kJetsamAgingPolicyLegacy:
  31. bucket = &memstat_bucket[JETSAM_PRIORITY_IDLE];
  32. jld_bucket_count = bucket->count;
  33. bucket = &memstat_bucket[JETSAM_PRIORITY_AGING_BAND1];
  34. jld_bucket_count += bucket->count;
  35. break;
  36. case kJetsamAgingPolicySysProcsReclaimedFirst:
  37. case kJetsamAgingPolicyAppsReclaimedFirst:
  38. bucket = &memstat_bucket[JETSAM_PRIORITY_IDLE];
  39. jld_bucket_count = bucket->count;
  40. bucket = &memstat_bucket[system_procs_aging_band];
  41. jld_bucket_count += bucket->count;
  42. bucket = &memstat_bucket[applications_aging_band];
  43. jld_bucket_count += bucket->count;
  44. break;
  45. case kJetsamAgingPolicyNone:
  46. default:
  47. bucket = &memstat_bucket[JETSAM_PRIORITY_IDLE];
  48. jld_bucket_count = bucket->count;
  49. break;
  50. }
  51. bucket = &memstat_bucket[JETSAM_PRIORITY_ELEVATED_INACTIVE];
  52. elevated_bucket_count = bucket->count;
  53. proc_list_unlock();
  54. /*
  55. * memorystatus_jld_eval_period_msecs is a tunable
  56. * memorystatus_jld_eval_aggressive_count is a tunable
  57. * memorystatus_jld_eval_aggressive_priority_band_max is a tunable
  58. */
  59. if ( (jld_bucket_count == 0) ||
  60. (jld_now_msecs > (jld_timestamp_msecs + memorystatus_jld_eval_period_msecs))) {
  61. /*
  62. * Refresh evaluation parameters
  63. */
  64. jld_timestamp_msecs = jld_now_msecs;
  65. jld_idle_kill_candidates = jld_bucket_count;
  66. *jld_idle_kills = 0;
  67. jld_eval_aggressive_count = 0;
  68. jld_priority_band_max = JETSAM_PRIORITY_UI_SUPPORT;
  69. }
  70. if (*jld_idle_kills > jld_idle_kill_candidates) {
  71. jld_eval_aggressive_count++;
  72. #if DEVELOPMENT || DEBUG
  73. printf("memorystatus: aggressive%d: beginning of window: %lld ms, : timestamp now: %lld ms\n",
  74. jld_eval_aggressive_count,
  75. jld_timestamp_msecs,
  76. jld_now_msecs);
  77. printf("memorystatus: aggressive%d: idle candidates: %d, idle kills: %d\n",
  78. jld_eval_aggressive_count,
  79. jld_idle_kill_candidates,
  80. *jld_idle_kills);
  81. #endif /* DEVELOPMENT || DEBUG */
  82. if ((jld_eval_aggressive_count == memorystatus_jld_eval_aggressive_count) &&
  83. (total_corpses_count() > 0) && (*corpse_list_purged == FALSE)) {
  84. /*
  85. * If we reach this aggressive cycle, corpses might be causing memory pressure.
  86. * So, in an effort to avoid jetsams in the FG band, we will attempt to purge
  87. * corpse memory prior to this final march through JETSAM_PRIORITY_UI_SUPPORT.
  88. */
  89. task_purge_all_corpses();
  90. *corpse_list_purged = TRUE;
  91. }
  92. else if (jld_eval_aggressive_count > memorystatus_jld_eval_aggressive_count) {
  93. /*
  94. * Bump up the jetsam priority limit (eg: the bucket index)
  95. * Enforce bucket index sanity.
  96. */
  97. if ((memorystatus_jld_eval_aggressive_priority_band_max < 0) ||
  98. (memorystatus_jld_eval_aggressive_priority_band_max >= MEMSTAT_BUCKET_COUNT)) {
  99. /*
  100. * Do nothing. Stick with the default level.
  101. */
  102. } else {
  103. jld_priority_band_max = memorystatus_jld_eval_aggressive_priority_band_max;
  104. }
  105. }
  106. /* Visit elevated processes first */
  107. while (elevated_bucket_count) {
  108. elevated_bucket_count--;
  109. /*
  110. * memorystatus_kill_elevated_process() drops a reference,
  111. * so take another one so we can continue to use this exit reason
  112. * even after it returns.
  113. */
  114. os_reason_ref(jetsam_reason);
  115. killed = memorystatus_kill_elevated_process(
  116. cause,
  117. jetsam_reason,
  118. JETSAM_PRIORITY_ELEVATED_INACTIVE,
  119. jld_eval_aggressive_count,
  120. &errors);
  121. if (killed) {
  122. *post_snapshot = TRUE;
  123. if (memorystatus_avail_pages_below_pressure()) {
  124. /*
  125. * Still under pressure.
  126. * Find another pinned processes.
  127. */
  128. continue;
  129. } else {
  130. return TRUE;
  131. }
  132. } else {
  133. /*
  134. * No pinned processes left to kill.
  135. * Abandon elevated band.
  136. */
  137. break;
  138. }
  139. }
  140. /*
  141. * memorystatus_kill_top_process_aggressive() allocates its own
  142. * jetsam_reason so the kMemorystatusKilledProcThrashing cause
  143. * is consistent throughout the aggressive march.
  144. */
  145. killed = memorystatus_kill_top_process_aggressive(
  146. kMemorystatusKilledProcThrashing,
  147. jld_eval_aggressive_count,
  148. jld_priority_band_max,
  149. &errors);
  150. if (killed) {
  151. /* Always generate logs after aggressive kill */
  152. *post_snapshot = TRUE;
  153. *jld_idle_kills = 0;
  154. return TRUE;
  155. }
  156. }
  157. return FALSE;
  158. }
  159. return FALSE;
  160. }

首先有一个jld_bucket_count,这里包含可以直接干掉的低优先级进程的数量。根据jetsam_aging_policy确定哪些优先级类型的进程需要被直接杀掉(正常情况下就是优先级极低的进程和一些正常情况下随时可回收的进程:JETSAM_PRIORITY_IDLEsystem_procs_aging_bandapplications_aging_band)。

如果内存压力依然存在,则通过memorystatus_kill_elevated_process杀掉后台进程。每杀掉一个后台进程,通过memorystatus_available_pages检测一下内存压力。如果memorystatus_available_pages还是小于阈值,则继续杀掉下一个进程。

如果杀掉了所有低优先级的进程,还有内存压力,再通过memorystatus_kill_top_process_aggressive杀掉优先级最低的进程。这里是触发FOOM的关键,如果当前前台进程已经是最低优先级的进程了,那就会发生FOOM。

LRU杀死top process

如果上面memorystatus_act_aggressive函数没有杀死任何进程,那么就需要通过LRU来杀死Jetsam队列中的第一个进程。

  1. /*
  2. * memorystatus_kill_top_process() drops a reference,
  3. * so take another one so we can continue to use this exit reason
  4. * even after it returns
  5. */
  6. os_reason_ref(jetsam_reason);
  7. /* LRU */
  8. killed = memorystatus_kill_top_process(TRUE, sort_flag, cause, jetsam_reason, &priority, &errors);
  9. sort_flag = FALSE;
  10. if (killed) {
  11. if (memorystatus_post_snapshot(priority, cause) == TRUE) {
  12. post_snapshot = TRUE;
  13. }
  14. /* Jetsam Loop Detection */
  15. if (memorystatus_jld_enabled == TRUE) {
  16. if ((priority == JETSAM_PRIORITY_IDLE) || (priority == system_procs_aging_band) || (priority == applications_aging_band)) {
  17. jld_idle_kills++;
  18. } else {
  19. /*
  20. * We've reached into bands beyond idle deferred.
  21. * We make no attempt to monitor them
  22. */
  23. }
  24. }
  25. if ((priority >= JETSAM_PRIORITY_UI_SUPPORT) && (total_corpses_count() > 0) && (corpse_list_purged == FALSE)) {
  26. /*
  27. * If we have jetsammed a process in or above JETSAM_PRIORITY_UI_SUPPORT
  28. * then we attempt to relieve pressure by purging corpse memory.
  29. */
  30. task_purge_all_corpses();
  31. corpse_list_purged = TRUE;
  32. }
  33. goto done;
  34. }
  35. if (memorystatus_avail_pages_below_critical()) {
  36. /*
  37. * Still under pressure and unable to kill a process - purge corpse memory
  38. */
  39. if (total_corpses_count() > 0) {
  40. task_purge_all_corpses();
  41. corpse_list_purged = TRUE;
  42. }
  43. if (memorystatus_avail_pages_below_critical()) {
  44. /*
  45. * Still under pressure and unable to kill a process - panic
  46. */
  47. panic("memorystatus_jetsam_thread: no victim! available pages:%llu\n", (uint64_t)memorystatus_available_pages);
  48. }
  49. }

当所有流程执行完毕,则做一些收尾的工作。

  1. /*
  2. * We do not want to over-kill when thrashing has been detected.
  3. * To avoid that, we reset the flag here and notify the
  4. * compressor.
  5. */
  6. if (is_reason_thrashing(kill_under_pressure_cause)) {
  7. kill_under_pressure_cause = 0;
  8. #if CONFIG_JETSAM
  9. vm_thrashing_jetsam_done();
  10. #endif /* CONFIG_JETSAM */
  11. } else if (is_reason_zone_map_exhaustion(kill_under_pressure_cause)) {
  12. kill_under_pressure_cause = 0;
  13. }
  14. os_reason_free(jetsam_reason);
  15. }
  16. kill_under_pressure_cause = 0;
  17. if (errors) {
  18. memorystatus_clear_errors();
  19. }
  20. if (post_snapshot) {
  21. proc_list_lock();
  22. size_t snapshot_size = sizeof(memorystatus_jetsam_snapshot_t) +
  23. sizeof(memorystatus_jetsam_snapshot_entry_t) * (memorystatus_jetsam_snapshot_count);
  24. uint64_t timestamp_now = mach_absolute_time();
  25. memorystatus_jetsam_snapshot->notification_time = timestamp_now;
  26. memorystatus_jetsam_snapshot->js_gencount++;
  27. if (memorystatus_jetsam_snapshot_count > 0 && (memorystatus_jetsam_snapshot_last_timestamp == 0 ||
  28. timestamp_now > memorystatus_jetsam_snapshot_last_timestamp + memorystatus_jetsam_snapshot_timeout)) {
  29. proc_list_unlock();
  30. int ret = memorystatus_send_note(kMemorystatusSnapshotNote, &snapshot_size, sizeof(snapshot_size));
  31. if (!ret) {
  32. proc_list_lock();
  33. memorystatus_jetsam_snapshot_last_timestamp = timestamp_now;
  34. proc_list_unlock();
  35. }
  36. } else {
  37. proc_list_unlock();
  38. }
  39. }
  40. KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT, BSD_MEMSTAT_SCAN) | DBG_FUNC_END,
  41. memorystatus_available_pages, 0, 0, 0, 0);
  42. memorystatus_thread_block(0, memorystatus_thread);

当检测到颠簸时,系统并不想过度杀戮。为避免这种情况,系统在此处重置标志并通知compressor。如果需要记录当前内存快照,记录后挂起当前线程,等待之后遇到OOM时再次唤醒。

如何触发OOM检测

memorystatus_thread初始化后,会立刻检测一次OOM。

task.c中,当物理内存达到限制时,触发回调,会调用memorystatus_on_ledger_footprint_exceeded,来同步触发per-process-limit类型的OOM。

与上一个类似的,如:memorystatus_kill_on_vnode_limit也是同步触发的。也就是最终调用了memorystatus_kill_process_sync方法,直接杀死对应的进程,如果pid为-1则杀死队列头部的进程。

  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. if (res == TRUE) {
  15. /* Fire off snapshot notification */
  16. proc_list_lock();
  17. size_t snapshot_size = sizeof(memorystatus_jetsam_snapshot_t) +
  18. sizeof(memorystatus_jetsam_snapshot_entry_t) * memorystatus_jetsam_snapshot_count;
  19. uint64_t timestamp_now = mach_absolute_time();
  20. memorystatus_jetsam_snapshot->notification_time = timestamp_now;
  21. if (memorystatus_jetsam_snapshot_count > 0 && (memorystatus_jetsam_snapshot_last_timestamp == 0 ||
  22. timestamp_now > memorystatus_jetsam_snapshot_last_timestamp + memorystatus_jetsam_snapshot_timeout)) {
  23. proc_list_unlock();
  24. int ret = memorystatus_send_note(kMemorystatusSnapshotNote, &snapshot_size, sizeof(snapshot_size));
  25. if (!ret) {
  26. proc_list_lock();
  27. memorystatus_jetsam_snapshot_last_timestamp = timestamp_now;
  28. proc_list_unlock();
  29. }
  30. } else {
  31. proc_list_unlock();
  32. }
  33. }
  34. return res;
  35. }

memorystatus_kill_on_VM_compressor_space_shortagememorystatus_kill_on_VM_compressor_thrashingmemorystatus_kill_on_FC_thrashing都是异步触发的,也就是说他们调用的是memorystatus_kill_process_sync方法。

  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) ||
  10. (cause != kMemorystatusKilledVMPageShortage &&
  11. cause != kMemorystatusKilledVMCompressorThrashing &&
  12. cause != kMemorystatusKilledVMCompressorSpaceShortage &&
  13. cause != kMemorystatusKilledFCThrashing &&
  14. cause != kMemorystatusKilledZoneMapExhaustion)) {
  15. return FALSE;
  16. }
  17. kill_under_pressure_cause = cause;
  18. memorystatus_thread_wake();
  19. return TRUE;
  20. }

也就是最终唤醒了memorystatus_thread,来执行刚刚咱们查看源码的那套流程。

memorystatus_kill_on_zone_map_exhaustion(pid_t pid)中,如果pid为-1,则调用异步方法;否则调用同步方法。

梳理源码逻辑流程

  1. JetSam线程初始化完毕,从外部接收到内存压力
  2. 如果接收到的内存压力是当前物理内存达到限制时,同步触发per-process-limit类型的OOM,退出流程
  3. 如果接受到的内存压力是其他类型时,则唤醒JetSam线程,判断kill_under_pressure_cause值为kMemorystatusKilledVMThrashingkMemorystatusKilledFCThrashingkMemorystatusKilledZoneMapExhaustion时,或者当前可用内存memorystatus_available_pages小于阈值memorystatus_available_pages_pressure时,进入OOM逻辑。
  4. 遍历优先级最低的每个进程,根据phys_footprint,判断当前进程是否高于阈值,如果没有超过阈值的,则据需查找下一个次低优先级的进程,直到找到后,触发high-water类型OOM
  5. 此时先回一个收优先级较低的进程或正常情况下随时可回收的进程,再次走到4的判断逻辑
  6. 当所有低优先级进程或正常情况下课随时回收的进程都被杀掉后,如果memorystatus_available_pages依然小于阈值,先杀掉后台的进程,每杀掉一个进程,判断一下memorystatus_available_pages是否还小于阈值,如果已经小于阈值了,则挂起线程,等待唤醒
  7. 当所有后台进程都被杀掉后,调用memorystatus_kill_top_process_aggressive,杀掉前台的进程,挂起线程,等待唤醒
  8. 如果上面的memorystatus_kill_top_process_aggressive没有杀掉任何进程,就通过LRU杀死Jetsam队列中的第一个进程,挂起线程,等待唤醒

如何判定发生了OOM

facebook和微信的Matrix都是采用的排除法。在Matrix初始化的时候调用checkRebootType方法,来判定是否发生了OOM,具体流程如下:

  1. 如果当前设备正在DEBUG,则直接返回,不继续执行。
  2. 上次打开app是否发生了普通的崩溃,如果不是继续执行
  3. 上次打开app后,是用户是否主动退出的应用(监听UIApplicationWillTerminateNotification消息),如果不是继续执行
  4. 上次打开app后,是否调用exit相关的函数(通过atexit函数监控),如果不是继续执行
  5. 上次打开app后,app是否挂起suspend或者执行backgroundFetch,如果此时没有被看门狗杀死,则是一种OOM,Matrix起名叫Suspend OOM,如果不是继续执行
  6. app的uuid是否变化了,如果不是继续执行
  7. 上次打开app后,系统是否升级了,如果不是继续执行
  8. 上次打开app后,设备是否重启了,如果不是继续执行
  9. 上次打开app时,app是否处于后台,如果是,则触发了Background OOM,如果不是继续执行
  10. 上次打开app后,app是否处于前台,是否主线程卡死了,如果没有卡死,则说明触发了Foreground OOM

我们平时谈论的OOM,其实大部分都是FOOM。因为如果我们的程序在后台,优先级很低,即便我们不占用大量的内存,也可能会由于前台应用程序占用了大量的内存,而把我们在后台的程序杀掉。这是系统的机制,我们没有太多的办法。

所以主要关注FOOM。而针对于FOOM,我们需要着重关注dirty pagesIOKit mappings,当然注意系统做的缓存,例如图片、字体等。针对于OOM问题监控与解决,可以参考Matrix和OOMDetector两个开源库。目前针对OOM的监控也处于探索阶段,日后如果在监控及处理OOM上有了一些经验后,也会主动分享给大家。

参考资料

OOM探究:XNU 内存状态管理

你真的了解OOM吗?——京东iOS APP内存优化实录

(译)Handling low memory conditions in iOS and Mavericks

iOS Out-Of-Memory 原理阐述及方案调研

iOS微信内存监控

本文链接http://www.taodudu.cc/news/show-5381.html

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

闽ICP备14008679号