I want to write a physical memory to a file. The memory itself will not be touched again, thus I want to use O_DIRECT to gain the best write performance.
My first idea was to open /dev/mem and mmap the memory and write everything to a file, which is opened with O_DIRECT. The write call fails (EFAULT) on the memory-address returned by mmap. If I do not use O_DIRECT, it results in a memcpy.
#include <cstdint>
#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <errno.h>
#include <malloc.h>
#include <sys/mman.h>
#define PRINT_ERRNO_REASON(reason) \
case reason: { std::cout << #reason << std::endl; } break;
void write_page_aligned_buffer(int out_fd)
{
const ssize_t PAGE_SIZE = getpagesize();
void* page_aligned_buffer = memalign(PAGE_SIZE, PAGE_SIZE);
if(!page_aligned_buffer)
{
std::cout << "Could not allocate page aligned buffer." << std::endl;
return;
}
std::cout << "Allocated a buffer at address " << page_aligned_buffer << "." << std::endl;
if(write(out_fd, page_aligned_buffer, PAGE_SIZE) < 0)
{
std::cout << "Could not write page-aligned user buffer to tmp-file. Quitting..." << std::endl;
std::cout << "Reason of fail is ";
switch(errno)
{
PRINT_ERRNO_REASON(EAGAIN);
PRINT_ERRNO_REASON(EBADF);
PRINT_ERRNO_REASON(EFAULT);
PRINT_ERRNO_REASON(EFBIG);
PRINT_ERRNO_REASON(EINTR);
PRINT_ERRNO_REASON(EINVAL);
PRINT_ERRNO_REASON(EIO);
PRINT_ERRNO_REASON(ENOSPC);
PRINT_ERRNO_REASON(EPIPE);
default:
std::cout << "Unknown" << std::endl;