Benefits of using the memory protection unit

Boot Time Memory Configuration

This is the configuration of the MPU after the kernel has started up. It should
contain the following:

  • Any configuration of memory regions which need to have special caching or
    write-back policies for basic hardware and driver function. Note that most
    MPUs have the concept of a default memory access policy map, which can be
    enabled as a “background” mapping for any area of memory that doesn’t
    have an MPU region configuring it. It is strongly recommended to use this
    to maximize the number of available MPU regions for the end user. On
    ARMv7-M/ARMv8-M this is called the System Address Map, other CPUs may
    have similar capabilities.

  • A read-only, executable region or regions for program text and ro-data, that
    is accessible to user mode. This could be further sub-divided into a
    read-only region for ro-data, and a read-only, executable region for text, but
    this will require an additional MPU region. This is required so that
    threads running in user mode can read ro-data and fetch instructions.

  • Depending on configuration, user-accessible read-write regions to support
    extra features like GCOV, HEP, etc.

What is MMU?

MMU stands for Memory Management Unit. It is a hardware component that manages memory in a computer system. It handles tasks such as paging and caching, and it provides protection against unauthorized access to memory.

  • MMUs are typically found in CPUs, but they can also be found in GPUs and other types of processors. MMUs became popular in the 1980s as a way to improve the efficiency of computer systems.
  • Today, they are an essential part of most computer systems. MMUs work by mapping virtual addresses to physical addresses. They keep track of which pages are in memory and which are not, and they use a variety of algorithms to determine how to best use the available memory.
  • MMUs play a vital role in the performance of computers, and they will continue to be an essential part of computing in the future.

What is a Microprocessor (MPU)?

The Microprocessor (MPU) is also known as Micro Processing Unit, it is the central unit of a computer system that performs arithmetic and logic operations. It also incorporates the function of a CPU on an integrated circuit.

Ref: Wikipedia

How does MPU work?

MPU basically accepts binary data as the input, processes the data according to instructions stored in its memory, and provides results (also in binary form) as output.

To understand how it works better, you can refer to a basic block diagram below:

Ref: Javapoint

As you can see, a microprocessor consists of an ALU, control unit and register array, Memory Unit:

  • ALU (Arithmetic and Logical Unit): Performs arithmetic and logical operations on the data received from an input device or memory
  • Control unit: Controls the instructions and flow of data within the computer
  • Register array: includes registers identified by letters and accumulator
  • Memory Unit: Stores data

Basic Terms to note

  • Bus: Describe the set of conductors that transmit data or that address or control information to the microprocessor’s different elements. (MPU usually has 3 types: data bus, the address bus, and control bus.)
  • Clock Speed: Normally measured in Hertz and expressed in measurements like MHz (megahertz) and GHz (gigahertz), refers to the speed at which a microprocessor could execute instructions.
  • Instruction Set: A series of commands that a microprocessor can understand, basically the interface between hardware and software.
  • Word Length: The number of bits in the processor’s internal data bus, an 8-bit MPU can process 8-bit data at one time.
  • Cache Memory: It stores data or instructions that the software or program frequently references during operation, increases overall speed as it allows the processor to access data more quickly.

Categories of MPU

Reduced Instruction Set Computer (RISC)

  • Generally utilised
  • Fewer instructions
  • Simpler circuits
  • Operates faster
  • More registers
  • Uses more RAM
  • Uses a fixed number of clock cycles

Complex Instruction Set Computer (CISC)

  • The direct opposite of RISC
  • Reduce the number of instructions
  • Complex instructions
  • Operates slower
  • Uses little RAM
  • Fewer registers
  • Numerous clock cycles
  • Automobile
  • Credit card processing unit
  • Security systems
  • Household devices

Ⅱ. The Difference of SoPC, MCU, MPU and SOC

2.1 The Difference Between MCU and MPU

MCU and MPU are both one of the branches developed from CPU.

MCU has integrated on-chip peripherals and can directly add simple peripherals (resistors, capacitors) to run the code. It is still essentially a complete microcontroller with a processor and various interfaces, and all the development is based on the already existing system architecture.

MPU without peripherals (such as memory arrays), is a highly integrated general-purpose structure of the processor, is removed from the integrated peripherals MCU. MCU such as ARM’s Cortex-A series, directly put the code can not run, because it is essentially just an enhanced version of the CPU, you must add the appropriate RAM and ROM.

2.2 The Difference Between CPU and SOC

SOC can be considered as the integration of MCU and MPU strong processing power of the advantages of two in one, where MCU is the CPU integrated with various peripherals, MPU is an enhanced version of the CPU. Semiconductor manufacturers add their own.

SOC is a holistic design methodology concept, which refers to a chip design approach that integrates various functional modules, each of which is programmed by a hardware description language and then implemented by a circuit within the SOC; each module is not a maturely designed ASIC device, but simply uses a portion of the chip’s resources to implement some traditional function.

2.3 What Makes SoPC Different from MCU, MPU and SOC

The most obvious difference between SoPC and MCU, MPU and SOC is that the hardware configuration can be changed, that is to say, you can construct your own chip.

To illustrate an example for easy understanding, the hardware configuration of a microcontroller is solidified, and what we can program and modify is the software configuration, which is originally a serial communication function, but by modifying the code it becomes an AD sampling function, that is, the hardware configuration is fixed, and we can only choose one or more functions by modifying the software.

And SoPC can modify the hardware configuration information to make it the corresponding chip, either MCU or SOC.

What is an MPU?

A Memory Protection Unit (MPU) is hardware that only allows access to memory and peripheral devices to the code that needs to access those resources. An MPU enhances both the stability and safety of embedded applications and is therefore often used in safety-critical applications, such as medical devices, avionics, industrial control, nuclear power plants, etc. MPUs are now finding their way into the Internet of Things (IoT) because limiting access to memory and peripherals can also improve product security. Specifically, crypto keys can be hidden from application code to deny attackers access. Isolating the flash memory controller with the MPU can also prevent an attacker from changing an application, therefore allowing only trusted code to perform code updates.

When wouldn’t you use an MPU?

There are two primary scenarios where you wouldn’t use the MPU on your processor; a simple project and a performance-critical project. The first is straightforward; a very simple application may not benefit from the added complexity of using the MPU. Your blinky demo can probably get by without you setting up MPU regions covering your flash, RAM, and peripherals.

If you need every last drop of performance out of your processor, then the overhead of using an MPU might be a deal breaker for you. The task context switch routines are longer in FreeRTOS ports using the MPU as each task has several MPU regions that need to be programmed. When a new task is being context switched in, the RTOS must program each task MPU region as well as performing its usual duties such as stacking used registers. Additionally, as the kernel code and data is protected by the MPU, all kernel function calls must be protected by a wrapper function. This wrapper function simply raises the privilege level of the processor before calling the kernel function, then restores the privilege and returning. This will not only increase the time required to run your code but also potentially increase the required stack size for your tasks. The task’s control block will also have to store information on its MPU regions and in the case of some safety critical RTOS’s like SAFERTOS, mirrors of this data will also be stored.

You should also be wary that working with an MPU can be difficult and, at times, frustrating. It will take more time to design your application as you must consider MPU regions for each of your tasks. Mistakes in these regions, such as incorrect region lengths, permissions or not linking the data of your application correctly can be confusing to debug.

Default Memory Map / PRIVDEFENA

Most of the examples I encountered enabled the MPU by simply writing an 1 to
the MPU control register.

That actually is sufficient in most cases but caused me a severe headache
when I was just starting out with a partial configuration.

At first I only wanted to configure a single 32k area as read only so I
could write an automated test that would read that memory and catch
an exception when writing there.

Instead as soon as I had configured that area and enabled the MPU with
the code shown above, the system would immediately generate a memory
exception and lock up.

The reason for that was that I had not set a default memory area.

The default behavior of the MPU is that access to all areas that
are not explicitly configured is blocked.
In my case that meant that pretty much every memory access, except
for read accesses to my 32k area was blocked due to that implicit
default rule.

There are two solutions for that.

Setting a default policy using memory region 0

The first solution is to configure memory region 0 to cover the whole
memory and have no access restrictions.

As we will see regions are prioritized and may overlap.
Therefore by allowing full access to everything in the lowest priority rule
(region 0) we effectively change the default behavior and can subsequently
exempt individual regions such as my 32k test area described above.

We can configure region 0 like this:

Using the default memory map

The second solution is to enable the processor’s default memory map by
setting the PRIVDEFENA flag of the MPU_CTRL register when enabling the MPU:

This flag enables a processor-specific background region that might or mighty not
be suitable in your case.

This is what it looks like for the Cortex-M3:

As we can see the default map allows read and write access to the whole memory
but sets execution and caching restrictions for some areas.
In most cases that should be a reasonable starting point.

Why is MPU used?

The MPU allows the privileged software to define memory regions and assign memory access permission and memory attributes to each of them. MPU monitors transactions, including instruction fetches and data accesses from the processor, which can trigger a fault exception when an access violation is detected.

What is MPU used for?

In summary, the MPU is a programmable security device used to protect the system memory and the user’s memory spaces from corrupting and attacking by undesired tasks. permissions in privileged and unprivileged access levels for some embedded operating systems (OS).

Is a CPU a microcontroller?

A microcontroller can be seen as a small computer, and this is because of the essential components inside of it; the Central Processing Unit (CPU), the Random-Access Memory (RAM), the Flash Memory, the Serial Bus Interface, the Input/Output Ports (I/O Ports), and in many cases, the Electrical Erasable Programmable Read …

What does MPU mean?

MPU

Acronym Definition
MPU Memory Protection Unit
MPU Messages per User
MPU Master Plan Update
MPU Main Processing Unit

What is the purpose of IP register?

A special-purpose register, usually called the instruction pointer (IP) or program counter (PC), keeps track of what instruction is being executed.

How many integrated circuits are in a microprocessor?

A microprocessor is a computer processor that incorporates the functions of a central processing unit on a single integrated circuit (IC), or sometimes up to 8 integrated circuits.

Преимущества МПУ перед другими технологиями

1. Высокая гибкость: МПУ способен выполнять широкий спектр задач благодаря возможности программного управления. Он может быть программирован для выполнения различных операций, что делает его универсальным и подходящим для использования в различных приложениях.

2. Высокая скорость обработки данных: МПУ обладает высокой производительностью и способностью обрабатывать большое количество информации за короткое время. Это делает его эффективным инструментом для выполнения сложных вычислений и обработки данных в реальном времени.

3. Низкая потребляемая мощность: МПУ обладает низким энергопотреблением, что позволяет ему работать долгое время от батарейки или небольшого источника питания. Это делает его идеальным решением для портативных устройств и мобильных приложений.

4. Удобство в работе: МПУ обладает простым и понятным интерфейсом, что позволяет пользователям легко управлять устройством. Он также может быть интегрирован с другими компонентами системы с помощью различных интерфейсов связи.

5. Малый размер и вес: МПУ обладает компактным размером и небольшим весом, что делает его идеальным решением для использования в ограниченном пространстве или в несущих устройствах.

6. Надежность и стабильность работы: МПУ имеет высокую надежность и стабильность работы благодаря использованию современных технологий производства и контроля качества. Он способен работать без сбоев и перерывов в течение длительного времени.

В целом, МПУ является мощным и универсальным устройством, которое предлагает ряд преимуществ перед другими технологиями. Он широко используется в различных отраслях, включая медицину, автомобильную промышленность, телекоммуникации, электронику и т. д. Благодаря своим возможностям и характеристикам, МПУ продолжает развиваться и находить новые применения в современных системах.

Высокая производительность и эффективность МПУ

Высокая производительность МПУ достигается за счет его многоядерной архитектуры и возможности параллельного выполнения инструкций. Каждое ядро МПУ работает независимо от других, что позволяет выполнять различные задачи параллельно и увеличивает общую производительность устройства.

Кроме того, МПУ обладает высокой эффективностью потребления энергии. Благодаря своей архитектуре, МПУ способен эффективно использовать энергию и предоставлять высокую производительность при минимальном потреблении энергии.

Высокая производительность и эффективность МПУ могут быть применены во многих областях, требующих обработки больших объемов данных. Например, МПУ часто используется в сетевых роутерах для обработки сетевых пакетов, в медицинских устройствах для анализа медицинских данных, а также в смартфонах и планшетах для обработки графики и видео.

В целом, высокая производительность и эффективность МПУ делают его незаменимым инструментом для работы с большим объемом данных в различных областях, где требуется скорость обработки и энергоэффективность.

Менее сложная архитектура и более низкая стоимость МПУ

Микропроцессорное устройство (МПУ) обладает менее сложной архитектурой по сравнению с другими технологиями. Это делает его более легким в использовании и программировании. Менее сложная архитектура МПУ позволяет разработчикам быстро создавать и модифицировать программное обеспечение для различных задач.

Еще одним преимуществом МПУ является его более низкая стоимость. В сравнении с аналогичными устройствами, МПУ имеет более доступную цену, что делает его привлекательным для широкого круга потребителей и разработчиков.

Менее сложная архитектура МПУ позволяет сократить время разработки и снизить затраты на производство. Это позволяет компаниям создавать более доступные и конкурентоспособные продукты на рынке.

Также, благодаря своей простоте и относительно низкой стоимости, МПУ стал широко используемым компонентом в различных областях, таких как электроника, автоматизация производства, медицинская техника, телекоммуникации и т.д. Более низкая стоимость МПУ позволяет получить высокую производительность и эффективность при оправданной цене.

В целом, менее сложная архитектура МПУ и его более низкая стоимость делают его привлекательным выбором для разработчиков и потребителей. Это позволяет создавать мощные системы и устройства по привлекательной цене, что является одним из основных преимуществ МПУ перед другими технологиями.

MPU-Plus Snapshot

The main purpose of MPU-Plus is to enhance the security of multitasking systems based upon the SMX RTOS. The main things MPU-Plus does to help achieve better security are to:

  1. allow defining different MPU templates for each task;
  2. handle MPU switching during task switches;
  3. provide an SVC API to allow unprivileged code to call privileged services;
  4. limit which services can be called from unprivileged code and what they can do;
  5. allow allocation of protected blocks and messages;
  6. run the SMX RTOS and system code in privileged mode and middleware and application code in unprivileged mode;
  7. allow tasks to be privileged or unprivileged.
  8. serve as a platform upon which to build security.

MPU-Plus had two principal design goals:

  1. Easier conversion of legacy code to use the MPU and the SVC API.
  2. Allow developers to focus on protection strategies without being tripped up by MPU peculiarities and other hardware details.

Implementing a good protection strategy is difficult enough. Excessive complication at the detailed level is not only frustrating but may result in adopting less-than-ideal system protection.

Register section

It is basically a storage device and transfers data from registers by using instructions.

  • Stack Pointer (SP) − The stack pointer is also a 16-bit register which is used as a memory pointer. It points to a memory location in Read/Write memory known as stack. In between execution of program, sometime data to be stored in stack. The beginning of the stack is defined by loading a 16-bit address in the stack pointer.

  • Program Counter (PC) − This 16-bit register deals with fourth operation to sequence the execution of instruction. This register is also a memory pointer. Memory location have 16-bit address. It is used to store the execution address. The function of the program counter is to point to memory address from which next byte is to be fetched.

  • Storage registers − These registers store 8-bit data during a program execution. These registers are identified as B, C, D, E, H, L. They can be combined as register pair BC, DE and HL to perform some 16 bit operations.

MPU vs MMU

The Memory Management Unit (MMU) is another memory access control mechanism available in some ARM processors such as Cortex-A5 and newer. Key differences between MPU and MMU include:

  • MPU has fixed regions while MMU uses page tables for memory maps
  • MPU controls access at system level while MMU works at process level

MPU is software-based while MMU handles mapping dynamically in hardware

MPU is simpler with lower overhead compared to MMU

MPU cannot handle virtual memory like MMU

Due to its simplicity, the MPU is well suited for resource constrained microcontroller-type systems that need memory protection. The MMU provides more advanced capabilities but with higher complexity.

Ⅰ. The Concept of SoPC, MCU, MPU and SOC

CPU (Central Processing Unit) is the core of computing and control of a computer, which consists of operators, controllers and registers, and the bus of data, control and status to realize the connection between them. The well-known three-stage pipeline: fetching, decoding, and execution is the object of the CPU, and the operation principle of almost all CPUs can be divided into four stages: Fetch, Decode, Execute, and Writeback.

The CPU takes instructions from memory or cache memory, puts them into the instruction register, decodes them, and executes them. The so-called programmability of the computer mainly refers to the programming of the CPU.

MPU (Micro Processor Unit), called microprocessor (not microcontroller MCU, computer (i.e., computer) is divided into giant machine, mainframe, medium-sized machine, small machine and microcomputer 5 categories. These five types of computer computing core is collectively known as the CPU, and the MPU is only the core processor of the microcomputer (microcomputer). In other words, the concept of CPU includes MPU, and MPU is a kind of CPU. In a microcomputer, the CPU is integrated on a super-large scale integrated circuit chip called a microprocessor (MPU), which is inserted in the cpu slot of the motherboard.

(Many people will confuse the microprocessor with the microcontroller.) It usually represents a powerful CPU (tentatively understood as an enhanced version of the CPU, right?), but not a chip designed for any pre-existing specific computing purpose. Such chips are often the core CPUs of personal computers and high-end workstations. e.g. Intel’s X86, some of ARM’s Cortex-A chips such as Freescale i.MX6, Allwinner A20, TI AM335X, etc. are all MPUs.

MCU (Micro Control Unit): called microcontroller, single-chip microcomputer or microcontroller, is the CPU frequency and specifications are appropriately reduced, and the memory, counter, A/D conversion, UART and other peripheral interfaces are integrated on a single chip to form a chip-based computer (with a computer of all basic functions) for different applications and different combinations of control.

With the emergence of large-scale integrated circuits and their development, the CPU, RAM, ROM, timing counter and a variety of I/O interfaces of a computer are integrated on a single chip to form a chip-level chip, such as 51, STC, AVR, Cortex-M these chips, there are RAM and ROM inside in addition to the CPU, which means that the whole computer system is integrated in a single chip. You can directly add simple peripheral devices (resistors, capacitors) to run the code.

It is still essentially a complete microcontroller, with a processor and various interfaces, all the development is based on the existing system architecture, all the applicant has to do is to develop the software program and add external devices. And like ARM (Cortex-A series) directly put the code can not run, because it is essentially just an enhanced version of the CPU, you must add the appropriate RAM and ROM.

SOC (System on Chip) is a system on a chip. A circuit system capable of performing certain functions consists of multiple modules, such as processors, interfaces, memories, analog-to-digital converters, and so on. These functional modules can be implemented by discrete devices, and then combined on a printed circuit board (PCB) to form a system on chip.

MCU is a chip-level chip, while SOC is a system-level chip, which has built-in RAM and ROM like MCU and is as powerful as MPU, not only for simple code, but also for system-level code, which means it can run operating systems (mainly Linux OS) (think of it as MCU integration and MPU processing power all in one). SOC integrates the functions of many MCUs, and what used to be done by multiple MCUs in cooperation is integrated, and the MCUs are no longer available. Therefore, the use of SOC is more integrated, smaller and compressed cost.

SoPC (System On a Programmable Chip) SOPC, English is System 0n Programmable Chip, it is a SOC (System 0n Chip) solution. It is proposed by Altera to construct system on chip using programmable logic device (FPGA).SOPC is a solution of SOC and also belongs to SOC.The advantages of this solution are: high flexibility, scalability, short development cycle, no need for mask and flow chip. The most obvious difference between SoPC and MCU, MPU and SOC is that the hardware configuration can be changed, i.e., the chip can be constructed by itself.

Cortex-M Privilege Levels

At power up, the Cortex-M starts in privileged mode, giving it access to all CPU features. It can access any memory or I/O location, enable/disable interrupts, set up the nested vectored interrupt controller (NVIC), and configure the FPU and MPU, etc.

To keep a system safe and secure, privileged mode code must be reserved for code that has been fully tested and is trusted. Because of the thorough testing that most RTOSes undergo, they are generally considered trusted while most application code is not. There are a few exceptions to this practice. ISRs, for example, are typically assumed to be trusted and, as a result, are also run in privileged mode, as long as those ISRs are kept as short as possible and not abused. This is a typical recommendation from most RTOS vendors.

Application code can be made to run on a Cortex-M in non-privileged mode, therefore restricting what the code can do. Specifically, non-privileged mode prevents code from disabling interrupts, changing the settings of the nested vectored interrupt controller (NVIC), changing the mode back to privileged, and altering MPU settings, as well as a few other things. This is a desirable feature because you don’t want untrusted code to give itself privileges and therefore change the protection put in place by the system designer.

Because the CPU always starts in privileged mode, tasks need to be either created from the start to run in non-privileged mode or switched to non-privileged mode (by calling an API) shortly after starting. After it is in non-privileged mode, the CPU can only switch back to privileged mode when servicing an interrupt or an exception.

What is the meaning of the word microprocessor?

The microprocessor is digital, using binary numbers and logic. Today the word ‘microprocessor’ means a single chip or single core CPU or processing unit. The word almost doesn’t have its original meaning because it obsoleted all the larger, component-based systems that it replaced.

Which is the first microprocessor in the world?

The Intel 4004, released in 1971, was the first single-chip microprocessor. It used MOS (metal–oxide–semiconductor) silicon gate technology (SGT). The microprocessor is digital, using binary numbers and logic. Today the word ‘microprocessor’ means a single chip or single core CPU or processing unit.

How are microprocessors selected for different applications?

Microprocessors can be selected for differing applications based on their word size, which is a measure of their complexity.

About
Bobbi Green

Access to RTOS Services from User Code

Because non-privileged code cannot disable interrupts either through the CPU or the NVIC, application code is forced to use RTOS services to gain access to shared resources. Because RTOS services need to run in privileged mode (to disable interrupts during critical sections), nonprivileged tasks must pass through a special mechanism on the Cortex-M, called the SuperVisor Call (SVC) to switch back to privileged mode. The SVC behaves like an interrupt but is invoked by a CPU instruction. This is also known as a software interrupt.

Because RTOS services need to run in privileged mode (to disable interrupts during critical sections), nonprivileged tasks must pass through a special mechanism on the Cortex-M called the SuperVisor Call (SVC) to switch back to privileged mode.

On the Cortex-M, the SVC instruction uses an 8-bit argument to specify which of 256 possible RTOS functions (or services) the caller wants to execute. The system designer decides what RTOS services should be made available to non-privileged code. For example, you might not want to allow a non-privileged task to terminate another task (or itself). Also, none of these services would allow interrupts to be disabled since that would defeat one of the purposes of running code in nonprivileged mode. Once invoked, the SVC instruction vectors to an exception handler called the SVC Handler.

ROM

The locations between $E000 and $FFFF are mapped to Read Only Memory (ROM). As the name suggests, we cannot write to here. In fact, any attempt to do so will simply be ignored. An example of ROM would be data stored on a game cartridge. As the console is booted up this memory can be read, but obviously cannot be written to or else the game data would be changed. If you wanted to modify something in ROM it would first need to be transferred into RAM.

It is up to us, the programmers, to keep track of where the data is stored and if it is stored appropriately. As we change from system to system we will also need to be aware that memory may be mapped differently.

We will end the discussion on memory with a slightly different topic: endianness. Whether a processor and language are little-endian or big-endian is based on how it orders bytes within a number. For example, a little-endian system will place the most significant bit of a number on the right. It takes 2 bytes to store the hexadecimal number ABCD. As the 6502 is little-endian the 2 bytes will, therefore, be ordered: CD, AB. Big-endian machines do the opposite. This will become important as we start to write code ourselves.

The Stack

The second page is also very important. The Stack ranges from 256 to 511. This area of memory is a last-in-first-out (LIFO) list. Effectively, this means that you can only retrieve from the stack the last thing you deposited into it. It is like a neat pile of papers on a desk, you can only ever access the top one. We then have a stack pointer (the register S) that points us to the memory address that corresponds to the top of this pile. The 6502 even gives us some manual control, allowing us to push and pull things to the stack at will using and . It might seem strange why you would want an area of memory like this. Let’s try to give an example where it would be useful.

Firstly, some terminology — we will call a set of instructions we use a lot a subroutine. You could imagine this kinda like a function you would write in Python. Now, let’s write a bit of pseudocode:

1. a = 12. b = 23. 4. c = subroutine1()5. x = a + b + c6.7. subroutine1:8.     y = subroutine2()9.     return y10. subroutine2:11.     z = 212.     return z

We will imagine the numbers we see on the left side to be locations in memory. At memory location 1 will be stored, and so on. As we go through each line our program counter will be incremented upward, so we know what will happen next. However, eventually, we will get to line 4 and we will have to call . To resolve this, we will have to jump to line 7. When this subroutine is over, how will we know how to get back home to line 5?

What will happen, to ensure this information is retrievable, is that the location where we will need to return will be pushed to the stack. We can now continue as normal from line 7, knowing that when we hit a return statement we can pull that information from the stack, add the location of line 5 to the program counter, and return home.

However, the example gets a little bit more complicated here. When we reach line 8 (inside we now have to enter at line 10. Automatically, the location of line 9 (where we will have to return to) will be pushed to the stack. The contents of the stack now look like this:

1. line92. line5

The location of line 9 is the last thing we pushed in, and therefore it will have to be the first thing we retrieve from it. As we will see though that will be the exact behaviour we want.

So, we are now at line 10 and inside . We can progress like normal to line 12. At line 12 the subroutine ends and we get a return statement. What should we do? Where do we go next? At this point, by pulling out the location at the top of the stack we know to go back to line 9.

Now that we are line 9 again we see this is another return statement. Let’s pull from the stack again and get the location of line 5. The program will now jump back here and finish.

It’s a really neat idea, and worth trying to get your head around. To very quickly sum it up (in my mind at least) the stack can be used as a way for your machine to “drop breadcrumbs”. By saving where it will need to return too, once it gets “lost” in a subroutine the LIFO mechanism of the stack guarantees it can find its way home.

Imagine for a moment however you kept entering subroutines. You would never get a chance to remove something from the stack. Eventually, the stack would fill with locations and run out of space, causing a crash. This is called a Stack Overflow (hey! that’s the name of that website!).

Using the MPU in ARM Cortex-M

In ARM Cortex-M processors, the MPU module is configured using registers in the System Control Block. Key steps include:

  1. Configure regions by setting start address, end address, access permissions, and other attributes

Enable the MPU globally using the CTRL register

Enable specific regions by setting the enable bit in that region’s registers

Set up NVIC to handle MPU faults as exceptions

On receiving fault, software can handle or terminate execution

MPU faults have the highest priority in Cortex-M so are handled before other faults. Software needs to carefully configure the regions and access permissions as per the system security requirements. The MPU improves system robustness by trapping unintended accesses early.

Frequently Asked Questions

Here are some frequently asked questions about the differences between MCU, MPU, and CPU:

1. What is the difference between MCU, MPU, and CPU?

MCU stands for Microcontroller Unit and is a small computer on a single chip that contains a CPU, memory, and peripherals. It is designed for specific tasks and applications.

MPU stands for Microprocessor Unit and is a general-purpose processor that performs calculations and executes instructions for various tasks. It requires additional external memory and peripherals to function.

2. How does an MCU differ from an MPU?

An MCU is a complete computing system on a chip, while an MPU requires external components such as memory and peripherals to function properly.

Additionally, an MCU is typically used in embedded systems and devices that require real-time control and low-power consumption. On the other hand, an MPU is more suitable for general-purpose computing tasks.

3. What are the advantages of using an MCU?

One of the main advantages of using an MCU is its compact size and low power consumption, making it ideal for small devices and battery-powered applications.

MCUs also have built-in peripherals and are designed for specific applications, providing a cost-effective solution for targeted tasks.

4. When should I choose an MPU over an MCU?

If you require more processing power and the flexibility to run complex tasks and applications, an MPU is the better choice.

MPUs offer greater performance and can handle more demanding computational tasks compared to MCUs. They also provide more memory and peripheral expansion options for enhanced functionality.

5. Can an MPU be used in embedded systems?

Yes, an MPU can be used in embedded systems. However, due to their higher power consumption and larger physical size compared to MCUs, MPUs are typically used in applications where processing power and flexibility are key requirements, and power constraints are less critical.

For applications that require real-time control and low power consumption, an MCU is usually a more suitable choice.

Понравилась статья? Поделиться с друзьями:
Портал компьютеров
Добавить комментарий

;-) :| :x :twisted: :smile: :shock: :sad: :roll: :razz: :oops: :o :mrgreen: :lol: :idea: :grin: :evil: :cry: :cool: :arrow: :???: :?: :!: