January 12, 2017

ARM Alignment issues

In its older versions, the ARM processor is fussy about data alignment. You must access 4 byte integers on 4 byte boundaries, and 2 byte integers on 2 byte boundaries.

More modern processors offer this behavior as an option, and the fussiness is commonly disabled.

If you access a 4 byte object on a 2 byte or odd boundary you get a data abort

If you access a 2 byte object on an odd boundary you tet a data abourt.

The good news is that modern ARM processors can support unaligned accesses.
The ARMv6 architecture introduced the first hardware support for unaligned accesses. ARM11 and Cortex-A/R processors can deal with unaligned accesses in hardware, removing the need for software routines.
This functionality is available both on the Cortex-A8 in the BBB and the Cortex-A7 in the Orange Pi.

What about the gcc "pack" pragma

Given the ability to make the ARM processor less fussy this may be somewhat moot, but this is an interesting and related topic. The "pragma pack" notation is more succinct, which is a vote in its favor. However it originated with Microsoft, which is a significant demerit.

Enabling unaligned access support

The ARM documents state:
Unaligned access support must be enabled by setting the SCTLR.A bit in the system control coprocessor. Attempts to perform unaligned accesses when not allowed will cause an alignment fault (data abort).
The way the above is worded is somewhat misleading. You need to clear this bit to allow unaligned accesses. With the bit set you have enabled exceptions on unaligned accesses, which is not what we are eager to do in this discussion.
#define SCTRL_A         0x0002

static void
enable_unaligned ( void )
{
        int scr;

        asm volatile("mrc p15, 0, %0, c1, c0, 0" : "=r" (scr) : : "cc");
        scr &= ~SCTRL_A;
        asm volatile("mcr p15, 0, %0, c1, c0, 0" : : "r" (scr) : "cc");
}
The documents also state tha this bit is clear on reset. On my experimentation with the Cortex-A8 on the BBB and the Cortex-A7mp on the Orange Pi, I have always found the bit set. I can only conclude that it is being set by U-boot.


Have any comments? Questions? Drop me a line!

Tom's electronics pages / tom@mmto.org