当前位置:网站首页>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

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 :

  1. A process is the smallest unit of resource allocation , Thread is CPU Minimum unit of scheduling .
  2. A thread can only belong to one process , And a process can have multiple threads , But at least one thread .
  3. Resources are allocated to processes , All threads of the same process share all resources of the process .
  4. 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 ,

 Please add a picture description

Task and its memory structure

 Please add a picture description

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

 Please add a picture description

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

 Please add a picture description

 Please add a picture description

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

 Please add a picture description

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 .

 Please add a picture description

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 :

 Please add a picture description

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:
 Please add a picture description

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 .

 Please add a picture description

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.

 Please add a picture description

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 :

  1. 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 .
  2. 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 .

 Please add a picture description

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 ”).

 Please add a picture description

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
 Please add a picture description

explain :

  1. Mission A call SVC To request task switching ( for example , Wait for some work to finish )
  2. OS Received request , Be prepared for context switching , And hang a PendSV abnormal .
  3. When CPU sign out SVC after , It immediately enters PendSV, To perform context switching .
  4. When PendSV After execution , Will return to the task B, Enter thread mode at the same time .
  5. An interrupt occurred , And the interrupt service program starts to execute
  6. stay ISR In the process of execution , happen SysTick abnormal , And grabbed the ISR.
  7. OS Perform the necessary actions , Then hang up PendSV Exception to prepare for context switching .
  8. When SysTick after , Go back to the previously occupied ISR in ,ISR Carry on
  9. ISR After execution and exit ,PendSV The service routine starts executing , And perform context switching inside
  10. 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 .

 Please add a picture description

My explanation :

  1. Task A In the process of execution , It happened. PendSV abnormal
  2. 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)
  3. Save manually R4-R11 To A The stack
  4. to update A Stack pointer to PSP array[]
  5. from PSP array[] Find Task B The stack pointer of
  6. according to Task B The stack pointer of , find Task B The stack , Manually stack R4-R11 The value of to register
  7. from PendSV Exception return ,xPSR, PC, LR, R12 as well as R3-R0 Automatically stack by hardware
  8. 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 ”! Please add a picture description

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)》

原网站

版权声明
本文为[Car chezi]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202140546258106.html

随机推荐