port.c 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568
  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 CM0 port.
  30. *----------------------------------------------------------*/
  31. /* Scheduler includes. */
  32. #include "FreeRTOS.h"
  33. #include "task.h"
  34. /* Constants required to manipulate the NVIC. */
  35. #define portNVIC_SYSTICK_CTRL_REG ( *( ( volatile uint32_t * ) 0xe000e010 ) )
  36. #define portNVIC_SYSTICK_LOAD_REG ( *( ( volatile uint32_t * ) 0xe000e014 ) )
  37. #define portNVIC_SYSTICK_CURRENT_VALUE_REG ( *( ( volatile uint32_t * ) 0xe000e018 ) )
  38. #define portNVIC_INT_CTRL_REG ( *( ( volatile uint32_t * ) 0xe000ed04 ) )
  39. #define portNVIC_SHPR3_REG ( *( ( volatile uint32_t * ) 0xe000ed20 ) )
  40. #define portNVIC_SYSTICK_CLK_BIT ( 1UL << 2UL )
  41. #define portNVIC_SYSTICK_INT_BIT ( 1UL << 1UL )
  42. #define portNVIC_SYSTICK_ENABLE_BIT ( 1UL << 0UL )
  43. #define portNVIC_SYSTICK_COUNT_FLAG_BIT ( 1UL << 16UL )
  44. #define portNVIC_PENDSVSET_BIT ( 1UL << 28UL )
  45. #define portMIN_INTERRUPT_PRIORITY ( 255UL )
  46. #define portNVIC_PENDSV_PRI ( portMIN_INTERRUPT_PRIORITY << 16UL )
  47. #define portNVIC_SYSTICK_PRI ( portMIN_INTERRUPT_PRIORITY << 24UL )
  48. /* Constants required to set up the initial stack. */
  49. #define portINITIAL_XPSR ( 0x01000000 )
  50. /* The systick is a 24-bit counter. */
  51. #define portMAX_24_BIT_NUMBER ( 0xffffffUL )
  52. /* A fiddle factor to estimate the number of SysTick counts that would have
  53. * occurred while the SysTick counter is stopped during tickless idle
  54. * calculations. */
  55. #ifndef portMISSED_COUNTS_FACTOR
  56. #define portMISSED_COUNTS_FACTOR ( 45UL )
  57. #endif
  58. /* Let the user override the pre-loading of the initial LR with the address of
  59. * prvTaskExitError() in case it messes up unwinding of the stack in the
  60. * debugger. */
  61. #ifdef configTASK_RETURN_ADDRESS
  62. #define portTASK_RETURN_ADDRESS configTASK_RETURN_ADDRESS
  63. #else
  64. #define portTASK_RETURN_ADDRESS prvTaskExitError
  65. #endif
  66. /*
  67. * Setup the timer to generate the tick interrupts. The implementation in this
  68. * file is weak to allow application writers to change the timer used to
  69. * generate the tick interrupt.
  70. */
  71. void vPortSetupTimerInterrupt( void );
  72. /*
  73. * Exception handlers.
  74. */
  75. void xPortPendSVHandler( void ) __attribute__( ( naked ) );
  76. void xPortSysTickHandler( void );
  77. void vPortSVCHandler( void );
  78. /*
  79. * Start first task is a separate function so it can be tested in isolation.
  80. */
  81. static void vPortStartFirstTask( void ) __attribute__( ( naked ) );
  82. /*
  83. * Used to catch tasks that attempt to return from their implementing function.
  84. */
  85. static void prvTaskExitError( void );
  86. /*-----------------------------------------------------------*/
  87. /* Each task maintains its own interrupt status in the critical nesting
  88. * variable. */
  89. static UBaseType_t uxCriticalNesting = 0xaaaaaaaa;
  90. /*-----------------------------------------------------------*/
  91. /*
  92. * The number of SysTick increments that make up one tick period.
  93. */
  94. #if ( configUSE_TICKLESS_IDLE == 1 )
  95. static uint32_t ulTimerCountsForOneTick = 0;
  96. #endif /* configUSE_TICKLESS_IDLE */
  97. /*
  98. * The maximum number of tick periods that can be suppressed is limited by the
  99. * 24 bit resolution of the SysTick timer.
  100. */
  101. #if ( configUSE_TICKLESS_IDLE == 1 )
  102. static uint32_t xMaximumPossibleSuppressedTicks = 0;
  103. #endif /* configUSE_TICKLESS_IDLE */
  104. /*
  105. * Compensate for the CPU cycles that pass while the SysTick is stopped (low
  106. * power functionality only.
  107. */
  108. #if ( configUSE_TICKLESS_IDLE == 1 )
  109. static uint32_t ulStoppedTimerCompensation = 0;
  110. #endif /* configUSE_TICKLESS_IDLE */
  111. /*-----------------------------------------------------------*/
  112. /*
  113. * See header file for description.
  114. */
  115. StackType_t * pxPortInitialiseStack( StackType_t * pxTopOfStack,
  116. TaskFunction_t pxCode,
  117. void * pvParameters )
  118. {
  119. /* Simulate the stack frame as it would be created by a context switch
  120. * interrupt. */
  121. pxTopOfStack--; /* Offset added to account for the way the MCU uses the stack on entry/exit of interrupts. */
  122. *pxTopOfStack = portINITIAL_XPSR; /* xPSR */
  123. pxTopOfStack--;
  124. *pxTopOfStack = ( StackType_t ) pxCode; /* PC */
  125. pxTopOfStack--;
  126. *pxTopOfStack = ( StackType_t ) portTASK_RETURN_ADDRESS; /* LR */
  127. pxTopOfStack -= 5; /* R12, R3, R2 and R1. */
  128. *pxTopOfStack = ( StackType_t ) pvParameters; /* R0 */
  129. pxTopOfStack -= 8; /* R11..R4. */
  130. return pxTopOfStack;
  131. }
  132. /*-----------------------------------------------------------*/
  133. static void prvTaskExitError( void )
  134. {
  135. volatile uint32_t ulDummy = 0UL;
  136. /* A function that implements a task must not exit or attempt to return to
  137. * its caller as there is nothing to return to. If a task wants to exit it
  138. * should instead call vTaskDelete( NULL ).
  139. *
  140. * Artificially force an assert() to be triggered if configASSERT() is
  141. * defined, then stop here so application writers can catch the error. */
  142. configASSERT( uxCriticalNesting == ~0UL );
  143. portDISABLE_INTERRUPTS();
  144. while( ulDummy == 0 )
  145. {
  146. /* This file calls prvTaskExitError() after the scheduler has been
  147. * started to remove a compiler warning about the function being defined
  148. * but never called. ulDummy is used purely to quieten other warnings
  149. * about code appearing after this function is called - making ulDummy
  150. * volatile makes the compiler think the function could return and
  151. * therefore not output an 'unreachable code' warning for code that appears
  152. * after it. */
  153. }
  154. }
  155. /*-----------------------------------------------------------*/
  156. void vPortSVCHandler( void )
  157. {
  158. /* This function is no longer used, but retained for backward
  159. * compatibility. */
  160. }
  161. /*-----------------------------------------------------------*/
  162. void vPortStartFirstTask( void )
  163. {
  164. /* The MSP stack is not reset as, unlike on M3/4 parts, there is no vector
  165. * table offset register that can be used to locate the initial stack value.
  166. * Not all M0 parts have the application vector table at address 0. */
  167. __asm volatile (
  168. " .syntax unified \n"
  169. " ldr r2, pxCurrentTCBConst2 \n"/* Obtain location of pxCurrentTCB. */
  170. " ldr r3, [r2] \n"
  171. " ldr r0, [r3] \n"/* The first item in pxCurrentTCB is the task top of stack. */
  172. " adds r0, #32 \n"/* Discard everything up to r0. */
  173. " msr psp, r0 \n"/* This is now the new top of stack to use in the task. */
  174. " movs r0, #2 \n"/* Switch to the psp stack. */
  175. " msr CONTROL, r0 \n"
  176. " isb \n"
  177. " pop {r0-r5} \n"/* Pop the registers that are saved automatically. */
  178. " mov lr, r5 \n"/* lr is now in r5. */
  179. " pop {r3} \n"/* Return address is now in r3. */
  180. " pop {r2} \n"/* Pop and discard XPSR. */
  181. " cpsie i \n"/* The first task has its context and interrupts can be enabled. */
  182. " bx r3 \n"/* Finally, jump to the user defined task code. */
  183. " \n"
  184. " .align 4 \n"
  185. "pxCurrentTCBConst2: .word pxCurrentTCB "
  186. );
  187. }
  188. /*-----------------------------------------------------------*/
  189. /*
  190. * See header file for description.
  191. */
  192. BaseType_t xPortStartScheduler( void )
  193. {
  194. /* Make PendSV, CallSV and SysTick the same priority as the kernel. */
  195. portNVIC_SHPR3_REG |= portNVIC_PENDSV_PRI;
  196. portNVIC_SHPR3_REG |= portNVIC_SYSTICK_PRI;
  197. /* Start the timer that generates the tick ISR. Interrupts are disabled
  198. * here already. */
  199. vPortSetupTimerInterrupt();
  200. /* Initialise the critical nesting count ready for the first task. */
  201. uxCriticalNesting = 0;
  202. /* Start the first task. */
  203. vPortStartFirstTask();
  204. /* Should never get here as the tasks will now be executing! Call the task
  205. * exit error function to prevent compiler warnings about a static function
  206. * not being called in the case that the application writer overrides this
  207. * functionality by defining configTASK_RETURN_ADDRESS. Call
  208. * vTaskSwitchContext() so link time optimisation does not remove the
  209. * symbol. */
  210. vTaskSwitchContext();
  211. prvTaskExitError();
  212. /* Should not get here! */
  213. return 0;
  214. }
  215. /*-----------------------------------------------------------*/
  216. void vPortEndScheduler( void )
  217. {
  218. /* Not implemented in ports where there is nothing to return to.
  219. * Artificially force an assert. */
  220. configASSERT( uxCriticalNesting == 1000UL );
  221. }
  222. /*-----------------------------------------------------------*/
  223. void vPortYield( void )
  224. {
  225. /* Set a PendSV to request a context switch. */
  226. portNVIC_INT_CTRL_REG = portNVIC_PENDSVSET_BIT;
  227. /* Barriers are normally not required but do ensure the code is completely
  228. * within the specified behaviour for the architecture. */
  229. __asm volatile ( "dsb" ::: "memory" );
  230. __asm volatile ( "isb" );
  231. }
  232. /*-----------------------------------------------------------*/
  233. void vPortEnterCritical( void )
  234. {
  235. portDISABLE_INTERRUPTS();
  236. uxCriticalNesting++;
  237. __asm volatile ( "dsb" ::: "memory" );
  238. __asm volatile ( "isb" );
  239. }
  240. /*-----------------------------------------------------------*/
  241. void vPortExitCritical( void )
  242. {
  243. configASSERT( uxCriticalNesting );
  244. uxCriticalNesting--;
  245. if( uxCriticalNesting == 0 )
  246. {
  247. portENABLE_INTERRUPTS();
  248. }
  249. }
  250. /*-----------------------------------------------------------*/
  251. uint32_t ulSetInterruptMaskFromISR( void )
  252. {
  253. __asm volatile (
  254. " mrs r0, PRIMASK \n"
  255. " cpsid i \n"
  256. " bx lr "
  257. ::: "memory"
  258. );
  259. }
  260. /*-----------------------------------------------------------*/
  261. void vClearInterruptMaskFromISR( __attribute__( ( unused ) ) uint32_t ulMask )
  262. {
  263. __asm volatile (
  264. " msr PRIMASK, r0 \n"
  265. " bx lr "
  266. ::: "memory"
  267. );
  268. }
  269. /*-----------------------------------------------------------*/
  270. void xPortPendSVHandler( void )
  271. {
  272. /* This is a naked function. */
  273. __asm volatile
  274. (
  275. " .syntax unified \n"
  276. " mrs r0, psp \n"
  277. " \n"
  278. " ldr r3, pxCurrentTCBConst \n"/* Get the location of the current TCB. */
  279. " ldr r2, [r3] \n"
  280. " \n"
  281. " subs r0, r0, #32 \n"/* Make space for the remaining low registers. */
  282. " str r0, [r2] \n"/* Save the new top of stack. */
  283. " stmia r0!, {r4-r7} \n"/* Store the low registers that are not saved automatically. */
  284. " mov r4, r8 \n"/* Store the high registers. */
  285. " mov r5, r9 \n"
  286. " mov r6, r10 \n"
  287. " mov r7, r11 \n"
  288. " stmia r0!, {r4-r7} \n"
  289. " \n"
  290. " push {r3, r14} \n"
  291. " cpsid i \n"
  292. " bl vTaskSwitchContext \n"
  293. " cpsie i \n"
  294. " pop {r2, r3} \n"/* lr goes in r3. r2 now holds tcb pointer. */
  295. " \n"
  296. " ldr r1, [r2] \n"
  297. " ldr r0, [r1] \n"/* The first item in pxCurrentTCB is the task top of stack. */
  298. " adds r0, r0, #16 \n"/* Move to the high registers. */
  299. " ldmia r0!, {r4-r7} \n"/* Pop the high registers. */
  300. " mov r8, r4 \n"
  301. " mov r9, r5 \n"
  302. " mov r10, r6 \n"
  303. " mov r11, r7 \n"
  304. " \n"
  305. " msr psp, r0 \n"/* Remember the new top of stack for the task. */
  306. " \n"
  307. " subs r0, r0, #32 \n"/* Go back for the low registers that are not automatically restored. */
  308. " ldmia r0!, {r4-r7} \n"/* Pop low registers. */
  309. " \n"
  310. " bx r3 \n"
  311. " \n"
  312. " .align 4 \n"
  313. "pxCurrentTCBConst: .word pxCurrentTCB "
  314. );
  315. }
  316. /*-----------------------------------------------------------*/
  317. void xPortSysTickHandler( void )
  318. {
  319. uint32_t ulPreviousMask;
  320. ulPreviousMask = portSET_INTERRUPT_MASK_FROM_ISR();
  321. {
  322. /* Increment the RTOS tick. */
  323. if( xTaskIncrementTick() != pdFALSE )
  324. {
  325. /* Pend a context switch. */
  326. portNVIC_INT_CTRL_REG = portNVIC_PENDSVSET_BIT;
  327. }
  328. }
  329. portCLEAR_INTERRUPT_MASK_FROM_ISR( ulPreviousMask );
  330. }
  331. /*-----------------------------------------------------------*/
  332. /*
  333. * Setup the systick timer to generate the tick interrupts at the required
  334. * frequency.
  335. */
  336. __attribute__( ( weak ) ) void vPortSetupTimerInterrupt( void )
  337. {
  338. /* Calculate the constants required to configure the tick interrupt. */
  339. #if ( configUSE_TICKLESS_IDLE == 1 )
  340. {
  341. ulTimerCountsForOneTick = ( configCPU_CLOCK_HZ / configTICK_RATE_HZ );
  342. xMaximumPossibleSuppressedTicks = portMAX_24_BIT_NUMBER / ulTimerCountsForOneTick;
  343. ulStoppedTimerCompensation = portMISSED_COUNTS_FACTOR;
  344. }
  345. #endif /* configUSE_TICKLESS_IDLE */
  346. /* Stop and reset the SysTick. */
  347. portNVIC_SYSTICK_CTRL_REG = 0UL;
  348. portNVIC_SYSTICK_CURRENT_VALUE_REG = 0UL;
  349. /* Configure SysTick to interrupt at the requested rate. */
  350. portNVIC_SYSTICK_LOAD_REG = ( configCPU_CLOCK_HZ / configTICK_RATE_HZ ) - 1UL;
  351. portNVIC_SYSTICK_CTRL_REG = portNVIC_SYSTICK_CLK_BIT | portNVIC_SYSTICK_INT_BIT | portNVIC_SYSTICK_ENABLE_BIT;
  352. }
  353. /*-----------------------------------------------------------*/
  354. #if ( configUSE_TICKLESS_IDLE == 1 )
  355. __attribute__( ( weak ) ) void vPortSuppressTicksAndSleep( TickType_t xExpectedIdleTime )
  356. {
  357. uint32_t ulReloadValue, ulCompleteTickPeriods, ulCompletedSysTickDecrements;
  358. TickType_t xModifiableIdleTime;
  359. /* Make sure the SysTick reload value does not overflow the counter. */
  360. if( xExpectedIdleTime > xMaximumPossibleSuppressedTicks )
  361. {
  362. xExpectedIdleTime = xMaximumPossibleSuppressedTicks;
  363. }
  364. /* Stop the SysTick momentarily. The time the SysTick is stopped for
  365. * is accounted for as best it can be, but using the tickless mode will
  366. * inevitably result in some tiny drift of the time maintained by the
  367. * kernel with respect to calendar time. */
  368. portNVIC_SYSTICK_CTRL_REG &= ~portNVIC_SYSTICK_ENABLE_BIT;
  369. /* Calculate the reload value required to wait xExpectedIdleTime
  370. * tick periods. -1 is used because this code will execute part way
  371. * through one of the tick periods. */
  372. ulReloadValue = portNVIC_SYSTICK_CURRENT_VALUE_REG + ( ulTimerCountsForOneTick * ( xExpectedIdleTime - 1UL ) );
  373. if( ulReloadValue > ulStoppedTimerCompensation )
  374. {
  375. ulReloadValue -= ulStoppedTimerCompensation;
  376. }
  377. /* Enter a critical section but don't use the taskENTER_CRITICAL()
  378. * method as that will mask interrupts that should exit sleep mode. */
  379. __asm volatile ( "cpsid i" ::: "memory" );
  380. __asm volatile ( "dsb" );
  381. __asm volatile ( "isb" );
  382. /* If a context switch is pending or a task is waiting for the scheduler
  383. * to be unsuspended then abandon the low power entry. */
  384. if( eTaskConfirmSleepModeStatus() == eAbortSleep )
  385. {
  386. /* Restart from whatever is left in the count register to complete
  387. * this tick period. */
  388. portNVIC_SYSTICK_LOAD_REG = portNVIC_SYSTICK_CURRENT_VALUE_REG;
  389. /* Restart SysTick. */
  390. portNVIC_SYSTICK_CTRL_REG |= portNVIC_SYSTICK_ENABLE_BIT;
  391. /* Reset the reload register to the value required for normal tick
  392. * periods. */
  393. portNVIC_SYSTICK_LOAD_REG = ulTimerCountsForOneTick - 1UL;
  394. /* Re-enable interrupts - see comments above the cpsid instruction()
  395. * above. */
  396. __asm volatile ( "cpsie i" ::: "memory" );
  397. }
  398. else
  399. {
  400. /* Set the new reload value. */
  401. portNVIC_SYSTICK_LOAD_REG = ulReloadValue;
  402. /* Clear the SysTick count flag and set the count value back to
  403. * zero. */
  404. portNVIC_SYSTICK_CURRENT_VALUE_REG = 0UL;
  405. /* Restart SysTick. */
  406. portNVIC_SYSTICK_CTRL_REG |= portNVIC_SYSTICK_ENABLE_BIT;
  407. /* Sleep until something happens. configPRE_SLEEP_PROCESSING() can
  408. * set its parameter to 0 to indicate that its implementation contains
  409. * its own wait for interrupt or wait for event instruction, and so wfi
  410. * should not be executed again. However, the original expected idle
  411. * time variable must remain unmodified, so a copy is taken. */
  412. xModifiableIdleTime = xExpectedIdleTime;
  413. configPRE_SLEEP_PROCESSING( xModifiableIdleTime );
  414. if( xModifiableIdleTime > 0 )
  415. {
  416. __asm volatile ( "dsb" ::: "memory" );
  417. __asm volatile ( "wfi" );
  418. __asm volatile ( "isb" );
  419. }
  420. configPOST_SLEEP_PROCESSING( xExpectedIdleTime );
  421. /* Re-enable interrupts to allow the interrupt that brought the MCU
  422. * out of sleep mode to execute immediately. see comments above
  423. * __disable_interrupt() call above. */
  424. __asm volatile ( "cpsie i" ::: "memory" );
  425. __asm volatile ( "dsb" );
  426. __asm volatile ( "isb" );
  427. /* Disable interrupts again because the clock is about to be stopped
  428. * and interrupts that execute while the clock is stopped will increase
  429. * any slippage between the time maintained by the RTOS and calendar
  430. * time. */
  431. __asm volatile ( "cpsid i" ::: "memory" );
  432. __asm volatile ( "dsb" );
  433. __asm volatile ( "isb" );
  434. /* Disable the SysTick clock without reading the
  435. * portNVIC_SYSTICK_CTRL_REG register to ensure the
  436. * portNVIC_SYSTICK_COUNT_FLAG_BIT is not cleared if it is set. Again,
  437. * the time the SysTick is stopped for is accounted for as best it can
  438. * be, but using the tickless mode will inevitably result in some tiny
  439. * drift of the time maintained by the kernel with respect to calendar
  440. * time*/
  441. portNVIC_SYSTICK_CTRL_REG = ( portNVIC_SYSTICK_CLK_BIT | portNVIC_SYSTICK_INT_BIT );
  442. /* Determine if the SysTick clock has already counted to zero and
  443. * been set back to the current reload value (the reload back being
  444. * correct for the entire expected idle time) or if the SysTick is yet
  445. * to count to zero (in which case an interrupt other than the SysTick
  446. * must have brought the system out of sleep mode). */
  447. if( ( portNVIC_SYSTICK_CTRL_REG & portNVIC_SYSTICK_COUNT_FLAG_BIT ) != 0 )
  448. {
  449. uint32_t ulCalculatedLoadValue;
  450. /* The tick interrupt is already pending, and the SysTick count
  451. * reloaded with ulReloadValue. Reset the
  452. * portNVIC_SYSTICK_LOAD_REG with whatever remains of this tick
  453. * period. */
  454. ulCalculatedLoadValue = ( ulTimerCountsForOneTick - 1UL ) - ( ulReloadValue - portNVIC_SYSTICK_CURRENT_VALUE_REG );
  455. /* Don't allow a tiny value, or values that have somehow
  456. * underflowed because the post sleep hook did something
  457. * that took too long. */
  458. if( ( ulCalculatedLoadValue < ulStoppedTimerCompensation ) || ( ulCalculatedLoadValue > ulTimerCountsForOneTick ) )
  459. {
  460. ulCalculatedLoadValue = ( ulTimerCountsForOneTick - 1UL );
  461. }
  462. portNVIC_SYSTICK_LOAD_REG = ulCalculatedLoadValue;
  463. /* As the pending tick will be processed as soon as this
  464. * function exits, the tick value maintained by the tick is stepped
  465. * forward by one less than the time spent waiting. */
  466. ulCompleteTickPeriods = xExpectedIdleTime - 1UL;
  467. }
  468. else
  469. {
  470. /* Something other than the tick interrupt ended the sleep.
  471. * Work out how long the sleep lasted rounded to complete tick
  472. * periods (not the ulReload value which accounted for part
  473. * ticks). */
  474. ulCompletedSysTickDecrements = ( xExpectedIdleTime * ulTimerCountsForOneTick ) - portNVIC_SYSTICK_CURRENT_VALUE_REG;
  475. /* How many complete tick periods passed while the processor
  476. * was waiting? */
  477. ulCompleteTickPeriods = ulCompletedSysTickDecrements / ulTimerCountsForOneTick;
  478. /* The reload value is set to whatever fraction of a single tick
  479. * period remains. */
  480. portNVIC_SYSTICK_LOAD_REG = ( ( ulCompleteTickPeriods + 1UL ) * ulTimerCountsForOneTick ) - ulCompletedSysTickDecrements;
  481. }
  482. /* Restart SysTick so it runs from portNVIC_SYSTICK_LOAD_REG
  483. * again, then set portNVIC_SYSTICK_LOAD_REG back to its standard
  484. * value. */
  485. portNVIC_SYSTICK_CURRENT_VALUE_REG = 0UL;
  486. portNVIC_SYSTICK_CTRL_REG |= portNVIC_SYSTICK_ENABLE_BIT;
  487. vTaskStepTick( ulCompleteTickPeriods );
  488. portNVIC_SYSTICK_LOAD_REG = ulTimerCountsForOneTick - 1UL;
  489. /* Exit with interrpts enabled. */
  490. __asm volatile ( "cpsie i" ::: "memory" );
  491. }
  492. }
  493. #endif /* configUSE_TICKLESS_IDLE */