port.c 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841
  1. /*
  2. * FreeRTOS Kernel V10.4.6
  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 CM4F port.
  30. *----------------------------------------------------------*/
  31. /* Scheduler includes. */
  32. #include "FreeRTOS.h"
  33. #include "task.h"
  34. #ifndef configSYSTICK_CLOCK_HZ
  35. #define configSYSTICK_CLOCK_HZ configCPU_CLOCK_HZ
  36. /* Ensure the SysTick is clocked at the same frequency as the core. */
  37. #define portNVIC_SYSTICK_CLK_BIT ( 1UL << 2UL )
  38. #else
  39. /* The way the SysTick is clocked is not modified in case it is not the same
  40. * as the core. */
  41. #define portNVIC_SYSTICK_CLK_BIT ( 0 )
  42. #endif
  43. /* Constants required to manipulate the core. Registers first... */
  44. #define portNVIC_SYSTICK_CTRL_REG ( *( ( volatile uint32_t * ) 0xe000e010 ) )
  45. #define portNVIC_SYSTICK_LOAD_REG ( *( ( volatile uint32_t * ) 0xe000e014 ) )
  46. #define portNVIC_SYSTICK_CURRENT_VALUE_REG ( *( ( volatile uint32_t * ) 0xe000e018 ) )
  47. #define portNVIC_SHPR3_REG ( *( ( volatile uint32_t * ) 0xe000ed20 ) )
  48. /* ...then bits in the registers. */
  49. #define portNVIC_SYSTICK_INT_BIT ( 1UL << 1UL )
  50. #define portNVIC_SYSTICK_ENABLE_BIT ( 1UL << 0UL )
  51. #define portNVIC_SYSTICK_COUNT_FLAG_BIT ( 1UL << 16UL )
  52. #define portNVIC_PENDSVCLEAR_BIT ( 1UL << 27UL )
  53. #define portNVIC_PEND_SYSTICK_CLEAR_BIT ( 1UL << 25UL )
  54. #define portNVIC_PENDSV_PRI ( ( ( uint32_t ) configKERNEL_INTERRUPT_PRIORITY ) << 16UL )
  55. #define portNVIC_SYSTICK_PRI ( ( ( uint32_t ) configKERNEL_INTERRUPT_PRIORITY ) << 24UL )
  56. /* Constants required to check the validity of an interrupt priority. */
  57. #define portFIRST_USER_INTERRUPT_NUMBER ( 16 )
  58. #define portNVIC_IP_REGISTERS_OFFSET_16 ( 0xE000E3F0 )
  59. #define portAIRCR_REG ( *( ( volatile uint32_t * ) 0xE000ED0C ) )
  60. #define portMAX_8_BIT_VALUE ( ( uint8_t ) 0xff )
  61. #define portTOP_BIT_OF_BYTE ( ( uint8_t ) 0x80 )
  62. #define portMAX_PRIGROUP_BITS ( ( uint8_t ) 7 )
  63. #define portPRIORITY_GROUP_MASK ( 0x07UL << 8UL )
  64. #define portPRIGROUP_SHIFT ( 8UL )
  65. /* Masks off all bits but the VECTACTIVE bits in the ICSR register. */
  66. #define portVECTACTIVE_MASK ( 0xFFUL )
  67. /* Constants required to manipulate the VFP. */
  68. #define portFPCCR ( ( volatile uint32_t * ) 0xe000ef34 ) /* Floating point context control register. */
  69. #define portASPEN_AND_LSPEN_BITS ( 0x3UL << 30UL )
  70. /* Constants required to set up the initial stack. */
  71. #define portINITIAL_XPSR ( 0x01000000 )
  72. #define portINITIAL_EXC_RETURN ( 0xfffffffd )
  73. /* The systick is a 24-bit counter. */
  74. #define portMAX_24_BIT_NUMBER ( 0xffffffUL )
  75. /* A fiddle factor to estimate the number of SysTick counts that would have
  76. * occurred while the SysTick counter is stopped during tickless idle
  77. * calculations. */
  78. #define portMISSED_COUNTS_FACTOR ( 45UL )
  79. /* Let the user override the pre-loading of the initial LR with the address of
  80. * prvTaskExitError() in case it messes up unwinding of the stack in the
  81. * debugger. */
  82. #ifdef configTASK_RETURN_ADDRESS
  83. #define portTASK_RETURN_ADDRESS configTASK_RETURN_ADDRESS
  84. #else
  85. #define portTASK_RETURN_ADDRESS prvTaskExitError
  86. #endif
  87. /* Cannot find a weak linkage attribute, so the
  88. * configOVERRIDE_DEFAULT_TICK_CONFIGURATION constant must be set to 1 if the
  89. * application writer wants to provide their own implementation of
  90. * vPortSetupTimerInterrupt(). Ensure configOVERRIDE_DEFAULT_TICK_CONFIGURATION
  91. * is defined. */
  92. #ifndef configOVERRIDE_DEFAULT_TICK_CONFIGURATION
  93. #define configOVERRIDE_DEFAULT_TICK_CONFIGURATION 0
  94. #endif
  95. /* Manual definition of missing asm names. */
  96. #define psp 9
  97. #define basepri 17
  98. #define msp 8
  99. #define ipsr 5
  100. #define control 20
  101. /* From port.c. */
  102. extern void * pxCurrentTCB;
  103. /* Each task maintains its own interrupt status in the critical nesting
  104. * variable. */
  105. static UBaseType_t uxCriticalNesting = 0xaaaaaaaa;
  106. /*
  107. * Setup the timer to generate the tick interrupts. The implementation in this
  108. * file is weak to allow application writers to change the timer used to
  109. * generate the tick interrupt.
  110. */
  111. void vPortSetupTimerInterrupt( void );
  112. /*
  113. * Exception handlers.
  114. */
  115. void xPortPendSVHandler( void );
  116. void xPortSysTickHandler( void );
  117. void vPortSVCHandler( void );
  118. /*
  119. * Start first task is a separate function so it can be tested in isolation.
  120. */
  121. static void prvPortStartFirstTask( void );
  122. /*
  123. * Function to enable the VFP.
  124. */
  125. static void vPortEnableVFP( void );
  126. /*
  127. * Used to catch tasks that attempt to return from their implementing function.
  128. */
  129. static void prvTaskExitError( void );
  130. /*-----------------------------------------------------------*/
  131. /*
  132. * The number of SysTick increments that make up one tick period.
  133. */
  134. #if ( configUSE_TICKLESS_IDLE == 1 )
  135. static uint32_t ulTimerCountsForOneTick = 0;
  136. #endif /* configUSE_TICKLESS_IDLE */
  137. /*
  138. * The maximum number of tick periods that can be suppressed is limited by the
  139. * 24 bit resolution of the SysTick timer.
  140. */
  141. #if ( configUSE_TICKLESS_IDLE == 1 )
  142. static uint32_t xMaximumPossibleSuppressedTicks = 0;
  143. #endif /* configUSE_TICKLESS_IDLE */
  144. /*
  145. * Compensate for the CPU cycles that pass while the SysTick is stopped (low
  146. * power functionality only.
  147. */
  148. #if ( configUSE_TICKLESS_IDLE == 1 )
  149. static uint32_t ulStoppedTimerCompensation = 0;
  150. #endif /* configUSE_TICKLESS_IDLE */
  151. /*
  152. * Used by the portASSERT_IF_INTERRUPT_PRIORITY_INVALID() macro to ensure
  153. * FreeRTOS API functions are not called from interrupts that have been assigned
  154. * a priority above configMAX_SYSCALL_INTERRUPT_PRIORITY.
  155. */
  156. #if ( configASSERT_DEFINED == 1 )
  157. static uint8_t ucMaxSysCallPriority = 0;
  158. static uint32_t ulMaxPRIGROUPValue = 0;
  159. #endif /* configASSERT_DEFINED */
  160. /*-----------------------------------------------------------*/
  161. /*
  162. * See header file for description.
  163. */
  164. StackType_t * pxPortInitialiseStack( StackType_t * pxTopOfStack,
  165. TaskFunction_t pxCode,
  166. void * pvParameters )
  167. {
  168. /* Simulate the stack frame as it would be created by a context switch
  169. * interrupt. */
  170. /* Offset added to account for the way the MCU uses the stack on entry/exit
  171. * of interrupts, and to ensure alignment. */
  172. pxTopOfStack--;
  173. /* Sometimes the parameters are loaded from the stack. */
  174. *pxTopOfStack = ( StackType_t ) pvParameters;
  175. pxTopOfStack--;
  176. *pxTopOfStack = portINITIAL_XPSR; /* xPSR */
  177. pxTopOfStack--;
  178. *pxTopOfStack = ( StackType_t ) pxCode; /* PC */
  179. pxTopOfStack--;
  180. *pxTopOfStack = ( StackType_t ) portTASK_RETURN_ADDRESS; /* LR */
  181. /* Save code space by skipping register initialisation. */
  182. pxTopOfStack -= 5; /* R12, R3, R2 and R1. */
  183. *pxTopOfStack = ( StackType_t ) pvParameters; /* R0 */
  184. /* A save method is being used that requires each task to maintain its
  185. * own exec return value. */
  186. pxTopOfStack--;
  187. *pxTopOfStack = portINITIAL_EXC_RETURN;
  188. pxTopOfStack -= 8; /* R11, R10, R9, R8, R7, R6, R5 and R4. */
  189. return pxTopOfStack;
  190. }
  191. /*-----------------------------------------------------------*/
  192. static void prvTaskExitError( void )
  193. {
  194. /* A function that implements a task must not exit or attempt to return to
  195. * its caller as there is nothing to return to. If a task wants to exit it
  196. * should instead call vTaskDelete( NULL ).
  197. *
  198. * Artificially force an assert() to be triggered if configASSERT() is
  199. * defined, then stop here so application writers can catch the error. */
  200. configASSERT( uxCriticalNesting == ~0UL );
  201. portDISABLE_INTERRUPTS();
  202. for( ; ; )
  203. {
  204. }
  205. }
  206. /*-----------------------------------------------------------*/
  207. void vPortSVCHandler( void ) iv IVT_INT_SVCall ics ICS_OFF
  208. {
  209. __asm {
  210. /* *INDENT-OFF* */
  211. ldr r3, =_pxCurrentTCB /* Restore the context. */
  212. ldr r1, [ r3 ] /* Use pxCurrentTCBConst to get the pxCurrentTCB address. */
  213. ldr r0, [ r1 ] /* The first item in pxCurrentTCB is the task top of stack. */
  214. ldm r0 !, ( r4 - r11, r14 ) /* Pop the registers that are not automatically saved on exception entry and the critical nesting count. */
  215. msr psp, r0 /* Restore the task stack pointer. */
  216. isb
  217. mov r0, #0
  218. msr basepri, r0
  219. bx r14
  220. /* *INDENT-ON* */
  221. };
  222. }
  223. /*-----------------------------------------------------------*/
  224. static void prvPortStartFirstTask( void )
  225. {
  226. __asm {
  227. /* *INDENT-OFF* */
  228. ldr r0, =0xE000ED08 /* Use the NVIC offset register to locate the stack. */
  229. ldr r0, [ r0 ]
  230. ldr r0, [ r0 ]
  231. msr msp, r0 /* Set the msp back to the start of the stack. */
  232. /* Clear the bit that indicates the FPU is in use in case the FPU was used
  233. * before the scheduler was started - which would otherwise result in the
  234. * unnecessary leaving of space in the SVC stack for lazy saving of FPU
  235. * registers. */
  236. mov r0, #0
  237. msr control, r0
  238. cpsie i /* Globally enable interrupts. */
  239. cpsie f
  240. dsb
  241. isb
  242. svc #0 /* System call to start first task. */
  243. nop
  244. /* *INDENT-ON* */
  245. };
  246. }
  247. /*-----------------------------------------------------------*/
  248. /*
  249. * See header file for description.
  250. */
  251. BaseType_t xPortStartScheduler( void )
  252. {
  253. /* configMAX_SYSCALL_INTERRUPT_PRIORITY must not be set to 0.
  254. * See https://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html */
  255. configASSERT( configMAX_SYSCALL_INTERRUPT_PRIORITY );
  256. #if ( configASSERT_DEFINED == 1 )
  257. {
  258. volatile uint32_t ulOriginalPriority;
  259. volatile uint8_t * const pucFirstUserPriorityRegister = ( volatile uint8_t * const ) ( portNVIC_IP_REGISTERS_OFFSET_16 + portFIRST_USER_INTERRUPT_NUMBER );
  260. volatile uint8_t ucMaxPriorityValue;
  261. /* Determine the maximum priority from which ISR safe FreeRTOS API
  262. * functions can be called. ISR safe functions are those that end in
  263. * "FromISR". FreeRTOS maintains separate thread and ISR API functions to
  264. * ensure interrupt entry is as fast and simple as possible.
  265. *
  266. * Save the interrupt priority value that is about to be clobbered. */
  267. ulOriginalPriority = *pucFirstUserPriorityRegister;
  268. /* Determine the number of priority bits available. First write to all
  269. * possible bits. */
  270. *pucFirstUserPriorityRegister = portMAX_8_BIT_VALUE;
  271. /* Read the value back to see how many bits stuck. */
  272. ucMaxPriorityValue = *pucFirstUserPriorityRegister;
  273. /* The kernel interrupt priority should be set to the lowest
  274. * priority. */
  275. configASSERT( ucMaxPriorityValue == ( configKERNEL_INTERRUPT_PRIORITY & ucMaxPriorityValue ) );
  276. /* Use the same mask on the maximum system call priority. */
  277. ucMaxSysCallPriority = configMAX_SYSCALL_INTERRUPT_PRIORITY & ucMaxPriorityValue;
  278. /* Calculate the maximum acceptable priority group value for the number
  279. * of bits read back. */
  280. ulMaxPRIGROUPValue = portMAX_PRIGROUP_BITS;
  281. while( ( ucMaxPriorityValue & portTOP_BIT_OF_BYTE ) == portTOP_BIT_OF_BYTE )
  282. {
  283. ulMaxPRIGROUPValue--;
  284. ucMaxPriorityValue <<= ( uint8_t ) 0x01;
  285. }
  286. #ifdef __NVIC_PRIO_BITS
  287. {
  288. /* Check the CMSIS configuration that defines the number of
  289. * priority bits matches the number of priority bits actually queried
  290. * from the hardware. */
  291. configASSERT( ( portMAX_PRIGROUP_BITS - ulMaxPRIGROUPValue ) == __NVIC_PRIO_BITS );
  292. }
  293. #endif
  294. #ifdef configPRIO_BITS
  295. {
  296. /* Check the FreeRTOS configuration that defines the number of
  297. * priority bits matches the number of priority bits actually queried
  298. * from the hardware. */
  299. configASSERT( ( portMAX_PRIGROUP_BITS - ulMaxPRIGROUPValue ) == configPRIO_BITS );
  300. }
  301. #endif
  302. /* Shift the priority group value back to its position within the AIRCR
  303. * register. */
  304. ulMaxPRIGROUPValue <<= portPRIGROUP_SHIFT;
  305. ulMaxPRIGROUPValue &= portPRIORITY_GROUP_MASK;
  306. /* Restore the clobbered interrupt priority register to its original
  307. * value. */
  308. *pucFirstUserPriorityRegister = ulOriginalPriority;
  309. }
  310. #endif /* configASSERT_DEFINED */
  311. /* Make PendSV and SysTick the lowest priority interrupts. */
  312. portNVIC_SHPR3_REG |= portNVIC_PENDSV_PRI;
  313. portNVIC_SHPR3_REG |= portNVIC_SYSTICK_PRI;
  314. /* Start the timer that generates the tick ISR. Interrupts are disabled
  315. * here already. */
  316. vPortSetupTimerInterrupt();
  317. /* Initialise the critical nesting count ready for the first task. */
  318. uxCriticalNesting = 0;
  319. /* Ensure the VFP is enabled - it should be anyway. */
  320. vPortEnableVFP();
  321. /* Lazy save always. */
  322. *( portFPCCR ) |= portASPEN_AND_LSPEN_BITS;
  323. /* Start the first task. */
  324. prvPortStartFirstTask();
  325. /* Should never get here as the tasks will now be executing! Call the task
  326. * exit error function to prevent compiler warnings about a static function
  327. * not being called in the case that the application writer overrides this
  328. * functionality by defining configTASK_RETURN_ADDRESS. */
  329. prvTaskExitError();
  330. /* Should not get here! */
  331. return 0;
  332. }
  333. /*-----------------------------------------------------------*/
  334. void vPortEndScheduler( void )
  335. {
  336. /* Not implemented in ports where there is nothing to return to.
  337. * Artificially force an assert. */
  338. configASSERT( uxCriticalNesting == 1000UL );
  339. }
  340. /*-----------------------------------------------------------*/
  341. void vPortEnterCritical( void )
  342. {
  343. portDISABLE_INTERRUPTS();
  344. uxCriticalNesting++;
  345. /* This is not the interrupt safe version of the enter critical function so
  346. * assert() if it is being called from an interrupt context. Only API
  347. * functions that end in "FromISR" can be used in an interrupt. Only assert if
  348. * the critical nesting count is 1 to protect against recursive calls if the
  349. * assert function also uses a critical section. */
  350. if( uxCriticalNesting == 1 )
  351. {
  352. configASSERT( ( portNVIC_INT_CTRL_REG & portVECTACTIVE_MASK ) == 0 );
  353. }
  354. }
  355. /*-----------------------------------------------------------*/
  356. void vPortExitCritical( void )
  357. {
  358. configASSERT( uxCriticalNesting );
  359. uxCriticalNesting--;
  360. if( uxCriticalNesting == 0 )
  361. {
  362. portENABLE_INTERRUPTS();
  363. }
  364. }
  365. /*-----------------------------------------------------------*/
  366. const uint8_t ucMaxSyscallInterruptPriority = configMAX_SYSCALL_INTERRUPT_PRIORITY;
  367. void xPortPendSVHandler( void ) iv IVT_INT_PendSV ics ICS_OFF
  368. {
  369. __asm {
  370. #ifdef HW_DEBUG
  371. /* *INDENT-OFF* */
  372. /* The function is not truly naked, so add back the 4 bytes subtracted
  373. * from the stack pointer by the function prologue. */
  374. add sp, sp, # 4
  375. #endif
  376. mrs r0, psp
  377. isb
  378. ldr r3, =_pxCurrentTCB /* Get the location of the current TCB. */
  379. ldr r2, [ r3 ]
  380. tst r14, #0x10 /* Is the task using the FPU context? If so, push high vfp registers. */
  381. it eq
  382. vstmdbeq r0 !, ( s16 - s31 )
  383. stmdb r0 !, ( r4 - r11, r14 ) /* Save the core registers. */
  384. str r0, [ r2 ] /* Save the new top of stack into the first member of the TCB. */
  385. stmdb sp !, ( r0, r3 )
  386. ldr r0, = _ucMaxSyscallInterruptPriority
  387. ldr r1, [ r0 ]
  388. msr basepri, r1
  389. dsb
  390. isb
  391. bl _vTaskSwitchContext
  392. mov r0, #0
  393. msr basepri, r0
  394. ldm sp !, ( r0, r3 )
  395. ldr r1, [ r3 ] /* The first item in pxCurrentTCB is the task top of stack. */
  396. ldr r0, [ r1 ]
  397. ldm r0 !, ( r4 - r11, r14 ) /* Pop the core registers. */
  398. tst r14, #0x10 /* Is the task using the FPU context? If so, pop the high vfp registers too. */
  399. it eq
  400. vldmiaeq r0 !, ( s16 - s31 )
  401. msr psp, r0
  402. isb
  403. bx r14
  404. /* *INDENT-ON* */
  405. }
  406. }
  407. /*-----------------------------------------------------------*/
  408. void xPortSysTickHandler( void ) iv IVT_INT_SysTick ics ICS_AUTO
  409. {
  410. /* The SysTick runs at the lowest interrupt priority, so when this interrupt
  411. * executes all interrupts must be unmasked. There is therefore no need to
  412. * save and then restore the interrupt mask value as its value is already
  413. * known - therefore the slightly faster portDISABLE_INTERRUPTS() function is
  414. * used in place of portSET_INTERRUPT_MASK_FROM_ISR(). */
  415. portDISABLE_INTERRUPTS();
  416. {
  417. /* Increment the RTOS tick. */
  418. if( xTaskIncrementTick() != pdFALSE )
  419. {
  420. /* A context switch is required. Context switching is performed in
  421. * the PendSV interrupt. Pend the PendSV interrupt. */
  422. portNVIC_INT_CTRL_REG = portNVIC_PENDSVSET_BIT;
  423. }
  424. }
  425. portENABLE_INTERRUPTS();
  426. }
  427. /*-----------------------------------------------------------*/
  428. #if ( ( configUSE_TICKLESS_IDLE == 1 ) && ( configOVERRIDE_DEFAULT_TICK_CONFIGURATION == 0 ) )
  429. void vPortSuppressTicksAndSleep( TickType_t xExpectedIdleTime )
  430. {
  431. uint32_t ulReloadValue, ulCompleteTickPeriods, ulCompletedSysTickDecrements;
  432. TickType_t xModifiableIdleTime;
  433. /* Make sure the SysTick reload value does not overflow the counter. */
  434. if( xExpectedIdleTime > xMaximumPossibleSuppressedTicks )
  435. {
  436. xExpectedIdleTime = xMaximumPossibleSuppressedTicks;
  437. }
  438. /* Stop the SysTick momentarily. The time the SysTick is stopped for
  439. * is accounted for as best it can be, but using the tickless mode will
  440. * inevitably result in some tiny drift of the time maintained by the
  441. * kernel with respect to calendar time. */
  442. portNVIC_SYSTICK_CTRL_REG &= ~portNVIC_SYSTICK_ENABLE_BIT;
  443. /* Calculate the reload value required to wait xExpectedIdleTime
  444. * tick periods. -1 is used because this code will execute part way
  445. * through one of the tick periods. */
  446. ulReloadValue = portNVIC_SYSTICK_CURRENT_VALUE_REG + ( ulTimerCountsForOneTick * ( xExpectedIdleTime - 1UL ) );
  447. if( ulReloadValue > ulStoppedTimerCompensation )
  448. {
  449. ulReloadValue -= ulStoppedTimerCompensation;
  450. }
  451. /* Enter a critical section but don't use the taskENTER_CRITICAL()
  452. * method as that will mask interrupts that should exit sleep mode. */
  453. __asm {
  454. "cpsid i"
  455. };
  456. __asm {
  457. "dsb"
  458. };
  459. __asm {
  460. "isb"
  461. };
  462. /* If a context switch is pending or a task is waiting for the scheduler
  463. * to be unsuspended then abandon the low power entry. */
  464. if( eTaskConfirmSleepModeStatus() == eAbortSleep )
  465. {
  466. /* Restart from whatever is left in the count register to complete
  467. * this tick period. */
  468. portNVIC_SYSTICK_LOAD_REG = portNVIC_SYSTICK_CURRENT_VALUE_REG;
  469. /* Restart SysTick. */
  470. portNVIC_SYSTICK_CTRL_REG |= portNVIC_SYSTICK_ENABLE_BIT;
  471. /* Reset the reload register to the value required for normal tick
  472. * periods. */
  473. portNVIC_SYSTICK_LOAD_REG = ulTimerCountsForOneTick - 1UL;
  474. /* Re-enable interrupts - see comments above the cpsid instruction()
  475. * above. */
  476. __asm {
  477. "cpsie i"
  478. };
  479. }
  480. else
  481. {
  482. /* Set the new reload value. */
  483. portNVIC_SYSTICK_LOAD_REG = ulReloadValue;
  484. /* Clear the SysTick count flag and set the count value back to
  485. * zero. */
  486. portNVIC_SYSTICK_CURRENT_VALUE_REG = 0UL;
  487. /* Restart SysTick. */
  488. portNVIC_SYSTICK_CTRL_REG |= portNVIC_SYSTICK_ENABLE_BIT;
  489. /* Sleep until something happens. configPRE_SLEEP_PROCESSING() can
  490. * set its parameter to 0 to indicate that its implementation contains
  491. * its own wait for interrupt or wait for event instruction, and so wfi
  492. * should not be executed again. However, the original expected idle
  493. * time variable must remain unmodified, so a copy is taken. */
  494. xModifiableIdleTime = xExpectedIdleTime;
  495. configPRE_SLEEP_PROCESSING( xModifiableIdleTime );
  496. if( xModifiableIdleTime > 0 )
  497. {
  498. __asm {
  499. "dsb"
  500. };
  501. __asm {
  502. "wfi"
  503. };
  504. __asm {
  505. "isb"
  506. };
  507. }
  508. configPOST_SLEEP_PROCESSING( xExpectedIdleTime );
  509. /* Re-enable interrupts to allow the interrupt that brought the MCU
  510. * out of sleep mode to execute immediately. see comments above
  511. * __disable_interrupt() call above. */
  512. __asm {
  513. "cpsie i"
  514. };
  515. __asm {
  516. "dsb"
  517. };
  518. __asm {
  519. "isb"
  520. };
  521. /* Disable interrupts again because the clock is about to be stopped
  522. * and interrupts that execute while the clock is stopped will increase
  523. * any slippage between the time maintained by the RTOS and calendar
  524. * time. */
  525. __asm {
  526. "cpsid i"
  527. };
  528. __asm {
  529. "dsb"
  530. };
  531. __asm {
  532. "isb"
  533. };
  534. /* Disable the SysTick clock without reading the
  535. * portNVIC_SYSTICK_CTRL_REG register to ensure the
  536. * portNVIC_SYSTICK_COUNT_FLAG_BIT is not cleared if it is set. Again,
  537. * the time the SysTick is stopped for is accounted for as best it can
  538. * be, but using the tickless mode will inevitably result in some tiny
  539. * drift of the time maintained by the kernel with respect to calendar
  540. * time*/
  541. portNVIC_SYSTICK_CTRL_REG = ( portNVIC_SYSTICK_CLK_BIT | portNVIC_SYSTICK_INT_BIT );
  542. /* Determine if the SysTick clock has already counted to zero and
  543. * been set back to the current reload value (the reload back being
  544. * correct for the entire expected idle time) or if the SysTick is yet
  545. * to count to zero (in which case an interrupt other than the SysTick
  546. * must have brought the system out of sleep mode). */
  547. if( ( portNVIC_SYSTICK_CTRL_REG & portNVIC_SYSTICK_COUNT_FLAG_BIT ) != 0 )
  548. {
  549. uint32_t ulCalculatedLoadValue;
  550. /* The tick interrupt is already pending, and the SysTick count
  551. * reloaded with ulReloadValue. Reset the
  552. * portNVIC_SYSTICK_LOAD_REG with whatever remains of this tick
  553. * period. */
  554. ulCalculatedLoadValue = ( ulTimerCountsForOneTick - 1UL ) - ( ulReloadValue - portNVIC_SYSTICK_CURRENT_VALUE_REG );
  555. /* Don't allow a tiny value, or values that have somehow
  556. * underflowed because the post sleep hook did something
  557. * that took too long. */
  558. if( ( ulCalculatedLoadValue < ulStoppedTimerCompensation ) || ( ulCalculatedLoadValue > ulTimerCountsForOneTick ) )
  559. {
  560. ulCalculatedLoadValue = ( ulTimerCountsForOneTick - 1UL );
  561. }
  562. portNVIC_SYSTICK_LOAD_REG = ulCalculatedLoadValue;
  563. /* As the pending tick will be processed as soon as this
  564. * function exits, the tick value maintained by the tick is stepped
  565. * forward by one less than the time spent waiting. */
  566. ulCompleteTickPeriods = xExpectedIdleTime - 1UL;
  567. }
  568. else
  569. {
  570. /* Something other than the tick interrupt ended the sleep.
  571. * Work out how long the sleep lasted rounded to complete tick
  572. * periods (not the ulReload value which accounted for part
  573. * ticks). */
  574. ulCompletedSysTickDecrements = ( xExpectedIdleTime * ulTimerCountsForOneTick ) - portNVIC_SYSTICK_CURRENT_VALUE_REG;
  575. /* How many complete tick periods passed while the processor
  576. * was waiting? */
  577. ulCompleteTickPeriods = ulCompletedSysTickDecrements / ulTimerCountsForOneTick;
  578. /* The reload value is set to whatever fraction of a single tick
  579. * period remains. */
  580. portNVIC_SYSTICK_LOAD_REG = ( ( ulCompleteTickPeriods + 1UL ) * ulTimerCountsForOneTick ) - ulCompletedSysTickDecrements;
  581. }
  582. /* Restart SysTick so it runs from portNVIC_SYSTICK_LOAD_REG
  583. * again, then set portNVIC_SYSTICK_LOAD_REG back to its standard
  584. * value. */
  585. portNVIC_SYSTICK_CURRENT_VALUE_REG = 0UL;
  586. portNVIC_SYSTICK_CTRL_REG |= portNVIC_SYSTICK_ENABLE_BIT;
  587. vTaskStepTick( ulCompleteTickPeriods );
  588. portNVIC_SYSTICK_LOAD_REG = ulTimerCountsForOneTick - 1UL;
  589. /* Exit with interrupts enabled. */
  590. __asm {
  591. "cpsie i"
  592. };
  593. }
  594. }
  595. #endif /* #if configUSE_TICKLESS_IDLE */
  596. /*-----------------------------------------------------------*/
  597. /*
  598. * Setup the systick timer to generate the tick interrupts at the required
  599. * frequency.
  600. */
  601. #if ( configOVERRIDE_DEFAULT_TICK_CONFIGURATION == 0 )
  602. void vPortSetupTimerInterrupt( void )
  603. {
  604. /* Calculate the constants required to configure the tick interrupt. */
  605. #if ( configUSE_TICKLESS_IDLE == 1 )
  606. {
  607. ulTimerCountsForOneTick = ( configSYSTICK_CLOCK_HZ / configTICK_RATE_HZ );
  608. xMaximumPossibleSuppressedTicks = portMAX_24_BIT_NUMBER / ulTimerCountsForOneTick;
  609. ulStoppedTimerCompensation = portMISSED_COUNTS_FACTOR / ( configCPU_CLOCK_HZ / configSYSTICK_CLOCK_HZ );
  610. }
  611. #endif /* configUSE_TICKLESS_IDLE */
  612. /* Reset SysTick. */
  613. portNVIC_SYSTICK_CTRL_REG = 0UL;
  614. portNVIC_SYSTICK_CURRENT_VALUE_REG = 0UL;
  615. /* Configure SysTick to interrupt at the requested rate. */
  616. portNVIC_SYSTICK_LOAD_REG = ( configSYSTICK_CLOCK_HZ / configTICK_RATE_HZ ) - 1UL;
  617. portNVIC_SYSTICK_CTRL_REG = ( portNVIC_SYSTICK_CLK_BIT | portNVIC_SYSTICK_INT_BIT | portNVIC_SYSTICK_ENABLE_BIT );
  618. }
  619. #endif /* configOVERRIDE_DEFAULT_TICK_CONFIGURATION */
  620. /*-----------------------------------------------------------*/
  621. /* This is a naked function. */
  622. static void vPortEnableVFP( void )
  623. {
  624. __asm {
  625. /* *INDENT-OFF* */
  626. ldr r0, =0xE000ED88 /* The FPU enable bits are in the CPACR. */
  627. ldr r1, [ r0 ]
  628. orr r1, r1, #0xF00000 /* Enable CP10 and CP11 coprocessors, then save back. */
  629. str r1, [ r0 ]
  630. bx r14
  631. /* *INDENT-ON* */
  632. };
  633. }
  634. /*-----------------------------------------------------------*/
  635. BaseType_t xPortIsInsideInterrupt( void )
  636. {
  637. BaseType_t xReturn;
  638. /* Obtain the number of the currently executing interrupt. */
  639. if( CPU_REG_GET( CPU_IPSR ) == 0 )
  640. {
  641. xReturn = pdFALSE;
  642. }
  643. else
  644. {
  645. xReturn = pdTRUE;
  646. }
  647. return xReturn;
  648. }
  649. /*-----------------------------------------------------------*/
  650. #if ( configASSERT_DEFINED == 1 )
  651. /* Limitations in the MikroC inline asm means ulCurrentInterrupt has to be
  652. * global - which makes vPortValidateInterruptPriority() non re-entrant.
  653. * However that should not matter as an interrupt can only itself be
  654. * interrupted by a higher priority interrupt. That means if
  655. * ulCurrentInterrupt, so ulCurrentInterrupt getting corrupted cannot lead to
  656. * an invalid interrupt priority being missed. */
  657. uint32_t ulCurrentInterrupt;
  658. uint8_t ucCurrentPriority;
  659. void vPortValidateInterruptPriority( void )
  660. {
  661. /* Obtain the number of the currently executing interrupt. */
  662. __asm {
  663. /* *INDENT-OFF* */
  664. push( r0, r1 )
  665. mrs r0, ipsr
  666. ldr r1, =_ulCurrentInterrupt
  667. str r0, [ r1 ]
  668. pop( r0, r1 )
  669. /* *INDENT-ON* */
  670. };
  671. /* Is the interrupt number a user defined interrupt? */
  672. if( ulCurrentInterrupt >= portFIRST_USER_INTERRUPT_NUMBER )
  673. {
  674. /* Look up the interrupt's priority. */
  675. ucCurrentPriority = *( ( uint8_t * ) ( portNVIC_IP_REGISTERS_OFFSET_16 + ulCurrentInterrupt ) );
  676. /* The following assertion will fail if a service routine (ISR) for
  677. * an interrupt that has been assigned a priority above
  678. * configMAX_SYSCALL_INTERRUPT_PRIORITY calls an ISR safe FreeRTOS API
  679. * function. ISR safe FreeRTOS API functions must *only* be called
  680. * from interrupts that have been assigned a priority at or below
  681. * configMAX_SYSCALL_INTERRUPT_PRIORITY.
  682. *
  683. * Numerically low interrupt priority numbers represent logically high
  684. * interrupt priorities, therefore the priority of the interrupt must
  685. * be set to a value equal to or numerically *higher* than
  686. * configMAX_SYSCALL_INTERRUPT_PRIORITY.
  687. *
  688. * Interrupts that use the FreeRTOS API must not be left at their
  689. * default priority of zero as that is the highest possible priority,
  690. * which is guaranteed to be above configMAX_SYSCALL_INTERRUPT_PRIORITY,
  691. * and therefore also guaranteed to be invalid.
  692. *
  693. * FreeRTOS maintains separate thread and ISR API functions to ensure
  694. * interrupt entry is as fast and simple as possible.
  695. *
  696. * The following links provide detailed information:
  697. * https://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html
  698. * https://www.FreeRTOS.org/FAQHelp.html */
  699. configASSERT( ucCurrentPriority >= ucMaxSysCallPriority );
  700. }
  701. /* Priority grouping: The interrupt controller (NVIC) allows the bits
  702. * that define each interrupt's priority to be split between bits that
  703. * define the interrupt's pre-emption priority bits and bits that define
  704. * the interrupt's sub-priority. For simplicity all bits must be defined
  705. * to be pre-emption priority bits. The following assertion will fail if
  706. * this is not the case (if some bits represent a sub-priority).
  707. *
  708. * If the application only uses CMSIS libraries for interrupt
  709. * configuration then the correct setting can be achieved on all Cortex-M
  710. * devices by calling NVIC_SetPriorityGrouping( 0 ); before starting the
  711. * scheduler. Note however that some vendor specific peripheral libraries
  712. * assume a non-zero priority group setting, in which cases using a value
  713. * of zero will result in unpredictable behaviour. */
  714. configASSERT( ( portAIRCR_REG & portPRIORITY_GROUP_MASK ) <= ulMaxPRIGROUPValue );
  715. }
  716. #endif /* configASSERT_DEFINED */