【问题标题】:Kernel copying CoW pages after child process exit子进程退出后内核复制 CoW 页面
【发布时间】:2019-05-16 17:33:25
【问题描述】:

在 Linux 中,每当一个进程被派生时,父进程的内存映射都会克隆到子进程中。实际上,出于性能原因,页面被设置为 copy-on-write —— 最初它们是共享的,如果两个进程之一在其中一个上写入,那么它们将被克隆 (MAP_PRIVATE)。

这是获取正在运行的程序状态快照的一种非常常见的机制——您执行一个 fork,这为您提供了该时间点进程内存的(一致)视图。

我做了一个简单的基准测试,其中包含两个组件:

  • 具有线程池的父进程写入数组
  • 具有线程池的子进程制作数组的快照并取消映射

在某些情况下(机器/架构/内存放置/线程数/...),我可以使复制比线程写入数组更早​​完成。

但是,当子进程退出时,在htop 中我仍然看到大部分 CPU 时间都花在了内核中,这与它用于处理 copy-on-write 每当父进程写入页面时。

在我的理解中,如果标记为copy-on-write的匿名页面是由单个进程映射的,则不应复制,而应直接使用。

我如何确定这确实是复制内存所花费的时间?

如果我是对的,我该如何避免这种开销?


基准测试的核心如下,现代 C++。

定义WITH_FORK 启用快照;保留未定义以禁用子进程。

#include <unistd.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/wait.h>

#include <numaif.h>
#include <numa.h>

#include <algorithm>
#include <cassert>
#include <condition_variable>
#include <mutex>
#include <iomanip>
#include <iostream>
#include <cmath>
#include <numeric>
#include <thread>
#include <vector>

#define ARRAY_SIZE 1073741824 // 1GB
#define NUM_WORKERS 28
#define NUM_CHECKPOINTERS 4
#define BATCH_SIZE 2097152 // 2MB

using inttype = uint64_t;
using timepoint = std::chrono::time_point<std::chrono::high_resolution_clock>;

constexpr uint64_t NUM_ELEMS() {
  return ARRAY_SIZE / sizeof(inttype);
}

int main() {

  // allocate array
  std::array<inttype, NUM_ELEMS()> *arrayptr = new std::array<inttype, NUM_ELEMS()>();
  std::array<inttype, NUM_ELEMS()> & array = *arrayptr;

  // allocate checkpoint space
  std::array<inttype, NUM_ELEMS()> *cpptr = new std::array<inttype, NUM_ELEMS()>();
  std::array<inttype, NUM_ELEMS()> & cp = *cpptr;

  // initialize array
  std::fill(array.begin(), array.end(), 123);

#ifdef WITH_FORK
  // spawn checkpointer threads
  int pid = fork();
  if (pid == -1) {
    perror("fork");
    exit(-1);
  }

  // child process -- do checkpoint
  if (pid == 0) {
    std::array<std::thread, NUM_CHECKPOINTERS> cpthreads;
    for (size_t tid = 0; tid < NUM_CHECKPOINTERS; tid++) {
      cpthreads[tid] = std::thread([&, tid] {
        // copy array
        const size_t numBatches = ARRAY_SIZE / BATCH_SIZE;
        for (size_t i = tid; i < numBatches; i += NUM_CHECKPOINTERS) {
          void *src = reinterpret_cast<void*>(
            reinterpret_cast<intptr_t>(array.data()) + i * BATCH_SIZE);
          void *dst = reinterpret_cast<void*>(
            reinterpret_cast<intptr_t>(cp.data()) + i * BATCH_SIZE);
          memcpy(dst, src, BATCH_SIZE);
          munmap(src, BATCH_SIZE);
        }
      });
    }
    for (std::thread& thread : cpthreads) {
      thread.join();
    }
    printf("CP finished successfully! Child exiting.\n");
    exit(0);
  }
#endif  // #ifdef WITH_FORK

  // spawn worker threads
  std::array<std::thread, NUM_WORKERS> threads;
  for (size_t tid = 0; tid < NUM_WORKERS; tid++) {
    threads[tid] = std::thread([&, tid] {
      // write to array
      std::array<inttype, NUM_ELEMS()>::iterator it;
      for (it = array.begin() + tid; it < array.end(); it += NUM_WORKERS) {
        *it = tid;
      }
    });
  }

  timepoint tStart = std::chrono::high_resolution_clock::now();

#ifdef WITH_FORK
  // allow reaping child process while workers work
  std::thread childWaitThread = std::thread([&] {
    if (waitpid(pid, nullptr, 0)) {
      perror("waitpid");
    }
    timepoint tChild = std::chrono::high_resolution_clock::now();
    std::chrono::duration<double> durationChild = tChild - tStart;
    printf("reunited with child after (s): %lf\n", durationChild.count());
  });
#endif

  // wait for workers to finish
  for (std::thread& thread : threads) {
    thread.join();
  }
  timepoint tEnd = std::chrono::high_resolution_clock::now();
  std::chrono::duration<double> duration = tEnd - tStart;
  printf("duration (s): %lf\n", duration.count());

#ifdef WITH_FORK
  childWaitThread.join();
#endif
}

【问题讨论】:

  • 没有“现代”C++ 这样的东西。如果您想具体一点,请谈谈您正在使用哪个版本进行编译,例如 C++14 或 C++17 等,以及如果您认为这是影响结果的一个因素,请说明使用什么编译器。
  • 我正在使用C++17,但我不确定这是否是最低要求标准:) 我只使用了gcc 8(试用clang 的好提示)
  • 在进一步阅读您的问题时,如果您在谈论内核如何处理页面,我认为这根本不是 C++ 的事情。这可能与您正在使用的内核有关,甚至可能与内核的编译方式有关。 Copy-on-Write 不是免费的,内核必须为此提供便利,因此您可能会看到与清理它相关的更高 CPU 使用率。 Redis 是一个著名的软件示例,它大量使用了 fork/dump 模型,这就是它制作定期快照的方式。
  • 如果您更深入地研究可以从/proc 获得的统计信息,您可能能够衡量内核为管理您的页面所做的工作。那里有令人眼花缭乱的旋钮、按钮和仪表,所以在四处寻找之前,您需要找到一个很好的参考,但确实有很多。
  • 对How can I be sure that this is indeed time being spent copying the memory?的回答是运行内核分析器。

标签: c++ performance memory linux-kernel copy-on-write


【解决方案1】:

数组的大小为1GB,大约是250K页,其中每页大小为4KB。对于这个程序,可以很容易地估计由于写入 CoW 页面而发生的页面错误的数量。它也可以使用 Linux perf 工具进行测量。 new 运算符将数组初始化为零。所以下面的代码行:

std::array<inttype, NUM_ELEMS()> *arrayptr = new std::array<inttype, NUM_ELEMS()>();

将导致大约 250K 页面错误。同样,下面这行代码:

std::array<inttype, NUM_ELEMS()> *cpptr = new std::array<inttype, NUM_ELEMS()>();

将导致另外 250K 页面错误。所有这些页面错误都是次要的,也就是说,它们可以在不访问磁盘驱动器的情况下进行处理。分配两个 1GB 阵列不会对物理内存大得多的系统造成任何重大故障。

此时,已经发生了大约 500K 的页面错误(当然还有程序其他内存访问导致的其他页面错误,但可以忽略不计)。 std::fill 的执行不会导致任何小故障,但数组的虚拟页面已经映射到专用物理页面。

然后程序的执行继续分叉子进程并创建父进程的工作线程。子进程的创建本身就足够做数组的快照了,所以子进程真的不需要做任何事情。事实上,当子进程被分叉时,两个数组的虚拟页面都被标记为写时复制。子进程从arrayptr 读取并写入cpptr,这会导致额外的250K 次要故障。父进程也会写入arrayptr,这也会导致额外的 250K 次要故障。因此,在子进程中制作副本并取消映射页面并不会提高性能。反之,缺页次数翻倍,性能明显下降。

您可以使用以下命令测量次要故障和主要故障的数量:

perf stat -r 3 -e minor-faults,major-faults ./binary

默认情况下,这将计算整个进程树的次要和主要故障。 -r 3 选项告诉perf 重复实验 3 次并报告平均值和标准差。

我还注意到线程总数为 28 + 4。最佳线程数大约等于系统上在线逻辑核心的总数。如果线程数多于或少得多,则会因创建过多线程并在它们之间切换的开销而降低性能。

以下循环中可能存在另一个潜在问题:

for (it = array.begin() + tid; it < array.end(); it += NUM_WORKERS) {
  *it = tid;
}

不同的线程可能会同时尝试多次写入同一缓存行,从而导致错误共享。这可能不是一个重大问题,具体取决于处理器缓存线的大小、线程数以及所有内核是否以相同的频率运行,因此如果不进行测量就很难说。更好的循环形状是让每个线程的元素在数组中是连续的。

【讨论】:

  • 嗨@Hadi - 感谢您花时间发布如此全面的答案!我一定会消化所有这些,并会回复你:)
  • 确实我遭受了错误共享的困扰——我已经修复了它(缓存行中的元素不会被不同的线程写入)。但似乎我仍然无法避免大多数页面错误,即使取消映射页面 VS 不取消映射它们,甚至当子进程在 VS 之前约 3 秒退出时,线程写入数组需要约 6 秒。
  • 例如,使用一个 8GB 数组、2 个 writer 线程和 28 个 checkpointer 线程并通过perf stat -r 3 -e minor-faults,major-faults numactl --interleave=all ./mybenchmark 运行它,我得到大约 10M小故障。我预计数组页面会出现 4M 到 8M 之间的小故障。
  • @JoãoNeto 您不需要两个数组,也不需要在子进程中执行任何操作来创建数组的快照。只需通过分叉子进程,就可以创建快照。这样做会非常有效。另外,我不明白为什么您应该为相同的确切代码获得 10M 次小故障。也许,您对我不知道的代码进行了更改。
  • @JoãoNeto 是什么让您认为内核在 子进程退出后复制页面?
猜你喜欢
  • 2013-03-13
  • 1970-01-01
  • 2015-12-12
  • 1970-01-01
  • 1970-01-01
  • 2021-10-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多