views:

64

answers:

1

I allocated some memory with anonymous mmap:

buff->addr = mmap(NULL, length, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS -1, 0);
fprintf(stderr, "allocated buffer: %p, %lu\n", buff->addr, (unsigned long)length);

then I'm writing to it using fd opened with O_DIRECT:

int fd = open(name, O_CREAT | O_TRUNC | O_WRONLY | O_DIRECT, 00300);
if(fd == -1)
{
    perror("failed to open for write");
    return;
}

fprintf(stderr, "writing to address: %p size: %lu\n", buff.addr, buff.length);
if(write(fd, buff.addr, buff.length) != size)
{
    perror("failed to write");
}

but get bad address error:

allocated buffer: 0x7f096ddff000, 512000
writing to address: 0x7f096ddff000 size: 512000
failed to write: Bad address

The address looks good to me.

If I allocate the buffer in .data and align to 512, the write works, so the open() and write() are ok, I have all permissions, etc.

What's wrong? Are there other requirements for direct IO than 512 alignment?

UPDATE:

for example, if I change mmap for this:

char buffer[ 1024000 ];
for(buff->addr = buffer; ((unsigned long)buff->addr % 512) != 0; buff->addr = buff->addr + 1);

it works:

allocated buffer: 0x500e00, 512000
writing to address: 0x500e00 size: 512000
+2  A: 

PROT_NONE Pages may not be accessed.

Shouldn't you atleast have PROT_READ as the 3. argument to mmap ? And to be useful in this case, you probably need PROT_READ|PROT_WRITE

nos
I misread the man. Thank you so much
n-alexander