Alex Rivera | Logout

How to write kernel space memory (physical address) to a file using O_DIRECT?

Asked 2011-06-22T11:30:43.113
12

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;
    
Edit
Report

2 Answers

2

Your problem looks a little strange. Since you are programming quite near to the hardware, you might consider using direct memory access (DMA). This might be a bit tricky, since you need to understand paging and parts of the I/O mechanism. You might want to read that:

http://www.linuxjournal.com/article/7104

(It's just mere introduction to get the idea.)

answered 2012-02-28T05:15:08.130
0

I tested tonight , if use O_DIRECT your write will be conditional.

answered 2011-12-25T00:35:30.323

Your Answer