首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何mmap()一个大文件而不冒OOM杀手的风险?

如何mmap()一个大文件而不冒OOM杀手的风险?
EN

Stack Overflow用户
提问于 2020-02-05 23:43:13
回答 1查看 691关注 0票数 15

我有一个嵌入式ARM Linux机器,内存有限(512MB),没有交换空间,我需要在上面创建并操作一个相当大的文件(~200MB)。将整个文件加载到RAM中,修改RAM中的内容,然后再次写回它,有时会调用OOM杀手,这是我想要避免的。

我的解决办法是使用mmap()将这个文件映射到进程的虚拟地址空间;这样,对映射的内存区的读取和写入将转到本地闪存文件系统,并且可以避免对象对象模型杀手,因为如果内存不足,Linux可以将一些mmap()d内存页面刷新回磁盘,以释放一些内存。(这可能会使我的程序变慢,但对于这个用例来说,慢是可以的。)

然而,即使使用mmap()调用,我仍然偶尔会看到进程在执行上述操作时被OOM杀手杀死。

我的问题是,我是不是对Linux在大型mmap()和有限RAM的情况下的行为过于乐观了?(也就是说,mmap()-ing一个200MB的文件,然后读/写mmap()的内存仍然需要200MB的可用内存才能可靠地完成吗?)或者mmap()是否应该足够聪明,在内存不足时将mmap的页面换出,但我在如何使用它方面做错了什么?

FWIW我的映射代码如下:

代码语言:javascript
复制
void FixedSizeDataBuffer :: TryMapToFile(const std::string & filePath, bool createIfNotPresent, bool autoDelete)
{
   const int fd = open(filePath.c_str(), (createIfNotPresent?(O_CREAT|O_EXCL|O_RDWR):O_RDONLY)|O_CLOEXEC, S_IRUSR|(createIfNotPresent?S_IWUSR:0));
   if (fd >= 0)
   {
      if ((autoDelete == false)||(unlink(filePath.c_str()) == 0))  // so the file will automatically go away when we're done with it, even if we crash
      {
         const int fallocRet = createIfNotPresent ? posix_fallocate(fd, 0, _numBytes) : 0;
         if (fallocRet == 0)
         {
            void * mappedArea = mmap(NULL, _numBytes, PROT_READ|(createIfNotPresent?PROT_WRITE:0), MAP_SHARED, fd, 0);
            if (mappedArea)
            {
               printf("FixedSizeDataBuffer %p: Using backing-store file [%s] for %zu bytes of data\n", this, filePath.c_str(), _numBytes);
               _buffer         = (uint8_t *) mappedArea;
               _isMappedToFile = true;
            }
            else printf("FixedSizeDataBuffer %p: Unable to mmap backing-store file [%s] to %zu bytes (%s)\n", this, filePath.c_str(), _numBytes, strerror(errno));
         }
         else printf("FixedSizeDataBuffer %p: Unable to pad backing-store file [%s] out to %zu bytes (%s)\n", this, filePath.c_str(), _numBytes, strerror(fallocRet));
      }
      else printf("FixedSizeDataBuffer %p: Unable to unlink backing-store file [%s] (%s)\n", this, filePath.c_str(), strerror(errno));

      close(fd); // no need to hold this anymore AFAIK, the memory-mapping itself will keep the backing store around
   }
   else printf("FixedSizeDataBuffer %p: Unable to create backing-store file [%s] (%s)\n", this, filePath.c_str(), strerror(errno));
}

如果有必要,我可以重写这段代码,只使用普通的-旧-文件-I/O,但如果mmap()能完成这项工作就更好了(如果不行,我至少想知道为什么不能)。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-07-12 06:45:42

经过进一步的实验,我确定OOM杀手访问我并不是因为系统耗尽了RAM,而是因为RAM偶尔会变得足够碎片化,以至于内核无法找到一组足够大的物理上连续的RAM页来满足其即时需求。当这种情况发生时,内核会调用OOM杀手来释放一些RAM,以避免内核崩溃,这对内核来说是很好的,但当它杀死用户所依赖的进程来完成他的工作时,就不是那么好了。:/

在尝试并没有找到说服Linux不这么做的方法之后(我认为启用交换分区可以避免OOM杀手,但在这些特定的机器上,这样做对我来说不是一个选择),我想出了一个解决办法;我在我的程序中添加了一些代码,定期检查Linux内核报告的内存碎片数量,如果内存碎片开始看起来太严重,就抢先命令进行内存碎片整理,这样OOM杀手(希望)将不会成为必要的。如果内存碎片整理过程看起来没有任何改进,那么在连续尝试20次之后,我们也会删除VM页面缓存,以此来释放连续的物理RAM。这一切都非常丑陋,但并不像凌晨3点接到用户的电话那样丑陋,用户想知道为什么他们的服务器程序刚刚崩溃。:/

解决方法的实现要点如下;请注意,DefragTick(Milliseconds)需要定期调用(最好是每秒调用一次)。

代码语言:javascript
复制
 // Returns how safe we are from the fragmentation-based-OOM-killer visits.
 // Returns -1 if we can't read the data for some reason.
 static int GetFragmentationSafetyLevel()
 {
    int ret = -1;
    FILE * fpIn = fopen("/sys/kernel/debug/extfrag/extfrag_index", "r");
    if (fpIn)
    {
       char buf[512];
       while(fgets(buf, sizeof(buf), fpIn))
       {  
          const char * dma = (strncmp(buf, "Node 0, zone", 12) == 0) ? strstr(buf+12, "DMA") : NULL;
          if (dma)
          {  
             // dma= e.g.:  "DMA -1.000 -1.000 -1.000 -1.000 0.852 0.926 0.963 0.982 0.991 0.996 0.998 0.999 1.000 1.000"
             const char * s = dma+4;  // skip past "DMA ";
             ret = 0; // ret now becomes a count of "safe values in a row"; a safe value is any number less than 0.500, per me
             while((s)&&((*s == '-')||(*s == '.')||(isdigit(*s))))
             {  
                const float fVal = atof(s);
                if (fVal < 0.500f)
                {  
                   ret++;
                   
                   // Advance (s) to the next number in the list
                   const char * space = strchr(s, ' ');   // to the next space
                   s = space ? (space+1) : NULL;
                }
                else break;  // oops, a dangerous value!  Run away!
             }
          }
       }
       fclose(fpIn);
    }
    return ret;
 }

 // should be called periodically (e.g. once per second)
 void DefragTick(Milliseconds current_time_in_milliseconds)
 {
     if ((current_time_in_milliseconds-m_last_fragmentation_check_time) >= Milliseconds(1000))
     {
        m_last_fragmentation_check_time = current_time_in_milliseconds;

        const int fragmentationSafetyLevel = GetFragmentationSafetyLevel();
        if (fragmentationSafetyLevel < 9)
        {
           m_defrag_pending = true;  // trouble seems to start at level 8
           m_fragged_count++;        // note that we still seem fragmented
        }
        else m_fragged_count = 0;    // we're in the clear!

        if ((m_defrag_pending)&&((current_time_in_milliseconds-m_last_defrag_time) >= Milliseconds(5000)))
        {
           if (m_fragged_count >= 20)
           {
              // FogBugz #17882
              FILE * fpOut = fopen("/proc/sys/vm/drop_caches", "w");
              if (fpOut)
              {
                 const char * warningText = "Persistent Memory fragmentation detected -- dropping filesystem PageCache to improve defragmentation.";
                 printf("%s (fragged count is %i)\n", warningText, m_fragged_count);
                 fprintf(fpOut, "3");
                 fclose(fpOut);

                 m_fragged_count = 0;
              }
              else
              {
                 const char * errorText = "Couldn't open /proc/sys/vm/drop_caches to drop filesystem PageCache!";
                 printf("%s\n", errorText);
              }
           }

           FILE * fpOut = fopen("/proc/sys/vm/compact_memory", "w");
           if (fpOut)
           {
              const char * warningText = "Memory fragmentation detected -- ordering a defragmentation to avoid the OOM-killer.";
              printf("%s (fragged count is %i)\n", warningText, m_fragged_count);
              fprintf(fpOut, "1");
              fclose(fpOut);

              m_defrag_pending   = false;
              m_last_defrag_time = current_time_in_milliseconds;
           }
           else
           {
              const char * errorText = "Couldn't open /proc/sys/vm/compact_memory to trigger a memory-defragmentation!";
              printf("%s\n", errorText);
           }
        }
     }
 }
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60079327

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档