1.. _mpu_stack_objects:
2
3MPU Stack Objects
4#################
5
6Thread Stack Creation
7*********************
8
9Thread stacks are declared statically with :c:macro:`K_THREAD_STACK_DEFINE()`.
10
11For architectures which utilize memory protection unit (MPU) hardware,
12stacks are physically contiguous allocations.  This contiguous allocation
13has implications for the placement of stacks in memory, as well as the
14implementation of other features such as stack protection and userspace.  The
15implications for placement are directly attributed to the alignment
16requirements for MPU regions.  This is discussed in the memory placement
17section below.
18
19Stack Guards
20************
21
22Stack protection mechanisms require hardware support that can restrict access
23to memory.  Memory protection units can provide this kind of support.
24The MPU provides a fixed number of regions.  Each region contains information
25about the start, end, size, and access attributes to be enforced on that
26particular region.
27
28Stack guards are implemented by using a single MPU region and setting the
29attributes for that region to not allow write access.  If invalid accesses
30occur, a fault ensues.  The stack guard is defined at the bottom (the lowest
31address) of the stack.
32
33Memory Placement
34****************
35
36During stack creation, a set of constraints are enforced on the allocation of
37memory.  These constraints include determining the alignment of the stack and
38the correct sizing of the stack.  During linking of the binary, these
39constraints are used to place the stacks properly.
40
41The main source of the memory constraints is the MPU design for the SoC.  The
42MPU design may require specific constraints on the region definition.  These
43can include alignment of beginning and end addresses, sizes of allocations,
44or even interactions between overlapping regions.
45
46Some MPUs require that each region be aligned to a power of two.  These SoCs
47will have :kconfig:option:`CONFIG_MPU_REQUIRES_POWER_OF_TWO_ALIGNMENT` defined.
48This means that a 1500 byte stack should be aligned to a 2kB boundary and the
49stack size should also be adjusted to 2kB to ensure that nothing else is
50placed in the remainder of the region.  SoCs which include the unmodified ARM
51v7m MPU will have these constraints.
52
53Some ARM MPUs use start and end addresses to define MPU regions and both the
54start and end addresses require 32 byte alignment.  An example of this kind of
55MPU is found in the NXP FRDM K64F.
56
57MPUs may have a region priority mechanisms that use the highest priority region
58that covers the memory access to determine the enforcement policy.  Others may
59logically OR regions to determine enforcement policy.
60
61Size and alignment constraints may result in stack allocations being larger
62than the requested size.  Region priority mechanisms may result in
63some added complexity when implementing stack guards.
64