Changes

Jump to: navigation, search

Computer Architecture

107 bytes added, 00:55, 20 February 2018
Sub-word and Unaligned Access
== Sub-word and Unaligned Access ==
Most processors use a [[Word|word]] size that is multiple of width of some common data types . However, it is often necessary to access data which is a fraction of this size -- for example, a system with a 32-bit [[Word#Hardware Word|hardware word size]] that is running applications which use UTF-8 character encoding may often need to read or write single [[Word#Byte|bytes]] of data. A byte-sized read will cause the CPU to perform a 32-bit read, followed by [[Bitwise Operations|masking and shifting operations]] to extract the desired byte from the 32-bit word. A single-byte write operation will cause the CPU to read the existing word, extract the unaffected bits within that word (with [[Bitwise Operations#AND|AND]]), [[Bitwise Operations#OR|OR]] in the new value, and then write the word back to memory.
Unaligned memory access causes similar issues. For example, to read a 32-bit value from the byte address 0x2, most 32-bit CPUs will read a 32-bit value starting at byte address 0x0 and perform an [[Bitwise Operations|AND]] to extract highest 16 bits, then a shift to move those bits to the lowest 16 bit positions. The CPU will then read a 32-bit value starting at byte address 0x4, perform an AND to extract the lowest 16 bits, shift those bits to the highest 16 bit positions, and then OR the high 16 bits and the low 16 bits together into a single 32 bit value. (Writing an unaligned 32-bit value is even worse!)
Obviously, unaligned access is far slower than aligned access, and should be avoided whenever possible. However, aligning all storage may result in increased memory usage (e.g., aligning 24-bit pixel values on 32-bit boundaries), and some data such as compressed data streams or network packets will almost always contain unaligned data.
Some processors , such as ARMv5 processors, do not have alignment-fixup hardware, and an unaligned access causes a processor exception. The operating system may ignore the unaligned access (usually leading to incorrect results), stop the program performing the unaligned access, or fix up the access in software and then resume execution of the process which caused the exception.
On a Linux system, the control file <code>/proc/cpu/alignment</code> controls how the operating system will handle alignment exceptions (on machines which lack alignment-fixup hardware). The possible values are:

Navigation menu