1

How we can check whether the buffer passing to disk driver is sector aligned or not by using c program? If the buffer is not sector aligned then how we can make it sector aligned ?

Anil
  • 117
  • 1
  • 7
  • 4
    @Someprogrammerdude "Why do you need the buffer *in memory* to be aligned according to some *disk*? The two are really unrelated." Low-level programming, kernel drivers, direct IO. Hardware for DMA transfers often has alignment restrictions on the memory it can operate on. [For example](https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/5/html/Global_File_System/s1-manage-direct-io.html): *When a file is opened with O_DIRECT ... all I/O operations must be done in block-size multiples of 512 bytes. The memory being read from or written to must also be 512-byte aligned.* – Andrew Henle Dec 15 '16 at 12:48
  • http://stackoverflow.com/questions/3839922/aligned-malloc-in-gcc – stark Dec 15 '16 at 18:27

1 Answers1

1

Check:

const long SECTOR_SIZE=512;  //MUST be a power of 2

bool isAligned(char *buf)
{
    long address = (long)(void *)buf;
    return ( (address & (SECTOR_SIZE-1)) == 0 );
}

Align: Note that when you allocate the buffer, you MUST allocate SECTOR_SIZE-1 additional bytes! When you free the buffer, free the ORIGINAL pointer!

char *align(char *buf)
{
    long address = (long)(void *)buf;
    return buf+((-address)&(SECTOR_SIZE-1));
}
Matt Timmermans
  • 53,709
  • 3
  • 46
  • 87