port.c 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822
  1. /*
  2. * FreeRTOS Kernel <DEVELOPMENT BRANCH>
  3. * Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
  4. *
  5. * SPDX-License-Identifier: MIT
  6. *
  7. * Permission is hereby granted, free of charge, to any person obtaining a copy of
  8. * this software and associated documentation files (the "Software"), to deal in
  9. * the Software without restriction, including without limitation the rights to
  10. * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
  11. * the Software, and to permit persons to whom the Software is furnished to do so,
  12. * subject to the following conditions:
  13. *
  14. * The above copyright notice and this permission notice shall be included in all
  15. * copies or substantial portions of the Software.
  16. *
  17. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
  19. * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
  20. * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
  21. * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  22. * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  23. *
  24. * https://www.FreeRTOS.org
  25. * https://github.com/FreeRTOS
  26. *
  27. */
  28. /*-----------------------------------------------------------
  29. * Implementation of functions defined in portable.h for the ARM CM3 port.
  30. *----------------------------------------------------------*/
  31. /* Scheduler includes. */
  32. #include "FreeRTOS.h"
  33. #include "task.h"
  34. /* Prototype of all Interrupt Service Routines (ISRs). */
  35. typedef void ( * portISR_t )( void );
  36. /* Constants required to manipulate the core. Registers first... */
  37. #define portNVIC_SYSTICK_CTRL_REG ( *( ( volatile uint32_t * ) 0xe000e010 ) )
  38. #define portNVIC_SYSTICK_LOAD_REG ( *( ( volatile uint32_t * ) 0xe000e014 ) )
  39. #define portNVIC_SYSTICK_CURRENT_VALUE_REG ( *( ( volatile uint32_t * ) 0xe000e018 ) )
  40. #define portNVIC_SHPR2_REG ( *( ( volatile uint32_t * ) 0xe000ed1c ) )
  41. #define portNVIC_SHPR3_REG ( *( ( volatile uint32_t * ) 0xe000ed20 ) )
  42. /* ...then bits in the registers. */
  43. #define portNVIC_SYSTICK_CLK_BIT ( 1UL << 2UL )
  44. #define portNVIC_SYSTICK_INT_BIT ( 1UL << 1UL )
  45. #define portNVIC_SYSTICK_ENABLE_BIT ( 1UL << 0UL )
  46. #define portNVIC_SYSTICK_COUNT_FLAG_BIT ( 1UL << 16UL )
  47. #define portNVIC_PENDSVCLEAR_BIT ( 1UL << 27UL )
  48. #define portNVIC_PEND_SYSTICK_SET_BIT ( 1UL << 26UL )
  49. #define portNVIC_PEND_SYSTICK_CLEAR_BIT ( 1UL << 25UL )
  50. #define portMIN_INTERRUPT_PRIORITY ( 255UL )
  51. #define portNVIC_PENDSV_PRI ( ( ( uint32_t ) portMIN_INTERRUPT_PRIORITY ) << 16UL )
  52. #define portNVIC_SYSTICK_PRI ( ( ( uint32_t ) portMIN_INTERRUPT_PRIORITY ) << 24UL )
  53. /* Constants used to check the installation of the FreeRTOS interrupt handlers. */
  54. #define portSCB_VTOR_REG ( *( ( portISR_t ** ) 0xE000ED08 ) )
  55. #define portVECTOR_INDEX_SVC ( 11 )
  56. #define portVECTOR_INDEX_PENDSV ( 14 )
  57. /* Constants required to check the validity of an interrupt priority. */
  58. #define portFIRST_USER_INTERRUPT_NUMBER ( 16 )
  59. #define portNVIC_IP_REGISTERS_OFFSET_16 ( 0xE000E3F0 )
  60. #define portAIRCR_REG ( *( ( volatile uint32_t * ) 0xE000ED0C ) )
  61. #define portMAX_8_BIT_VALUE ( ( uint8_t ) 0xff )
  62. #define portTOP_BIT_OF_BYTE ( ( uint8_t ) 0x80 )
  63. #define portMAX_PRIGROUP_BITS ( ( uint8_t ) 7 )
  64. #define portPRIORITY_GROUP_MASK ( 0x07UL << 8UL )
  65. #define portPRIGROUP_SHIFT ( 8UL )
  66. /* Masks off all bits but the VECTACTIVE bits in the ICSR register. */
  67. #define portVECTACTIVE_MASK ( 0xFFUL )
  68. /* Constants required to set up the initial stack. */
  69. #define portINITIAL_XPSR ( 0x01000000UL )
  70. /* The systick is a 24-bit counter. */
  71. #define portMAX_24_BIT_NUMBER ( 0xffffffUL )
  72. /* A fiddle factor to estimate the number of SysTick counts that would have
  73. * occurred while the SysTick counter is stopped during tickless idle
  74. * calculations. */
  75. #define portMISSED_COUNTS_FACTOR ( 94UL )
  76. /* For strict compliance with the Cortex-M spec the task start address should
  77. * have bit-0 clear, as it is loaded into the PC on exit from an ISR. */
  78. #define portSTART_ADDRESS_MASK ( ( StackType_t ) 0xfffffffeUL )
  79. /* Let the user override the default SysTick clock rate. If defined by the
  80. * user, this symbol must equal the SysTick clock rate when the CLK bit is 0 in the
  81. * configuration register. */
  82. #ifndef configSYSTICK_CLOCK_HZ
  83. #define configSYSTICK_CLOCK_HZ ( configCPU_CLOCK_HZ )
  84. /* Ensure the SysTick is clocked at the same frequency as the core. */
  85. #define portNVIC_SYSTICK_CLK_BIT_CONFIG ( portNVIC_SYSTICK_CLK_BIT )
  86. #else
  87. /* Select the option to clock SysTick not at the same frequency as the core. */
  88. #define portNVIC_SYSTICK_CLK_BIT_CONFIG ( 0 )
  89. #endif
  90. /* Let the user override the pre-loading of the initial LR with the address of
  91. * prvTaskExitError() in case it messes up unwinding of the stack in the
  92. * debugger. */
  93. #ifdef configTASK_RETURN_ADDRESS
  94. #define portTASK_RETURN_ADDRESS configTASK_RETURN_ADDRESS
  95. #else
  96. #define portTASK_RETURN_ADDRESS prvTaskExitError
  97. #endif
  98. /*
  99. * Setup the timer to generate the tick interrupts. The implementation in this
  100. * file is weak to allow application writers to change the timer used to
  101. * generate the tick interrupt.
  102. */
  103. void vPortSetupTimerInterrupt( void );
  104. /*
  105. * Exception handlers.
  106. */
  107. void xPortPendSVHandler( void ) __attribute__( ( naked ) );
  108. void xPortSysTickHandler( void );
  109. void vPortSVCHandler( void ) __attribute__( ( naked ) );
  110. /*
  111. * Start first task is a separate function so it can be tested in isolation.
  112. */
  113. static void prvPortStartFirstTask( void ) __attribute__( ( naked ) );
  114. /*
  115. * Used to catch tasks that attempt to return from their implementing function.
  116. */
  117. static void prvTaskExitError( void );
  118. /*-----------------------------------------------------------*/
  119. /* Each task maintains its own interrupt status in the critical nesting
  120. * variable. */
  121. static UBaseType_t uxCriticalNesting = 0xaaaaaaaa;
  122. /*
  123. * The number of SysTick increments that make up one tick period.
  124. */
  125. #if ( configUSE_TICKLESS_IDLE == 1 )
  126. static uint32_t ulTimerCountsForOneTick = 0;
  127. #endif /* configUSE_TICKLESS_IDLE */
  128. /*
  129. * The maximum number of tick periods that can be suppressed is limited by the
  130. * 24 bit resolution of the SysTick timer.
  131. */
  132. #if ( configUSE_TICKLESS_IDLE == 1 )
  133. static uint32_t xMaximumPossibleSuppressedTicks = 0;
  134. #endif /* configUSE_TICKLESS_IDLE */
  135. /*
  136. * Compensate for the CPU cycles that pass while the SysTick is stopped (low
  137. * power functionality only.
  138. */
  139. #if ( configUSE_TICKLESS_IDLE == 1 )
  140. static uint32_t ulStoppedTimerCompensation = 0;
  141. #endif /* configUSE_TICKLESS_IDLE */
  142. /*
  143. * Used by the portASSERT_IF_INTERRUPT_PRIORITY_INVALID() macro to ensure
  144. * FreeRTOS API functions are not called from interrupts that have been assigned
  145. * a priority above configMAX_SYSCALL_INTERRUPT_PRIORITY.
  146. */
  147. #if ( configASSERT_DEFINED == 1 )
  148. static uint8_t ucMaxSysCallPriority = 0;
  149. static uint32_t ulMaxPRIGROUPValue = 0;
  150. static const volatile uint8_t * const pcInterruptPriorityRegisters = ( const volatile uint8_t * const ) portNVIC_IP_REGISTERS_OFFSET_16;
  151. #endif /* configASSERT_DEFINED */
  152. /*-----------------------------------------------------------*/
  153. /*
  154. * See header file for description.
  155. */
  156. StackType_t * pxPortInitialiseStack( StackType_t * pxTopOfStack,
  157. TaskFunction_t pxCode,
  158. void * pvParameters )
  159. {
  160. /* Simulate the stack frame as it would be created by a context switch
  161. * interrupt. */
  162. pxTopOfStack--; /* Offset added to account for the way the MCU uses the stack on entry/exit of interrupts. */
  163. *pxTopOfStack = portINITIAL_XPSR; /* xPSR */
  164. pxTopOfStack--;
  165. *pxTopOfStack = ( ( StackType_t ) pxCode ) & portSTART_ADDRESS_MASK; /* PC */
  166. pxTopOfStack--;
  167. *pxTopOfStack = ( StackType_t ) portTASK_RETURN_ADDRESS; /* LR */
  168. pxTopOfStack -= 5; /* R12, R3, R2 and R1. */
  169. *pxTopOfStack = ( StackType_t ) pvParameters; /* R0 */
  170. pxTopOfStack -= 8; /* R11, R10, R9, R8, R7, R6, R5 and R4. */
  171. return pxTopOfStack;
  172. }
  173. /*-----------------------------------------------------------*/
  174. static void prvTaskExitError( void )
  175. {
  176. volatile uint32_t ulDummy = 0UL;
  177. /* A function that implements a task must not exit or attempt to return to
  178. * its caller as there is nothing to return to. If a task wants to exit it
  179. * should instead call vTaskDelete( NULL ).
  180. *
  181. * Artificially force an assert() to be triggered if configASSERT() is
  182. * defined, then stop here so application writers can catch the error. */
  183. configASSERT( uxCriticalNesting == ~0UL );
  184. portDISABLE_INTERRUPTS();
  185. while( ulDummy == 0 )
  186. {
  187. /* This file calls prvTaskExitError() after the scheduler has been
  188. * started to remove a compiler warning about the function being defined
  189. * but never called. ulDummy is used purely to quieten other warnings
  190. * about code appearing after this function is called - making ulDummy
  191. * volatile makes the compiler think the function could return and
  192. * therefore not output an 'unreachable code' warning for code that appears
  193. * after it. */
  194. }
  195. }
  196. /*-----------------------------------------------------------*/
  197. void vPortSVCHandler( void )
  198. {
  199. __asm volatile (
  200. " ldr r3, =pxCurrentTCB \n" /* Restore the context. */
  201. " ldr r1, [r3] \n" /* Get the pxCurrentTCB address. */
  202. " ldr r0, [r1] \n" /* The first item in pxCurrentTCB is the task top of stack. */
  203. " ldmia r0!, {r4-r11} \n" /* Pop the registers that are not automatically saved on exception entry and the critical nesting count. */
  204. " msr psp, r0 \n" /* Restore the task stack pointer. */
  205. " isb \n"
  206. " mov r0, #0 \n"
  207. " msr basepri, r0 \n"
  208. " orr r14, #0xd \n"
  209. " bx r14 \n"
  210. " \n"
  211. " .ltorg \n"
  212. );
  213. }
  214. /*-----------------------------------------------------------*/
  215. static void prvPortStartFirstTask( void )
  216. {
  217. __asm volatile (
  218. " ldr r0, =0xE000ED08 \n" /* Use the NVIC offset register to locate the stack. */
  219. " ldr r0, [r0] \n"
  220. " ldr r0, [r0] \n"
  221. " msr msp, r0 \n" /* Set the msp back to the start of the stack. */
  222. " cpsie i \n" /* Globally enable interrupts. */
  223. " cpsie f \n"
  224. " dsb \n"
  225. " isb \n"
  226. " svc 0 \n" /* System call to start first task. */
  227. " nop \n"
  228. " .ltorg \n"
  229. );
  230. }
  231. /*-----------------------------------------------------------*/
  232. /*
  233. * See header file for description.
  234. */
  235. BaseType_t xPortStartScheduler( void )
  236. {
  237. /* An application can install FreeRTOS interrupt handlers in one of the
  238. * following ways:
  239. * 1. Direct Routing - Install the functions vPortSVCHandler and
  240. * xPortPendSVHandler for SVCall and PendSV interrupts respectively.
  241. * 2. Indirect Routing - Install separate handlers for SVCall and PendSV
  242. * interrupts and route program control from those handlers to
  243. * vPortSVCHandler and xPortPendSVHandler functions.
  244. *
  245. * Applications that use Indirect Routing must set
  246. * configCHECK_HANDLER_INSTALLATION to 0 in their FreeRTOSConfig.h. Direct
  247. * routing, which is validated here when configCHECK_HANDLER_INSTALLATION
  248. * is 1, should be preferred when possible. */
  249. #if ( configCHECK_HANDLER_INSTALLATION == 1 )
  250. {
  251. const portISR_t * const pxVectorTable = portSCB_VTOR_REG;
  252. /* Validate that the application has correctly installed the FreeRTOS
  253. * handlers for SVCall and PendSV interrupts. We do not check the
  254. * installation of the SysTick handler because the application may
  255. * choose to drive the RTOS tick using a timer other than the SysTick
  256. * timer by overriding the weak function vPortSetupTimerInterrupt().
  257. *
  258. * Assertion failures here indicate incorrect installation of the
  259. * FreeRTOS handlers. For help installing the FreeRTOS handlers, see
  260. * https://www.freertos.org/Why-FreeRTOS/FAQs.
  261. *
  262. * Systems with a configurable address for the interrupt vector table
  263. * can also encounter assertion failures or even system faults here if
  264. * VTOR is not set correctly to point to the application's vector table. */
  265. configASSERT( pxVectorTable[ portVECTOR_INDEX_SVC ] == vPortSVCHandler );
  266. configASSERT( pxVectorTable[ portVECTOR_INDEX_PENDSV ] == xPortPendSVHandler );
  267. }
  268. #endif /* configCHECK_HANDLER_INSTALLATION */
  269. #if ( configASSERT_DEFINED == 1 )
  270. {
  271. volatile uint8_t ucOriginalPriority;
  272. volatile uint32_t ulImplementedPrioBits = 0;
  273. volatile uint8_t * const pucFirstUserPriorityRegister = ( volatile uint8_t * const ) ( portNVIC_IP_REGISTERS_OFFSET_16 + portFIRST_USER_INTERRUPT_NUMBER );
  274. volatile uint8_t ucMaxPriorityValue;
  275. /* Determine the maximum priority from which ISR safe FreeRTOS API
  276. * functions can be called. ISR safe functions are those that end in
  277. * "FromISR". FreeRTOS maintains separate thread and ISR API functions to
  278. * ensure interrupt entry is as fast and simple as possible.
  279. *
  280. * Save the interrupt priority value that is about to be clobbered. */
  281. ucOriginalPriority = *pucFirstUserPriorityRegister;
  282. /* Determine the number of priority bits available. First write to all
  283. * possible bits. */
  284. *pucFirstUserPriorityRegister = portMAX_8_BIT_VALUE;
  285. /* Read the value back to see how many bits stuck. */
  286. ucMaxPriorityValue = *pucFirstUserPriorityRegister;
  287. /* Use the same mask on the maximum system call priority. */
  288. ucMaxSysCallPriority = configMAX_SYSCALL_INTERRUPT_PRIORITY & ucMaxPriorityValue;
  289. /* Check that the maximum system call priority is nonzero after
  290. * accounting for the number of priority bits supported by the
  291. * hardware. A priority of 0 is invalid because setting the BASEPRI
  292. * register to 0 unmasks all interrupts, and interrupts with priority 0
  293. * cannot be masked using BASEPRI.
  294. * See https://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html */
  295. configASSERT( ucMaxSysCallPriority );
  296. /* Check that the bits not implemented in hardware are zero in
  297. * configMAX_SYSCALL_INTERRUPT_PRIORITY. */
  298. configASSERT( ( configMAX_SYSCALL_INTERRUPT_PRIORITY & ( ~ucMaxPriorityValue ) ) == 0U );
  299. /* Calculate the maximum acceptable priority group value for the number
  300. * of bits read back. */
  301. while( ( ucMaxPriorityValue & portTOP_BIT_OF_BYTE ) == portTOP_BIT_OF_BYTE )
  302. {
  303. ulImplementedPrioBits++;
  304. ucMaxPriorityValue <<= ( uint8_t ) 0x01;
  305. }
  306. if( ulImplementedPrioBits == 8 )
  307. {
  308. /* When the hardware implements 8 priority bits, there is no way for
  309. * the software to configure PRIGROUP to not have sub-priorities. As
  310. * a result, the least significant bit is always used for sub-priority
  311. * and there are 128 preemption priorities and 2 sub-priorities.
  312. *
  313. * This may cause some confusion in some cases - for example, if
  314. * configMAX_SYSCALL_INTERRUPT_PRIORITY is set to 5, both 5 and 4
  315. * priority interrupts will be masked in Critical Sections as those
  316. * are at the same preemption priority. This may appear confusing as
  317. * 4 is higher (numerically lower) priority than
  318. * configMAX_SYSCALL_INTERRUPT_PRIORITY and therefore, should not
  319. * have been masked. Instead, if we set configMAX_SYSCALL_INTERRUPT_PRIORITY
  320. * to 4, this confusion does not happen and the behaviour remains the same.
  321. *
  322. * The following assert ensures that the sub-priority bit in the
  323. * configMAX_SYSCALL_INTERRUPT_PRIORITY is clear to avoid the above mentioned
  324. * confusion. */
  325. configASSERT( ( configMAX_SYSCALL_INTERRUPT_PRIORITY & 0x1U ) == 0U );
  326. ulMaxPRIGROUPValue = 0;
  327. }
  328. else
  329. {
  330. ulMaxPRIGROUPValue = portMAX_PRIGROUP_BITS - ulImplementedPrioBits;
  331. }
  332. /* Shift the priority group value back to its position within the AIRCR
  333. * register. */
  334. ulMaxPRIGROUPValue <<= portPRIGROUP_SHIFT;
  335. ulMaxPRIGROUPValue &= portPRIORITY_GROUP_MASK;
  336. /* Restore the clobbered interrupt priority register to its original
  337. * value. */
  338. *pucFirstUserPriorityRegister = ucOriginalPriority;
  339. }
  340. #endif /* configASSERT_DEFINED */
  341. /* Make PendSV and SysTick the lowest priority interrupts, and make SVCall
  342. * the highest priority. */
  343. portNVIC_SHPR3_REG |= portNVIC_PENDSV_PRI;
  344. portNVIC_SHPR3_REG |= portNVIC_SYSTICK_PRI;
  345. portNVIC_SHPR2_REG = 0;
  346. /* Start the timer that generates the tick ISR. Interrupts are disabled
  347. * here already. */
  348. vPortSetupTimerInterrupt();
  349. /* Initialise the critical nesting count ready for the first task. */
  350. uxCriticalNesting = 0;
  351. /* Start the first task. */
  352. prvPortStartFirstTask();
  353. /* Should never get here as the tasks will now be executing! Call the task
  354. * exit error function to prevent compiler warnings about a static function
  355. * not being called in the case that the application writer overrides this
  356. * functionality by defining configTASK_RETURN_ADDRESS. Call
  357. * vTaskSwitchContext() so link time optimisation does not remove the
  358. * symbol. */
  359. vTaskSwitchContext();
  360. prvTaskExitError();
  361. /* Should not get here! */
  362. return 0;
  363. }
  364. /*-----------------------------------------------------------*/
  365. void vPortEndScheduler( void )
  366. {
  367. /* Not implemented in ports where there is nothing to return to.
  368. * Artificially force an assert. */
  369. configASSERT( uxCriticalNesting == 1000UL );
  370. }
  371. /*-----------------------------------------------------------*/
  372. void vPortEnterCritical( void )
  373. {
  374. portDISABLE_INTERRUPTS();
  375. uxCriticalNesting++;
  376. /* This is not the interrupt safe version of the enter critical function so
  377. * assert() if it is being called from an interrupt context. Only API
  378. * functions that end in "FromISR" can be used in an interrupt. Only assert if
  379. * the critical nesting count is 1 to protect against recursive calls if the
  380. * assert function also uses a critical section. */
  381. if( uxCriticalNesting == 1 )
  382. {
  383. configASSERT( ( portNVIC_INT_CTRL_REG & portVECTACTIVE_MASK ) == 0 );
  384. }
  385. }
  386. /*-----------------------------------------------------------*/
  387. void vPortExitCritical( void )
  388. {
  389. configASSERT( uxCriticalNesting );
  390. uxCriticalNesting--;
  391. if( uxCriticalNesting == 0 )
  392. {
  393. portENABLE_INTERRUPTS();
  394. }
  395. }
  396. /*-----------------------------------------------------------*/
  397. void xPortPendSVHandler( void )
  398. {
  399. /* This is a naked function. */
  400. __asm volatile
  401. (
  402. " mrs r0, psp \n"
  403. " isb \n"
  404. " \n"
  405. " ldr r3, =pxCurrentTCB \n" /* Get the location of the current TCB. */
  406. " ldr r2, [r3] \n"
  407. " \n"
  408. " stmdb r0!, {r4-r11} \n" /* Save the remaining registers. */
  409. " str r0, [r2] \n" /* Save the new top of stack into the first member of the TCB. */
  410. " \n"
  411. " stmdb sp!, {r3, r14} \n"
  412. " mov r0, %0 \n"
  413. " msr basepri, r0 \n"
  414. " bl vTaskSwitchContext \n"
  415. " mov r0, #0 \n"
  416. " msr basepri, r0 \n"
  417. " ldmia sp!, {r3, r14} \n"
  418. " \n" /* Restore the context, including the critical nesting count. */
  419. " ldr r1, [r3] \n"
  420. " ldr r0, [r1] \n" /* The first item in pxCurrentTCB is the task top of stack. */
  421. " ldmia r0!, {r4-r11} \n" /* Pop the registers. */
  422. " msr psp, r0 \n"
  423. " isb \n"
  424. " bx r14 \n"
  425. " \n"
  426. " .ltorg \n"
  427. ::"i" ( configMAX_SYSCALL_INTERRUPT_PRIORITY )
  428. );
  429. }
  430. /*-----------------------------------------------------------*/
  431. void xPortSysTickHandler( void )
  432. {
  433. /* The SysTick runs at the lowest interrupt priority, so when this interrupt
  434. * executes all interrupts must be unmasked. There is therefore no need to
  435. * save and then restore the interrupt mask value as its value is already
  436. * known. */
  437. portDISABLE_INTERRUPTS();
  438. traceISR_ENTER();
  439. {
  440. /* Increment the RTOS tick. */
  441. if( xTaskIncrementTick() != pdFALSE )
  442. {
  443. traceISR_EXIT_TO_SCHEDULER();
  444. /* A context switch is required. Context switching is performed in
  445. * the PendSV interrupt. Pend the PendSV interrupt. */
  446. portNVIC_INT_CTRL_REG = portNVIC_PENDSVSET_BIT;
  447. }
  448. else
  449. {
  450. traceISR_EXIT();
  451. }
  452. }
  453. portENABLE_INTERRUPTS();
  454. }
  455. /*-----------------------------------------------------------*/
  456. #if ( configUSE_TICKLESS_IDLE == 1 )
  457. __attribute__( ( weak ) ) void vPortSuppressTicksAndSleep( TickType_t xExpectedIdleTime )
  458. {
  459. uint32_t ulReloadValue, ulCompleteTickPeriods, ulCompletedSysTickDecrements, ulSysTickDecrementsLeft;
  460. TickType_t xModifiableIdleTime;
  461. /* Make sure the SysTick reload value does not overflow the counter. */
  462. if( xExpectedIdleTime > xMaximumPossibleSuppressedTicks )
  463. {
  464. xExpectedIdleTime = xMaximumPossibleSuppressedTicks;
  465. }
  466. /* Enter a critical section but don't use the taskENTER_CRITICAL()
  467. * method as that will mask interrupts that should exit sleep mode. */
  468. __asm volatile ( "cpsid i" ::: "memory" );
  469. __asm volatile ( "dsb" );
  470. __asm volatile ( "isb" );
  471. /* If a context switch is pending or a task is waiting for the scheduler
  472. * to be unsuspended then abandon the low power entry. */
  473. if( eTaskConfirmSleepModeStatus() == eAbortSleep )
  474. {
  475. /* Re-enable interrupts - see comments above the cpsid instruction
  476. * above. */
  477. __asm volatile ( "cpsie i" ::: "memory" );
  478. }
  479. else
  480. {
  481. /* Stop the SysTick momentarily. The time the SysTick is stopped for
  482. * is accounted for as best it can be, but using the tickless mode will
  483. * inevitably result in some tiny drift of the time maintained by the
  484. * kernel with respect to calendar time. */
  485. portNVIC_SYSTICK_CTRL_REG = ( portNVIC_SYSTICK_CLK_BIT_CONFIG | portNVIC_SYSTICK_INT_BIT );
  486. /* Use the SysTick current-value register to determine the number of
  487. * SysTick decrements remaining until the next tick interrupt. If the
  488. * current-value register is zero, then there are actually
  489. * ulTimerCountsForOneTick decrements remaining, not zero, because the
  490. * SysTick requests the interrupt when decrementing from 1 to 0. */
  491. ulSysTickDecrementsLeft = portNVIC_SYSTICK_CURRENT_VALUE_REG;
  492. if( ulSysTickDecrementsLeft == 0 )
  493. {
  494. ulSysTickDecrementsLeft = ulTimerCountsForOneTick;
  495. }
  496. /* Calculate the reload value required to wait xExpectedIdleTime
  497. * tick periods. -1 is used because this code normally executes part
  498. * way through the first tick period. But if the SysTick IRQ is now
  499. * pending, then clear the IRQ, suppressing the first tick, and correct
  500. * the reload value to reflect that the second tick period is already
  501. * underway. The expected idle time is always at least two ticks. */
  502. ulReloadValue = ulSysTickDecrementsLeft + ( ulTimerCountsForOneTick * ( xExpectedIdleTime - 1UL ) );
  503. if( ( portNVIC_INT_CTRL_REG & portNVIC_PEND_SYSTICK_SET_BIT ) != 0 )
  504. {
  505. portNVIC_INT_CTRL_REG = portNVIC_PEND_SYSTICK_CLEAR_BIT;
  506. ulReloadValue -= ulTimerCountsForOneTick;
  507. }
  508. if( ulReloadValue > ulStoppedTimerCompensation )
  509. {
  510. ulReloadValue -= ulStoppedTimerCompensation;
  511. }
  512. /* Set the new reload value. */
  513. portNVIC_SYSTICK_LOAD_REG = ulReloadValue;
  514. /* Clear the SysTick count flag and set the count value back to
  515. * zero. */
  516. portNVIC_SYSTICK_CURRENT_VALUE_REG = 0UL;
  517. /* Restart SysTick. */
  518. portNVIC_SYSTICK_CTRL_REG |= portNVIC_SYSTICK_ENABLE_BIT;
  519. /* Sleep until something happens. configPRE_SLEEP_PROCESSING() can
  520. * set its parameter to 0 to indicate that its implementation contains
  521. * its own wait for interrupt or wait for event instruction, and so wfi
  522. * should not be executed again. However, the original expected idle
  523. * time variable must remain unmodified, so a copy is taken. */
  524. xModifiableIdleTime = xExpectedIdleTime;
  525. configPRE_SLEEP_PROCESSING( xModifiableIdleTime );
  526. if( xModifiableIdleTime > 0 )
  527. {
  528. __asm volatile ( "dsb" ::: "memory" );
  529. __asm volatile ( "wfi" );
  530. __asm volatile ( "isb" );
  531. }
  532. configPOST_SLEEP_PROCESSING( xExpectedIdleTime );
  533. /* Re-enable interrupts to allow the interrupt that brought the MCU
  534. * out of sleep mode to execute immediately. See comments above
  535. * the cpsid instruction above. */
  536. __asm volatile ( "cpsie i" ::: "memory" );
  537. __asm volatile ( "dsb" );
  538. __asm volatile ( "isb" );
  539. /* Disable interrupts again because the clock is about to be stopped
  540. * and interrupts that execute while the clock is stopped will increase
  541. * any slippage between the time maintained by the RTOS and calendar
  542. * time. */
  543. __asm volatile ( "cpsid i" ::: "memory" );
  544. __asm volatile ( "dsb" );
  545. __asm volatile ( "isb" );
  546. /* Disable the SysTick clock without reading the
  547. * portNVIC_SYSTICK_CTRL_REG register to ensure the
  548. * portNVIC_SYSTICK_COUNT_FLAG_BIT is not cleared if it is set. Again,
  549. * the time the SysTick is stopped for is accounted for as best it can
  550. * be, but using the tickless mode will inevitably result in some tiny
  551. * drift of the time maintained by the kernel with respect to calendar
  552. * time*/
  553. portNVIC_SYSTICK_CTRL_REG = ( portNVIC_SYSTICK_CLK_BIT_CONFIG | portNVIC_SYSTICK_INT_BIT );
  554. /* Determine whether the SysTick has already counted to zero. */
  555. if( ( portNVIC_SYSTICK_CTRL_REG & portNVIC_SYSTICK_COUNT_FLAG_BIT ) != 0 )
  556. {
  557. uint32_t ulCalculatedLoadValue;
  558. /* The tick interrupt ended the sleep (or is now pending), and
  559. * a new tick period has started. Reset portNVIC_SYSTICK_LOAD_REG
  560. * with whatever remains of the new tick period. */
  561. ulCalculatedLoadValue = ( ulTimerCountsForOneTick - 1UL ) - ( ulReloadValue - portNVIC_SYSTICK_CURRENT_VALUE_REG );
  562. /* Don't allow a tiny value, or values that have somehow
  563. * underflowed because the post sleep hook did something
  564. * that took too long or because the SysTick current-value register
  565. * is zero. */
  566. if( ( ulCalculatedLoadValue <= ulStoppedTimerCompensation ) || ( ulCalculatedLoadValue > ulTimerCountsForOneTick ) )
  567. {
  568. ulCalculatedLoadValue = ( ulTimerCountsForOneTick - 1UL );
  569. }
  570. portNVIC_SYSTICK_LOAD_REG = ulCalculatedLoadValue;
  571. /* As the pending tick will be processed as soon as this
  572. * function exits, the tick value maintained by the tick is stepped
  573. * forward by one less than the time spent waiting. */
  574. ulCompleteTickPeriods = xExpectedIdleTime - 1UL;
  575. }
  576. else
  577. {
  578. /* Something other than the tick interrupt ended the sleep. */
  579. /* Use the SysTick current-value register to determine the
  580. * number of SysTick decrements remaining until the expected idle
  581. * time would have ended. */
  582. ulSysTickDecrementsLeft = portNVIC_SYSTICK_CURRENT_VALUE_REG;
  583. #if ( portNVIC_SYSTICK_CLK_BIT_CONFIG != portNVIC_SYSTICK_CLK_BIT )
  584. {
  585. /* If the SysTick is not using the core clock, the current-
  586. * value register might still be zero here. In that case, the
  587. * SysTick didn't load from the reload register, and there are
  588. * ulReloadValue decrements remaining in the expected idle
  589. * time, not zero. */
  590. if( ulSysTickDecrementsLeft == 0 )
  591. {
  592. ulSysTickDecrementsLeft = ulReloadValue;
  593. }
  594. }
  595. #endif /* portNVIC_SYSTICK_CLK_BIT_CONFIG */
  596. /* Work out how long the sleep lasted rounded to complete tick
  597. * periods (not the ulReload value which accounted for part
  598. * ticks). */
  599. ulCompletedSysTickDecrements = ( xExpectedIdleTime * ulTimerCountsForOneTick ) - ulSysTickDecrementsLeft;
  600. /* How many complete tick periods passed while the processor
  601. * was waiting? */
  602. ulCompleteTickPeriods = ulCompletedSysTickDecrements / ulTimerCountsForOneTick;
  603. /* The reload value is set to whatever fraction of a single tick
  604. * period remains. */
  605. portNVIC_SYSTICK_LOAD_REG = ( ( ulCompleteTickPeriods + 1UL ) * ulTimerCountsForOneTick ) - ulCompletedSysTickDecrements;
  606. }
  607. /* Restart SysTick so it runs from portNVIC_SYSTICK_LOAD_REG again,
  608. * then set portNVIC_SYSTICK_LOAD_REG back to its standard value. If
  609. * the SysTick is not using the core clock, temporarily configure it to
  610. * use the core clock. This configuration forces the SysTick to load
  611. * from portNVIC_SYSTICK_LOAD_REG immediately instead of at the next
  612. * cycle of the other clock. Then portNVIC_SYSTICK_LOAD_REG is ready
  613. * to receive the standard value immediately. */
  614. portNVIC_SYSTICK_CURRENT_VALUE_REG = 0UL;
  615. portNVIC_SYSTICK_CTRL_REG = portNVIC_SYSTICK_CLK_BIT | portNVIC_SYSTICK_INT_BIT | portNVIC_SYSTICK_ENABLE_BIT;
  616. #if ( portNVIC_SYSTICK_CLK_BIT_CONFIG == portNVIC_SYSTICK_CLK_BIT )
  617. {
  618. portNVIC_SYSTICK_LOAD_REG = ulTimerCountsForOneTick - 1UL;
  619. }
  620. #else
  621. {
  622. /* The temporary usage of the core clock has served its purpose,
  623. * as described above. Resume usage of the other clock. */
  624. portNVIC_SYSTICK_CTRL_REG = portNVIC_SYSTICK_CLK_BIT | portNVIC_SYSTICK_INT_BIT;
  625. if( ( portNVIC_SYSTICK_CTRL_REG & portNVIC_SYSTICK_COUNT_FLAG_BIT ) != 0 )
  626. {
  627. /* The partial tick period already ended. Be sure the SysTick
  628. * counts it only once. */
  629. portNVIC_SYSTICK_CURRENT_VALUE_REG = 0;
  630. }
  631. portNVIC_SYSTICK_LOAD_REG = ulTimerCountsForOneTick - 1UL;
  632. portNVIC_SYSTICK_CTRL_REG = portNVIC_SYSTICK_CLK_BIT_CONFIG | portNVIC_SYSTICK_INT_BIT | portNVIC_SYSTICK_ENABLE_BIT;
  633. }
  634. #endif /* portNVIC_SYSTICK_CLK_BIT_CONFIG */
  635. /* Step the tick to account for any tick periods that elapsed. */
  636. vTaskStepTick( ulCompleteTickPeriods );
  637. /* Exit with interrupts enabled. */
  638. __asm volatile ( "cpsie i" ::: "memory" );
  639. }
  640. }
  641. #endif /* configUSE_TICKLESS_IDLE */
  642. /*-----------------------------------------------------------*/
  643. /*
  644. * Setup the systick timer to generate the tick interrupts at the required
  645. * frequency.
  646. */
  647. __attribute__( ( weak ) ) void vPortSetupTimerInterrupt( void )
  648. {
  649. /* Calculate the constants required to configure the tick interrupt. */
  650. #if ( configUSE_TICKLESS_IDLE == 1 )
  651. {
  652. ulTimerCountsForOneTick = ( configSYSTICK_CLOCK_HZ / configTICK_RATE_HZ );
  653. xMaximumPossibleSuppressedTicks = portMAX_24_BIT_NUMBER / ulTimerCountsForOneTick;
  654. ulStoppedTimerCompensation = portMISSED_COUNTS_FACTOR / ( configCPU_CLOCK_HZ / configSYSTICK_CLOCK_HZ );
  655. }
  656. #endif /* configUSE_TICKLESS_IDLE */
  657. /* Stop and clear the SysTick. */
  658. portNVIC_SYSTICK_CTRL_REG = 0UL;
  659. portNVIC_SYSTICK_CURRENT_VALUE_REG = 0UL;
  660. /* Configure SysTick to interrupt at the requested rate. */
  661. portNVIC_SYSTICK_LOAD_REG = ( configSYSTICK_CLOCK_HZ / configTICK_RATE_HZ ) - 1UL;
  662. portNVIC_SYSTICK_CTRL_REG = ( portNVIC_SYSTICK_CLK_BIT_CONFIG | portNVIC_SYSTICK_INT_BIT | portNVIC_SYSTICK_ENABLE_BIT );
  663. }
  664. /*-----------------------------------------------------------*/
  665. #if ( configASSERT_DEFINED == 1 )
  666. void vPortValidateInterruptPriority( void )
  667. {
  668. uint32_t ulCurrentInterrupt;
  669. uint8_t ucCurrentPriority;
  670. /* Obtain the number of the currently executing interrupt. */
  671. __asm volatile ( "mrs %0, ipsr" : "=r" ( ulCurrentInterrupt )::"memory" );
  672. /* Is the interrupt number a user defined interrupt? */
  673. if( ulCurrentInterrupt >= portFIRST_USER_INTERRUPT_NUMBER )
  674. {
  675. /* Look up the interrupt's priority. */
  676. ucCurrentPriority = pcInterruptPriorityRegisters[ ulCurrentInterrupt ];
  677. /* The following assertion will fail if a service routine (ISR) for
  678. * an interrupt that has been assigned a priority above
  679. * configMAX_SYSCALL_INTERRUPT_PRIORITY calls an ISR safe FreeRTOS API
  680. * function. ISR safe FreeRTOS API functions must *only* be called
  681. * from interrupts that have been assigned a priority at or below
  682. * configMAX_SYSCALL_INTERRUPT_PRIORITY.
  683. *
  684. * Numerically low interrupt priority numbers represent logically high
  685. * interrupt priorities, therefore the priority of the interrupt must
  686. * be set to a value equal to or numerically *higher* than
  687. * configMAX_SYSCALL_INTERRUPT_PRIORITY.
  688. *
  689. * Interrupts that use the FreeRTOS API must not be left at their
  690. * default priority of zero as that is the highest possible priority,
  691. * which is guaranteed to be above configMAX_SYSCALL_INTERRUPT_PRIORITY,
  692. * and therefore also guaranteed to be invalid.
  693. *
  694. * FreeRTOS maintains separate thread and ISR API functions to ensure
  695. * interrupt entry is as fast and simple as possible.
  696. *
  697. * The following links provide detailed information:
  698. * https://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html
  699. * https://www.freertos.org/Why-FreeRTOS/FAQs */
  700. configASSERT( ucCurrentPriority >= ucMaxSysCallPriority );
  701. }
  702. /* Priority grouping: The interrupt controller (NVIC) allows the bits
  703. * that define each interrupt's priority to be split between bits that
  704. * define the interrupt's pre-emption priority bits and bits that define
  705. * the interrupt's sub-priority. For simplicity all bits must be defined
  706. * to be pre-emption priority bits. The following assertion will fail if
  707. * this is not the case (if some bits represent a sub-priority).
  708. *
  709. * If the application only uses CMSIS libraries for interrupt
  710. * configuration then the correct setting can be achieved on all Cortex-M
  711. * devices by calling NVIC_SetPriorityGrouping( 0 ); before starting the
  712. * scheduler. Note however that some vendor specific peripheral libraries
  713. * assume a non-zero priority group setting, in which cases using a value
  714. * of zero will result in unpredictable behaviour. */
  715. configASSERT( ( portAIRCR_REG & portPRIORITY_GROUP_MASK ) <= ulMaxPRIGROUPValue );
  716. }
  717. #endif /* configASSERT_DEFINED */