Data Structure Alignment - Hardware Significance of Alignment Requirements

Hardware Significance of Alignment Requirements

Alignment concerns can affect areas much larger than a C structure when the purpose is the efficient mapping of that area through a hardware address translation mechanism (PCI remapping, operation of a MMU).

For instance, on a 32bit operating system, a 4KB page is not just an arbitrary 4KB chunk of data. Instead, it is usually a region of memory that's aligned on a 4KB boundary. This is because aligning a page on a page-sized boundary lets the hardware map a virtual address to a physical address by substituting the higher bits in the address, rather than doing complex arithmetic.

Example: Assume that we have a TLB mapping of virtual address 0x2cfc7000 to physical address 0x12345000. (Note that both these addresses are aligned at 4KB boundaries.) Accessing data located at virtual address va=0x2cfc7abc causes a TLB resolution of 0x2cfc7 to 0x12345 to issue a physical access to pa=0x12345abc. Here, the 20/12bit split luckily match the hexadecimal representation split at 5/3 digits. The hardware can implement this translation by simply combining the first 20 bits of the physical address (0x12345) and the last 12 bits of the virtual address (0xabc). This is also referred to as virtually indexed(abc) physically tagged(12345).

A block of data of size 2^(n+1)-1 always has one sub-block of size 2^n aligned on 2^n bytes.

This is how a dynamic allocator that has no knowledge of alignment, can be used to provide aligned buffers, at the price of a factor two in data loss.

Example: get a 12bit aligned 4KBytes buffer with malloc // unaligned pointer to large area void *up=malloc((1<<13)-1); // well aligned pointer to 4KBytes void *ap=aligntonext(up,12); where aligntonext is meant as: move p to the right until next well aligned address if not correct already. A possible implementation is // PSEUDOCODE assumes uint32_t p,bits; for readability // --- not typesafe, not side-effect safe #define alignto(p,bits) (p>>bits<

Read more about this topic:  Data Structure Alignment

Famous quotes containing the words hardware and/or significance:

    A friend of mine spoke of books that are dedicated like this: “To my wife, by whose helpful criticism ...” and so on. He said the dedication should really read: “To my wife. If it had not been for her continual criticism and persistent nagging doubt as to my ability, this book would have appeared in Harper’s instead of The Hardware Age.”
    Brenda Ueland (1891–1985)

    Politics is not an end, but a means. It is not a product, but a process. It is the art of government. Like other values it has its counterfeits. So much emphasis has been placed upon the false that the significance of the true has been obscured and politics has come to convey the meaning of crafty and cunning selfishness, instead of candid and sincere service.
    Calvin Coolidge (1872–1933)