162306a36Sopenharmony_ci=========================
262306a36Sopenharmony_ciUnaligned Memory Accesses
362306a36Sopenharmony_ci=========================
462306a36Sopenharmony_ci
562306a36Sopenharmony_ci:Author: Daniel Drake <dsd@gentoo.org>,
662306a36Sopenharmony_ci:Author: Johannes Berg <johannes@sipsolutions.net>
762306a36Sopenharmony_ci
862306a36Sopenharmony_ci:With help from: Alan Cox, Avuton Olrich, Heikki Orsila, Jan Engelhardt,
962306a36Sopenharmony_ci  Kyle McMartin, Kyle Moffett, Randy Dunlap, Robert Hancock, Uli Kunitz,
1062306a36Sopenharmony_ci  Vadim Lobanov
1162306a36Sopenharmony_ci
1262306a36Sopenharmony_ci
1362306a36Sopenharmony_ciLinux runs on a wide variety of architectures which have varying behaviour
1462306a36Sopenharmony_ciwhen it comes to memory access. This document presents some details about
1562306a36Sopenharmony_ciunaligned accesses, why you need to write code that doesn't cause them,
1662306a36Sopenharmony_ciand how to write such code!
1762306a36Sopenharmony_ci
1862306a36Sopenharmony_ci
1962306a36Sopenharmony_ciThe definition of an unaligned access
2062306a36Sopenharmony_ci=====================================
2162306a36Sopenharmony_ci
2262306a36Sopenharmony_ciUnaligned memory accesses occur when you try to read N bytes of data starting
2362306a36Sopenharmony_cifrom an address that is not evenly divisible by N (i.e. addr % N != 0).
2462306a36Sopenharmony_ciFor example, reading 4 bytes of data from address 0x10004 is fine, but
2562306a36Sopenharmony_cireading 4 bytes of data from address 0x10005 would be an unaligned memory
2662306a36Sopenharmony_ciaccess.
2762306a36Sopenharmony_ci
2862306a36Sopenharmony_ciThe above may seem a little vague, as memory access can happen in different
2962306a36Sopenharmony_ciways. The context here is at the machine code level: certain instructions read
3062306a36Sopenharmony_cior write a number of bytes to or from memory (e.g. movb, movw, movl in x86
3162306a36Sopenharmony_ciassembly). As will become clear, it is relatively easy to spot C statements
3262306a36Sopenharmony_ciwhich will compile to multiple-byte memory access instructions, namely when
3362306a36Sopenharmony_cidealing with types such as u16, u32 and u64.
3462306a36Sopenharmony_ci
3562306a36Sopenharmony_ci
3662306a36Sopenharmony_ciNatural alignment
3762306a36Sopenharmony_ci=================
3862306a36Sopenharmony_ci
3962306a36Sopenharmony_ciThe rule mentioned above forms what we refer to as natural alignment:
4062306a36Sopenharmony_ciWhen accessing N bytes of memory, the base memory address must be evenly
4162306a36Sopenharmony_cidivisible by N, i.e. addr % N == 0.
4262306a36Sopenharmony_ci
4362306a36Sopenharmony_ciWhen writing code, assume the target architecture has natural alignment
4462306a36Sopenharmony_cirequirements.
4562306a36Sopenharmony_ci
4662306a36Sopenharmony_ciIn reality, only a few architectures require natural alignment on all sizes
4762306a36Sopenharmony_ciof memory access. However, we must consider ALL supported architectures;
4862306a36Sopenharmony_ciwriting code that satisfies natural alignment requirements is the easiest way
4962306a36Sopenharmony_cito achieve full portability.
5062306a36Sopenharmony_ci
5162306a36Sopenharmony_ci
5262306a36Sopenharmony_ciWhy unaligned access is bad
5362306a36Sopenharmony_ci===========================
5462306a36Sopenharmony_ci
5562306a36Sopenharmony_ciThe effects of performing an unaligned memory access vary from architecture
5662306a36Sopenharmony_cito architecture. It would be easy to write a whole document on the differences
5762306a36Sopenharmony_cihere; a summary of the common scenarios is presented below:
5862306a36Sopenharmony_ci
5962306a36Sopenharmony_ci - Some architectures are able to perform unaligned memory accesses
6062306a36Sopenharmony_ci   transparently, but there is usually a significant performance cost.
6162306a36Sopenharmony_ci - Some architectures raise processor exceptions when unaligned accesses
6262306a36Sopenharmony_ci   happen. The exception handler is able to correct the unaligned access,
6362306a36Sopenharmony_ci   at significant cost to performance.
6462306a36Sopenharmony_ci - Some architectures raise processor exceptions when unaligned accesses
6562306a36Sopenharmony_ci   happen, but the exceptions do not contain enough information for the
6662306a36Sopenharmony_ci   unaligned access to be corrected.
6762306a36Sopenharmony_ci - Some architectures are not capable of unaligned memory access, but will
6862306a36Sopenharmony_ci   silently perform a different memory access to the one that was requested,
6962306a36Sopenharmony_ci   resulting in a subtle code bug that is hard to detect!
7062306a36Sopenharmony_ci
7162306a36Sopenharmony_ciIt should be obvious from the above that if your code causes unaligned
7262306a36Sopenharmony_cimemory accesses to happen, your code will not work correctly on certain
7362306a36Sopenharmony_ciplatforms and will cause performance problems on others.
7462306a36Sopenharmony_ci
7562306a36Sopenharmony_ci
7662306a36Sopenharmony_ciCode that does not cause unaligned access
7762306a36Sopenharmony_ci=========================================
7862306a36Sopenharmony_ci
7962306a36Sopenharmony_ciAt first, the concepts above may seem a little hard to relate to actual
8062306a36Sopenharmony_cicoding practice. After all, you don't have a great deal of control over
8162306a36Sopenharmony_cimemory addresses of certain variables, etc.
8262306a36Sopenharmony_ci
8362306a36Sopenharmony_ciFortunately things are not too complex, as in most cases, the compiler
8462306a36Sopenharmony_ciensures that things will work for you. For example, take the following
8562306a36Sopenharmony_cistructure::
8662306a36Sopenharmony_ci
8762306a36Sopenharmony_ci	struct foo {
8862306a36Sopenharmony_ci		u16 field1;
8962306a36Sopenharmony_ci		u32 field2;
9062306a36Sopenharmony_ci		u8 field3;
9162306a36Sopenharmony_ci	};
9262306a36Sopenharmony_ci
9362306a36Sopenharmony_ciLet us assume that an instance of the above structure resides in memory
9462306a36Sopenharmony_cistarting at address 0x10000. With a basic level of understanding, it would
9562306a36Sopenharmony_cinot be unreasonable to expect that accessing field2 would cause an unaligned
9662306a36Sopenharmony_ciaccess. You'd be expecting field2 to be located at offset 2 bytes into the
9762306a36Sopenharmony_cistructure, i.e. address 0x10002, but that address is not evenly divisible
9862306a36Sopenharmony_ciby 4 (remember, we're reading a 4 byte value here).
9962306a36Sopenharmony_ci
10062306a36Sopenharmony_ciFortunately, the compiler understands the alignment constraints, so in the
10162306a36Sopenharmony_ciabove case it would insert 2 bytes of padding in between field1 and field2.
10262306a36Sopenharmony_ciTherefore, for standard structure types you can always rely on the compiler
10362306a36Sopenharmony_cito pad structures so that accesses to fields are suitably aligned (assuming
10462306a36Sopenharmony_ciyou do not cast the field to a type of different length).
10562306a36Sopenharmony_ci
10662306a36Sopenharmony_ciSimilarly, you can also rely on the compiler to align variables and function
10762306a36Sopenharmony_ciparameters to a naturally aligned scheme, based on the size of the type of
10862306a36Sopenharmony_cithe variable.
10962306a36Sopenharmony_ci
11062306a36Sopenharmony_ciAt this point, it should be clear that accessing a single byte (u8 or char)
11162306a36Sopenharmony_ciwill never cause an unaligned access, because all memory addresses are evenly
11262306a36Sopenharmony_cidivisible by one.
11362306a36Sopenharmony_ci
11462306a36Sopenharmony_ciOn a related topic, with the above considerations in mind you may observe
11562306a36Sopenharmony_cithat you could reorder the fields in the structure in order to place fields
11662306a36Sopenharmony_ciwhere padding would otherwise be inserted, and hence reduce the overall
11762306a36Sopenharmony_ciresident memory size of structure instances. The optimal layout of the
11862306a36Sopenharmony_ciabove example is::
11962306a36Sopenharmony_ci
12062306a36Sopenharmony_ci	struct foo {
12162306a36Sopenharmony_ci		u32 field2;
12262306a36Sopenharmony_ci		u16 field1;
12362306a36Sopenharmony_ci		u8 field3;
12462306a36Sopenharmony_ci	};
12562306a36Sopenharmony_ci
12662306a36Sopenharmony_ciFor a natural alignment scheme, the compiler would only have to add a single
12762306a36Sopenharmony_cibyte of padding at the end of the structure. This padding is added in order
12862306a36Sopenharmony_cito satisfy alignment constraints for arrays of these structures.
12962306a36Sopenharmony_ci
13062306a36Sopenharmony_ciAnother point worth mentioning is the use of __attribute__((packed)) on a
13162306a36Sopenharmony_cistructure type. This GCC-specific attribute tells the compiler never to
13262306a36Sopenharmony_ciinsert any padding within structures, useful when you want to use a C struct
13362306a36Sopenharmony_cito represent some data that comes in a fixed arrangement 'off the wire'.
13462306a36Sopenharmony_ci
13562306a36Sopenharmony_ciYou might be inclined to believe that usage of this attribute can easily
13662306a36Sopenharmony_cilead to unaligned accesses when accessing fields that do not satisfy
13762306a36Sopenharmony_ciarchitectural alignment requirements. However, again, the compiler is aware
13862306a36Sopenharmony_ciof the alignment constraints and will generate extra instructions to perform
13962306a36Sopenharmony_cithe memory access in a way that does not cause unaligned access. Of course,
14062306a36Sopenharmony_cithe extra instructions obviously cause a loss in performance compared to the
14162306a36Sopenharmony_cinon-packed case, so the packed attribute should only be used when avoiding
14262306a36Sopenharmony_cistructure padding is of importance.
14362306a36Sopenharmony_ci
14462306a36Sopenharmony_ci
14562306a36Sopenharmony_ciCode that causes unaligned access
14662306a36Sopenharmony_ci=================================
14762306a36Sopenharmony_ci
14862306a36Sopenharmony_ciWith the above in mind, let's move onto a real life example of a function
14962306a36Sopenharmony_cithat can cause an unaligned memory access. The following function taken
15062306a36Sopenharmony_cifrom include/linux/etherdevice.h is an optimized routine to compare two
15162306a36Sopenharmony_ciethernet MAC addresses for equality::
15262306a36Sopenharmony_ci
15362306a36Sopenharmony_ci  bool ether_addr_equal(const u8 *addr1, const u8 *addr2)
15462306a36Sopenharmony_ci  {
15562306a36Sopenharmony_ci  #ifdef CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS
15662306a36Sopenharmony_ci	u32 fold = ((*(const u32 *)addr1) ^ (*(const u32 *)addr2)) |
15762306a36Sopenharmony_ci		   ((*(const u16 *)(addr1 + 4)) ^ (*(const u16 *)(addr2 + 4)));
15862306a36Sopenharmony_ci
15962306a36Sopenharmony_ci	return fold == 0;
16062306a36Sopenharmony_ci  #else
16162306a36Sopenharmony_ci	const u16 *a = (const u16 *)addr1;
16262306a36Sopenharmony_ci	const u16 *b = (const u16 *)addr2;
16362306a36Sopenharmony_ci	return ((a[0] ^ b[0]) | (a[1] ^ b[1]) | (a[2] ^ b[2])) == 0;
16462306a36Sopenharmony_ci  #endif
16562306a36Sopenharmony_ci  }
16662306a36Sopenharmony_ci
16762306a36Sopenharmony_ciIn the above function, when the hardware has efficient unaligned access
16862306a36Sopenharmony_cicapability, there is no issue with this code.  But when the hardware isn't
16962306a36Sopenharmony_ciable to access memory on arbitrary boundaries, the reference to a[0] causes
17062306a36Sopenharmony_ci2 bytes (16 bits) to be read from memory starting at address addr1.
17162306a36Sopenharmony_ci
17262306a36Sopenharmony_ciThink about what would happen if addr1 was an odd address such as 0x10003.
17362306a36Sopenharmony_ci(Hint: it'd be an unaligned access.)
17462306a36Sopenharmony_ci
17562306a36Sopenharmony_ciDespite the potential unaligned access problems with the above function, it
17662306a36Sopenharmony_ciis included in the kernel anyway but is understood to only work normally on
17762306a36Sopenharmony_ci16-bit-aligned addresses. It is up to the caller to ensure this alignment or
17862306a36Sopenharmony_cinot use this function at all. This alignment-unsafe function is still useful
17962306a36Sopenharmony_cias it is a decent optimization for the cases when you can ensure alignment,
18062306a36Sopenharmony_ciwhich is true almost all of the time in ethernet networking context.
18162306a36Sopenharmony_ci
18262306a36Sopenharmony_ci
18362306a36Sopenharmony_ciHere is another example of some code that could cause unaligned accesses::
18462306a36Sopenharmony_ci
18562306a36Sopenharmony_ci	void myfunc(u8 *data, u32 value)
18662306a36Sopenharmony_ci	{
18762306a36Sopenharmony_ci		[...]
18862306a36Sopenharmony_ci		*((u32 *) data) = cpu_to_le32(value);
18962306a36Sopenharmony_ci		[...]
19062306a36Sopenharmony_ci	}
19162306a36Sopenharmony_ci
19262306a36Sopenharmony_ciThis code will cause unaligned accesses every time the data parameter points
19362306a36Sopenharmony_cito an address that is not evenly divisible by 4.
19462306a36Sopenharmony_ci
19562306a36Sopenharmony_ciIn summary, the 2 main scenarios where you may run into unaligned access
19662306a36Sopenharmony_ciproblems involve:
19762306a36Sopenharmony_ci
19862306a36Sopenharmony_ci 1. Casting variables to types of different lengths
19962306a36Sopenharmony_ci 2. Pointer arithmetic followed by access to at least 2 bytes of data
20062306a36Sopenharmony_ci
20162306a36Sopenharmony_ci
20262306a36Sopenharmony_ciAvoiding unaligned accesses
20362306a36Sopenharmony_ci===========================
20462306a36Sopenharmony_ci
20562306a36Sopenharmony_ciThe easiest way to avoid unaligned access is to use the get_unaligned() and
20662306a36Sopenharmony_ciput_unaligned() macros provided by the <asm/unaligned.h> header file.
20762306a36Sopenharmony_ci
20862306a36Sopenharmony_ciGoing back to an earlier example of code that potentially causes unaligned
20962306a36Sopenharmony_ciaccess::
21062306a36Sopenharmony_ci
21162306a36Sopenharmony_ci	void myfunc(u8 *data, u32 value)
21262306a36Sopenharmony_ci	{
21362306a36Sopenharmony_ci		[...]
21462306a36Sopenharmony_ci		*((u32 *) data) = cpu_to_le32(value);
21562306a36Sopenharmony_ci		[...]
21662306a36Sopenharmony_ci	}
21762306a36Sopenharmony_ci
21862306a36Sopenharmony_ciTo avoid the unaligned memory access, you would rewrite it as follows::
21962306a36Sopenharmony_ci
22062306a36Sopenharmony_ci	void myfunc(u8 *data, u32 value)
22162306a36Sopenharmony_ci	{
22262306a36Sopenharmony_ci		[...]
22362306a36Sopenharmony_ci		value = cpu_to_le32(value);
22462306a36Sopenharmony_ci		put_unaligned(value, (u32 *) data);
22562306a36Sopenharmony_ci		[...]
22662306a36Sopenharmony_ci	}
22762306a36Sopenharmony_ci
22862306a36Sopenharmony_ciThe get_unaligned() macro works similarly. Assuming 'data' is a pointer to
22962306a36Sopenharmony_cimemory and you wish to avoid unaligned access, its usage is as follows::
23062306a36Sopenharmony_ci
23162306a36Sopenharmony_ci	u32 value = get_unaligned((u32 *) data);
23262306a36Sopenharmony_ci
23362306a36Sopenharmony_ciThese macros work for memory accesses of any length (not just 32 bits as
23462306a36Sopenharmony_ciin the examples above). Be aware that when compared to standard access of
23562306a36Sopenharmony_cialigned memory, using these macros to access unaligned memory can be costly in
23662306a36Sopenharmony_citerms of performance.
23762306a36Sopenharmony_ci
23862306a36Sopenharmony_ciIf use of such macros is not convenient, another option is to use memcpy(),
23962306a36Sopenharmony_ciwhere the source or destination (or both) are of type u8* or unsigned char*.
24062306a36Sopenharmony_ciDue to the byte-wise nature of this operation, unaligned accesses are avoided.
24162306a36Sopenharmony_ci
24262306a36Sopenharmony_ci
24362306a36Sopenharmony_ciAlignment vs. Networking
24462306a36Sopenharmony_ci========================
24562306a36Sopenharmony_ci
24662306a36Sopenharmony_ciOn architectures that require aligned loads, networking requires that the IP
24762306a36Sopenharmony_ciheader is aligned on a four-byte boundary to optimise the IP stack. For
24862306a36Sopenharmony_ciregular ethernet hardware, the constant NET_IP_ALIGN is used. On most
24962306a36Sopenharmony_ciarchitectures this constant has the value 2 because the normal ethernet
25062306a36Sopenharmony_ciheader is 14 bytes long, so in order to get proper alignment one needs to
25162306a36Sopenharmony_ciDMA to an address which can be expressed as 4*n + 2. One notable exception
25262306a36Sopenharmony_cihere is powerpc which defines NET_IP_ALIGN to 0 because DMA to unaligned
25362306a36Sopenharmony_ciaddresses can be very expensive and dwarf the cost of unaligned loads.
25462306a36Sopenharmony_ci
25562306a36Sopenharmony_ciFor some ethernet hardware that cannot DMA to unaligned addresses like
25662306a36Sopenharmony_ci4*n+2 or non-ethernet hardware, this can be a problem, and it is then
25762306a36Sopenharmony_cirequired to copy the incoming frame into an aligned buffer. Because this is
25862306a36Sopenharmony_ciunnecessary on architectures that can do unaligned accesses, the code can be
25962306a36Sopenharmony_cimade dependent on CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS like so::
26062306a36Sopenharmony_ci
26162306a36Sopenharmony_ci	#ifdef CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS
26262306a36Sopenharmony_ci		skb = original skb
26362306a36Sopenharmony_ci	#else
26462306a36Sopenharmony_ci		skb = copy skb
26562306a36Sopenharmony_ci	#endif
266