写点什么

FreeRTOS 记录(三、RTOS 任务调度原理解析 _Systick、PendSV、SVC)

作者:矜辰所致
  • 2022 年 9 月 07 日
    江苏
  • 本文字数:18710 字

    阅读完需:约 61 分钟

FreeRTOS记录(三、RTOS任务调度原理解析_Systick、PendSV、SVC)
RTOS的任务调度原理和所使用的内核中断、寄存器息息相关文中截图大多是《Cortex-M3与Cortex-M4权威指南》翻译版本里面的内容需要对内核有一定的了解,本文尽量用简单的描述表达清楚虽然是FreeRTOS的记录,但是原理上来说对于其他RTOS也是一样的!
复制代码


总结写在前面:


在 Cortex-M 内核上,FreeRTOS 使用 Systick 定时器作为心跳时钟,一般默认心跳时钟为 1ms,进入 Systick 中断后,内核会进入处理模式进行处理,在 Systick 中断处理中,系统会在 ReadList 就绪链表从高优先级到低优先找需要执行的任务,进行调度,如果有任务的状态发生了变化,改变了状态链表,就会产生一个 pendSV 异常,进入 pendSV 异常,通过改变进程栈指针(PSP)切换到不同的任务。


对于相同优先级的任务,每隔一个 Systick,运行过的任务被自动排放至该优先级链表的尾部(时间片调度)


用户也可以在线程模式下主动触发 PendSV,进行任务切换。


在 FreeRTOS 中 SVC 只使用了一次(M0 中没有使用),就是第一次。


FreeRTOS 进入临界区是通过配置 BASEPRI 寄存器来进行的。

一、 Systick

我们已经知道,在 Cortex-M 系列中 systick 是作为 FreeRTOS 的心跳时钟,是调度器的核心。


系统是在 Systick 中进行上下文切换。


那么他是如何进行上下文切换的呢,那就得来说说内核的中断管理了,记住一句话


操作系统的入口是中断(好像是废话,嵌入式所有程序的入口都是中断= =!)

Systick 源码解析

Systick 初始化

systick 的初始化在port.c中, vPortSetupTimerInterrupt函数:


/* * Setup the systick timer to generate the tick interrupts at the required * frequency. */__attribute__(( weak )) void vPortSetupTimerInterrupt( void ){  /* Calculate the constants required to configure the tick interrupt. */  #if( configUSE_TICKLESS_IDLE == 1 )  {    ulTimerCountsForOneTick = ( configSYSTICK_CLOCK_HZ / configTICK_RATE_HZ );    xMaximumPossibleSuppressedTicks = portMAX_24_BIT_NUMBER / ulTimerCountsForOneTick;    ulStoppedTimerCompensation = portMISSED_COUNTS_FACTOR / ( configCPU_CLOCK_HZ / configSYSTICK_CLOCK_HZ );  }  #endif /* configUSE_TICKLESS_IDLE */
/* Stop and clear the SysTick. 清0,保证上电后的准确性 */ portNVIC_SYSTICK_CTRL_REG = 0UL; portNVIC_SYSTICK_CURRENT_VALUE_REG = 0UL; /* Configure SysTick to interrupt at the requested rate. portNVIC_SYSTICK_LOAD_REG systick装载值 portNVIC_SYSTICK_CTRL_REG systick控制寄存器 配置系统时钟源,开启中断,使能 */ portNVIC_SYSTICK_LOAD_REG = ( configSYSTICK_CLOCK_HZ / configTICK_RATE_HZ ) - 1UL; portNVIC_SYSTICK_CTRL_REG = ( portNVIC_SYSTICK_CLK_BIT | portNVIC_SYSTICK_INT_BIT | portNVIC_SYSTICK_ENABLE_BIT );}/*-----------------------------------------------------------*/
复制代码

Systick 中断服务函数

每一节拍进入一次 Systick 中断,因为 Systick 如果调度器返回 true,触发 pendSV 异常:


/*-----------------------------------------------------------*/
void xPortSysTickHandler( void ){ /* The SysTick runs at the lowest interrupt priority, so when this interrupt executes all interrupts must be unmasked. There is therefore no need to save and then restore the interrupt mask value as its value is already known. 进入临界区,在上面一篇文章讲过,通过配置BASEPRI寄存器,关闭的中断等级在CubeMX中设置 */ portDISABLE_INTERRUPTS(); { /* Increment the RTOS tick. 操作系统调度接口 如果调度器返回true,触发pendSV异常 */ if( xTaskIncrementTick() != pdFALSE ) { /* A context switch is required. Context switching is performed in the PendSV interrupt. Pend the PendSV interrupt. 往中断控制及状态寄存器ICSR(地址:0xE000_ED04)的bit28写1挂起一次PendSV中断 触发pendSV */ portNVIC_INT_CTRL_REG = portNVIC_PENDSVSET_BIT; } } /* 开中断,执行pendSV */ portENABLE_INTERRUPTS();}
复制代码

Systick 任务调度

Systick 中断中调用xTaskIncrementTick任务调度如下,源码注释:


/*----------------------------------------------------------*/
BaseType_t xTaskIncrementTick( void ){TCB_t * pxTCB;TickType_t xItemValue;BaseType_t xSwitchRequired = pdFALSE;// 返回值,表示是否进行上下文切换
/* Called by the portable layer each time a tick interrupt occurs. Increments the tick then checks to see if the new tick value will cause any tasks to be unblocked. */ traceTASK_INCREMENT_TICK( xTickCount ); /* uxSchedulerSuspended 表示内核调度器是否挂起 pdFALSE 表示内核没有挂起 */ if( uxSchedulerSuspended == ( UBaseType_t ) pdFALSE ) { /* Minor optimisation. The tick count cannot change in this block. tick计数增加1 */ const TickType_t xConstTickCount = xTickCount + ( TickType_t ) 1; /* Increment the RTOS tick, switching the delayed and overflowed delayed lists if it wraps to 0. */ xTickCount = xConstTickCount;
/* 判断tick是否溢出越界 */ if( xConstTickCount == ( TickType_t ) 0U ) /*lint !e774 'if' does not always evaluate to false as it is looking for an overflow. */ { taskSWITCH_DELAYED_LISTS();//如果溢出,要更新延时列表 } else { mtCOVERAGE_TEST_MARKER(); }
/* See if this tick has made a timeout expire. Tasks are stored in the queue in the order of their wake time - meaning once one task has been found whose block time has not expired there is no need to look any further down the list. 当前节拍大于时间片的锁定时间 说明有任务需要进行调度了,时间片用完了 */ if( xConstTickCount >= xNextTaskUnblockTime ) { /* 会一直遍历整个任务延时列表, 找到时间片最短的任务,进行切换 */ for( ;; ) { /* 判断任务延时列表中,是否为空, 也就是说,有没有任务在等待调度 */ if( listLIST_IS_EMPTY( pxDelayedTaskList ) != pdFALSE ) { /* The delayed list is empty. Set xNextTaskUnblockTime to the maximum possible value so it is extremely unlikely that the if( xTickCount >= xNextTaskUnblockTime ) test will pass next time through. 如果没有任务等待,把时间片赋值为最大值,不再调度 */ xNextTaskUnblockTime = portMAX_DELAY; /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ break; } else { /* The delayed list is not empty, get the value of the item at the head of the delayed list. This is the time at which the task at the head of the delayed list must be removed from the Blocked state. 1、从任务延时列表中,获取第一个任务控制块 2、延时列表,插入永远是把时间片最短的任务,放在第一个 3、获取任务控制块的延时时间 */ pxTCB = listGET_OWNER_OF_HEAD_ENTRY( pxDelayedTaskList ); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */ xItemValue = listGET_LIST_ITEM_VALUE( &( pxTCB->xStateListItem ) ); /* 再次判断,这个任务的时间片是否到达 */ if( xConstTickCount < xItemValue ) { /* It is not time to unblock this item yet, but the item value is the time at which the task at the head of the blocked list must be removed from the Blocked state - so record the item value in xNextTaskUnblockTime. 没有到达,把此任务的时间片更新为当前系统的时间片 */ xNextTaskUnblockTime = xItemValue; /* 直接退出,不用调度 */ break; /*lint !e9011 Code structure here is deedmed easier to understand with multiple breaks. */ } else { mtCOVERAGE_TEST_MARKER(); }
/* It is time to remove the item from the Blocked state. 把任务从延时列表中移除 */ ( void ) uxListRemove( &( pxTCB->xStateListItem ) );
/* Is the task waiting on an event also? If so remove it from the event list. 把任务从事件列表中移除 */ if( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) != NULL ) { ( void ) uxListRemove( &( pxTCB->xEventListItem ) ); } else { mtCOVERAGE_TEST_MARKER(); }
/* Place the unblocked task into the appropriate ready list. 把任务添加到就绪列表中 */ prvAddTaskToReadyList( pxTCB );
/* A task being unblocked cannot cause an immediate context switch if preemption is turned off. 抢占式处理 */ #if ( configUSE_PREEMPTION == 1 ) { /* Preemption is on, but a context switch should only be performed if the unblocked task has a priority that is equal to or higher than the currently executing task. 判断优先级是否大于当前任务 大于则进行调度 */ if( pxTCB->uxPriority >= pxCurrentTCB->uxPriority ) { xSwitchRequired = pdTRUE; } else { mtCOVERAGE_TEST_MARKER(); } } #endif /* configUSE_PREEMPTION */ } } }
/* Tasks of equal priority to the currently running task will share processing time (time slice) if preemption is on, and the application writer has not explicitly turned time slicing off. 时间片处理机制 1、获取就绪列表长度 2、就绪列表指的是,当前任务优先级的列表 3、如果有其他任务在就绪列表中,就开始调度 */ #if ( ( configUSE_PREEMPTION == 1 ) && ( configUSE_TIME_SLICING == 1 ) ) { if( listCURRENT_LIST_LENGTH( &( pxReadyTasksLists[ pxCurrentTCB->uxPriority ] ) ) > ( UBaseType_t ) 1 ) { xSwitchRequired = pdTRUE; } else { mtCOVERAGE_TEST_MARKER(); } } #endif /* ( ( configUSE_PREEMPTION == 1 ) && ( configUSE_TIME_SLICING == 1 ) ) */
#if ( configUSE_TICK_HOOK == 1 ) { /* Guard against the tick hook being called when the pended tick count is being unwound (when the scheduler is being unlocked). */ if( uxPendedTicks == ( UBaseType_t ) 0U ) { vApplicationTickHook(); } else { mtCOVERAGE_TEST_MARKER(); } } #endif /* configUSE_TICK_HOOK */ } else //内核调度器挂起了 { ++uxPendedTicks;//挂起的tick+1
/* The tick hook gets called at regular intervals, even if the scheduler is locked. */ #if ( configUSE_TICK_HOOK == 1 ) { vApplicationTickHook(); } #endif } /* 如果是抢占模式,要开启调度 */ #if ( configUSE_PREEMPTION == 1 ) { if( xYieldPending != pdFALSE ) { xSwitchRequired = pdTRUE; } else { mtCOVERAGE_TEST_MARKER(); } } #endif /* configUSE_PREEMPTION */
return xSwitchRequired;//返回调度器状态}
复制代码


Systick 优先级分析


结合后面的中断管理和任务调度相关的内容,需要说明一下 Systick 优先级的问题。先来看一下简单的任务调度模型。



在上面图示中,可以看到优先级 SysTick 优先级最高!那么这和我们常听到的 SysTick 优先级需要设置为最低优先级怎么相互冲突呢?初学者往往在这个问题上感到困惑。


首先要明白:SysTick 是中断,中断优先级和任务优先级没有任何关系,不管中断优先级是多少,中断的优先级永远高于任何线程任务的优先级。


那么在上图中的线程,不管什么线程,SysTick 中断来了肯定是需要去执行 SysTick 中断事件的。


上图中还有一个 IRQ,比 SysTick 优先级低,这也是可能的,但是实际上我们应用过程中,一般都把 SysTick 优先级设置为最低,因为不想让 SysTick 中断打断用户的 IRQ 中断。


那么 SysTick 中断优先级和外设中断优先级是怎么确定的?


1、SysTick 属于内核异常,用 SHPRx(x=1.2.3)来设置其优先级;外设中断属于 ISR,用 NVIC_IPRx 来设置优先级。


SPRH1-SPRH3 是一个 32 位的寄存器,只能通过字节访问,每 8 个字段控制着一个内核外设的中断优先级的配置。位 7:4 这高四位有效,所以可编程为 0 ~ 15。如果软件优先级配置相同,那就根据他们在中断向量表里面的位置编号来决定优先级大小,编号越小,优先级越高。


对于 SysTick 的配置,系统默认配置为 15,

(1UL << __NVIC_PRIO_BITS) - 1UL) 在 m3、m4 中__NVIC_PRIO_BITS为 4:


/*core_cm0/3/4.h中关于SysTick_Config m3 m4 中是 4 ,4位就是0~15  #define __NVIC_PRIO_BITS          4U m0 中是2, 2位就是 0 ~ 3   #endif  */__STATIC_INLINE uint32_t SysTick_Config(uint32_t ticks){  if ((ticks - 1UL) > SysTick_LOAD_RELOAD_Msk)  {    return (1UL);                                                   /* Reload value impossible */  }
SysTick->LOAD = (uint32_t)(ticks - 1UL); /* set reload register */ NVIC_SetPriority (SysTick_IRQn, (1UL << __NVIC_PRIO_BITS) - 1UL); /* set Priority for Systick Interrupt */ SysTick->VAL = 0UL; /* Load the SysTick Counter Value */ SysTick->CTRL = SysTick_CTRL_CLKSOURCE_Msk | SysTick_CTRL_TICKINT_Msk | SysTick_CTRL_ENABLE_Msk; /* Enable SysTick IRQ and SysTick Timer */ return (0UL); /* Function successful */}
/*NVIC_SetPriority对中断分了类,分内核中断和外设中断,内核外设中断枚举值小于0,普通外设>=0。其中,SysTick_IRQn = -1。*/__STATIC_INLINE void NVIC_SetPriority(IRQn_Type IRQn, uint32_t priority){ if ((int32_t)(IRQn) < 0) { SCB->SHP[(((uint32_t)(int32_t)IRQn) & 0xFUL)-4UL] = (uint8_t)((priority << (8U - __NVIC_PRIO_BITS)) & (uint32_t)0xFFUL); } else { NVIC->IP[((uint32_t)(int32_t)IRQn)] = (uint8_t)((priority << (8U - __NVIC_PRIO_BITS)) & (uint32_t)0xFFUL); }}
复制代码


2、NVIC 的中断优先级分组不仅对片上外设有效,同样对内核的外设也有效。


systick 的优先级 15 转换成二进制值就是 1111,又因为 NVIC 的优先级分组 2,那么前两位的 11 就是 3,3 抢占,后两位的 11 也是 3,3 子优先级。这样就可以和外设的优先级进行对比。


如果外设中断的优先级也分成了 15,无论怎么分组,SYSTICK 优先级高于同优先级的外设(毕竟内核异常优先级高于外设中断,因为中断向量表里面的位置编号内核的靠前更小)。


3、设置 systick 优先级的方法NVIC_SetPriority (SysTick_IRQn, (1<<__NVIC_PRIO_BITS) - 15);SCB->SHP[11] = 0x00;设置最高的话可以得到精准延时,但是会频繁打断用户使用的中断程序,不建议。

二、内核中断管理

中断是微处理器外部发送的,通过中断通道送入处理器内部,一般是硬件引起的;而异常通常是微处理器内部发生的,大多是软件引起的,比如除法出错异常,特权调用异常。

Cortex-M 的异常类型

如下图:


Cortex-M 的寄存器

如下图:



这个图主要记住 R13 寄存器,有两个指针:MSP: 主栈指针 和 PSP: 进程栈指针,相关说明如下:


Cortex-M 的特殊寄存器

如下图:


xPSR

组合程序状态寄存器,该寄存器由三个程序状态寄存器组成应用 PSR(APSR) : 包含前一条指令执行后的条件标志中断 PSR(IPSR) : 包含当前 ISR 的异常编号执行 PSR(EPSR) : 包含 Thumb 状态位


PRIMSK

PRIMSK:中断屏蔽特殊寄存器。

利用 PRIMSK,可以禁止除 HardFault 和 NMI 外的所有异常。



BASEPRI

利用 BASEPRI 寄存器来选择屏蔽低于特定优先级的异常或中断。(在上一篇博文中的进入临界区所使用的寄存器就是这个寄存器)


CONTROL

CONTROL:控制寄存器,部分介绍如下:





Cortex-M 的工作模式

Cortex-M 有两种工作模式和两种工作状态:


线程模式(Thread Mode):芯片复位后,进入线程模式,执行用户程序;


处理模式(Handler Mode):当处理器发生了异常或者中断,则进入处理模式,处理完后返回线程模式。


Thumb 状态: 正常运行时处理器的状态


调试状态:调试程序时处理器的状态



进入 Systick 后,发生异常,则进入处理模式进行处理:


如果是裸机编程,从哪里进去就返回哪里


但是用了操作系统,该返回哪里呢?


所以这里就有必要单独讲解下 MSP 和 PSP

三 、影子栈指针

在上面的 Cortex-M 的寄存器图中我们标注过 R13 寄存器:堆栈指针 SP。在处理模式下,只能使用主堆栈(MSP)。在线程模式下,可以使用主堆栈也可以使用进程栈。由 CONTROL 寄存器控制,如下:



四、PendSV 和 SVC 异常

PendSV 异常用于任务切换。


为了保证操作系统的实时性,除了使用 Systick 的时间片调度,还得加入 pendSV 异常加入抢占式调度。


PendSV(可挂起的系统调用),异常编号为 14,可编程。可以写入中断控制和状态寄存器(ICSR)设置挂起位以触发 PendSV 异常。它是不精确的。因此,它的挂起状态可以在更高优先级异常处理内设置,且会在高优先级处理完成后执行。

为什么需要 PendSV 异常?

如下图所示,如果中断请求在 Systick 异常前产生,则 Systick 可能会抢占 IRQ 处理(图中的 IRQ 优先级小于 Systick)。这样执行上下文切换会导致 IRQ 延时处理,这种行为在任何一种实时操作系统中都是不能容忍的,在 CortexM3 中如果 OS 在活跃时尝试切入线程模式,将触发 Fault 异常。



为了解决上面的问题,使用了 PendSV 异常。 PendSV 异常会自动延迟上下文切换的请求,直到其他的 eISR 都完成了处理后才放行。为实现这个机制,需要把 PendSV 编程为最低优先级的异常。


在 FreeRTOS 中,每一次进入 Systick 中断,系统都会检测是否有新的进入就绪态的任务需要运行,如果有,则悬挂 PendSV 异常,来缓期执行上下文切换。

如下:



在 Systick 中会挂起一个 PendSV 异常用于上下文切换,每产生一个 Systick,系统检测到任务链表变化都会触发一个 PendSV 如下图:



PendSV 业务流程


中断过程中不但要像一般的 C 函数调用一样保存(R0-R3,R12,LR,PSR),还要保存中断返回地址(return address)。中断的硬件机制会把 EXC_RETURN 放进 LR,在中断返回时触发中断返回。如下图:



如何触发 PendSV 异常


触发 PendSV 异常,向 PendSV 中断寄存器写 1,触发一次 PendSV 异常。用户可以主动调用portYIELD函数进行任务切换,portYIELD函数如下:


/* Scheduler utilities. */#define portYIELD()                               \{                                        \  /* Set a PendSV to request a context switch. */                \  portNVIC_INT_CTRL_REG = portNVIC_PENDSVSET_BIT;                \                                        \  /* Barriers are normally not required but do ensure the code is completely  \  within the specified behaviour for the architecture. */            \  __asm volatile( "dsb" ::: "memory" );                    \  __asm volatile( "isb" );                          \}
复制代码

PendSV 源码简析

PendSV 中断服务函数

我这里使用的是 M0 内核中 FreeRTOS 的源码xPortPendSVHandler


void xPortPendSVHandler( void ){  /* This is a naked function.    1.产生PendSV中断,硬件自动保存栈帧到任务A的栈中    2.读取当前任务A的栈指针PSP,手动把一些寄存器压栈到当前任务栈。    3.把当前任务A栈顶指针保存到任务A的任务控制块中。    4.找到下一个任务B的任务控制块。(查找下一个优先级最高的就绪任务)    5.把任务B控制块的栈顶指针指向的数据弹出到寄存器中    6.更新PSP为任务B的栈顶指针。    7.跳出PendSV中断。    8.硬件自动弹出任务B栈中的栈帧。 */  __asm volatile  (  "  .syntax unified            \n"   "  mrs r0, psp              \n"/*将psp值放到r0,此时sp得值为msp*/  "                    \n"  "  ldr  r3, pxCurrentTCBConst      \n" /* Get the location of the current TCB. 获取当前任务控制块,其实就获取任务栈顶 */  "  ldr  r2, [r3]            \n"/*将r3寄存器值作为指针取内容存到r2,此时r2保存的为任务控制块首地址*/  "                    \n"  "  subs r0, r0, #32          \n" /* Make space for the remaining low registers. */  "  str r0, [r2]            \n" /* Save the new top of stack. */  "  stmia r0!, {r4-r7}          \n" /* Store the low registers that are not saved automatically. */  "   mov r4, r8              \n" /* Store the high registers. */  "   mov r5, r9              \n"  "   mov r6, r10              \n"  "   mov r7, r11              \n"  "   stmia r0!, {r4-r7}          \n"  "                    \n"  "  push {r3, r14}            \n"  "  cpsid i                \n"  "  bl vTaskSwitchContext        \n"/*执行上线文切换*/  "  cpsie i                \n"  "  pop {r2, r3}            \n" /* lr goes in r3. r2 now holds tcb pointer. */  "                    \n"  "  ldr r1, [r2]            \n"  "  ldr r0, [r1]            \n" /* The first item in pxCurrentTCB is the task top of stack. */  "  adds r0, r0, #16          \n" /* Move to the high registers. */  "  ldmia r0!, {r4-r7}          \n" /* Pop the high registers. */  "   mov r8, r4              \n"  "   mov r9, r5              \n"  "   mov r10, r6              \n"  "   mov r11, r7              \n"  "                    \n"  "  msr psp, r0              \n" /* Remember the new top of stack for the task.记住新的栈顶指针 */  "                    \n"  "  subs r0, r0, #32          \n" /* Go back for the low registers that are not automatically restored. */  "   ldmia r0!, {r4-r7}          \n" /* Pop low registers.  */  "                    \n"  "  bx r3                \n"  "                    \n"  "  .align 4              \n"  "pxCurrentTCBConst: .word pxCurrentTCB    "  );}
复制代码

PendSV 上下文切换函数

xPortPendSVHandler中调用的上下文切换vTaskSwitchContext,其核心任务就是找到当前处于就绪态的最高优先级的任务:


void vTaskSwitchContext( void ){  if( uxSchedulerSuspended != ( UBaseType_t ) pdFALSE )  {    /* The scheduler is currently suspended - do not allow a context    switch.     标记调度器状态    */    xYieldPending = pdTRUE;  }  else  {    xYieldPending = pdFALSE;    traceTASK_SWITCHED_OUT();
#if ( configGENERATE_RUN_TIME_STATS == 1 ) { } #endif /* configGENERATE_RUN_TIME_STATS */
/* Check for stack overflow, if configured. 检查任务栈是否溢出 */ taskCHECK_FOR_STACK_OVERFLOW();
/* Select a new task to run using either the generic C or port optimised asm code. 选择优先级最高的任务,把当前的任务控制块进行赋值 */ taskSELECT_HIGHEST_PRIORITY_TASK(); traceTASK_SWITCHED_IN();
#if ( configUSE_NEWLIB_REENTRANT == 1 ) { } #endif /* configUSE_NEWLIB_REENTRANT */ }}
复制代码

寻找最高优先级函数

上下文切换vTaskSwitchContext中调用了taskSELECT_HIGHEST_PRIORITY_TASK()寻找最高优先级的任务:


taskSELECT_HIGHEST_PRIORITY_TASK()的硬件方式:


  /*-----------------------------------------------------------*/  /*  这里注释解释  #define portGET_HIGHEST_PRIORITY( uxTopPriority, uxReadyPriorities ) uxTopPriority = ( 31UL - ( uint32_t ) ucPortCountLeadingZeros( ( uxReadyPriorities ) ) )
#define configASSERT( x ) if ((x) == 0) {taskDISABLE_INTERRUPTS(); for( ;; );}
#define listGET_OWNER_OF_NEXT_ENTRY( pxTCB, pxList ) \ { \ List_t * const pxConstList = ( pxList ); // pxIndex 为上一个任务索引,下一个要执行的即pxNext \ ( pxConstList )->pxIndex = ( pxConstList )->pxIndex->pxNext; \ if( ( void * ) ( pxConstList )->pxIndex == ( void * ) &( ( pxConstList )->xListEnd ) ) \ { // 由于是环形列表,切默认有一个结束项(xListEnd),如果pxIndex刚好为最后一项,则再指向后面一项 \ ( pxConstList )->pxIndex = ( pxConstList )->pxIndex->pxNext; \ } \ ( pxTCB ) = ( pxConstList )->pxIndex->pvOwner; \ } 由于相同优先级的任务可能会存在多个,需要从就绪任务列表中找到位于最前面的任务 将其赋值给pxCurrentTCB。 */ #define taskSELECT_HIGHEST_PRIORITY_TASK() \ { \ UBaseType_t uxTopPriority; \ \ /* Find the highest priority list that contains ready tasks. */ \ portGET_HIGHEST_PRIORITY( uxTopPriority, uxTopReadyPriority ); \ configASSERT( listCURRENT_LIST_LENGTH( &( pxReadyTasksLists[ uxTopPriority ] ) ) > 0 ); \ listGET_OWNER_OF_NEXT_ENTRY( pxCurrentTCB, &( pxReadyTasksLists[ uxTopPriority ] ) ); \ } /* taskSELECT_HIGHEST_PRIORITY_TASK() */
复制代码


taskSELECT_HIGHEST_PRIORITY_TASK()的通用方式:


  /*-----------------------------------------------------------*/
#define taskSELECT_HIGHEST_PRIORITY_TASK() \ { /* uxTopReadyPriority 在每次把任务添加到就绪列表的时候会更新*/ \ UBaseType_t uxTopPriority = uxTopReadyPriority; \ \ /* Find the highest priority queue that contains ready tasks. 一个优先级一个列表,查看当前最高优先级就绪列表下是否有任务 */ \ while( listLIST_IS_EMPTY( &( pxReadyTasksLists[ uxTopPriority ] ) ) ) \ { \ configASSERT( uxTopPriority ); \ /* 如果当前最高优先级就绪列表没任务就查看下一个优先级列表 */ \ --uxTopPriority; \ } \ \ /* listGET_OWNER_OF_NEXT_ENTRY indexes through the list, so the tasks of \ the same priority get an equal share of the processor time. 获取下一个优先级最高任务的任务控制块*/ \ listGET_OWNER_OF_NEXT_ENTRY( pxCurrentTCB, &( pxReadyTasksLists[ uxTopPriority ] ) ); \ uxTopReadyPriority = uxTopPriority; \ } /* taskSELECT_HIGHEST_PRIORITY_TASK */
复制代码

SVC 异常

SVC(请求管理调用),异常编号为 11,可编程。SVC 产生的中断必须立即得到响应,否则将触发硬 Fault。


系统调用处理异常,用户与内核进行交互,用户想做一些内核相关功能的时候必须通过 SVC 异常,让内核处于异常模式,才能调用执行内核的源码。触发 SVC 异常,会立即执行 SVC 异常代码。


下面的启动源码简析中我们可以知道系统在启动调度器函数vTaskStartSchedulerp最后运行到 rvPortStartFirstTask中会调用 SVC 并启动第一个任务。


为什么要用 SVC 启动第一个任务?


因为使用了 OS,任务都交给内核。总不能像裸机调用普通函数一样启动一个任务。


M4 只在上电的触发 SVC 异常,在 SVC 异常中启动第一个任务,只上电运行一次,M0 上没有。


SVC 源码简析

M0 上面没用,特意生成了一个 M4 的来看看源码vPortSVCHandler


void vPortSVCHandler( void ){  __asm volatile (          /* 获取当前任务控制块.           任务控制块的第一成员是------任务的栈顶          获取到栈顶之后,剩下的事就是出栈工作          出栈--------任务的堆栈          */          "  ldr  r3, pxCurrentTCBConst2    \n" /* Restore the context. */          "  ldr r1, [r3]          \n" /* Use pxCurrentTCBConst to get the pxCurrentTCB address. */          "  ldr r0, [r1]          \n" /* The first item in pxCurrentTCB is the task top of stack. */          "  ldmia r0!, {r4-r11, r14}    \n" /* Pop the registers that are not automatically saved on exception entry and the critical nesting count. 出栈内核寄存器 R14其实就是异常返回值          表示异常退出后,使用PSP*/          "  msr psp, r0            \n" /* Restore the task stack pointer.更新栈指针到PSP */          "  isb                \n"          "  mov r0, #0             \n"          "  msr  basepri, r0          \n"/* 把basepri赋值为0,打开屏蔽中断 */          "  bx r14              \n"          "                  \n"          "  .align 4            \n"          "pxCurrentTCBConst2: .word pxCurrentTCB        \n"        );        /*        为什么没有恢复其他寄存器????其他在出栈的时候就会自动恢复(由硬件处理)        最终跳转到任务的执行函数里面        */}
复制代码

FreeRTOS 多任务启动源码简析

通过 main.c 中的 main 函数调用了osKernelStart();


osStatus osKernelStart (void){  vTaskStartScheduler();    return osOK;}
复制代码

vTaskStartScheduler

创建空闲任务,启动任务调度器vTaskStartScheduler


void vTaskStartScheduler( void ){BaseType_t xReturn;
/* Add the idle task at the lowest priority. 下面部分根据配置的支持动态任何还是静态任务 创建一个优先级最低的空闲任务 */ #if( configSUPPORT_STATIC_ALLOCATION == 1 ) { StaticTask_t *pxIdleTaskTCBBuffer = NULL; StackType_t *pxIdleTaskStackBuffer = NULL; uint32_t ulIdleTaskStackSize;
/* The Idle task is created using user provided RAM - obtain the address of the RAM then create the idle task. */ vApplicationGetIdleTaskMemory( &pxIdleTaskTCBBuffer, &pxIdleTaskStackBuffer, &ulIdleTaskStackSize ); xIdleTaskHandle = xTaskCreateStatic( prvIdleTask, configIDLE_TASK_NAME, ulIdleTaskStackSize, ( void * ) NULL, /*lint !e961. The cast is not redundant for all compilers. */ portPRIVILEGE_BIT, /* In effect ( tskIDLE_PRIORITY | portPRIVILEGE_BIT ), but tskIDLE_PRIORITY is zero. */ pxIdleTaskStackBuffer, pxIdleTaskTCBBuffer ); /*lint !e961 MISRA exception, justified as it is not a redundant explicit cast to all supported compilers. */
if( xIdleTaskHandle != NULL ) { xReturn = pdPASS; } else { xReturn = pdFAIL; } } #else { /* The Idle task is being created using dynamically allocated RAM. */ xReturn = xTaskCreate( prvIdleTask, configIDLE_TASK_NAME, configMINIMAL_STACK_SIZE, ( void * ) NULL, portPRIVILEGE_BIT, /* In effect ( tskIDLE_PRIORITY | portPRIVILEGE_BIT ), but tskIDLE_PRIORITY is zero. */ &xIdleTaskHandle ); /*lint !e961 MISRA exception, justified as it is not a redundant explicit cast to all supported compilers. */ } #endif /* configSUPPORT_STATIC_ALLOCATION */
/* 如果使能了软件定时器,还会创建一个软件定时器 */ #if ( configUSE_TIMERS == 1 ) { if( xReturn == pdPASS ) { xReturn = xTimerCreateTimerTask(); } else { mtCOVERAGE_TEST_MARKER(); } } #endif /* configUSE_TIMERS */
if( xReturn == pdPASS ) { /* freertos_tasks_c_additions_init() should only be called if the user definable macro FREERTOS_TASKS_C_ADDITIONS_INIT() is defined, as that is the only macro called by the function. */ #ifdef FREERTOS_TASKS_C_ADDITIONS_INIT { freertos_tasks_c_additions_init(); } #endif
/* Interrupts are turned off here, to ensure a tick does not occur before or during the call to xPortStartScheduler(). The stacks of the created tasks contain a status word with interrupts switched on so interrupts will automatically get re-enabled when the first task starts to run. 此处关闭中断,以确保不会发生滴答声 在呼叫 xPortstarts 计划之前或期间 ()。 堆栈 创建的任务包含打开中断的状态字 因此,当第一个任务完成时,中断会自动重新启用 开始运行。 */ portDISABLE_INTERRUPTS();
#if ( configUSE_NEWLIB_REENTRANT == 1 ) { /* Switch Newlib's _impure_ptr variable to point to the _reent structure specific to the task that will run first. */ _impure_ptr = &( pxCurrentTCB->xNewLib_reent ); } #endif /* configUSE_NEWLIB_REENTRANT */
/* 下一个任务锁定时间赋值为最大 不让时间片进行调度 */ xNextTaskUnblockTime = portMAX_DELAY; xSchedulerRunning = pdTRUE; //调度器的运行状态置位,标记开始运行了 xTickCount = ( TickType_t ) configINITIAL_TICK_COUNT; //初始化 系统的节拍值为0
/* If configGENERATE_RUN_TIME_STATS is defined then the following macro must be defined to configure the timer/counter used to generate the run time counter time base. NOTE: If configGENERATE_RUN_TIME_STATS is set to 0 and the following line fails to build then ensure you do not have portCONFIGURE_TIMER_FOR_RUN_TIME_STATS() defined in your FreeRTOSConfig.h file. */ portCONFIGURE_TIMER_FOR_RUN_TIME_STATS();
traceTASK_SWITCHED_IN();
/* Setting up the timer tick is hardware specific and thus in the portable interface. 启动调度器 */ if( xPortStartScheduler() != pdFALSE ) { /* Should not reach here as if the scheduler is running the function will not return. */ } else { /* Should only reach here if a task calls xTaskEndScheduler(). */ } } else { /* This line will only be reached if the kernel could not be started, because there was not enough FreeRTOS heap to create the idle task or the timer task. 只有在无法启动内核时才能到达此行, 因为没有足够的自由 BrTAS 堆来创建空闲任务 或时间器任务。 */ configASSERT( xReturn != errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY ); }
/* Prevent compiler warnings if INCLUDE_xTaskGetIdleTaskHandle is set to 0, meaning xIdleTaskHandle is not used anywhere else. */ ( void ) xIdleTaskHandle;}
复制代码

xPortStartScheduler

启动调度器xPortStartScheduler


/* * See header file for description. */BaseType_t xPortStartScheduler( void ){  /*  前面一大段不用深入了解,先不看,我们找到配置 systick pendsv开始   */  /* configMAX_SYSCALL_INTERRUPT_PRIORITY must not be set to 0.  See http://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html */  configASSERT( configMAX_SYSCALL_INTERRUPT_PRIORITY );
/* This port can be used on all revisions of the Cortex-M7 core other than the r0p1 parts. r0p1 parts should use the port from the /source/portable/GCC/ARM_CM7/r0p1 directory. */ configASSERT( portCPUID != portCORTEX_M7_r0p1_ID ); configASSERT( portCPUID != portCORTEX_M7_r0p0_ID );
#if( configASSERT_DEFINED == 1 ) { volatile uint32_t ulOriginalPriority; volatile uint8_t * const pucFirstUserPriorityRegister = ( volatile uint8_t * const ) ( portNVIC_IP_REGISTERS_OFFSET_16 + portFIRST_USER_INTERRUPT_NUMBER ); volatile uint8_t ucMaxPriorityValue;
/* Determine the maximum priority from which ISR safe FreeRTOS API functions can be called. ISR safe functions are those that end in "FromISR". FreeRTOS maintains separate thread and ISR API functions to ensure interrupt entry is as fast and simple as possible.
Save the interrupt priority value that is about to be clobbered. */ ulOriginalPriority = *pucFirstUserPriorityRegister;
/* Determine the number of priority bits available. First write to all possible bits. */ *pucFirstUserPriorityRegister = portMAX_8_BIT_VALUE;
/* Read the value back to see how many bits stuck. */ ucMaxPriorityValue = *pucFirstUserPriorityRegister;
/* Use the same mask on the maximum system call priority. */ ucMaxSysCallPriority = configMAX_SYSCALL_INTERRUPT_PRIORITY & ucMaxPriorityValue;
/* Calculate the maximum acceptable priority group value for the number of bits read back. */ ulMaxPRIGROUPValue = portMAX_PRIGROUP_BITS; while( ( ucMaxPriorityValue & portTOP_BIT_OF_BYTE ) == portTOP_BIT_OF_BYTE ) { ulMaxPRIGROUPValue--; ucMaxPriorityValue <<= ( uint8_t ) 0x01; }
#ifdef __NVIC_PRIO_BITS { /* Check the CMSIS configuration that defines the number of priority bits matches the number of priority bits actually queried from the hardware. */ configASSERT( ( portMAX_PRIGROUP_BITS - ulMaxPRIGROUPValue ) == __NVIC_PRIO_BITS ); } #endif
#ifdef configPRIO_BITS { /* Check the FreeRTOS configuration that defines the number of priority bits matches the number of priority bits actually queried from the hardware. */ configASSERT( ( portMAX_PRIGROUP_BITS - ulMaxPRIGROUPValue ) == configPRIO_BITS ); } #endif
/* Shift the priority group value back to its position within the AIRCR register. */ ulMaxPRIGROUPValue <<= portPRIGROUP_SHIFT; ulMaxPRIGROUPValue &= portPRIORITY_GROUP_MASK;
/* Restore the clobbered interrupt priority register to its original value. */ *pucFirstUserPriorityRegister = ulOriginalPriority; } #endif /* conifgASSERT_DEFINED */
/* Make PendSV and SysTick the lowest priority interrupts. 配置 systick pendsv为最低的优先级,为了保证系统的实时性 */ portNVIC_SYSPRI2_REG |= portNVIC_PENDSV_PRI; portNVIC_SYSPRI2_REG |= portNVIC_SYSTICK_PRI;
/* Start the timer that generates the tick ISR. Interrupts are disabled here already. 1、初始化systick----》配置为1ms的中断产生时基 2、开启systick中断 */ vPortSetupTimerInterrupt();
/* Initialise the critical nesting count ready for the first task. 初始化关键嵌套计数,为第一个任务做好准备。 临界段? */ uxCriticalNesting = 0;
/* Ensure the VFP is enabled - it should be anyway. 初始化浮点数寄存器 M4特有,需要初始化 */ vPortEnableVFP();
/* Lazy save always. */ *( portFPCCR ) |= portASPEN_AND_LSPEN_BITS;
/* Start the first task. 启动第一个任务 */ prvPortStartFirstTask();
/* Should never get here as the tasks will now be executing! Call the task exit error function to prevent compiler warnings about a static function not being called in the case that the application writer overrides this functionality by defining configTASK_RETURN_ADDRESS. Call vTaskSwitchContext() so link time optimisation does not remove the symbol. */ vTaskSwitchContext(); prvTaskExitError();
/* Should not get here! */ return 0;}
复制代码

prvPortStartFirstTask

启动第一个任务prvPortStartFirstTask


static void prvPortStartFirstTask( void ){  /* Start the first task.  This also clears the bit that indicates the FPU is  in use in case the FPU was used before the scheduler was started - which  would otherwise result in the unnecessary leaving of space in the SVC stack  for lazy saving of FPU registers. */  __asm volatile(          /*             0xE000ED08 它是中断向量表的一个地址            它存储的是MSP的指针            最终获取到MSP的RAM的地址          */          " ldr r0, =0xE000ED08   \n" /* Use the NVIC offset register to locate the stack. */          " ldr r0, [r0]       \n"          " ldr r0, [r0]       \n"          /*             Set the msp back to the start of the stack.             重新把MSP的地址,赋值为MSP             为什么需要加这一步,如果我们有在线升级功能            使用了我们用户的Bootloder,            中断向量表会更新,所以要重新赋值MSP          */          " msr msp, r0      \n" /* Set the msp back to the start of the stack. 把MSP的地址,赋值为MSP */          " mov r0, #0      \n" /* Clear the bit that indicates the FPU is in use, see comment above. */          " msr control, r0    \n"          " cpsie i        \n" /* Globally enable interrupts. 开启全局中断 */          " cpsie f        \n"          " dsb          \n"          " isb          \n"          " svc 0          \n" /* System call to start first task. 调用SVC */          " nop          \n"        );}/*-----------------------------------------------------------*/
复制代码


发布于: 刚刚阅读数: 5
用户头像

矜辰所致

关注

CSDN、知乎、微信公众号: 矜辰所致 2022.08.02 加入

不浮夸,不将就,认真对待学知识的我们,矜辰所致,金石为开! 为了活下去的嵌入式工程师,画画板子,敲敲代码,玩玩RTOS,搞搞Linux ...

评论

发布
暂无评论
FreeRTOS记录(三、RTOS任务调度原理解析_Systick、PendSV、SVC)_Svc_矜辰所致_InfoQ写作社区