【问题标题】:User level bounce buffer for fs io ? Why write file buffer address space should be aligned?fs io 的用户级反弹缓冲区?为什么写文件缓冲区地址空间要对齐?
【发布时间】:2014-10-17 01:41:32
【问题描述】:

我看到一段代码是这样做磁盘 io 的:

static bool is_aligned(unsigned char *buffer) {
  return ( ((unsigned long)buffer) & (DISK_PAGE_SIZE -1)) == 0;
}


void do_write_IO(int fd, unsignced char *buffer, unsigned long buffer_bytes) {
  ...

  if (is_aligned(buffer)) {
    write_to_file(fd, buffer, io_size);
  } else {
    // bounce buffer is an aligned memory space.
    // if buffer not aligned, copy to an aligned address
    // and do fs write. WHY ?
    // What are the benefits ? 
    memcpy(bounce_buffer, buffer, io_size);
    write_to_file(fd, bounce_buffer, io_size);
  }

  ...
}

// Just call posix write, write output to fd, with bytes_to_write size.
static void write_to_file(int fd, 
          unsigned char *output,
          unsigned long bytes_to_write) 
{
  __sync_fetch_and_add(&stat_bytes_written, bytes_to_write);
  while(bytes_to_write) {
    unsigned long bytes_written = write(fd, output, bytes_to_write);
    if(bytes_written == -1UL) {
      if(errno != EAGAIN) {
        BOOST_LOG_TRIVIAL(fatal) << 
          "Stream writeout unsuccessful:" << strerror(errno);
        exit(-1);
      }
    }
    else {
      output += bytes_written;
      bytes_to_write -= bytes_written;
    }
  }
}

我注意到它使用地址空间对齐的缓冲区写入文件。 那么,写入具有对齐缓冲区的文件有什么好处吗?

【问题讨论】:

    标签: linux io filesystems posix memory-alignment


    【解决方案1】:

    我认为“正常工作”是一种好处。为此,您需要满足您调用的每个函数的先决条件。

    write_to_file 需要一个对齐的缓冲区,如果 write 需要,这取决于设备。可能您的fd 是用O_DIRECT 打开的。 open 手册页说:

    O_DIRECT 标志可能会对用户空间缓冲区的长度和地址以及 I/O 的文件偏移施加对齐限制。

    在 Linux 2.4 下,传输大小,以及用户缓冲区和文件偏移的对齐方式都必须是文件系统逻辑块大小的倍数。在 Linux 2.6 下,对齐到 512 字节边界就足够了。

    如果您不遵守此前提条件,write 手册页将记录一个错误:

    EINVAL fd 附加到不适合书写的对象上;或者文件是使用O_DIRECT 标志打开的,并且buf 中指定的地址、count 中指定的值或当前文件偏移量未适当对齐。

    【讨论】:

    • 是的!确切地说,fd 是用 O_DIRECT 打开的。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2012-01-19
    • 2014-09-12
    • 1970-01-01
    • 1970-01-01
    • 2011-07-02
    • 2021-06-13
    • 2011-09-08
    • 2018-10-03
    相关资源
    最近更新 更多