the ARM Cortex-M3 Processor - 8

이재하·2023년 6월 12일

Chapter 13 The Memory Protection Unit

13.1 OVERVIEW

The Cortex M3 design includes an optional Memory protection Unit(MPU). Including the MPU in the microcontrollers or system on chip(SoC) products provides memory protection features, which can make the developed products more robust. The MPU needs to be programmed and enabled before use. If the MPU is not enabled, the memory system behavior is the same as though no MPU is preset.

The MPU can improve the reliability of an embedded system by

  • Preventing user applications from corrupting data used by the operating system.
  • Separating data between processing tasks by blocking tasks from accessing others' data
  • Allowing memory regions to be define as read only so that vital data can be protected
  • Detecting unexpected memory accesses(for example, stack corruption )
  • Detecting unexpected memory accesses(for example, stack corruption )

In addtion, the MPU can also be used to define memory access characteristics such as caching and buffering behaviors for different regions.

The MPU sets up the protection by defining the memory map as a number of regions. Up to eight regions can be defined, but it is also possible to define a default background memory map for a default background memory map for privileged accesses. Accesses to memory locations that are not defined in the MPU regions or not permitted by the regions settings will cause the memory management fault exception to take place.

MPU regions can be overlapped. If a memory location falls on two regions, the memory access attributes and permission will be based on the highter-numbered region. For example, if a transfer address is within the address range defined for region 1 and region 4, the region 4 settings will be used.

13.2 MPU registers

The MPU contains a number of registers. The first one is the MPU type register. the MPU type register can be used to determine whether the MPU us fitted. If the DREGION field is read as 0, the MPU is not implemented.

The MPU is controlled by a number of register. The first one is the MPU control register(see Table 13.2). This register has three control bits. After reset, the reset value of this register is zero, which disables the MPU. To enable the MPU, the software should set up the settings for each MPU regions and then set the ENABLE bit in the MPU Control register.

By using PRIVDEFENA and if no ohter regions are set up, privileged programs will be able to access all memory locations, and only user programs will be bloced. However, if other MPU regions are programmed and enabled, they can override the background region. For example , for two systems with similar region setups but only one with PPIVDEFENA set to 1 will allow privileged access to background regions.

Setting the enable bit in the MPU control register is usually the last step in the MPU setup code. Otherwise, the MPU might generate faults by accident before the region configuration is done. In some situations, it might be worth clearing the MPU Enable at the start of the MPU configuration routine to make sure that the MPU faults won't be triggered by accident during setup of MPU regions.


Table 13.3 MPU Region Number Register (0xE000ED98)

BitsNameTypeReset ValueDescription
7:0REGIONR/W-Select the region that is being programmed.

The next MPU control register is the MPU region Number register(see Table 13.3), before each region is set up, write to this register to select the region to be programmed.

The starting address of each region is defined by the MPU Region Base Address register. Using the VALID and REGION fields in this register, we can skip the step of programming the MPU Region Nubmer register. This might reduece the complexity of the program code, especially if the whole MPU setup is defined in a lookup table.

We also need to define the properties of each region. This is controlled by the MPU Region Base Attribute and Size register(see Table 13.5).

The REGION SIZE field ( 5 bits) in the MPU Region Base Attribute and Size register determines the size of the region.

Table 13.4 MPU Regsion Base Address Register (0xE000ED9C)

BitsNameTypeReset ValueDescription
31:NADDRR/W-Base address of the region;N is dependent on the region size - for example, a 64KB size region will have a base address field of [31:16].
4VALIDR/W-If this is 1, the REGION defined in bit [3:0] will be used in this programming step; otherwise, the region selected by the MPU region Number override is ignored if the value of the REGION field is larger than 7.
3:0REGIONR/W-This field overrides the MPU Region Number register if VALID is 1; otherwise, it is ignored. Because eight regions are supported in the Cortex-M3 MPU, the region number override is ignored if the value of the REGION fiedld is larger than 7.

Table 13.5 MPU Region Base Attribute and Size Register (0xE000EDA0)

BitsNameTypeReset ValueDescription
31:29Reserved---
28XNR/W-Instruction Access Disable ( 1 = disable instruction fetch from this region; an attempt to do so will result in a memory management fault)
27Reserved---
26:24APR/W-Data Access Permission field
23:22Reserved---
21:19TEXR/W-Type Extension field
18SR/W-Shareable
17CR/W-Cacheable
16BR/W-Bufferable
15:8SRDR/W-Subregion disable
7:6ReservedR/W--
5:1REGION SIZER/W-MPU Protection Region size
-ENABLER/W-Region enable

Table 13.6 Encoding of REGION Field for Different Memory

Table 13.7 Encoding of AP Field for Various Access Permission Configurations

Table 13.8 ARMv7- Memory Attributes

TEXCBDescriptionRegion Shareability
b00000Strongly ordered(transfers carry out and complete in programmed order)shareable
b00010Outer and inner write-through;nowrite allocate[S]

...

UsageMemory typeCommonly used memory attribute
Flash/ROMNormal memoryNonshareable, write through
Internal SRAMNormal MemoryShareable, write through
External SRAMNormal MemoryShareable, write back
PeripheralsDevice memoryShareable device

In v6 and v7 architecture, the memory system can have two cache levels : inner cache and outehr cache. They can have different caching policies. Because the Cortex-M3 processor itself does not have a cache controller, the cache policy only affects write buffering in the internal BusMatrix and possibly the memory controller.

If you are using a microcontroller with cache memory, then you should program the MPU according to the cache policy you want to use(e.f., cache disable/write through cache/write back cache). When TEX[2] is 1. the cache and inner cache is as hown in table 13.9

Table 13.9 Encoding of inner and Outer Cache Policy When Most Significant Bit of TEX is Set to 1
|Memory Attribute Encoding(AA and BB)|Cache Policy|
|00|Noncacheable|
|01|Write Back,write,and read allocate|
|10|write through, no write allocate|
|11|Write back, no write allocate|

▶Write Through란?

CPU가 데이터를 사용하면 캐시에 저장되게 되는데, 데이터가 캐시 됨과 동시에 주기억장치 또는 디스크로 기입되는 방식을 지원하는 구조의 캐시이다. 즉, 캐시와 메모리 둘다에 업데이트를 해버리는 방식이다.

장점 : 캐시와 메모리에 업데이트를 같이 하여, 데이터 일관성을 유지할 수 있어서 안정적이다.
단점 : 속도가 느린 주기억장치 또는 보조기억장치에 데이터를 기록할 때, CPU가 대기하는 시간이 필요하기 때문에 성능이 떨어진다.

데이터 로스가 발생하면 안되는 상황에서는 Write Through를 사용하는 것이 좋다.



▶Write Back이란?

CPU 데이터를 사용할 때 데이터는 먼저 캐시로 기록되는데, 캐시 내에 일시적으로 저장된 후에 블록 단위에 캐시로부터 해제되는 때(캐시안에 있는 내용을 버릴시) 에만 주기억장치 또는 보조기억장치에 기록되는 방식이다. 즉, 데이터를 쓸 때 메모리에는 쓰지 않고 캐시에만 업데이트를 하다가 필요할 때에만 주기억장치나 보조기억장치에 기록하는 방법이다.

장점 : Write Through보다 훨씬 빠르다.
단점 : 속도가 빠르지만 캐시에 업데이트 하고 메모리에는 바로 업데이트를 하지 않기 때문에, 캐시와 메모리가 서로 값이 다른 경우가 발생할 때가 있다.

빠른 서비스를 요하는 상황에서는 Write Back을 사용하는 것이 좋다.

13.3 SETTING UP THE MPU

The MPU register might look complicated, but as long as you have a clear idea of the memory regions that are required for your applicaion. it should not be difficult. Typically, you need to have the following memory regions :

  • Program code for privileged progmras(for example, OS kernel and excetpion handlers)
  • Program code for user programs
  • Data memory for privileged and user programs in various memory regions(e.g., data and stack of the application situated in the SRAM( Static Random Access Memory) memory region
  • Other peripherals

Table 13.10 MPU Register Names in CMSIS

Register NamesMPU RegisterAddress
MPU->TYPEMPU Type register0xE00ED90
MPU->CTRLMPU Control register0xE00ED94
MPU->RNRMPU Region Number register0xE00ED98
MPU->RBARMPU Region Base Address register0xE000ED9C
MPU->RASRMPU Region Attribute and Size register0xE000EDA0
MPU->RBAR_A1MPU Alias 1 Region Base Address register0xE000EDA4
MPU->RBAR_A2MPU Alias 2 Region Base Address register0xE000EDB4
MPU->RASR_A1MPU Alias 1 Region Attribute and Size Register0xE000EDB0

...

For a simple case of only four required regions, the MPU setup cdoe(without the region checking and enabling) looks like this :

MPU -> RNR = 0; // MPU Region Number Register
				// select region 0
MPU -> RBAR = 0x00000000; //MPU Region Base Address Register
MPU -> RASR = 0x0307002F; // Region Attribute and Size Register
// R/W, TEX=0, S=1, C=1, B=1, 16MB, Enable=1
// Select region 1
...
...
...
MPU->RASR = 0x01040027 // Privileged R/W. TEX = 0, S = 1, C = 0, B = 0,
// 1MB, Enable = 1
MPU->CTRL = 1; //MPU Control register - Enable MPU

This can also be coded in assembly language :


FIGURE 13.3
Example Steps to Set Up the MPU.

Check MPU Type register to see if MPU exists and there are enough regions

Disable MPU

Region selection and programming of region registers can be combined in on setp

Select region #0
Program region base address and configuration

Setup for other regions

Enable MPU


One way to handle this is to use a subroutine(MpuRegionSetup) that can set up a region based on a number of input parameters and then call it several times to set tup different regions :

void MpuRegionSetup ( unsigned int addr, unsigned int region, unsigned int size, unsigned int ap, unsigned int MemAttrib, unsigned int srd, unsigned int XM, unsigned int enable)

{ // Setup procedure for each region
MPU -> RBAR = (addr & 0xFFFFFFE0) | (region & 0xF) | 0x10;
MPU->RASR = ((XN & 01 ) << 28) | ((ap & 0x7) << 24 ) | ((MemAttrib & 0x3F) << 16)

13.4 TYPICAL SETUP

In typical applications, the MPU is used when there is a need to prevent user programs from accessing privieged process data and program regions. Usually, this is done by the embedded OS. Between each context switching, the MPU is reprogrammed by the OS to allow user applications to access their application code and data and any other resources they are entitled to access. When developing the setup routine for the MPU, you need to condier a number of regions :

  1. Code region :
    a. Privieged code, including a starting vector table
    b. User code
  2. SRAM region :
    a. Privileged data, including the main stack
    b. User data, including the process stack
    c. Privileged bit-band alias region
    d. User bit-band alias region
  3. Peripherals :
    a. Privileged peripherals
    b. User peripherals
    c. Privileged peripheral bit-band alias region
    d. User peripheral bit-band alias region

0개의 댓글