当前位置:网站首页>Explain task scheduling based on Cortex-M3 in detail (Part 1)
Explain task scheduling based on Cortex-M3 in detail (Part 1)
2022-07-05 08:04:00 【Car chezi】
List of articles
What is a mission
For embedded RTOS, I think the task (task) It's actually a thread . Why do you say that ? First , There are several knowledge points to be clear :
- A process is the smallest unit of resource allocation , Thread is CPU Minimum unit of scheduling .
- A thread can only belong to one process , And a process can have multiple threads , But at least one thread .
- Resources are allocated to processes , All threads of the same process share all resources of the process .
- Processors are allocated to threads , That is to say, what is running on the processor is the thread .
secondly , Each process has its own storage space , They are isolated from each other . For example, you are browsing the web , The browser crashed , But it will not affect the music player . But for threads , Resources are shared , Therefore, there will be competition for access to shared resources , Then there is the critical zone , Mutually exclusive 、 Semaphore and other concepts . If a thread crashes , It is highly likely to affect other threads in the process .
about MCU Resources on , Every task is shared , It can be considered as a single process multithreading model .MCU Generally, there is no memory management module , This does not guarantee the security of the process , This is also the reason why when a task flies, the whole program will crash .
It is commonly believed , There is only one process when the embedded system is running , And those program modules after decomposing this process , Because there is no independent memory space , It's essentially a thread . stay μC/OS-II in , Call such a thread a task .
Intuitively speaking ,
Task and its memory structure
Since it is task scheduling , That requires the system to manage tasks , The data structure of system management tasks is called task control block (TCB)
With μC/OS-II For example , The task control block records the attributes of a task , Equivalent to the ID card of the task .TCB Two pointers in are particularly important :
- Pointer to the task : During task initialization , This pointer points to the code entry of the task
- Pointer to the task stack : Stack pointing to task . Each task has its own stack , Used to hold local variables , And snapshots of registers . In these registers , The most important thing is PC, Point to the code that the task is currently running
There are usually multiple tasks in the system , These tasks are TCB Use a linked list , You can also use arrays .
Context switch
To schedule tasks , It's about context switching .
Let's first look at how threads deal with interrupts . When the thread is executing , All you do is get instructions from memory 、 decoding 、 perform . In the whole process ,CPU The value of the register in the is constantly updated . At this time, if an interrupt comes , that CPU It is necessary to save the value of the core register to a certain place in memory ( For example, the stack of this thread ), Then respond to the interrupt . When the interrupt execution is finished , Then load the value just saved into the corresponding register , Continue from where you just interrupted ( By program counter PC Record ).
The same is true of task switching , If you want to put the current task A Swap out , You have to find A Stack of tasks , Save the current register information on the stack , Then find the task to be replaced B, And find B Stack of tasks , Restore the register value saved on the stack to the register , Finally let B Began to run .
A lot of bedding has been done in front , Next, we will combine a specific one CPU Speaking of task scheduling .
CM3 Register set for
Be careful , stay CM3 There are two stack pointers in the processor core , So it supports two stacks . When referencing R13( Or writing SP) when , It refers to the one currently in use , The other must be accessed with special instructions (MRS,MSR Instructions ). These two stack pointers are :
- Main stack pointer (MSP), Or writing SP_main. This is the default stack pointer , It consists of OS kernel 、 Exception service routines and all application code requiring privileged access to use .
- Process stack pointer (PSP), Or writing SP_process. For general application code ( When not in an abnormal taking routine ).
It should be noted that , Not every program needs two stack pointers to complete . Simple applications only use MSP That's enough .
In the sample code for this article , Double stack .
CM3 Of CONTROL register
After reset ,CONTROL[0]=0 , That is to say, the thread mode is at the privilege level .
Cortex-M3 The processor supports two operating modes of the processor , It also supports two-level privileged operations .
The two operation modes are :handler Mode and thread mode (thread mode). The original intention of introducing two modes , Is the code used to distinguish between ordinary application code and exception service routine .
The two levels of privilege are : Privilege level and user level . This can provide a protection mechanism for memory access , So that ordinary user program code can not accidentally 、 Even maliciously perform operations involving key points .
There is a sentence in the sample code :
__set_CONTROL(0x3); // Switch to use Process Stack, unprivileged state
It means forcibly switching to the user level , And use PSP( It will be said immediately later )
Double stack
We already know that CM3 There are two stacks of : Main stack and process stack ,CONTROL[1] Decide how to choose .
When CONTROL[1]=0 when , Use only MSP, At this time, the user program and exception handler Share the same stack , This is also the default usage after reset .
Our example code uses double stacks .
When CONTROL[1]=1 when , Threading mode will no longer be used MSP, And switch to PSP( Be careful :handler Mode is always used MSP). What are the advantages of doing this ? original , In the use of OS Under the environment of , We want to make OS The kernel is only in handler Execution in mode , The user program is executed only in user mode , The advantage of this dual stack mechanism is : In case the user stack crashes , It won't involve OS The stack .
In dual stack mode , The automatic stack pressing when entering an exception uses the process stack , After entering the exception, it will be automatically changed to MSP, Switch back to PSP, And pop data from the process stack . As shown in the figure below :
CM3 The interrupt
Task switching is usually carried out in interruption , So understand CPU The interruption process of is very necessary .
When CM3 When starting to respond to an interrupt , Three undercurrents will rush up in its small body :
- Push : hold 8 The value of a register is pushed onto the stack
- Take the vector : Find the entry address of the corresponding service program from the vector table
- Update register : Select stack pointer MSP/PSP, Update stack pointer SP, Update connection register LR, Update program counter PC
good , One by one .
Push
The automatic stack registers are 8 individual , See table 9.1:
Take the vector
When the data bus ( The system bus ) When you are busy with the stack operation , Instruction bus (I-Code) It's not to stand idly by —— It is carrying out another important task nervously and orderly in response to interruption : Find the correct exception vector from the vector table , Then prefetch at the entrance of the service program . From this, we can see the benefits of each having a dedicated bus : Stacking and fetching can be done at the same time .
Update register
After the stack and vector fetching operations are completed , Before executing the service routine , Also update a series of registers :
- SP: After entering the stack, the stack pointer (PSP or MSP) Update to new location . When executing a service routine , Will be made by MSP Responsible for access to the stack .
- PSR: to update IPSR The value of the bit field is the exception number of the new response .
- PC: After taking the vector ,PC Will point to the entry address of the service routine .
- LR: In and out ISR When ,LR The value of will have new meaning , This special value is called “EXC_RETURN”, When an exception enters, it is calculated by the system and assigned to LR, And use it when the exception returns .EXC_RETURN Except for the lowest 4 All of them are 1, And its lowest 4 Bit has another meaning ( See table 9.3 And table 9.4).
The above is the change of general register in response to exception . On the other hand , stay NVIC in , Several related registers will also be updated . for example , The suspended bit of the new response exception will be cleared , At the same time, its active bit will be set .
Exception return
When the exception service routine is executed , It needs to be done formally “ Exception return ” The action sequence of , So as to restore the previous system state , So that the interrupted program can continue to execute . In form , Yes 3 There are two ways to trigger an exception return sequence , As shown in the table 9.2 Shown . No matter which one is used , All need to use the previous storage LR Of EXC_RETURN.
In the sample code , The first method is used :
BX LR // Return
After starting the interrupt return sequence , The following processing will be carried out :
- Out of the stack : The register value previously pushed into the stack is restored to the corresponding register , The order of stack out corresponds to that of stack in , The stack pointer is also changed back to the previous value .
- to update NVIC register : With the return of the exception , Its active bit is also cleared by the hardware . For external interrupts , If the interrupt input is set to valid again , The suspended position will also be set again , A new interrupt response can also start again .
Timing of switching
Already said. , Task switching is carried out in interruption , But in which interrupt ?
for example , There are two tasks in a system , The occasion when context switching is triggered can be :
- Perform a system call (SVC abnormal )
- System tick timer (SYSTICK) interrupt ,( Rotation scheduling requires )
Let's take a simple example . Suppose there is such a system , There are two ready tasks , And through SysTick Abnormal start context switching . Pictured 7.15 Shown .
The above figure is the schematic diagram of two task rotation scheduling . But if it occurs in SysTick Responding to an interrupt when exception , be SysTick Exceptions will preempt their ISR. under these circumstances ,OS Context switching cannot be performed , Otherwise, the interrupt request will be delayed , Moreover, in real systems, the delay time is often unpredictable —— Any system with the slightest real-time requirement will never tolerate this kind of thing . therefore , stay CM3 It is also strictly forbidden not to discuss —— If OS Try to cut into thread mode when an interrupt is active , Will trigger usage fault abnormal ( But there are exceptions , Interested readers can see at the end of this article “ Non base threading mode ”).
To solve this problem , In the early OS Most of them will detect whether there is currently an interrupt active , Only when there is no interruption to respond , To perform context switching ( Unable to respond to interrupt during switching ). However , The disadvantage of this method is that , It can delay the task switching action for a long time ( Because if you seize IRQ, This time SysTick Context switching is not allowed after execution , Just wait for the next time SysTick abnormal ), Especially when the frequency of an interrupt source and SysTick When the abnormal frequency is relatively close , It's going to happen “ resonance ”, Delay context switching .
Ok now , Yes PendSV To solve the problem perfectly .PendSV Exceptions automatically delay requests for context switching . To achieve this mechanism , Need to put PendSV Exceptions programmed to the lowest priority . if OS Context switching is required , It will hang a PendSV abnormal , And in PendSV Perform context switching within the exception . Pictured 7.17 Shown
explain :
- Mission A call SVC To request task switching ( for example , Wait for some work to finish )
- OS Received request , Be prepared for context switching , And hang a PendSV abnormal .
- When CPU sign out SVC after , It immediately enters PendSV, To perform context switching .
- When PendSV After execution , Will return to the task B, Enter thread mode at the same time .
- An interrupt occurred , And the interrupt service program starts to execute
- stay ISR In the process of execution , happen SysTick abnormal , And grabbed the ISR.
- OS Perform the necessary actions , Then hang up PendSV Exception to prepare for context switching .
- When SysTick after , Go back to the previously occupied ISR in ,ISR Carry on
- ISR After execution and exit ,PendSV The service routine starts executing , And perform context switching inside
- When PendSV After execution , Back to task A, At the same time, the system enters thread mode again .
remaining problems : When debugging , In my submission SysTick The exception will enter immediately after it returns PendSV Service routine , You should see Tail chaining The phenomenon , But the test result is SysTick After interrupt processing, it returns to the task B, A little bit , Enter at once PendSV
Switch
The specific switching is shown in the figure below .
My explanation :
- Task A In the process of execution , It happened. PendSV abnormal
- xPSR, PC, LR, R12 as well as R3-R0 Automatically stack by hardware ( Be careful : When something goes wrong , Which stack does the current code use , Just press into which stack , The figure shows that PSP. Once you enter the service routine , Will use MSP)
- Save manually R4-R11 To A The stack
- to update A Stack pointer to PSP array[]
- from PSP array[] Find Task B The stack pointer of
- according to Task B The stack pointer of , find Task B The stack , Manually stack R4-R11 The value of to register
- from PendSV Exception return ,xPSR, PC, LR, R12 as well as R3-R0 Automatically stack by hardware
- Task B Start execution
Non base threading mode ( Supplementary materials )
stay CM3 in , In principle, the exception service program should be in handler Execution in mode , But it is also allowed to switch to thread mode in service routines . By setting NVIC Configure and control registers “ Non base threading mode allows ” position (NONBASETHRDENA, Bit shift :0), You can switch the processor into thread mode in the service routine . Why do you do this ? If the interrupt service routine is part of the user program , You may need to make it execute in threaded mode , To restrict its access to resources under the privilege level , This function can be used at this time .
If you use this function , You need to manually adjust the stack pointer , Also rebuild the data in the stack . This great shift of heaven and earth is a highly dangerous operation , It's easy to break the whole system if you're not careful . So we must take it very seriously . in addition , When use , The system designer must also ensure that the service routine can return correctly . Because interrupt return is not allowed in thread mode , So you have to use a little wrist . If you let it go , Then the interrupt cannot exit , This will block other peer and lower priority interrupts forever . Usually , The system software is responsible for this kind of work .
This section has nothing to do with the main idea of this article , So just put a picture here , Prompt readers “ It can be operated like this ”!
Code
Confined to space , The code will be discussed in the next blog post .
Readers are welcome to criticize and correct .
Reference material
【0】RTOS The task in is thread 、 process 、 Or Xiecheng ?- Bread board community
【1】 Mission 、 Difference between process and thread ( From blog Park ) - Lei Ming - Blog Garden
【2】《Cortex-M3 Authoritative guide 》
【3】《The Definitive Guide to ARM Cortex-M3 and Cortex-M4 Processors(Third Edition)》
边栏推荐
- Makefile application
- Altium designer 19.1.18 - Import frame
- matlab timeserise
- How to migrate the device data accessed by the RTSP of the easycvr platform to easynvr?
- Altium designer 19.1.18 - hide the fly line of a network
- Network communication model -- Network OSI tcp/ip layering
- Extended application of single chip microcomputer-06 independent key
- UEFI development learning 6 - creation of protocol
- 【论文阅读】2022年最新迁移学习综述笔注(Transferability in Deep Learning: A Survey)
- Random function usage notes
猜你喜欢
C language enhancement -- pointer
C language # and #
Consul安装
Screen record of the opening ceremony of the Beijing winter olympics 2
Hardware 1 -- relationship between gain and magnification
Shell script basic syntax
Nb-iot technical summary
Altium designer 19.1.18 - change the transparency of copper laying
生产中影响滑环质量的因素
Volatile of C language
随机推荐
[trio basic tutorial 16 from introduction to proficiency] UDP communication test supplement
Some thoughts on extracting perspectives from ealfa and Ebeta
C, Numerical Recipes in C, solution of linear algebraic equations, LU decomposition source program
[tutorial 19 of trio basic from introduction to proficiency] detailed introduction of trio as a slave station connecting to the third-party bus (anybus PROFIBUS DP...)
Global and Chinese market of resistivity meter 2022-2028: Research Report on technology, participants, trends, market size and share
Nb-iot technical summary
找不到实时聊天软件?给你推荐电商企业都在用的!
Global and Chinese markets for anesthesia, breathing and sleep apnea devices 2022-2028: Research Report on technology, participants, trends, market size and share
UEFI development learning 6 - creation of protocol
Measurement fitting based on Halcon learning [III] PM_ measure_ board. Hdev routine
Global and Chinese market of core pallets 2022-2028: Research Report on technology, participants, trends, market size and share
C WinForm [exit application] - practice 3
Makefile application
Live555 push RTSP audio and video stream summary (I) cross compilation
Sql Server的存儲過程詳解
Extern keyword function
[tutorial 15 of trio basic from introduction to proficiency] trio free serial communication
The firmware of the connected j-link does not support the following memory access
C WinForm [change the position of the form after running] - Practical Exercise 4
研究发现,跨境电商客服系统都有这五点功能!