2 * FreeRTOS Kernel V10.4.3
3 * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
5 * Permission is hereby granted, free of charge, to any person obtaining a copy of
6 * this software and associated documentation files (the "Software"), to deal in
7 * the Software without restriction, including without limitation the rights to
8 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
9 * the Software, and to permit persons to whom the Software is furnished to do so,
10 * subject to the following conditions:
12 * The above copyright notice and this permission notice shall be included in all
13 * copies or substantial portions of the Software.
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
17 * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
18 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
19 * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
20 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 * https://www.FreeRTOS.org
23 * https://github.com/FreeRTOS
27 /* Standard includes. */
31 /* Defining MPU_WRAPPERS_INCLUDED_FROM_API_FILE prevents task.h from redefining
32 * all the API functions to use the MPU wrappers. That should only be done when
33 * task.h is included from an application file. */
34 #define MPU_WRAPPERS_INCLUDED_FROM_API_FILE
36 #define DEBUG_UNIT FREERTOS_TASKS
38 /* FreeRTOS includes. */
42 #include "stack_macros.h"
44 /* Lint e9021, e961 and e750 are suppressed as a MISRA exception justified
45 * because the MPU ports require MPU_WRAPPERS_INCLUDED_FROM_API_FILE to be defined
46 * for the header files above, but not in this file, in order to generate the
47 * correct privileged Vs unprivileged linkage and placement. */
48 #undef MPU_WRAPPERS_INCLUDED_FROM_API_FILE /*lint !e961 !e750 !e9021. */
50 /* Set configUSE_STATS_FORMATTING_FUNCTIONS to 2 to include the stats formatting
51 * functions but without including stdio.h here. */
52 #if ( configUSE_STATS_FORMATTING_FUNCTIONS == 1 )
54 /* At the bottom of this file are two optional functions that can be used
55 * to generate human readable text from the raw data generated by the
56 * uxTaskGetSystemState() function. Note the formatting functions are provided
57 * for convenience only, and are NOT considered part of the kernel. */
59 #endif /* configUSE_STATS_FORMATTING_FUNCTIONS == 1 ) */
61 #if ( configUSE_PREEMPTION == 0 )
63 /* If the cooperative scheduler is being used then a yield should not be
64 * performed just because a higher priority task has been woken. */
65 #define taskYIELD_IF_USING_PREEMPTION()
67 #define taskYIELD_IF_USING_PREEMPTION() vTaskYieldWithinAPI()
70 /* Values that can be assigned to the ucNotifyState member of the TCB. */
71 #define taskNOT_WAITING_NOTIFICATION ( ( uint8_t ) 0 ) /* Must be zero as it is the initialised value. */
72 #define taskWAITING_NOTIFICATION ( ( uint8_t ) 1 )
73 #define taskNOTIFICATION_RECEIVED ( ( uint8_t ) 2 )
76 * The value used to fill the stack of a task when the task is created. This
77 * is used purely for checking the high water mark for tasks.
79 #define tskSTACK_FILL_BYTE ( 0xa5U )
81 /* Bits used to record how a task's stack and TCB were allocated. */
82 #define tskDYNAMICALLY_ALLOCATED_STACK_AND_TCB ( ( uint8_t ) 0 )
83 #define tskSTATICALLY_ALLOCATED_STACK_ONLY ( ( uint8_t ) 1 )
84 #define tskSTATICALLY_ALLOCATED_STACK_AND_TCB ( ( uint8_t ) 2 )
86 /* If any of the following are set then task stacks are filled with a known
87 * value so the high water mark can be determined. If none of the following are
88 * set then don't fill the stack so there is no unnecessary dependency on memset. */
89 #if ( ( configCHECK_FOR_STACK_OVERFLOW > 1 ) || ( configUSE_TRACE_FACILITY == 1 ) || ( INCLUDE_uxTaskGetStackHighWaterMark == 1 ) || ( INCLUDE_uxTaskGetStackHighWaterMark2 == 1 ) )
90 #define tskSET_NEW_STACKS_TO_KNOWN_VALUE 1
92 #define tskSET_NEW_STACKS_TO_KNOWN_VALUE 0
96 * Macros used by vListTask to indicate which state a task is in.
98 #define tskRUNNING_CHAR ( 'X' )
99 #define tskBLOCKED_CHAR ( 'B' )
100 #define tskREADY_CHAR ( 'R' )
101 #define tskDELETED_CHAR ( 'D' )
102 #define tskSUSPENDED_CHAR ( 'S' )
105 * Some kernel aware debuggers require the data the debugger needs access to to
106 * be global, rather than file scope.
108 #ifdef portREMOVE_STATIC_QUALIFIER
112 /* The name allocated to the Idle task. This can be overridden by defining
113 * configIDLE_TASK_NAME in FreeRTOSConfig.h. */
114 #ifndef configIDLE_TASK_NAME
115 #define configIDLE_TASK_NAME "IDLE"
118 #if ( configUSE_PORT_OPTIMISED_TASK_SELECTION == 0 )
120 /* If configUSE_PORT_OPTIMISED_TASK_SELECTION is 0 then task selection is
121 * performed in a generic way that is not optimised to any particular
122 * microcontroller architecture. */
124 /* uxTopReadyPriority holds the priority of the highest priority ready
126 #define taskRECORD_READY_PRIORITY( uxPriority ) \
128 if( ( uxPriority ) > uxTopReadyPriority ) \
130 uxTopReadyPriority = ( uxPriority ); \
132 } /* taskRECORD_READY_PRIORITY */
134 /*-----------------------------------------------------------*/
136 /* Define away taskRESET_READY_PRIORITY() and portRESET_READY_PRIORITY() as
137 * they are only required when a port optimised method of task selection is
139 #define taskRESET_READY_PRIORITY( uxPriority )
140 #define portRESET_READY_PRIORITY( uxPriority, uxTopReadyPriority )
142 #else /* configUSE_PORT_OPTIMISED_TASK_SELECTION */
144 #error configUSE_PORT_OPTIMISED_TASK_SELECTION not yet supported in SMP
146 /* If configUSE_PORT_OPTIMISED_TASK_SELECTION is 1 then task selection is
147 * performed in a way that is tailored to the particular microcontroller
148 * architecture being used. */
150 /* A port optimised version is provided. Call the port defined macros. */
151 #define taskRECORD_READY_PRIORITY( uxPriority ) portRECORD_READY_PRIORITY( uxPriority, uxTopReadyPriority )
153 /*-----------------------------------------------------------*/
155 /* A port optimised version is provided, call it only if the TCB being reset
156 * is being referenced from a ready list. If it is referenced from a delayed
157 * or suspended list then it won't be in a ready list. */
158 #define taskRESET_READY_PRIORITY( uxPriority ) \
160 if( listCURRENT_LIST_LENGTH( &( pxReadyTasksLists[ ( uxPriority ) ] ) ) == ( UBaseType_t ) 0 ) \
162 portRESET_READY_PRIORITY( ( uxPriority ), ( uxTopReadyPriority ) ); \
166 #endif /* configUSE_PORT_OPTIMISED_TASK_SELECTION */
168 /*-----------------------------------------------------------*/
170 /* pxDelayedTaskList and pxOverflowDelayedTaskList are switched when the tick
171 * count overflows. */
172 #define taskSWITCH_DELAYED_LISTS() \
176 /* The delayed tasks list should be empty when the lists are switched. */ \
177 configASSERT( ( listLIST_IS_EMPTY( pxDelayedTaskList ) ) ); \
179 pxTemp = pxDelayedTaskList; \
180 pxDelayedTaskList = pxOverflowDelayedTaskList; \
181 pxOverflowDelayedTaskList = pxTemp; \
183 prvResetNextTaskUnblockTime(); \
186 /*-----------------------------------------------------------*/
189 * Place the task represented by pxTCB into the appropriate ready list for
190 * the task. It is inserted at the end of the list.
192 #define prvAddTaskToReadyList( pxTCB ) \
193 traceMOVED_TASK_TO_READY_STATE( pxTCB ); \
194 taskRECORD_READY_PRIORITY( ( pxTCB )->uxPriority ); \
195 vListInsertEnd( &( pxReadyTasksLists[ ( pxTCB )->uxPriority ] ), &( ( pxTCB )->xStateListItem ) ); \
196 tracePOST_MOVED_TASK_TO_READY_STATE( pxTCB )
197 /*-----------------------------------------------------------*/
200 * Several functions take a TaskHandle_t parameter that can optionally be NULL,
201 * where NULL is used to indicate that the handle of the currently executing
202 * task should be used in place of the parameter. This macro simply checks to
203 * see if the parameter is NULL and returns a pointer to the appropriate TCB.
205 #define prvGetTCBFromHandle( pxHandle ) ( ( ( pxHandle ) == NULL ) ? pxCurrentTCB : ( pxHandle ) )
207 /* The item value of the event list item is normally used to hold the priority
208 * of the task to which it belongs (coded to allow it to be held in reverse
209 * priority order). However, it is occasionally borrowed for other purposes. It
210 * is important its value is not updated due to a task priority change while it is
211 * being used for another purpose. The following bit definition is used to inform
212 * the scheduler that the value should not be changed - in which case it is the
213 * responsibility of whichever module is using the value to ensure it gets set back
214 * to its original value when it is released. */
215 #if ( configUSE_16_BIT_TICKS == 1 )
216 #define taskEVENT_LIST_ITEM_VALUE_IN_USE 0x8000U
218 #define taskEVENT_LIST_ITEM_VALUE_IN_USE 0x80000000UL
221 /* Indicates that the task is not actively running on any core. */
222 #define taskTASK_NOT_RUNNING ( TaskRunning_t ) ( -1 )
224 /* Indicates that the task is actively running but scheduled to yield. */
225 #define taskTASK_YIELDING ( TaskRunning_t ) ( -2 )
227 /* Returns pdTRUE if the task is actively running and not scheduled to yield. */
228 #define taskTASK_IS_RUNNING( xTaskRunState ) ( ( 0 <= xTaskRunState ) && ( xTaskRunState < configNUM_CORES ) )
230 typedef BaseType_t TaskRunning_t;
233 * Task control block. A task control block (TCB) is allocated for each task,
234 * and stores task state information, including a pointer to the task's context
235 * (the task's run time environment, including register values)
237 typedef struct tskTaskControlBlock /* The old naming convention is used to prevent breaking kernel aware debuggers. */
239 volatile StackType_t * pxTopOfStack; /*< Points to the location of the last item placed on the tasks stack. THIS MUST BE THE FIRST MEMBER OF THE TCB STRUCT. */
241 #if ( portUSING_MPU_WRAPPERS == 1 )
242 xMPU_SETTINGS xMPUSettings; /*< The MPU settings are defined as part of the port layer. THIS MUST BE THE SECOND MEMBER OF THE TCB STRUCT. */
245 ListItem_t xStateListItem; /*< The list that the state list item of a task is reference from denotes the state of that task (Ready, Blocked, Suspended ). */
246 ListItem_t xEventListItem; /*< Used to reference a task from an event list. */
247 UBaseType_t uxPriority; /*< The priority of the task. 0 is the lowest priority. */
248 StackType_t * pxStack; /*< Points to the start of the stack. */
249 volatile TaskRunning_t xTaskRunState; /*< Used to identify the core the task is running on, if any. */
250 BaseType_t xIsIdle; /*< Used to identify the idle tasks. */
251 char pcTaskName[ configMAX_TASK_NAME_LEN ]; /*< Descriptive name given to the task when created. Facilitates debugging only. */ /*lint !e971 Unqualified char types are allowed for strings and single characters only. */
253 #if ( configUSE_TASK_PREEMPTION_DISABLE == 1 )
254 BaseType_t xPreemptionDisable; /*< Used to prevent the task from being preempted */
257 #if ( configUSE_CORE_AFFINITY == 1 && configNUM_CORES > 1 )
258 UBaseType_t uxCoreAffinityMask; /*< Used to link the task to certain cores. UBaseType_t must have >= the same number of bits as SMP confNUM_CORES */
261 #if ( ( portSTACK_GROWTH > 0 ) || ( configRECORD_STACK_HIGH_ADDRESS == 1 ) )
262 StackType_t * pxEndOfStack; /*< Points to the highest valid address for the stack. */
265 #if ( portCRITICAL_NESTING_IN_TCB == 1 )
266 UBaseType_t uxCriticalNesting; /*< Holds the critical section nesting depth for ports that do not maintain their own count in the port layer. */
269 #if ( configUSE_TRACE_FACILITY == 1 )
270 UBaseType_t uxTCBNumber; /*< Stores a number that increments each time a TCB is created. It allows debuggers to determine when a task has been deleted and then recreated. */
271 UBaseType_t uxTaskNumber; /*< Stores a number specifically for use by third party trace code. */
274 #if ( configUSE_MUTEXES == 1 )
275 UBaseType_t uxBasePriority; /*< The priority last assigned to the task - used by the priority inheritance mechanism. */
276 UBaseType_t uxMutexesHeld;
279 #if ( configUSE_APPLICATION_TASK_TAG == 1 )
280 TaskHookFunction_t pxTaskTag;
283 #if ( configNUM_THREAD_LOCAL_STORAGE_POINTERS > 0 )
284 void * pvThreadLocalStoragePointers[ configNUM_THREAD_LOCAL_STORAGE_POINTERS ];
287 #if ( configGENERATE_RUN_TIME_STATS == 1 )
288 uint32_t ulRunTimeCounter; /*< Stores the amount of time the task has spent in the Running state. */
291 #if ( configUSE_NEWLIB_REENTRANT == 1 )
292 /* Allocate a Newlib reent structure that is specific to this task.
293 * Note Newlib support has been included by popular demand, but is not
294 * used by the FreeRTOS maintainers themselves. FreeRTOS is not
295 * responsible for resulting newlib operation. User must be familiar with
296 * newlib and must provide system-wide implementations of the necessary
297 * stubs. Be warned that (at the time of writing) the current newlib design
298 * implements a system-wide malloc() that must be provided with locks.
300 * See the third party link http://www.nadler.com/embedded/newlibAndFreeRTOS.html
301 * for additional information. */
302 struct _reent xNewLib_reent;
305 #if ( configUSE_TASK_NOTIFICATIONS == 1 )
306 volatile uint32_t ulNotifiedValue[ configTASK_NOTIFICATION_ARRAY_ENTRIES ];
307 volatile uint8_t ucNotifyState[ configTASK_NOTIFICATION_ARRAY_ENTRIES ];
310 /* See the comments in FreeRTOS.h with the definition of
311 * tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE. */
312 #if ( tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE != 0 ) /*lint !e731 !e9029 Macro has been consolidated for readability reasons. */
313 uint8_t ucStaticallyAllocated; /*< Set to pdTRUE if the task is a statically allocated to ensure no attempt is made to free the memory. */
316 #if ( INCLUDE_xTaskAbortDelay == 1 )
317 uint8_t ucDelayAborted;
320 #if ( configUSE_POSIX_ERRNO == 1 )
325 /* The old tskTCB name is maintained above then typedefed to the new TCB_t name
326 * below to enable the use of older kernel aware debuggers. */
327 typedef tskTCB TCB_t;
329 /*lint -save -e956 A manual analysis and inspection has been used to determine
330 * which static variables must be declared volatile. */
331 PRIVILEGED_DATA TCB_t * volatile pxCurrentTCBs[ configNUM_CORES ] = { NULL };
332 #define pxCurrentTCB xTaskGetCurrentTaskHandle()
334 /* Lists for ready and blocked tasks. --------------------
335 * xDelayedTaskList1 and xDelayedTaskList2 could be moved to function scope but
336 * doing so breaks some kernel aware debuggers and debuggers that rely on removing
337 * the static qualifier. */
338 PRIVILEGED_DATA static List_t pxReadyTasksLists[ configMAX_PRIORITIES ]; /*< Prioritised ready tasks. */
339 PRIVILEGED_DATA static List_t xDelayedTaskList1; /*< Delayed tasks. */
340 PRIVILEGED_DATA static List_t xDelayedTaskList2; /*< Delayed tasks (two lists are used - one for delays that have overflowed the current tick count. */
341 PRIVILEGED_DATA static List_t * volatile pxDelayedTaskList; /*< Points to the delayed task list currently being used. */
342 PRIVILEGED_DATA static List_t * volatile pxOverflowDelayedTaskList; /*< Points to the delayed task list currently being used to hold tasks that have overflowed the current tick count. */
343 PRIVILEGED_DATA static List_t xPendingReadyList; /*< Tasks that have been readied while the scheduler was suspended. They will be moved to the ready list when the scheduler is resumed. */
345 #if ( INCLUDE_vTaskDelete == 1 )
347 PRIVILEGED_DATA static List_t xTasksWaitingTermination; /*< Tasks that have been deleted - but their memory not yet freed. */
348 PRIVILEGED_DATA static volatile UBaseType_t uxDeletedTasksWaitingCleanUp = ( UBaseType_t ) 0U;
352 #if ( INCLUDE_vTaskSuspend == 1 )
354 PRIVILEGED_DATA static List_t xSuspendedTaskList; /*< Tasks that are currently suspended. */
358 /* Global POSIX errno. Its value is changed upon context switching to match
359 * the errno of the currently running task. */
360 #if ( configUSE_POSIX_ERRNO == 1 )
361 int FreeRTOS_errno = 0;
364 /* Other file private variables. --------------------------------*/
365 PRIVILEGED_DATA static volatile UBaseType_t uxCurrentNumberOfTasks = ( UBaseType_t ) 0U;
366 PRIVILEGED_DATA static volatile TickType_t xTickCount = ( TickType_t ) configINITIAL_TICK_COUNT;
367 PRIVILEGED_DATA static volatile UBaseType_t uxTopReadyPriority = tskIDLE_PRIORITY;
368 PRIVILEGED_DATA static volatile BaseType_t xSchedulerRunning = pdFALSE;
369 PRIVILEGED_DATA static volatile TickType_t xPendedTicks = ( TickType_t ) 0U;
370 PRIVILEGED_DATA static volatile BaseType_t xYieldPendings[ configNUM_CORES ] = { pdFALSE };
371 PRIVILEGED_DATA static volatile BaseType_t xNumOfOverflows = ( BaseType_t ) 0;
372 PRIVILEGED_DATA static UBaseType_t uxTaskNumber = ( UBaseType_t ) 0U;
373 PRIVILEGED_DATA static volatile TickType_t xNextTaskUnblockTime = ( TickType_t ) 0U; /* Initialised to portMAX_DELAY before the scheduler starts. */
374 PRIVILEGED_DATA static TaskHandle_t xIdleTaskHandle[ configNUM_CORES ] = { NULL }; /*< Holds the handle of the idle task. The idle task is created automatically when the scheduler is started. */
376 #define xYieldPending prvGetCurrentYieldPending()
378 /* Improve support for OpenOCD. The kernel tracks Ready tasks via priority lists.
379 * For tracking the state of remote threads, OpenOCD uses uxTopUsedPriority
380 * to determine the number of priority lists to read back from the remote target. */
381 const volatile UBaseType_t uxTopUsedPriority = configMAX_PRIORITIES - 1U;
383 /* Context switches are held pending while the scheduler is suspended. Also,
384 * interrupts must not manipulate the xStateListItem of a TCB, or any of the
385 * lists the xStateListItem can be referenced from, if the scheduler is suspended.
386 * If an interrupt needs to unblock a task while the scheduler is suspended then it
387 * moves the task's event list item into the xPendingReadyList, ready for the
388 * kernel to move the task from the pending ready list into the real ready list
389 * when the scheduler is unsuspended. The pending ready list itself can only be
390 * accessed from a critical section.
392 * Updates to uxSchedulerSuspended must be protected by both the task and ISR locks and
393 * must not be done by an ISR. Reads must be protected by either lock and may be done by
394 * either an ISR or a task. */
395 PRIVILEGED_DATA static volatile UBaseType_t uxSchedulerSuspended = ( UBaseType_t ) pdFALSE;
397 #if ( configGENERATE_RUN_TIME_STATS == 1 )
399 /* Do not move these variables to function scope as doing so prevents the
400 * code working with debuggers that need to remove the static qualifier. */
401 PRIVILEGED_DATA static uint32_t ulTaskSwitchedInTime = 0UL; /*< Holds the value of a timer/counter the last time a task was switched in. */
402 PRIVILEGED_DATA static volatile uint32_t ulTotalRunTime = 0UL; /*< Holds the total amount of execution time as defined by the run time counter clock. */
408 /*-----------------------------------------------------------*/
410 /* File private functions. --------------------------------*/
413 * Creates the idle tasks during scheduler start
415 static BaseType_t prvCreateIdleTasks( void );
418 * Returns the yield pending count for the calling core.
420 static BaseType_t prvGetCurrentYieldPending( void );
423 * Checks to see if another task moved the current task out of the ready
424 * list while it was waiting to enter a critical section and yields if so.
426 static void prvCheckForRunStateChange( void );
429 * Yields the given core.
431 static void prvYieldCore( BaseType_t xCoreID );
434 * Yields a core, or cores if multiple priorities are not allowed to run
435 * simultaneously, to allow the task pxTCB to run.
437 static void prvYieldForTask( TCB_t * pxTCB,
438 const BaseType_t xPreemptEqualPriority );
441 * Selects the highest priority available task
443 static BaseType_t prvSelectHighestPriorityTask( const BaseType_t xCoreID );
446 * Utility task that simply returns pdTRUE if the task referenced by xTask is
447 * currently in the Suspended state, or pdFALSE if the task referenced by xTask
448 * is in any other state.
450 #if ( INCLUDE_vTaskSuspend == 1 )
452 static BaseType_t prvTaskIsTaskSuspended( const TaskHandle_t xTask ) PRIVILEGED_FUNCTION;
454 #endif /* INCLUDE_vTaskSuspend */
457 * Utility to ready all the lists used by the scheduler. This is called
458 * automatically upon the creation of the first task.
460 static void prvInitialiseTaskLists( void ) PRIVILEGED_FUNCTION;
463 * The idle task, which as all tasks is implemented as a never ending loop.
464 * The idle task is automatically created and added to the ready lists upon
465 * creation of the first user task.
468 static portTASK_FUNCTION_PROTO( prvIdleTask, pvParameters ) PRIVILEGED_FUNCTION;
469 #if ( configNUM_CORES > 1 )
470 static portTASK_FUNCTION_PROTO( prvMinimalIdleTask, pvParameters ) PRIVILEGED_FUNCTION;
474 * Utility to free all memory allocated by the scheduler to hold a TCB,
475 * including the stack pointed to by the TCB.
477 * This does not free memory allocated by the task itself (i.e. memory
478 * allocated by calls to pvPortMalloc from within the tasks application code).
480 #if ( INCLUDE_vTaskDelete == 1 )
482 static void prvDeleteTCB( TCB_t * pxTCB ) PRIVILEGED_FUNCTION;
487 * Used only by the idle task. This checks to see if anything has been placed
488 * in the list of tasks waiting to be deleted. If so the task is cleaned up
489 * and its TCB deleted.
491 static void prvCheckTasksWaitingTermination( void ) PRIVILEGED_FUNCTION;
494 * The currently executing task is entering the Blocked state. Add the task to
495 * either the current or the overflow delayed task list.
497 static void prvAddCurrentTaskToDelayedList( TickType_t xTicksToWait,
498 const BaseType_t xCanBlockIndefinitely ) PRIVILEGED_FUNCTION;
501 * Fills an TaskStatus_t structure with information on each task that is
502 * referenced from the pxList list (which may be a ready list, a delayed list,
503 * a suspended list, etc.).
505 * THIS FUNCTION IS INTENDED FOR DEBUGGING ONLY, AND SHOULD NOT BE CALLED FROM
506 * NORMAL APPLICATION CODE.
508 #if ( configUSE_TRACE_FACILITY == 1 )
510 static UBaseType_t prvListTasksWithinSingleList( TaskStatus_t * pxTaskStatusArray,
512 eTaskState eState ) PRIVILEGED_FUNCTION;
517 * Searches pxList for a task with name pcNameToQuery - returning a handle to
518 * the task if it is found, or NULL if the task is not found.
520 #if ( INCLUDE_xTaskGetHandle == 1 )
522 static TCB_t * prvSearchForNameWithinSingleList( List_t * pxList,
523 const char pcNameToQuery[] ) PRIVILEGED_FUNCTION;
528 * When a task is created, the stack of the task is filled with a known value.
529 * This function determines the 'high water mark' of the task stack by
530 * determining how much of the stack remains at the original preset value.
532 #if ( ( configUSE_TRACE_FACILITY == 1 ) || ( INCLUDE_uxTaskGetStackHighWaterMark == 1 ) || ( INCLUDE_uxTaskGetStackHighWaterMark2 == 1 ) )
534 static configSTACK_DEPTH_TYPE prvTaskCheckFreeStackSpace( const uint8_t * pucStackByte ) PRIVILEGED_FUNCTION;
539 * Return the amount of time, in ticks, that will pass before the kernel will
540 * next move a task from the Blocked state to the Running state.
542 * This conditional compilation should use inequality to 0, not equality to 1.
543 * This is to ensure portSUPPRESS_TICKS_AND_SLEEP() can be called when user
544 * defined low power mode implementations require configUSE_TICKLESS_IDLE to be
545 * set to a value other than 1.
547 #if ( configUSE_TICKLESS_IDLE != 0 )
549 static TickType_t prvGetExpectedIdleTime( void ) PRIVILEGED_FUNCTION;
554 * Set xNextTaskUnblockTime to the time at which the next Blocked state task
555 * will exit the Blocked state.
557 static void prvResetNextTaskUnblockTime( void ) PRIVILEGED_FUNCTION;
559 #if ( ( configUSE_TRACE_FACILITY == 1 ) && ( configUSE_STATS_FORMATTING_FUNCTIONS > 0 ) )
562 * Helper function used to pad task names with spaces when printing out
563 * human readable tables of task information.
565 static char * prvWriteNameToBuffer( char * pcBuffer,
566 const char * pcTaskName ) PRIVILEGED_FUNCTION;
571 * Called after a Task_t structure has been allocated either statically or
572 * dynamically to fill in the structure's members.
574 static void prvInitialiseNewTask( TaskFunction_t pxTaskCode,
575 const char * const pcName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */
576 const uint32_t ulStackDepth,
577 void * const pvParameters,
578 UBaseType_t uxPriority,
579 TaskHandle_t * const pxCreatedTask,
581 const MemoryRegion_t * const xRegions ) PRIVILEGED_FUNCTION;
584 * Called after a new task has been created and initialised to place the task
585 * under the control of the scheduler.
587 static void prvAddNewTaskToReadyList( TCB_t * pxNewTCB ) PRIVILEGED_FUNCTION;
590 * freertos_tasks_c_additions_init() should only be called if the user definable
591 * macro FREERTOS_TASKS_C_ADDITIONS_INIT() is defined, as that is the only macro
592 * called by the function.
594 #ifdef FREERTOS_TASKS_C_ADDITIONS_INIT
596 static void freertos_tasks_c_additions_init( void ) PRIVILEGED_FUNCTION;
600 /*-----------------------------------------------------------*/
602 static BaseType_t prvGetCurrentYieldPending( void )
607 ulState = portDISABLE_INTERRUPTS();
608 xReturn = xYieldPendings[ portGET_CORE_ID() ];
609 portRESTORE_INTERRUPTS( ulState );
614 /*-----------------------------------------------------------*/
616 static void prvCheckForRunStateChange( void )
618 UBaseType_t uxPrevCriticalNesting;
619 UBaseType_t uxPrevSchedulerSuspended;
622 /* This should be skipped when entering a critical section within
623 * an ISR. If the task on the current core is no longer running, then
624 * vTaskSwitchContext() probably should be run before returning, but
625 * we don't have a way to force that to happen from here. */
626 if( portCHECK_IF_IN_ISR() == pdFALSE )
628 /* This function is always called with interrupts disabled
629 * so this is safe. */
630 pxThisTCB = pxCurrentTCBs[ portGET_CORE_ID() ];
632 while( pxThisTCB->xTaskRunState == taskTASK_YIELDING )
634 /* We are only here if we just entered a critical section
635 * or if we just suspended the scheduler, and another task
636 * has requested that we yield.
638 * This is slightly complicated since we need to save and restore
639 * the suspension and critical nesting counts, as well as release
640 * and reacquire the correct locks. And then do it all over again
641 * if our state changed again during the reacquisition. */
643 uxPrevCriticalNesting = pxThisTCB->uxCriticalNesting;
644 uxPrevSchedulerSuspended = uxSchedulerSuspended;
646 /* this must only be called the first time we enter into a critical
647 * section, otherwise it could context switch in the middle of a
648 * critical section. */
649 configASSERT( uxPrevCriticalNesting + uxPrevSchedulerSuspended == 1U );
651 uxSchedulerSuspended = 0U;
653 if( uxPrevCriticalNesting > 0U )
655 pxThisTCB->uxCriticalNesting = 0U;
656 portRELEASE_ISR_LOCK();
657 portRELEASE_TASK_LOCK();
661 /* uxPrevSchedulerSuspended must be 1 */
662 portRELEASE_TASK_LOCK();
665 portMEMORY_BARRIER();
666 configASSERT( pxThisTCB->xTaskRunState == taskTASK_YIELDING );
668 portENABLE_INTERRUPTS();
670 /* Enabling interrupts should cause this core to immediately
671 * service the pending interrupt and yield. If the run state is still
672 * yielding here then that is a problem. */
673 configASSERT( pxThisTCB->xTaskRunState != taskTASK_YIELDING );
675 portDISABLE_INTERRUPTS();
678 pxCurrentTCB->uxCriticalNesting = uxPrevCriticalNesting;
679 uxSchedulerSuspended = uxPrevSchedulerSuspended;
681 if( uxPrevCriticalNesting == 0U )
683 /* uxPrevSchedulerSuspended must be 1 */
684 configASSERT( uxPrevSchedulerSuspended != ( UBaseType_t ) pdFALSE );
685 portRELEASE_ISR_LOCK();
691 /*-----------------------------------------------------------*/
693 static void prvYieldCore( BaseType_t xCoreID )
695 /* This must be called from a critical section and
696 * xCoreID must be valid. */
698 if( portCHECK_IF_IN_ISR() && ( xCoreID == portGET_CORE_ID() ) )
700 xYieldPendings[ xCoreID ] = pdTRUE;
702 else if( pxCurrentTCBs[ xCoreID ]->xTaskRunState != taskTASK_YIELDING )
704 if( xCoreID == portGET_CORE_ID() )
706 xYieldPendings[ xCoreID ] = pdTRUE;
710 portYIELD_CORE( xCoreID );
711 pxCurrentTCBs[ xCoreID ]->xTaskRunState = taskTASK_YIELDING;
716 /*-----------------------------------------------------------*/
718 static void prvYieldForTask( TCB_t * pxTCB,
719 const BaseType_t xPreemptEqualPriority )
721 BaseType_t xLowestPriority;
722 BaseType_t xTaskPriority;
723 BaseType_t xLowestPriorityCore = -1;
724 BaseType_t xYieldCount = 0;
726 TaskRunning_t xTaskRunState;
728 /* THIS FUNCTION MUST BE CALLED FROM A CRITICAL SECTION */
730 configASSERT( pxCurrentTCB->uxCriticalNesting > 0U );
732 #if ( ( configRUN_MULTIPLE_PRIORITIES == 0 ) && ( configNUM_CORES > 1 ) )
734 /* No task should yield for this one if it is a lower priority
735 * than priority level of currently ready tasks. */
736 if( pxTCB->uxPriority < uxTopReadyPriority )
743 xLowestPriority = ( BaseType_t ) pxTCB->uxPriority;
745 if( xPreemptEqualPriority == pdFALSE )
747 /* xLowestPriority will be decremented to -1 if the priority of pxTCB
748 * is 0. This is ok as we will give system idle tasks a priority of -1 below. */
752 for( x = ( BaseType_t ) 0; x < ( BaseType_t ) configNUM_CORES; x++ )
754 /* System idle tasks are being assigned a priority of tskIDLE_PRIORITY - 1 here */
755 xTaskPriority = ( BaseType_t ) pxCurrentTCBs[ x ]->uxPriority - pxCurrentTCBs[ x ]->xIsIdle;
756 xTaskRunState = pxCurrentTCBs[ x ]->xTaskRunState;
758 if( ( taskTASK_IS_RUNNING( xTaskRunState ) != pdFALSE ) && ( xYieldPendings[ x ] == pdFALSE ) )
760 if( xTaskPriority <= xLowestPriority )
762 #if ( configNUM_CORES > 1 )
763 #if ( configUSE_CORE_AFFINITY == 1 )
764 if( ( pxTCB->uxCoreAffinityMask & ( 1 << x ) ) != 0 )
768 #if ( configUSE_TASK_PREEMPTION_DISABLE == 1 )
769 if( pxCurrentTCBs[ x ]->xPreemptionDisable == pdFALSE )
772 xLowestPriority = xTaskPriority;
773 xLowestPriorityCore = x;
779 mtCOVERAGE_TEST_MARKER();
782 #if ( ( configRUN_MULTIPLE_PRIORITIES == 0 ) && ( configNUM_CORES > 1 ) ) && 1
784 /* Yield all currently running non-idle tasks with a priority lower than
785 * the task that needs to run. */
786 if( ( ( BaseType_t ) tskIDLE_PRIORITY - 1 < xTaskPriority ) && ( xTaskPriority < ( BaseType_t ) pxTCB->uxPriority ) )
793 mtCOVERAGE_TEST_MARKER();
796 #endif /* if ( ( configRUN_MULTIPLE_PRIORITIES == 0 ) && ( configNUM_CORES > 1 ) ) && 1 */
800 mtCOVERAGE_TEST_MARKER();
804 if( ( xYieldCount == 0 ) && taskVALID_CORE_ID( xLowestPriorityCore ) )
806 prvYieldCore( xLowestPriorityCore );
810 #if ( ( configRUN_MULTIPLE_PRIORITIES == 0 ) && ( configNUM_CORES > 1 ) )
811 /* Verify that the calling core always yields to higher priority tasks */
812 if( !pxCurrentTCBs[ portGET_CORE_ID() ]->xIsIdle && ( pxTCB->uxPriority > pxCurrentTCBs[ portGET_CORE_ID() ]->uxPriority ) )
814 configASSERT( xYieldPendings[ portGET_CORE_ID() ] == pdTRUE || taskTASK_IS_RUNNING( pxCurrentTCBs[ portGET_CORE_ID() ]->xTaskRunState ) == pdFALSE );
818 /*-----------------------------------------------------------*/
820 #if ( configUSE_PORT_OPTIMISED_TASK_SELECTION == 0 )
822 static BaseType_t prvSelectHighestPriorityTask( const BaseType_t xCoreID )
824 UBaseType_t uxCurrentPriority = uxTopReadyPriority;
825 BaseType_t xTaskScheduled = pdFALSE;
826 BaseType_t xDecrementTopPriority = pdTRUE;
828 #if ( configUSE_CORE_AFFINITY == 1 )
829 TCB_t * pxPreviousTCB = NULL;
831 #if ( ( configRUN_MULTIPLE_PRIORITIES == 0 ) && ( configNUM_CORES > 1 ) )
832 BaseType_t xPriorityDropped = pdFALSE;
835 while( xTaskScheduled == pdFALSE )
837 #if ( ( configRUN_MULTIPLE_PRIORITIES == 0 ) && ( configNUM_CORES > 1 ) )
839 if( uxCurrentPriority < uxTopReadyPriority )
841 /* We can't schedule any tasks, other than idle, that have a
842 * priority lower than the priority of a task currently running
843 * on another core. */
844 uxCurrentPriority = tskIDLE_PRIORITY;
849 if( listLIST_IS_EMPTY( &( pxReadyTasksLists[ uxCurrentPriority ] ) ) == pdFALSE )
851 List_t * const pxReadyList = &( pxReadyTasksLists[ uxCurrentPriority ] );
852 ListItem_t * pxLastTaskItem = pxReadyList->pxIndex->pxPrevious;
853 ListItem_t * pxTaskItem = pxLastTaskItem;
855 if( ( void * ) pxLastTaskItem == ( void * ) &( pxReadyList->xListEnd ) )
857 pxLastTaskItem = pxLastTaskItem->pxPrevious;
860 /* The ready task list for uxCurrentPriority is not empty, so uxTopReadyPriority
861 * must not be decremented any further */
862 xDecrementTopPriority = pdFALSE;
868 pxTaskItem = pxTaskItem->pxNext;
870 if( ( void * ) pxTaskItem == ( void * ) &( pxReadyList->xListEnd ) )
872 pxTaskItem = pxTaskItem->pxNext;
875 pxTCB = pxTaskItem->pvOwner;
877 /*debug_printf("Attempting to schedule %s on core %d\n", pxTCB->pcTaskName, portGET_CORE_ID() ); */
879 #if ( ( configRUN_MULTIPLE_PRIORITIES == 0 ) && ( configNUM_CORES > 1 ) )
881 /* When falling back to the idle priority because only one priority
882 * level is allowed to run at a time, we should ONLY schedule the true
883 * idle tasks, not user tasks at the idle priority. */
884 if( uxCurrentPriority < uxTopReadyPriority )
886 if( pxTCB->xIsIdle == pdFALSE )
892 #endif /* if ( ( configRUN_MULTIPLE_PRIORITIES == 0 ) && ( configNUM_CORES > 1 ) ) */
894 if( pxTCB->xTaskRunState == taskTASK_NOT_RUNNING )
896 #if ( configNUM_CORES > 1 )
897 #if ( configUSE_CORE_AFFINITY == 1 )
898 if( ( pxTCB->uxCoreAffinityMask & ( 1 << xCoreID ) ) != 0 )
902 /* If the task is not being executed by any core swap it in */
903 pxCurrentTCBs[ xCoreID ]->xTaskRunState = taskTASK_NOT_RUNNING;
904 #if ( configUSE_CORE_AFFINITY == 1 )
905 pxPreviousTCB = pxCurrentTCBs[ xCoreID ];
907 pxTCB->xTaskRunState = ( TaskRunning_t ) xCoreID;
908 pxCurrentTCBs[ xCoreID ] = pxTCB;
909 xTaskScheduled = pdTRUE;
912 else if( pxTCB == pxCurrentTCBs[ xCoreID ] )
914 configASSERT( ( pxTCB->xTaskRunState == xCoreID ) || ( pxTCB->xTaskRunState == taskTASK_YIELDING ) );
915 #if ( configNUM_CORES > 1 )
916 #if ( configUSE_CORE_AFFINITY == 1 )
917 if( ( pxTCB->uxCoreAffinityMask & ( 1 << xCoreID ) ) != 0 )
921 /* The task is already running on this core, mark it as scheduled */
922 pxTCB->xTaskRunState = ( TaskRunning_t ) xCoreID;
923 xTaskScheduled = pdTRUE;
927 if( xTaskScheduled != pdFALSE )
929 /* Once a task has been selected to run on this core,
930 * move it to the end of the ready task list. */
931 uxListRemove( pxTaskItem );
932 vListInsertEnd( pxReadyList, pxTaskItem );
935 } while( pxTaskItem != pxLastTaskItem );
939 if( xDecrementTopPriority != pdFALSE )
941 uxTopReadyPriority--;
942 #if ( ( configRUN_MULTIPLE_PRIORITIES == 0 ) && ( configNUM_CORES > 1 ) )
944 xPriorityDropped = pdTRUE;
950 /* This function can get called by vTaskSuspend() before the scheduler is started.
951 * In that case, since the idle tasks have not yet been created it is possible that we
952 * won't find a new task to schedule. Return pdFALSE in this case. */
953 if( ( xSchedulerRunning == pdFALSE ) && ( uxCurrentPriority == tskIDLE_PRIORITY ) && ( xTaskScheduled == pdFALSE ) )
958 configASSERT( ( uxCurrentPriority > tskIDLE_PRIORITY ) || ( xTaskScheduled == pdTRUE ) );
962 configASSERT( taskTASK_IS_RUNNING( pxCurrentTCBs[ xCoreID ]->xTaskRunState ) );
964 #if ( ( configRUN_MULTIPLE_PRIORITIES == 0 ) && ( configNUM_CORES > 1 ) )
965 if( xPriorityDropped != pdFALSE )
967 /* There may be several ready tasks that were being prevented from running because there was
968 * a higher priority task running. Now that the last of the higher priority tasks is no longer
969 * running, make sure all the other idle tasks yield. */
972 for( x = ( BaseType_t ) 0; x < ( BaseType_t ) configNUM_CORES; x++ )
974 if( pxCurrentTCBs[ x ]->xIsIdle != pdFALSE )
980 #endif /* if ( ( configRUN_MULTIPLE_PRIORITIES == 0 ) && ( configNUM_CORES > 1 ) ) */
982 #if ( configNUM_CORES > 1 )
983 #if ( configUSE_CORE_AFFINITY == 1 )
984 if( ( pxPreviousTCB != NULL ) && ( listIS_CONTAINED_WITHIN( &( pxReadyTasksLists[ pxPreviousTCB->uxPriority ] ), &( pxPreviousTCB->xStateListItem ) ) != pdFALSE ) )
986 /* A ready task was just bumped off this core. Look at the cores it can run from
987 * from to see if it is able to run on any of them */
988 UBaseType_t uxCoreMap = pxPreviousTCB->uxCoreAffinityMask;
989 BaseType_t xLowestPriority = pxPreviousTCB->uxPriority - pxPreviousTCB->xIsIdle;
990 BaseType_t xLowestPriorityCore = -1;
992 if( ( uxCoreMap & ( 1 << xCoreID ) ) != 0 )
994 /* The ready task that was removed from this core is not excluded from it.
995 * Only look at the intersection of the cores the removed task is allowed to run
996 * on with the cores that the new task is excluded from. It is possible that the
997 * new task was only placed onto this core because it is excluded from another.
998 * Check to see if the previous task could run on one of those cores. */
999 uxCoreMap &= ~( pxCurrentTCBs[ xCoreID ]->uxCoreAffinityMask );
1003 /* The ready task that was removed from this core is excluded from it. */
1006 uxCoreMap &= ( ( 1 << configNUM_CORES ) - 1 );
1008 while( uxCoreMap != 0 )
1010 int uxCore = 31UL - ( uint32_t ) __builtin_clz( uxCoreMap );
1012 xassert( taskVALID_CORE_ID( uxCore ) );
1014 uxCoreMap &= ~( 1 << uxCore );
1016 BaseType_t xTaskPriority = ( BaseType_t ) pxCurrentTCBs[ uxCore ]->uxPriority - pxCurrentTCBs[ uxCore ]->xIsIdle;
1018 if( ( xTaskPriority < xLowestPriority ) && ( taskTASK_IS_RUNNING( pxCurrentTCBs[ uxCore ]->xTaskRunState ) != pdFALSE ) && ( xYieldPendings[ uxCore ] == pdFALSE ) )
1020 #if ( configUSE_TASK_PREEMPTION_DISABLE == 1 )
1021 if( pxCurrentTCBs[ uxCore ]->xPreemptionDisable == pdFALSE )
1024 xLowestPriority = xTaskPriority;
1025 xLowestPriorityCore = uxCore;
1030 if( taskVALID_CORE_ID( xLowestPriorityCore ) )
1032 prvYieldCore( xLowestPriorityCore );
1035 #endif /* if ( configUSE_CORE_AFFINITY == 1 ) */
1036 #endif /* if ( configNUM_CORES > 1 ) */
1041 #else /* configUSE_PORT_OPTIMISED_TASK_SELECTION */
1043 static void prvSelectHighestPriorityTask( BaseType_t xCoreID )
1045 UBaseType_t uxTopPriority;
1047 /* Find the highest priority list that contains ready tasks. */
1048 portGET_HIGHEST_PRIORITY( uxTopPriority, uxTopReadyPriority );
1049 configASSERT( listCURRENT_LIST_LENGTH( &( pxReadyTasksLists[ uxTopPriority ] ) ) > 0 );
1050 listGET_OWNER_OF_NEXT_ENTRY( pxCurrentTCB, &( pxReadyTasksLists[ uxTopPriority ] ) );
1053 #endif /* configUSE_PORT_OPTIMISED_TASK_SELECTION */
1054 /*-----------------------------------------------------------*/
1056 #if ( configSUPPORT_STATIC_ALLOCATION == 1 )
1058 TaskHandle_t xTaskCreateStatic( TaskFunction_t pxTaskCode,
1059 const char * const pcName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */
1060 const uint32_t ulStackDepth,
1061 void * const pvParameters,
1062 UBaseType_t uxPriority,
1063 StackType_t * const puxStackBuffer,
1064 StaticTask_t * const pxTaskBuffer )
1067 TaskHandle_t xReturn;
1069 configASSERT( puxStackBuffer != NULL );
1070 configASSERT( pxTaskBuffer != NULL );
1072 #if ( configASSERT_DEFINED == 1 )
1074 /* Sanity check that the size of the structure used to declare a
1075 * variable of type StaticTask_t equals the size of the real task
1077 volatile size_t xSize = sizeof( StaticTask_t );
1078 configASSERT( xSize == sizeof( TCB_t ) );
1079 ( void ) xSize; /* Prevent lint warning when configASSERT() is not used. */
1081 #endif /* configASSERT_DEFINED */
1083 if( ( pxTaskBuffer != NULL ) && ( puxStackBuffer != NULL ) )
1085 /* The memory used for the task's TCB and stack are passed into this
1086 * function - use them. */
1087 pxNewTCB = ( TCB_t * ) pxTaskBuffer; /*lint !e740 !e9087 Unusual cast is ok as the structures are designed to have the same alignment, and the size is checked by an assert. */
1088 pxNewTCB->pxStack = ( StackType_t * ) puxStackBuffer;
1090 #if ( tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE != 0 ) /*lint !e731 !e9029 Macro has been consolidated for readability reasons. */
1092 /* Tasks can be created statically or dynamically, so note this
1093 * task was created statically in case the task is later deleted. */
1094 pxNewTCB->ucStaticallyAllocated = tskSTATICALLY_ALLOCATED_STACK_AND_TCB;
1096 #endif /* tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE */
1098 prvInitialiseNewTask( pxTaskCode, pcName, ulStackDepth, pvParameters, uxPriority, &xReturn, pxNewTCB, NULL );
1099 prvAddNewTaskToReadyList( pxNewTCB );
1109 #endif /* SUPPORT_STATIC_ALLOCATION */
1110 /*-----------------------------------------------------------*/
1112 #if ( ( portUSING_MPU_WRAPPERS == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) )
1114 BaseType_t xTaskCreateRestrictedStatic( const TaskParameters_t * const pxTaskDefinition,
1115 TaskHandle_t * pxCreatedTask )
1118 BaseType_t xReturn = errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY;
1120 configASSERT( pxTaskDefinition->puxStackBuffer != NULL );
1121 configASSERT( pxTaskDefinition->pxTaskBuffer != NULL );
1123 if( ( pxTaskDefinition->puxStackBuffer != NULL ) && ( pxTaskDefinition->pxTaskBuffer != NULL ) )
1125 /* Allocate space for the TCB. Where the memory comes from depends
1126 * on the implementation of the port malloc function and whether or
1127 * not static allocation is being used. */
1128 pxNewTCB = ( TCB_t * ) pxTaskDefinition->pxTaskBuffer;
1130 /* Store the stack location in the TCB. */
1131 pxNewTCB->pxStack = pxTaskDefinition->puxStackBuffer;
1133 #if ( tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE != 0 )
1135 /* Tasks can be created statically or dynamically, so note this
1136 * task was created statically in case the task is later deleted. */
1137 pxNewTCB->ucStaticallyAllocated = tskSTATICALLY_ALLOCATED_STACK_AND_TCB;
1139 #endif /* tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE */
1141 prvInitialiseNewTask( pxTaskDefinition->pvTaskCode,
1142 pxTaskDefinition->pcName,
1143 ( uint32_t ) pxTaskDefinition->usStackDepth,
1144 pxTaskDefinition->pvParameters,
1145 pxTaskDefinition->uxPriority,
1146 pxCreatedTask, pxNewTCB,
1147 pxTaskDefinition->xRegions );
1149 prvAddNewTaskToReadyList( pxNewTCB );
1156 #endif /* ( portUSING_MPU_WRAPPERS == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) */
1157 /*-----------------------------------------------------------*/
1159 #if ( ( portUSING_MPU_WRAPPERS == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) )
1161 BaseType_t xTaskCreateRestricted( const TaskParameters_t * const pxTaskDefinition,
1162 TaskHandle_t * pxCreatedTask )
1165 BaseType_t xReturn = errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY;
1167 configASSERT( pxTaskDefinition->puxStackBuffer );
1169 if( pxTaskDefinition->puxStackBuffer != NULL )
1171 /* Allocate space for the TCB. Where the memory comes from depends
1172 * on the implementation of the port malloc function and whether or
1173 * not static allocation is being used. */
1174 pxNewTCB = ( TCB_t * ) pvPortMalloc( sizeof( TCB_t ) );
1176 if( pxNewTCB != NULL )
1178 /* Store the stack location in the TCB. */
1179 pxNewTCB->pxStack = pxTaskDefinition->puxStackBuffer;
1181 #if ( tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE != 0 )
1183 /* Tasks can be created statically or dynamically, so note
1184 * this task had a statically allocated stack in case it is
1185 * later deleted. The TCB was allocated dynamically. */
1186 pxNewTCB->ucStaticallyAllocated = tskSTATICALLY_ALLOCATED_STACK_ONLY;
1188 #endif /* tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE */
1190 prvInitialiseNewTask( pxTaskDefinition->pvTaskCode,
1191 pxTaskDefinition->pcName,
1192 ( uint32_t ) pxTaskDefinition->usStackDepth,
1193 pxTaskDefinition->pvParameters,
1194 pxTaskDefinition->uxPriority,
1195 pxCreatedTask, pxNewTCB,
1196 pxTaskDefinition->xRegions );
1198 prvAddNewTaskToReadyList( pxNewTCB );
1206 #endif /* portUSING_MPU_WRAPPERS */
1207 /*-----------------------------------------------------------*/
1209 #if ( configSUPPORT_DYNAMIC_ALLOCATION == 1 )
1211 BaseType_t xTaskCreate( TaskFunction_t pxTaskCode,
1212 const char * const pcName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */
1213 const configSTACK_DEPTH_TYPE usStackDepth,
1214 void * const pvParameters,
1215 UBaseType_t uxPriority,
1216 TaskHandle_t * const pxCreatedTask )
1221 /* If the stack grows down then allocate the stack then the TCB so the stack
1222 * does not grow into the TCB. Likewise if the stack grows up then allocate
1223 * the TCB then the stack. */
1224 #if ( portSTACK_GROWTH > 0 )
1226 /* Allocate space for the TCB. Where the memory comes from depends on
1227 * the implementation of the port malloc function and whether or not static
1228 * allocation is being used. */
1229 pxNewTCB = ( TCB_t * ) pvPortMalloc( sizeof( TCB_t ) );
1231 if( pxNewTCB != NULL )
1233 /* Allocate space for the stack used by the task being created.
1234 * The base of the stack memory stored in the TCB so the task can
1235 * be deleted later if required. */
1236 pxNewTCB->pxStack = ( StackType_t * ) pvPortMallocStack( ( ( ( size_t ) usStackDepth ) * sizeof( StackType_t ) ) ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */
1238 if( pxNewTCB->pxStack == NULL )
1240 /* Could not allocate the stack. Delete the allocated TCB. */
1241 vPortFree( pxNewTCB );
1246 #else /* portSTACK_GROWTH */
1248 StackType_t * pxStack;
1250 /* Allocate space for the stack used by the task being created. */
1251 pxStack = pvPortMallocStack( ( ( ( size_t ) usStackDepth ) * sizeof( StackType_t ) ) ); /*lint !e9079 All values returned by pvPortMalloc() have at least the alignment required by the MCU's stack and this allocation is the stack. */
1253 if( pxStack != NULL )
1255 /* Allocate space for the TCB. */
1256 pxNewTCB = ( TCB_t * ) pvPortMalloc( sizeof( TCB_t ) ); /*lint !e9087 !e9079 All values returned by pvPortMalloc() have at least the alignment required by the MCU's stack, and the first member of TCB_t is always a pointer to the task's stack. */
1258 if( pxNewTCB != NULL )
1260 /* Store the stack location in the TCB. */
1261 pxNewTCB->pxStack = pxStack;
1265 /* The stack cannot be used as the TCB was not created. Free
1267 vPortFreeStack( pxStack );
1275 #endif /* portSTACK_GROWTH */
1277 if( pxNewTCB != NULL )
1279 #if ( tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE != 0 ) /*lint !e9029 !e731 Macro has been consolidated for readability reasons. */
1281 /* Tasks can be created statically or dynamically, so note this
1282 * task was created dynamically in case it is later deleted. */
1283 pxNewTCB->ucStaticallyAllocated = tskDYNAMICALLY_ALLOCATED_STACK_AND_TCB;
1285 #endif /* tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE */
1287 prvInitialiseNewTask( pxTaskCode, pcName, ( uint32_t ) usStackDepth, pvParameters, uxPriority, pxCreatedTask, pxNewTCB, NULL );
1288 prvAddNewTaskToReadyList( pxNewTCB );
1293 xReturn = errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY;
1299 #endif /* configSUPPORT_DYNAMIC_ALLOCATION */
1300 /*-----------------------------------------------------------*/
1302 static void prvInitialiseNewTask( TaskFunction_t pxTaskCode,
1303 const char * const pcName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */
1304 const uint32_t ulStackDepth,
1305 void * const pvParameters,
1306 UBaseType_t uxPriority,
1307 TaskHandle_t * const pxCreatedTask,
1309 const MemoryRegion_t * const xRegions )
1311 StackType_t * pxTopOfStack;
1314 #if ( portUSING_MPU_WRAPPERS == 1 )
1315 /* Should the task be created in privileged mode? */
1316 BaseType_t xRunPrivileged;
1318 if( ( uxPriority & portPRIVILEGE_BIT ) != 0U )
1320 xRunPrivileged = pdTRUE;
1324 xRunPrivileged = pdFALSE;
1326 uxPriority &= ~portPRIVILEGE_BIT;
1327 #endif /* portUSING_MPU_WRAPPERS == 1 */
1329 /* Avoid dependency on memset() if it is not required. */
1330 #if ( tskSET_NEW_STACKS_TO_KNOWN_VALUE == 1 )
1332 /* Fill the stack with a known value to assist debugging. */
1333 ( void ) memset( pxNewTCB->pxStack, ( int ) tskSTACK_FILL_BYTE, ( size_t ) ulStackDepth * sizeof( StackType_t ) );
1335 #endif /* tskSET_NEW_STACKS_TO_KNOWN_VALUE */
1337 /* Calculate the top of stack address. This depends on whether the stack
1338 * grows from high memory to low (as per the 80x86) or vice versa.
1339 * portSTACK_GROWTH is used to make the result positive or negative as required
1341 #if ( portSTACK_GROWTH < 0 )
1343 pxTopOfStack = &( pxNewTCB->pxStack[ ulStackDepth - ( uint32_t ) 1 ] );
1344 pxTopOfStack = ( StackType_t * ) ( ( ( portPOINTER_SIZE_TYPE ) pxTopOfStack ) & ( ~( ( portPOINTER_SIZE_TYPE ) portBYTE_ALIGNMENT_MASK ) ) ); /*lint !e923 !e9033 !e9078 MISRA exception. Avoiding casts between pointers and integers is not practical. Size differences accounted for using portPOINTER_SIZE_TYPE type. Checked by assert(). */
1346 /* Check the alignment of the calculated top of stack is correct. */
1347 configASSERT( ( ( ( portPOINTER_SIZE_TYPE ) pxTopOfStack & ( portPOINTER_SIZE_TYPE ) portBYTE_ALIGNMENT_MASK ) == 0UL ) );
1349 #if ( configRECORD_STACK_HIGH_ADDRESS == 1 )
1351 /* Also record the stack's high address, which may assist
1353 pxNewTCB->pxEndOfStack = pxTopOfStack;
1355 #endif /* configRECORD_STACK_HIGH_ADDRESS */
1357 #else /* portSTACK_GROWTH */
1359 pxTopOfStack = pxNewTCB->pxStack;
1361 /* Check the alignment of the stack buffer is correct. */
1362 configASSERT( ( ( ( portPOINTER_SIZE_TYPE ) pxNewTCB->pxStack & ( portPOINTER_SIZE_TYPE ) portBYTE_ALIGNMENT_MASK ) == 0UL ) );
1364 /* The other extreme of the stack space is required if stack checking is
1366 pxNewTCB->pxEndOfStack = pxNewTCB->pxStack + ( ulStackDepth - ( uint32_t ) 1 );
1368 #endif /* portSTACK_GROWTH */
1370 /* Store the task name in the TCB. */
1371 if( pcName != NULL )
1373 for( x = ( UBaseType_t ) 0; x < ( UBaseType_t ) configMAX_TASK_NAME_LEN; x++ )
1375 pxNewTCB->pcTaskName[ x ] = pcName[ x ];
1377 /* Don't copy all configMAX_TASK_NAME_LEN if the string is shorter than
1378 * configMAX_TASK_NAME_LEN characters just in case the memory after the
1379 * string is not accessible (extremely unlikely). */
1380 if( pcName[ x ] == ( char ) 0x00 )
1386 mtCOVERAGE_TEST_MARKER();
1390 /* Ensure the name string is terminated in the case that the string length
1391 * was greater or equal to configMAX_TASK_NAME_LEN. */
1392 pxNewTCB->pcTaskName[ configMAX_TASK_NAME_LEN - 1 ] = '\0';
1396 /* The task has not been given a name, so just ensure there is a NULL
1397 * terminator when it is read out. */
1398 pxNewTCB->pcTaskName[ 0 ] = 0x00;
1401 /* This is used as an array index so must ensure it's not too large. First
1402 * remove the privilege bit if one is present. */
1403 if( uxPriority >= ( UBaseType_t ) configMAX_PRIORITIES )
1405 uxPriority = ( UBaseType_t ) configMAX_PRIORITIES - ( UBaseType_t ) 1U;
1409 mtCOVERAGE_TEST_MARKER();
1412 pxNewTCB->uxPriority = uxPriority;
1413 #if ( configUSE_MUTEXES == 1 )
1415 pxNewTCB->uxBasePriority = uxPriority;
1416 pxNewTCB->uxMutexesHeld = 0;
1418 #endif /* configUSE_MUTEXES */
1420 vListInitialiseItem( &( pxNewTCB->xStateListItem ) );
1421 vListInitialiseItem( &( pxNewTCB->xEventListItem ) );
1423 /* Set the pxNewTCB as a link back from the ListItem_t. This is so we can get
1424 * back to the containing TCB from a generic item in a list. */
1425 listSET_LIST_ITEM_OWNER( &( pxNewTCB->xStateListItem ), pxNewTCB );
1427 /* Event lists are always in priority order. */
1428 listSET_LIST_ITEM_VALUE( &( pxNewTCB->xEventListItem ), ( TickType_t ) configMAX_PRIORITIES - ( TickType_t ) uxPriority ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */
1429 listSET_LIST_ITEM_OWNER( &( pxNewTCB->xEventListItem ), pxNewTCB );
1431 #if ( portCRITICAL_NESTING_IN_TCB == 1 )
1433 pxNewTCB->uxCriticalNesting = ( UBaseType_t ) 0U;
1435 #endif /* portCRITICAL_NESTING_IN_TCB */
1437 #if ( configUSE_APPLICATION_TASK_TAG == 1 )
1439 pxNewTCB->pxTaskTag = NULL;
1441 #endif /* configUSE_APPLICATION_TASK_TAG */
1443 #if ( configGENERATE_RUN_TIME_STATS == 1 )
1445 pxNewTCB->ulRunTimeCounter = 0UL;
1447 #endif /* configGENERATE_RUN_TIME_STATS */
1449 #if ( portUSING_MPU_WRAPPERS == 1 )
1451 vPortStoreTaskMPUSettings( &( pxNewTCB->xMPUSettings ), xRegions, pxNewTCB->pxStack, ulStackDepth );
1455 /* Avoid compiler warning about unreferenced parameter. */
1460 #if ( configNUM_THREAD_LOCAL_STORAGE_POINTERS != 0 )
1462 memset( ( void * ) &( pxNewTCB->pvThreadLocalStoragePointers[ 0 ] ), 0x00, sizeof( pxNewTCB->pvThreadLocalStoragePointers ) );
1466 #if ( configUSE_TASK_NOTIFICATIONS == 1 )
1468 memset( ( void * ) &( pxNewTCB->ulNotifiedValue[ 0 ] ), 0x00, sizeof( pxNewTCB->ulNotifiedValue ) );
1469 memset( ( void * ) &( pxNewTCB->ucNotifyState[ 0 ] ), 0x00, sizeof( pxNewTCB->ucNotifyState ) );
1473 #if ( configUSE_NEWLIB_REENTRANT == 1 )
1475 /* Initialise this task's Newlib reent structure.
1476 * See the third party link http://www.nadler.com/embedded/newlibAndFreeRTOS.html
1477 * for additional information. */
1478 _REENT_INIT_PTR( ( &( pxNewTCB->xNewLib_reent ) ) );
1482 #if ( INCLUDE_xTaskAbortDelay == 1 )
1484 pxNewTCB->ucDelayAborted = pdFALSE;
1488 #if ( configNUM_CORES > 1 )
1489 #if ( configUSE_CORE_AFFINITY == 1 )
1491 pxNewTCB->uxCoreAffinityMask = tskNO_AFFINITY;
1495 #if ( configUSE_TASK_PREEMPTION_DISABLE == 1 )
1497 pxNewTCB->xPreemptionDisable = 0;
1501 /* Initialize the TCB stack to look as if the task was already running,
1502 * but had been interrupted by the scheduler. The return address is set
1503 * to the start of the task function. Once the stack has been initialised
1504 * the top of stack variable is updated. */
1505 #if ( portUSING_MPU_WRAPPERS == 1 )
1507 /* If the port has capability to detect stack overflow,
1508 * pass the stack end address to the stack initialization
1509 * function as well. */
1510 #if ( portHAS_STACK_OVERFLOW_CHECKING == 1 )
1512 #if ( portSTACK_GROWTH < 0 )
1514 pxNewTCB->pxTopOfStack = pxPortInitialiseStack( pxTopOfStack, pxNewTCB->pxStack, pxTaskCode, pvParameters, xRunPrivileged );
1516 #else /* portSTACK_GROWTH */
1518 pxNewTCB->pxTopOfStack = pxPortInitialiseStack( pxTopOfStack, pxNewTCB->pxEndOfStack, pxTaskCode, pvParameters, xRunPrivileged );
1520 #endif /* portSTACK_GROWTH */
1522 #else /* portHAS_STACK_OVERFLOW_CHECKING */
1524 pxNewTCB->pxTopOfStack = pxPortInitialiseStack( pxTopOfStack, pxTaskCode, pvParameters, xRunPrivileged );
1526 #endif /* portHAS_STACK_OVERFLOW_CHECKING */
1528 #else /* portUSING_MPU_WRAPPERS */
1530 /* If the port has capability to detect stack overflow,
1531 * pass the stack end address to the stack initialization
1532 * function as well. */
1533 #if ( portHAS_STACK_OVERFLOW_CHECKING == 1 )
1535 #if ( portSTACK_GROWTH < 0 )
1537 pxNewTCB->pxTopOfStack = pxPortInitialiseStack( pxTopOfStack, pxNewTCB->pxStack, pxTaskCode, pvParameters );
1539 #else /* portSTACK_GROWTH */
1541 pxNewTCB->pxTopOfStack = pxPortInitialiseStack( pxTopOfStack, pxNewTCB->pxEndOfStack, pxTaskCode, pvParameters );
1543 #endif /* portSTACK_GROWTH */
1545 #else /* portHAS_STACK_OVERFLOW_CHECKING */
1547 pxNewTCB->pxTopOfStack = pxPortInitialiseStack( pxTopOfStack, pxTaskCode, pvParameters );
1549 #endif /* portHAS_STACK_OVERFLOW_CHECKING */
1551 #endif /* portUSING_MPU_WRAPPERS */
1553 /* Initialize to not running */
1554 pxNewTCB->xTaskRunState = taskTASK_NOT_RUNNING;
1556 /* Is this an idle task? */
1557 if( pxTaskCode == prvIdleTask )
1559 pxNewTCB->xIsIdle = pdTRUE;
1562 #if ( configNUM_CORES > 1 )
1563 else if( pxTaskCode == prvMinimalIdleTask )
1565 pxNewTCB->xIsIdle = pdTRUE;
1570 pxNewTCB->xIsIdle = pdFALSE;
1573 if( pxCreatedTask != NULL )
1575 /* Pass the handle out in an anonymous way. The handle can be used to
1576 * change the created task's priority, delete the created task, etc.*/
1577 *pxCreatedTask = ( TaskHandle_t ) pxNewTCB;
1581 mtCOVERAGE_TEST_MARKER();
1584 /*-----------------------------------------------------------*/
1586 static void prvAddNewTaskToReadyList( TCB_t * pxNewTCB )
1588 /* Ensure interrupts don't access the task lists while the lists are being
1590 taskENTER_CRITICAL();
1592 uxCurrentNumberOfTasks++;
1594 if( xSchedulerRunning == pdFALSE )
1596 if( uxCurrentNumberOfTasks == ( UBaseType_t ) 1 )
1598 /* This is the first task to be created so do the preliminary
1599 * initialisation required. We will not recover if this call
1600 * fails, but we will report the failure. */
1601 prvInitialiseTaskLists();
1605 mtCOVERAGE_TEST_MARKER();
1608 if( pxNewTCB->xIsIdle != pdFALSE )
1612 /* Check if a core is free. */
1613 for( xCoreID = ( UBaseType_t ) 0; xCoreID < ( UBaseType_t ) configNUM_CORES; xCoreID++ )
1615 if( pxCurrentTCBs[ xCoreID ] == NULL )
1617 pxNewTCB->xTaskRunState = xCoreID;
1618 pxCurrentTCBs[ xCoreID ] = pxNewTCB;
1626 mtCOVERAGE_TEST_MARKER();
1631 #if ( configUSE_TRACE_FACILITY == 1 )
1633 /* Add a counter into the TCB for tracing only. */
1634 pxNewTCB->uxTCBNumber = uxTaskNumber;
1636 #endif /* configUSE_TRACE_FACILITY */
1637 traceTASK_CREATE( pxNewTCB );
1639 prvAddTaskToReadyList( pxNewTCB );
1641 portSETUP_TCB( pxNewTCB );
1643 if( xSchedulerRunning != pdFALSE )
1645 /* If the created task is of a higher priority than another
1646 * currently running task and preemption is on then it should
1648 #if ( configUSE_PREEMPTION == 1 )
1649 prvYieldForTask( pxNewTCB, pdFALSE );
1654 mtCOVERAGE_TEST_MARKER();
1657 taskEXIT_CRITICAL();
1659 /*-----------------------------------------------------------*/
1661 #if ( INCLUDE_vTaskDelete == 1 )
1663 void vTaskDelete( TaskHandle_t xTaskToDelete )
1666 TaskRunning_t xTaskRunningOnCore;
1668 taskENTER_CRITICAL();
1670 /* If null is passed in here then it is the calling task that is
1672 pxTCB = prvGetTCBFromHandle( xTaskToDelete );
1674 xTaskRunningOnCore = pxTCB->xTaskRunState;
1676 /* Remove task from the ready/delayed list. */
1677 if( uxListRemove( &( pxTCB->xStateListItem ) ) == ( UBaseType_t ) 0 )
1679 taskRESET_READY_PRIORITY( pxTCB->uxPriority );
1683 mtCOVERAGE_TEST_MARKER();
1686 /* Is the task waiting on an event also? */
1687 if( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) != NULL )
1689 ( void ) uxListRemove( &( pxTCB->xEventListItem ) );
1693 mtCOVERAGE_TEST_MARKER();
1696 /* Increment the uxTaskNumber also so kernel aware debuggers can
1697 * detect that the task lists need re-generating. This is done before
1698 * portPRE_TASK_DELETE_HOOK() as in the Windows port that macro will
1702 /* If the task is running (or yielding), we must add it to the
1703 * termination list so that an idle task can delete it when it is
1704 * no longer running. */
1705 if( xTaskRunningOnCore != taskTASK_NOT_RUNNING )
1707 /* A running task is being deleted. This cannot complete within the
1708 * task itself, as a context switch to another task is required.
1709 * Place the task in the termination list. The idle task will
1710 * check the termination list and free up any memory allocated by
1711 * the scheduler for the TCB and stack of the deleted task. */
1712 vListInsertEnd( &xTasksWaitingTermination, &( pxTCB->xStateListItem ) );
1714 /* Increment the ucTasksDeleted variable so the idle task knows
1715 * there is a task that has been deleted and that it should therefore
1716 * check the xTasksWaitingTermination list. */
1717 ++uxDeletedTasksWaitingCleanUp;
1719 /* Call the delete hook before portPRE_TASK_DELETE_HOOK() as
1720 * portPRE_TASK_DELETE_HOOK() does not return in the Win32 port. */
1721 traceTASK_DELETE( pxTCB );
1723 /* The pre-delete hook is primarily for the Windows simulator,
1724 * in which Windows specific clean up operations are performed,
1725 * after which it is not possible to yield away from this task -
1726 * hence xYieldPending is used to latch that a context switch is
1728 portPRE_TASK_DELETE_HOOK( pxTCB, &xYieldPendings[ pxTCB->xTaskRunState ] );
1732 --uxCurrentNumberOfTasks;
1733 traceTASK_DELETE( pxTCB );
1734 prvDeleteTCB( pxTCB );
1736 /* Reset the next expected unblock time in case it referred to
1737 * the task that has just been deleted. */
1738 prvResetNextTaskUnblockTime();
1741 /* Force a reschedule if the task that has just been deleted was running. */
1742 if( ( xSchedulerRunning != pdFALSE ) && ( taskTASK_IS_RUNNING( xTaskRunningOnCore ) ) )
1746 xCoreID = portGET_CORE_ID();
1748 if( xTaskRunningOnCore == xCoreID )
1750 configASSERT( uxSchedulerSuspended == 0 );
1751 vTaskYieldWithinAPI();
1755 prvYieldCore( xTaskRunningOnCore );
1759 taskEXIT_CRITICAL();
1762 #endif /* INCLUDE_vTaskDelete */
1763 /*-----------------------------------------------------------*/
1765 #if ( INCLUDE_xTaskDelayUntil == 1 )
1767 BaseType_t xTaskDelayUntil( TickType_t * const pxPreviousWakeTime,
1768 const TickType_t xTimeIncrement )
1770 TickType_t xTimeToWake;
1771 BaseType_t xAlreadyYielded, xShouldDelay = pdFALSE;
1773 configASSERT( pxPreviousWakeTime );
1774 configASSERT( ( xTimeIncrement > 0U ) );
1778 configASSERT( uxSchedulerSuspended == 1 );
1780 /* Minor optimisation. The tick count cannot change in this
1782 const TickType_t xConstTickCount = xTickCount;
1784 /* Generate the tick time at which the task wants to wake. */
1785 xTimeToWake = *pxPreviousWakeTime + xTimeIncrement;
1787 if( xConstTickCount < *pxPreviousWakeTime )
1789 /* The tick count has overflowed since this function was
1790 * lasted called. In this case the only time we should ever
1791 * actually delay is if the wake time has also overflowed,
1792 * and the wake time is greater than the tick time. When this
1793 * is the case it is as if neither time had overflowed. */
1794 if( ( xTimeToWake < *pxPreviousWakeTime ) && ( xTimeToWake > xConstTickCount ) )
1796 xShouldDelay = pdTRUE;
1800 mtCOVERAGE_TEST_MARKER();
1805 /* The tick time has not overflowed. In this case we will
1806 * delay if either the wake time has overflowed, and/or the
1807 * tick time is less than the wake time. */
1808 if( ( xTimeToWake < *pxPreviousWakeTime ) || ( xTimeToWake > xConstTickCount ) )
1810 xShouldDelay = pdTRUE;
1814 mtCOVERAGE_TEST_MARKER();
1818 /* Update the wake time ready for the next call. */
1819 *pxPreviousWakeTime = xTimeToWake;
1821 if( xShouldDelay != pdFALSE )
1823 traceTASK_DELAY_UNTIL( xTimeToWake );
1825 /* prvAddCurrentTaskToDelayedList() needs the block time, not
1826 * the time to wake, so subtract the current tick count. */
1827 prvAddCurrentTaskToDelayedList( xTimeToWake - xConstTickCount, pdFALSE );
1831 mtCOVERAGE_TEST_MARKER();
1834 xAlreadyYielded = xTaskResumeAll();
1836 /* Force a reschedule if xTaskResumeAll has not already done so, we may
1837 * have put ourselves to sleep. */
1838 if( xAlreadyYielded == pdFALSE )
1840 vTaskYieldWithinAPI();
1844 mtCOVERAGE_TEST_MARKER();
1847 return xShouldDelay;
1850 #endif /* INCLUDE_xTaskDelayUntil */
1851 /*-----------------------------------------------------------*/
1853 #if ( INCLUDE_vTaskDelay == 1 )
1855 void vTaskDelay( const TickType_t xTicksToDelay )
1857 BaseType_t xAlreadyYielded = pdFALSE;
1859 /* A delay time of zero just forces a reschedule. */
1860 if( xTicksToDelay > ( TickType_t ) 0U )
1864 configASSERT( uxSchedulerSuspended == 1 );
1867 /* A task that is removed from the event list while the
1868 * scheduler is suspended will not get placed in the ready
1869 * list or removed from the blocked list until the scheduler
1872 * This task cannot be in an event list as it is the currently
1873 * executing task. */
1874 prvAddCurrentTaskToDelayedList( xTicksToDelay, pdFALSE );
1876 xAlreadyYielded = xTaskResumeAll();
1880 mtCOVERAGE_TEST_MARKER();
1883 /* Force a reschedule if xTaskResumeAll has not already done so, we may
1884 * have put ourselves to sleep. */
1885 if( xAlreadyYielded == pdFALSE )
1887 vTaskYieldWithinAPI();
1891 mtCOVERAGE_TEST_MARKER();
1895 #endif /* INCLUDE_vTaskDelay */
1896 /*-----------------------------------------------------------*/
1898 #if ( ( INCLUDE_eTaskGetState == 1 ) || ( configUSE_TRACE_FACILITY == 1 ) || ( INCLUDE_xTaskAbortDelay == 1 ) )
1900 eTaskState eTaskGetState( TaskHandle_t xTask )
1903 List_t const * pxStateList, * pxDelayedList, * pxOverflowedDelayedList;
1904 const TCB_t * const pxTCB = xTask;
1906 configASSERT( pxTCB );
1908 taskENTER_CRITICAL();
1910 pxStateList = listLIST_ITEM_CONTAINER( &( pxTCB->xStateListItem ) );
1911 pxDelayedList = pxDelayedTaskList;
1912 pxOverflowedDelayedList = pxOverflowDelayedTaskList;
1914 taskEXIT_CRITICAL();
1916 if( ( pxStateList == pxDelayedList ) || ( pxStateList == pxOverflowedDelayedList ) )
1918 /* The task being queried is referenced from one of the Blocked
1923 #if ( INCLUDE_vTaskSuspend == 1 )
1924 else if( pxStateList == &xSuspendedTaskList )
1926 /* The task being queried is referenced from the suspended
1927 * list. Is it genuinely suspended or is it blocked
1929 if( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) == NULL )
1931 #if ( configUSE_TASK_NOTIFICATIONS == 1 )
1935 /* The task does not appear on the event list item of
1936 * and of the RTOS objects, but could still be in the
1937 * blocked state if it is waiting on its notification
1938 * rather than waiting on an object. If not, is
1940 eReturn = eSuspended;
1942 for( x = 0; x < configTASK_NOTIFICATION_ARRAY_ENTRIES; x++ )
1944 if( pxTCB->ucNotifyState[ x ] == taskWAITING_NOTIFICATION )
1951 #else /* if ( configUSE_TASK_NOTIFICATIONS == 1 ) */
1953 eReturn = eSuspended;
1955 #endif /* if ( configUSE_TASK_NOTIFICATIONS == 1 ) */
1962 #endif /* if ( INCLUDE_vTaskSuspend == 1 ) */
1964 #if ( INCLUDE_vTaskDelete == 1 )
1965 else if( ( pxStateList == &xTasksWaitingTermination ) || ( pxStateList == NULL ) )
1967 /* The task being queried is referenced from the deleted
1968 * tasks list, or it is not referenced from any lists at
1974 else /*lint !e525 Negative indentation is intended to make use of pre-processor clearer. */
1976 /* If the task is not in any other state, it must be in the
1977 * Ready (including pending ready) state. */
1978 if( taskTASK_IS_RUNNING( pxTCB->xTaskRunState ) )
1980 /* Is it actively running on a core? */
1990 } /*lint !e818 xTask cannot be a pointer to const because it is a typedef. */
1992 #endif /* INCLUDE_eTaskGetState */
1993 /*-----------------------------------------------------------*/
1995 #if ( INCLUDE_uxTaskPriorityGet == 1 )
1997 UBaseType_t uxTaskPriorityGet( const TaskHandle_t xTask )
1999 TCB_t const * pxTCB;
2000 UBaseType_t uxReturn;
2002 taskENTER_CRITICAL();
2004 /* If null is passed in here then it is the priority of the task
2005 * that called uxTaskPriorityGet() that is being queried. */
2006 pxTCB = prvGetTCBFromHandle( xTask );
2007 uxReturn = pxTCB->uxPriority;
2009 taskEXIT_CRITICAL();
2014 #endif /* INCLUDE_uxTaskPriorityGet */
2015 /*-----------------------------------------------------------*/
2017 #if ( INCLUDE_uxTaskPriorityGet == 1 )
2019 UBaseType_t uxTaskPriorityGetFromISR( const TaskHandle_t xTask )
2021 TCB_t const * pxTCB;
2022 UBaseType_t uxReturn, uxSavedInterruptState;
2024 /* RTOS ports that support interrupt nesting have the concept of a
2025 * maximum system call (or maximum API call) interrupt priority.
2026 * Interrupts that are above the maximum system call priority are keep
2027 * permanently enabled, even when the RTOS kernel is in a critical section,
2028 * but cannot make any calls to FreeRTOS API functions. If configASSERT()
2029 * is defined in FreeRTOSConfig.h then
2030 * portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion
2031 * failure if a FreeRTOS API function is called from an interrupt that has
2032 * been assigned a priority above the configured maximum system call
2033 * priority. Only FreeRTOS functions that end in FromISR can be called
2034 * from interrupts that have been assigned a priority at or (logically)
2035 * below the maximum system call interrupt priority. FreeRTOS maintains a
2036 * separate interrupt safe API to ensure interrupt entry is as fast and as
2037 * simple as possible. More information (albeit Cortex-M specific) is
2038 * provided on the following link:
2039 * https://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html */
2040 portASSERT_IF_INTERRUPT_PRIORITY_INVALID();
2042 uxSavedInterruptState = portSET_INTERRUPT_MASK_FROM_ISR();
2044 /* If null is passed in here then it is the priority of the calling
2045 * task that is being queried. */
2046 pxTCB = prvGetTCBFromHandle( xTask );
2047 uxReturn = pxTCB->uxPriority;
2049 portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptState );
2054 #endif /* INCLUDE_uxTaskPriorityGet */
2055 /*-----------------------------------------------------------*/
2057 #if ( INCLUDE_vTaskPrioritySet == 1 )
2059 void vTaskPrioritySet( TaskHandle_t xTask,
2060 UBaseType_t uxNewPriority )
2063 UBaseType_t uxCurrentBasePriority, uxPriorityUsedOnEntry;
2064 BaseType_t xYieldRequired = pdFALSE;
2065 BaseType_t xYieldForTask = pdFALSE;
2068 configASSERT( ( uxNewPriority < configMAX_PRIORITIES ) );
2070 /* Ensure the new priority is valid. */
2071 if( uxNewPriority >= ( UBaseType_t ) configMAX_PRIORITIES )
2073 uxNewPriority = ( UBaseType_t ) configMAX_PRIORITIES - ( UBaseType_t ) 1U;
2077 mtCOVERAGE_TEST_MARKER();
2080 taskENTER_CRITICAL();
2082 /* If null is passed in here then it is the priority of the calling
2083 * task that is being changed. */
2084 pxTCB = prvGetTCBFromHandle( xTask );
2086 traceTASK_PRIORITY_SET( pxTCB, uxNewPriority );
2088 #if ( configUSE_MUTEXES == 1 )
2090 uxCurrentBasePriority = pxTCB->uxBasePriority;
2094 uxCurrentBasePriority = pxTCB->uxPriority;
2098 if( uxCurrentBasePriority != uxNewPriority )
2100 /* The priority change may have readied a task of higher
2101 * priority than a running task. */
2102 if( uxNewPriority > uxCurrentBasePriority )
2104 /* The priority of a task is being raised so
2105 * perform a yield for this task later. */
2106 xYieldForTask = pdTRUE;
2108 else if( taskTASK_IS_RUNNING( pxTCB->xTaskRunState ) )
2110 /* Setting the priority of a running task down means
2111 * there may now be another task of higher priority that
2112 * is ready to execute. */
2113 #if ( configUSE_TASK_PREEMPTION_DISABLE == 1 )
2114 if( pxTCB->xPreemptionDisable == pdFALSE )
2117 xCoreID = ( BaseType_t ) pxTCB->xTaskRunState;
2118 xYieldRequired = pdTRUE;
2123 /* Setting the priority of any other task down does not
2124 * require a yield as the running task must be above the
2125 * new priority of the task being modified. */
2128 /* Remember the ready list the task might be referenced from
2129 * before its uxPriority member is changed so the
2130 * taskRESET_READY_PRIORITY() macro can function correctly. */
2131 uxPriorityUsedOnEntry = pxTCB->uxPriority;
2133 #if ( configUSE_MUTEXES == 1 )
2135 /* Only change the priority being used if the task is not
2136 * currently using an inherited priority. */
2137 if( pxTCB->uxBasePriority == pxTCB->uxPriority )
2139 pxTCB->uxPriority = uxNewPriority;
2143 mtCOVERAGE_TEST_MARKER();
2146 /* The base priority gets set whatever. */
2147 pxTCB->uxBasePriority = uxNewPriority;
2149 #else /* if ( configUSE_MUTEXES == 1 ) */
2151 pxTCB->uxPriority = uxNewPriority;
2153 #endif /* if ( configUSE_MUTEXES == 1 ) */
2155 /* Only reset the event list item value if the value is not
2156 * being used for anything else. */
2157 if( ( listGET_LIST_ITEM_VALUE( &( pxTCB->xEventListItem ) ) & taskEVENT_LIST_ITEM_VALUE_IN_USE ) == 0UL )
2159 listSET_LIST_ITEM_VALUE( &( pxTCB->xEventListItem ), ( ( TickType_t ) configMAX_PRIORITIES - ( TickType_t ) uxNewPriority ) ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */
2163 mtCOVERAGE_TEST_MARKER();
2166 /* If the task is in the blocked or suspended list we need do
2167 * nothing more than change its priority variable. However, if
2168 * the task is in a ready list it needs to be removed and placed
2169 * in the list appropriate to its new priority. */
2170 if( listIS_CONTAINED_WITHIN( &( pxReadyTasksLists[ uxPriorityUsedOnEntry ] ), &( pxTCB->xStateListItem ) ) != pdFALSE )
2172 /* The task is currently in its ready list - remove before
2173 * adding it to its new ready list. As we are in a critical
2174 * section we can do this even if the scheduler is suspended. */
2175 if( uxListRemove( &( pxTCB->xStateListItem ) ) == ( UBaseType_t ) 0 )
2177 /* It is known that the task is in its ready list so
2178 * there is no need to check again and the port level
2179 * reset macro can be called directly. */
2180 portRESET_READY_PRIORITY( uxPriorityUsedOnEntry, uxTopReadyPriority );
2184 mtCOVERAGE_TEST_MARKER();
2187 prvAddTaskToReadyList( pxTCB );
2191 /* It's possible that xYieldForTask was already set to pdTRUE because
2192 * its priority is being raised. However, since it is not in a ready list
2193 * we don't actually need to yield for it. */
2194 xYieldForTask = pdFALSE;
2197 #if ( configUSE_PREEMPTION == 1 )
2198 if( xYieldRequired != pdFALSE )
2200 prvYieldCore( xCoreID );
2202 else if( xYieldForTask != pdFALSE )
2204 prvYieldForTask( pxTCB, pdTRUE );
2208 mtCOVERAGE_TEST_MARKER();
2210 #endif /* if ( configUSE_PREEMPTION == 1 ) */
2212 /* Remove compiler warning about unused variables when the port
2213 * optimised task selection is not being used. */
2214 ( void ) uxPriorityUsedOnEntry;
2217 taskEXIT_CRITICAL();
2220 #endif /* INCLUDE_vTaskPrioritySet */
2221 /*-----------------------------------------------------------*/
2223 #if ( configNUM_CORES > 1 )
2224 #if ( configUSE_CORE_AFFINITY == 1 )
2226 void vTaskCoreAffinitySet( const TaskHandle_t xTask,
2227 UBaseType_t uxCoreAffinityMask )
2232 taskENTER_CRITICAL();
2234 pxTCB = prvGetTCBFromHandle( xTask );
2236 pxTCB->uxCoreAffinityMask = uxCoreAffinityMask;
2238 if( xSchedulerRunning != pdFALSE )
2240 if( taskTASK_IS_RUNNING( pxTCB->xTaskRunState ) )
2242 xCoreID = ( BaseType_t ) pxTCB->xTaskRunState;
2244 if( ( uxCoreAffinityMask & ( 1 << xCoreID ) ) == 0 )
2246 prvYieldCore( xCoreID );
2251 taskEXIT_CRITICAL();
2254 #endif /* configUSE_CORE_AFFINITY */
2255 #endif /* if ( configNUM_CORES > 1 ) */
2256 /*-----------------------------------------------------------*/
2258 #if ( configNUM_CORES > 1 )
2259 #if ( configUSE_CORE_AFFINITY == 1 )
2261 UBaseType_t vTaskCoreAffinityGet( const TaskHandle_t xTask )
2264 UBaseType_t uxCoreAffinityMask;
2266 taskENTER_CRITICAL();
2268 pxTCB = prvGetTCBFromHandle( xTask );
2269 uxCoreAffinityMask = pxTCB->uxCoreAffinityMask;
2271 taskEXIT_CRITICAL();
2273 return uxCoreAffinityMask;
2276 #endif /* configUSE_CORE_AFFINITY */
2277 #endif /* if ( configNUM_CORES > 1 ) */
2279 /*-----------------------------------------------------------*/
2281 #if ( configUSE_TASK_PREEMPTION_DISABLE == 1 )
2283 void vTaskPreemptionDisable( const TaskHandle_t xTask )
2287 taskENTER_CRITICAL();
2289 pxTCB = prvGetTCBFromHandle( xTask );
2291 pxTCB->xPreemptionDisable = pdTRUE;
2293 taskEXIT_CRITICAL();
2296 #endif /* configUSE_TASK_PREEMPTION_DISABLE */
2297 /*-----------------------------------------------------------*/
2299 #if ( configUSE_TASK_PREEMPTION_DISABLE == 1 )
2301 void vTaskPreemptionEnable( const TaskHandle_t xTask )
2306 taskENTER_CRITICAL();
2308 pxTCB = prvGetTCBFromHandle( xTask );
2310 pxTCB->xPreemptionDisable = pdFALSE;
2312 if( xSchedulerRunning != pdFALSE )
2314 if( taskTASK_IS_RUNNING( pxTCB->xTaskRunState ) )
2316 xCoreID = ( BaseType_t ) pxTCB->xTaskRunState;
2317 prvYieldCore( xCoreID );
2321 taskEXIT_CRITICAL();
2324 #endif /* configUSE_TASK_PREEMPTION_DISABLE */
2325 /*-----------------------------------------------------------*/
2327 #if ( INCLUDE_vTaskSuspend == 1 )
2329 void vTaskSuspend( TaskHandle_t xTaskToSuspend )
2332 TaskRunning_t xTaskRunningOnCore;
2334 taskENTER_CRITICAL();
2336 /* If null is passed in here then it is the running task that is
2337 * being suspended. */
2338 pxTCB = prvGetTCBFromHandle( xTaskToSuspend );
2340 traceTASK_SUSPEND( pxTCB );
2342 xTaskRunningOnCore = pxTCB->xTaskRunState;
2344 /* Remove task from the ready/delayed list and place in the
2345 * suspended list. */
2346 if( uxListRemove( &( pxTCB->xStateListItem ) ) == ( UBaseType_t ) 0 )
2348 taskRESET_READY_PRIORITY( pxTCB->uxPriority );
2352 mtCOVERAGE_TEST_MARKER();
2355 /* Is the task waiting on an event also? */
2356 if( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) != NULL )
2358 ( void ) uxListRemove( &( pxTCB->xEventListItem ) );
2362 mtCOVERAGE_TEST_MARKER();
2365 vListInsertEnd( &xSuspendedTaskList, &( pxTCB->xStateListItem ) );
2367 #if ( configUSE_TASK_NOTIFICATIONS == 1 )
2371 for( x = 0; x < configTASK_NOTIFICATION_ARRAY_ENTRIES; x++ )
2373 if( pxTCB->ucNotifyState[ x ] == taskWAITING_NOTIFICATION )
2375 /* The task was blocked to wait for a notification, but is
2376 * now suspended, so no notification was received. */
2377 pxTCB->ucNotifyState[ x ] = taskNOT_WAITING_NOTIFICATION;
2381 #endif /* if ( configUSE_TASK_NOTIFICATIONS == 1 ) */
2383 if( xSchedulerRunning != pdFALSE )
2385 /* Reset the next expected unblock time in case it referred to the
2386 * task that is now in the Suspended state. */
2387 prvResetNextTaskUnblockTime();
2391 mtCOVERAGE_TEST_MARKER();
2394 if( taskTASK_IS_RUNNING( xTaskRunningOnCore ) )
2396 if( xSchedulerRunning != pdFALSE )
2398 if( xTaskRunningOnCore == portGET_CORE_ID() )
2400 /* The current task has just been suspended. */
2401 configASSERT( uxSchedulerSuspended == 0 );
2402 vTaskYieldWithinAPI();
2406 prvYieldCore( xTaskRunningOnCore );
2409 taskEXIT_CRITICAL();
2413 taskEXIT_CRITICAL();
2415 configASSERT( pxTCB == pxCurrentTCBs[ xTaskRunningOnCore ] );
2417 /* The scheduler is not running, but the task that was pointed
2418 * to by pxCurrentTCB has just been suspended and pxCurrentTCB
2419 * must be adjusted to point to a different task. */
2420 if( listCURRENT_LIST_LENGTH( &xSuspendedTaskList ) == uxCurrentNumberOfTasks ) /*lint !e931 Right has no side effect, just volatile. */
2422 /* No other tasks are ready, so set the core's TCB back to
2423 * NULL so when the next task is created the core's TCB will
2424 * be able to be set to point to it no matter what its relative
2426 pxTCB->xTaskRunState = taskTASK_NOT_RUNNING;
2427 pxCurrentTCBs[ xTaskRunningOnCore ] = NULL;
2431 /* Attempt to switch in a new task. This could fail since the idle tasks
2432 * haven't been created yet. If it does then set the core's TCB back to
2434 if( prvSelectHighestPriorityTask( xTaskRunningOnCore ) == pdFALSE )
2436 pxTCB->xTaskRunState = taskTASK_NOT_RUNNING;
2437 pxCurrentTCBs[ xTaskRunningOnCore ] = NULL;
2444 taskEXIT_CRITICAL();
2446 } /* taskEXIT_CRITICAL() - already exited in one of three cases above */
2449 #endif /* INCLUDE_vTaskSuspend */
2450 /*-----------------------------------------------------------*/
2452 #if ( INCLUDE_vTaskSuspend == 1 )
2454 static BaseType_t prvTaskIsTaskSuspended( const TaskHandle_t xTask )
2456 BaseType_t xReturn = pdFALSE;
2457 const TCB_t * const pxTCB = xTask;
2459 /* Accesses xPendingReadyList so must be called from a critical section. */
2461 /* It does not make sense to check if the calling task is suspended. */
2462 configASSERT( xTask );
2464 /* Is the task being resumed actually in the suspended list? */
2465 if( listIS_CONTAINED_WITHIN( &xSuspendedTaskList, &( pxTCB->xStateListItem ) ) != pdFALSE )
2467 /* Has the task already been resumed from within an ISR? */
2468 if( listIS_CONTAINED_WITHIN( &xPendingReadyList, &( pxTCB->xEventListItem ) ) == pdFALSE )
2470 /* Is it in the suspended list because it is in the Suspended
2471 * state, or because is is blocked with no timeout? */
2472 if( listIS_CONTAINED_WITHIN( NULL, &( pxTCB->xEventListItem ) ) != pdFALSE ) /*lint !e961. The cast is only redundant when NULL is used. */
2478 mtCOVERAGE_TEST_MARKER();
2483 mtCOVERAGE_TEST_MARKER();
2488 mtCOVERAGE_TEST_MARKER();
2492 } /*lint !e818 xTask cannot be a pointer to const because it is a typedef. */
2494 #endif /* INCLUDE_vTaskSuspend */
2495 /*-----------------------------------------------------------*/
2497 #if ( INCLUDE_vTaskSuspend == 1 )
2499 void vTaskResume( TaskHandle_t xTaskToResume )
2501 TCB_t * const pxTCB = xTaskToResume;
2503 /* It does not make sense to resume the calling task. */
2504 configASSERT( xTaskToResume );
2506 /* The parameter cannot be NULL as it is impossible to resume the
2507 * currently executing task. It is also impossible to resume a task
2508 * that is actively running on another core but it is too dangerous
2509 * to check their run state here. Safer to get into a critical section
2510 * and check if it is actually suspended or not below. */
2513 taskENTER_CRITICAL();
2515 if( prvTaskIsTaskSuspended( pxTCB ) != pdFALSE )
2517 traceTASK_RESUME( pxTCB );
2519 /* The ready list can be accessed even if the scheduler is
2520 * suspended because this is inside a critical section. */
2521 ( void ) uxListRemove( &( pxTCB->xStateListItem ) );
2522 prvAddTaskToReadyList( pxTCB );
2524 /* A higher priority task may have just been resumed. */
2525 #if ( configUSE_PREEMPTION == 1 )
2527 prvYieldForTask( pxTCB, pdTRUE );
2533 mtCOVERAGE_TEST_MARKER();
2536 taskEXIT_CRITICAL();
2540 mtCOVERAGE_TEST_MARKER();
2544 #endif /* INCLUDE_vTaskSuspend */
2546 /*-----------------------------------------------------------*/
2548 #if ( ( INCLUDE_xTaskResumeFromISR == 1 ) && ( INCLUDE_vTaskSuspend == 1 ) )
2550 BaseType_t xTaskResumeFromISR( TaskHandle_t xTaskToResume )
2552 BaseType_t xYieldRequired = pdFALSE;
2553 TCB_t * const pxTCB = xTaskToResume;
2554 UBaseType_t uxSavedInterruptStatus;
2556 configASSERT( xTaskToResume );
2558 /* RTOS ports that support interrupt nesting have the concept of a
2559 * maximum system call (or maximum API call) interrupt priority.
2560 * Interrupts that are above the maximum system call priority are keep
2561 * permanently enabled, even when the RTOS kernel is in a critical section,
2562 * but cannot make any calls to FreeRTOS API functions. If configASSERT()
2563 * is defined in FreeRTOSConfig.h then
2564 * portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion
2565 * failure if a FreeRTOS API function is called from an interrupt that has
2566 * been assigned a priority above the configured maximum system call
2567 * priority. Only FreeRTOS functions that end in FromISR can be called
2568 * from interrupts that have been assigned a priority at or (logically)
2569 * below the maximum system call interrupt priority. FreeRTOS maintains a
2570 * separate interrupt safe API to ensure interrupt entry is as fast and as
2571 * simple as possible. More information (albeit Cortex-M specific) is
2572 * provided on the following link:
2573 * https://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html */
2574 portASSERT_IF_INTERRUPT_PRIORITY_INVALID();
2576 uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR();
2578 if( prvTaskIsTaskSuspended( pxTCB ) != pdFALSE )
2580 traceTASK_RESUME_FROM_ISR( pxTCB );
2582 /* Check the ready lists can be accessed. */
2583 if( uxSchedulerSuspended == ( UBaseType_t ) pdFALSE )
2585 /* Ready lists can be accessed so move the task from the
2586 * suspended list to the ready list directly. */
2588 ( void ) uxListRemove( &( pxTCB->xStateListItem ) );
2589 prvAddTaskToReadyList( pxTCB );
2593 /* The delayed or ready lists cannot be accessed so the task
2594 * is held in the pending ready list until the scheduler is
2596 vListInsertEnd( &( xPendingReadyList ), &( pxTCB->xEventListItem ) );
2599 #if ( configUSE_PREEMPTION == 1 )
2600 prvYieldForTask( pxTCB, pdTRUE );
2602 if( xYieldPendings[ portGET_CORE_ID() ] != pdFALSE )
2604 xYieldRequired = pdTRUE;
2610 mtCOVERAGE_TEST_MARKER();
2613 portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus );
2615 return xYieldRequired;
2618 #endif /* ( ( INCLUDE_xTaskResumeFromISR == 1 ) && ( INCLUDE_vTaskSuspend == 1 ) ) */
2619 /*-----------------------------------------------------------*/
2621 static BaseType_t prvCreateIdleTasks( void )
2623 BaseType_t xReturn = pdPASS;
2625 char cIdleName[ configMAX_TASK_NAME_LEN ];
2627 /* Add each idle task at the lowest priority. */
2628 for( xCoreID = ( BaseType_t ) 0; xCoreID < ( BaseType_t ) configNUM_CORES; xCoreID++ )
2632 if( xReturn == pdFAIL )
2638 mtCOVERAGE_TEST_MARKER();
2641 for( x = ( BaseType_t ) 0; x < ( BaseType_t ) configMAX_TASK_NAME_LEN; x++ )
2643 cIdleName[ x ] = configIDLE_TASK_NAME[ x ];
2645 /* Don't copy all configMAX_TASK_NAME_LEN if the string is shorter than
2646 * configMAX_TASK_NAME_LEN characters just in case the memory after the
2647 * string is not accessible (extremely unlikely). */
2648 if( cIdleName[ x ] == ( char ) 0x00 )
2654 mtCOVERAGE_TEST_MARKER();
2658 /* Append the idle task number to the end of the name if there is space */
2659 if( x < configMAX_TASK_NAME_LEN )
2661 cIdleName[ x++ ] = xCoreID + '0';
2663 /* And append a null character if there is space */
2664 if( x < configMAX_TASK_NAME_LEN )
2666 cIdleName[ x ] = '\0';
2670 mtCOVERAGE_TEST_MARKER();
2675 mtCOVERAGE_TEST_MARKER();
2678 #if ( configSUPPORT_STATIC_ALLOCATION == 1 )
2682 StaticTask_t * pxIdleTaskTCBBuffer = NULL;
2683 StackType_t * pxIdleTaskStackBuffer = NULL;
2684 uint32_t ulIdleTaskStackSize;
2686 /* The Idle task is created using user provided RAM - obtain the
2687 * address of the RAM then create the idle task. */
2688 vApplicationGetIdleTaskMemory( &pxIdleTaskTCBBuffer, &pxIdleTaskStackBuffer, &ulIdleTaskStackSize );
2689 xIdleTaskHandle[ xCoreID ] = xTaskCreateStatic( prvIdleTask,
2691 ulIdleTaskStackSize,
2692 ( void * ) NULL, /*lint !e961. The cast is not redundant for all compilers. */
2693 portPRIVILEGE_BIT, /* In effect ( tskIDLE_PRIORITY | portPRIVILEGE_BIT ), but tskIDLE_PRIORITY is zero. */
2694 pxIdleTaskStackBuffer,
2695 pxIdleTaskTCBBuffer ); /*lint !e961 MISRA exception, justified as it is not a redundant explicit cast to all supported compilers. */
2698 #if ( configNUM_CORES > 1 )
2701 static StaticTask_t xIdleTCBBuffers[ configNUM_CORES - 1 ];
2702 static StackType_t xIdleTaskStackBuffers[ configNUM_CORES - 1 ][ configMINIMAL_STACK_SIZE ];
2704 xIdleTaskHandle[ xCoreID ] = xTaskCreateStatic( prvMinimalIdleTask,
2706 configMINIMAL_STACK_SIZE,
2707 ( void * ) NULL, /*lint !e961. The cast is not redundant for all compilers. */
2708 portPRIVILEGE_BIT, /* In effect ( tskIDLE_PRIORITY | portPRIVILEGE_BIT ), but tskIDLE_PRIORITY is zero. */
2709 xIdleTaskStackBuffers[ xCoreID - 1 ],
2710 &xIdleTCBBuffers[ xCoreID - 1 ] ); /*lint !e961 MISRA exception, justified as it is not a redundant explicit cast to all supported compilers. */
2712 #endif /* if ( configNUM_CORES > 1 ) */
2714 if( xIdleTaskHandle[ xCoreID ] != NULL )
2723 #else /* if ( configSUPPORT_STATIC_ALLOCATION == 1 ) */
2727 /* The Idle task is being created using dynamically allocated RAM. */
2728 xReturn = xTaskCreate( prvIdleTask,
2730 configMINIMAL_STACK_SIZE,
2732 portPRIVILEGE_BIT, /* In effect ( tskIDLE_PRIORITY | portPRIVILEGE_BIT ), but tskIDLE_PRIORITY is zero. */
2733 &xIdleTaskHandle[ xCoreID ] ); /*lint !e961 MISRA exception, justified as it is not a redundant explicit cast to all supported compilers. */
2736 #if ( configNUM_CORES > 1 )
2739 xReturn = xTaskCreate( prvMinimalIdleTask,
2741 configMINIMAL_STACK_SIZE,
2743 portPRIVILEGE_BIT, /* In effect ( tskIDLE_PRIORITY | portPRIVILEGE_BIT ), but tskIDLE_PRIORITY is zero. */
2744 &xIdleTaskHandle[ xCoreID ] ); /*lint !e961 MISRA exception, justified as it is not a redundant explicit cast to all supported compilers. */
2748 #endif /* configSUPPORT_STATIC_ALLOCATION */
2754 void vTaskStartScheduler( void )
2758 #if ( configUSE_TIMERS == 1 )
2760 xReturn = xTimerCreateTimerTask();
2762 #endif /* configUSE_TIMERS */
2764 xReturn = prvCreateIdleTasks();
2766 if( xReturn == pdPASS )
2768 /* freertos_tasks_c_additions_init() should only be called if the user
2769 * definable macro FREERTOS_TASKS_C_ADDITIONS_INIT() is defined, as that is
2770 * the only macro called by the function. */
2771 #ifdef FREERTOS_TASKS_C_ADDITIONS_INIT
2773 freertos_tasks_c_additions_init();
2777 /* Interrupts are turned off here, to ensure a tick does not occur
2778 * before or during the call to xPortStartScheduler(). The stacks of
2779 * the created tasks contain a status word with interrupts switched on
2780 * so interrupts will automatically get re-enabled when the first task
2782 portDISABLE_INTERRUPTS();
2784 #if ( configUSE_NEWLIB_REENTRANT == 1 )
2786 /* Switch Newlib's _impure_ptr variable to point to the _reent
2787 * structure specific to the task that will run first.
2788 * See the third party link http://www.nadler.com/embedded/newlibAndFreeRTOS.html
2789 * for additional information. */
2790 _impure_ptr = &( pxCurrentTCB->xNewLib_reent );
2792 #endif /* configUSE_NEWLIB_REENTRANT */
2794 xNextTaskUnblockTime = portMAX_DELAY;
2795 xSchedulerRunning = pdTRUE;
2796 xTickCount = ( TickType_t ) configINITIAL_TICK_COUNT;
2798 /* If configGENERATE_RUN_TIME_STATS is defined then the following
2799 * macro must be defined to configure the timer/counter used to generate
2800 * the run time counter time base. NOTE: If configGENERATE_RUN_TIME_STATS
2801 * is set to 0 and the following line fails to build then ensure you do not
2802 * have portCONFIGURE_TIMER_FOR_RUN_TIME_STATS() defined in your
2803 * FreeRTOSConfig.h file. */
2804 portCONFIGURE_TIMER_FOR_RUN_TIME_STATS();
2806 traceTASK_SWITCHED_IN();
2808 /* Setting up the timer tick is hardware specific and thus in the
2809 * portable interface. */
2810 if( xPortStartScheduler() != pdFALSE )
2812 /* Should not reach here as if the scheduler is running the
2813 * function will not return. */
2817 /* Should only reach here if a task calls xTaskEndScheduler(). */
2822 /* This line will only be reached if the kernel could not be started,
2823 * because there was not enough FreeRTOS heap to create the idle task
2824 * or the timer task. */
2825 configASSERT( xReturn != errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY );
2828 /* Prevent compiler warnings if INCLUDE_xTaskGetIdleTaskHandle is set to 0,
2829 * meaning xIdleTaskHandle is not used anywhere else. */
2830 ( void ) xIdleTaskHandle;
2832 /* OpenOCD makes use of uxTopUsedPriority for thread debugging. Prevent uxTopUsedPriority
2833 * from getting optimized out as it is no longer used by the kernel. */
2834 ( void ) uxTopUsedPriority;
2836 /*-----------------------------------------------------------*/
2838 void vTaskEndScheduler( void )
2840 /* Stop the scheduler interrupts and call the portable scheduler end
2841 * routine so the original ISRs can be restored if necessary. The port
2842 * layer must ensure interrupts enable bit is left in the correct state. */
2843 portDISABLE_INTERRUPTS();
2844 xSchedulerRunning = pdFALSE;
2845 vPortEndScheduler();
2847 /*----------------------------------------------------------*/
2849 void vTaskSuspendAll( void )
2851 UBaseType_t ulState;
2853 /* This must only be called from within a task */
2854 portASSERT_IF_IN_ISR();
2856 if( xSchedulerRunning != pdFALSE )
2858 /* writes to uxSchedulerSuspended must be protected by both the task AND ISR locks.
2859 * We must disable interrupts before we grab the locks in the event that this task is
2860 * interrupted and switches context before incrementing uxSchedulerSuspended.
2861 * It is safe to re-enable interrupts after releasing the ISR lock and incrementing
2862 * uxSchedulerSuspended since that will prevent context switches. */
2863 ulState = portDISABLE_INTERRUPTS();
2865 /* portSOFRWARE_BARRIER() is only implemented for emulated/simulated ports that
2866 * do not otherwise exhibit real time behaviour. */
2867 portSOFTWARE_BARRIER();
2869 portGET_TASK_LOCK();
2872 /* The scheduler is suspended if uxSchedulerSuspended is non-zero. An increment
2873 * is used to allow calls to vTaskSuspendAll() to nest. */
2874 ++uxSchedulerSuspended;
2875 portRELEASE_ISR_LOCK();
2877 if( ( uxSchedulerSuspended == 1U ) && ( pxCurrentTCB->uxCriticalNesting == 0U ) )
2879 prvCheckForRunStateChange();
2882 portRESTORE_INTERRUPTS( ulState );
2886 mtCOVERAGE_TEST_MARKER();
2889 /*----------------------------------------------------------*/
2891 #if ( configUSE_TICKLESS_IDLE != 0 )
2893 static TickType_t prvGetExpectedIdleTime( void )
2896 UBaseType_t uxHigherPriorityReadyTasks = pdFALSE;
2898 /* uxHigherPriorityReadyTasks takes care of the case where
2899 * configUSE_PREEMPTION is 0, so there may be tasks above the idle priority
2900 * task that are in the Ready state, even though the idle task is
2902 #if ( configUSE_PORT_OPTIMISED_TASK_SELECTION == 0 )
2904 if( uxTopReadyPriority > tskIDLE_PRIORITY )
2906 uxHigherPriorityReadyTasks = pdTRUE;
2911 const UBaseType_t uxLeastSignificantBit = ( UBaseType_t ) 0x01;
2913 /* When port optimised task selection is used the uxTopReadyPriority
2914 * variable is used as a bit map. If bits other than the least
2915 * significant bit are set then there are tasks that have a priority
2916 * above the idle priority that are in the Ready state. This takes
2917 * care of the case where the co-operative scheduler is in use. */
2918 if( uxTopReadyPriority > uxLeastSignificantBit )
2920 uxHigherPriorityReadyTasks = pdTRUE;
2923 #endif /* if ( configUSE_PORT_OPTIMISED_TASK_SELECTION == 0 ) */
2925 if( pxCurrentTCB->uxPriority > tskIDLE_PRIORITY )
2929 else if( listCURRENT_LIST_LENGTH( &( pxReadyTasksLists[ tskIDLE_PRIORITY ] ) ) > 1 )
2931 /* There are other idle priority tasks in the ready state. If
2932 * time slicing is used then the very next tick interrupt must be
2936 else if( uxHigherPriorityReadyTasks != pdFALSE )
2938 /* There are tasks in the Ready state that have a priority above the
2939 * idle priority. This path can only be reached if
2940 * configUSE_PREEMPTION is 0. */
2945 xReturn = xNextTaskUnblockTime - xTickCount;
2951 #endif /* configUSE_TICKLESS_IDLE */
2952 /*----------------------------------------------------------*/
2954 BaseType_t xTaskResumeAll( void )
2956 TCB_t * pxTCB = NULL;
2957 BaseType_t xAlreadyYielded = pdFALSE;
2959 if( xSchedulerRunning != pdFALSE )
2961 /* It is possible that an ISR caused a task to be removed from an event
2962 * list while the scheduler was suspended. If this was the case then the
2963 * removed task will have been added to the xPendingReadyList. Once the
2964 * scheduler has been resumed it is safe to move all the pending ready
2965 * tasks from this list into their appropriate ready list. */
2966 taskENTER_CRITICAL();
2970 xCoreID = portGET_CORE_ID();
2972 /* If uxSchedulerSuspended is zero then this function does not match a
2973 * previous call to vTaskSuspendAll(). */
2974 configASSERT( uxSchedulerSuspended );
2976 --uxSchedulerSuspended;
2977 portRELEASE_TASK_LOCK();
2979 if( uxSchedulerSuspended == ( UBaseType_t ) pdFALSE )
2981 if( uxCurrentNumberOfTasks > ( UBaseType_t ) 0U )
2983 /* Move any readied tasks from the pending list into the
2984 * appropriate ready list. */
2985 while( listLIST_IS_EMPTY( &xPendingReadyList ) == pdFALSE )
2987 pxTCB = listGET_OWNER_OF_HEAD_ENTRY( ( &xPendingReadyList ) ); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */
2988 ( void ) uxListRemove( &( pxTCB->xEventListItem ) );
2989 ( void ) uxListRemove( &( pxTCB->xStateListItem ) );
2990 prvAddTaskToReadyList( pxTCB );
2992 /* All appropriate tasks yield at the moment a task is added to xPendingReadyList.
2993 * If the current core yielded then vTaskSwitchContext() has already been called
2994 * which sets xYieldPendings for the current core to pdTRUE. */
2999 /* A task was unblocked while the scheduler was suspended,
3000 * which may have prevented the next unblock time from being
3001 * re-calculated, in which case re-calculate it now. Mainly
3002 * important for low power tickless implementations, where
3003 * this can prevent an unnecessary exit from low power
3005 prvResetNextTaskUnblockTime();
3008 /* If any ticks occurred while the scheduler was suspended then
3009 * they should be processed now. This ensures the tick count does
3010 * not slip, and that any delayed tasks are resumed at the correct
3013 * It should be safe to call xTaskIncrementTick here from any core
3014 * since we are in a critical section and xTaskIncrementTick itself
3015 * protects itself within a critical section. Suspending the scheduler
3016 * from any core causes xTaskIncrementTick to increment uxPendedCounts.*/
3018 TickType_t xPendedCounts = xPendedTicks; /* Non-volatile copy. */
3020 if( xPendedCounts > ( TickType_t ) 0U )
3024 if( xTaskIncrementTick() != pdFALSE )
3026 /* other cores are interrupted from
3027 * within xTaskIncrementTick(). */
3028 xYieldPendings[ xCoreID ] = pdTRUE;
3032 mtCOVERAGE_TEST_MARKER();
3036 } while( xPendedCounts > ( TickType_t ) 0U );
3042 mtCOVERAGE_TEST_MARKER();
3046 if( xYieldPendings[ xCoreID ] != pdFALSE )
3048 /* If xYieldPendings is true then taskEXIT_CRITICAL()
3049 * will yield, so make sure we return true to let the
3050 * caller know a yield has already happened. */
3051 xAlreadyYielded = pdTRUE;
3057 mtCOVERAGE_TEST_MARKER();
3060 taskEXIT_CRITICAL();
3064 mtCOVERAGE_TEST_MARKER();
3067 return xAlreadyYielded;
3069 /*-----------------------------------------------------------*/
3071 TickType_t xTaskGetTickCount( void )
3075 /* Critical section required if running on a 16 bit processor. */
3076 portTICK_TYPE_ENTER_CRITICAL();
3078 xTicks = xTickCount;
3080 portTICK_TYPE_EXIT_CRITICAL();
3084 /*-----------------------------------------------------------*/
3086 TickType_t xTaskGetTickCountFromISR( void )
3089 UBaseType_t uxSavedInterruptStatus;
3091 /* RTOS ports that support interrupt nesting have the concept of a maximum
3092 * system call (or maximum API call) interrupt priority. Interrupts that are
3093 * above the maximum system call priority are kept permanently enabled, even
3094 * when the RTOS kernel is in a critical section, but cannot make any calls to
3095 * FreeRTOS API functions. If configASSERT() is defined in FreeRTOSConfig.h
3096 * then portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion
3097 * failure if a FreeRTOS API function is called from an interrupt that has been
3098 * assigned a priority above the configured maximum system call priority.
3099 * Only FreeRTOS functions that end in FromISR can be called from interrupts
3100 * that have been assigned a priority at or (logically) below the maximum
3101 * system call interrupt priority. FreeRTOS maintains a separate interrupt
3102 * safe API to ensure interrupt entry is as fast and as simple as possible.
3103 * More information (albeit Cortex-M specific) is provided on the following
3104 * link: https://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html */
3105 portASSERT_IF_INTERRUPT_PRIORITY_INVALID();
3107 uxSavedInterruptStatus = portTICK_TYPE_SET_INTERRUPT_MASK_FROM_ISR();
3109 xReturn = xTickCount;
3111 portTICK_TYPE_CLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus );
3115 /*-----------------------------------------------------------*/
3117 UBaseType_t uxTaskGetNumberOfTasks( void )
3119 /* A critical section is not required because the variables are of type
3121 return uxCurrentNumberOfTasks;
3123 /*-----------------------------------------------------------*/
3125 char * pcTaskGetName( TaskHandle_t xTaskToQuery ) /*lint !e971 Unqualified char types are allowed for strings and single characters only. */
3129 /* If null is passed in here then the name of the calling task is being
3131 pxTCB = prvGetTCBFromHandle( xTaskToQuery );
3132 configASSERT( pxTCB );
3133 return &( pxTCB->pcTaskName[ 0 ] );
3135 /*-----------------------------------------------------------*/
3137 #if ( INCLUDE_xTaskGetHandle == 1 )
3139 static TCB_t * prvSearchForNameWithinSingleList( List_t * pxList,
3140 const char pcNameToQuery[] )
3142 TCB_t * pxNextTCB, * pxFirstTCB, * pxReturn = NULL;
3145 BaseType_t xBreakLoop;
3147 /* This function is called with the scheduler suspended. */
3149 if( listCURRENT_LIST_LENGTH( pxList ) > ( UBaseType_t ) 0 )
3151 listGET_OWNER_OF_NEXT_ENTRY( pxFirstTCB, pxList ); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */
3155 listGET_OWNER_OF_NEXT_ENTRY( pxNextTCB, pxList ); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */
3157 /* Check each character in the name looking for a match or
3159 xBreakLoop = pdFALSE;
3161 for( x = ( UBaseType_t ) 0; x < ( UBaseType_t ) configMAX_TASK_NAME_LEN; x++ )
3163 cNextChar = pxNextTCB->pcTaskName[ x ];
3165 if( cNextChar != pcNameToQuery[ x ] )
3167 /* Characters didn't match. */
3168 xBreakLoop = pdTRUE;
3170 else if( cNextChar == ( char ) 0x00 )
3172 /* Both strings terminated, a match must have been
3174 pxReturn = pxNextTCB;
3175 xBreakLoop = pdTRUE;
3179 mtCOVERAGE_TEST_MARKER();
3182 if( xBreakLoop != pdFALSE )
3188 if( pxReturn != NULL )
3190 /* The handle has been found. */
3193 } while( pxNextTCB != pxFirstTCB );
3197 mtCOVERAGE_TEST_MARKER();
3203 #endif /* INCLUDE_xTaskGetHandle */
3204 /*-----------------------------------------------------------*/
3206 #if ( INCLUDE_xTaskGetHandle == 1 )
3208 TaskHandle_t xTaskGetHandle( const char * pcNameToQuery ) /*lint !e971 Unqualified char types are allowed for strings and single characters only. */
3210 UBaseType_t uxQueue = configMAX_PRIORITIES;
3213 /* Task names will be truncated to configMAX_TASK_NAME_LEN - 1 bytes. */
3214 configASSERT( strlen( pcNameToQuery ) < configMAX_TASK_NAME_LEN );
3218 /* Search the ready lists. */
3222 pxTCB = prvSearchForNameWithinSingleList( ( List_t * ) &( pxReadyTasksLists[ uxQueue ] ), pcNameToQuery );
3226 /* Found the handle. */
3229 } while( uxQueue > ( UBaseType_t ) tskIDLE_PRIORITY ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */
3231 /* Search the delayed lists. */
3234 pxTCB = prvSearchForNameWithinSingleList( ( List_t * ) pxDelayedTaskList, pcNameToQuery );
3239 pxTCB = prvSearchForNameWithinSingleList( ( List_t * ) pxOverflowDelayedTaskList, pcNameToQuery );
3242 #if ( INCLUDE_vTaskSuspend == 1 )
3246 /* Search the suspended list. */
3247 pxTCB = prvSearchForNameWithinSingleList( &xSuspendedTaskList, pcNameToQuery );
3252 #if ( INCLUDE_vTaskDelete == 1 )
3256 /* Search the deleted list. */
3257 pxTCB = prvSearchForNameWithinSingleList( &xTasksWaitingTermination, pcNameToQuery );
3262 ( void ) xTaskResumeAll();
3267 #endif /* INCLUDE_xTaskGetHandle */
3268 /*-----------------------------------------------------------*/
3270 #if ( configUSE_TRACE_FACILITY == 1 )
3272 UBaseType_t uxTaskGetSystemState( TaskStatus_t * const pxTaskStatusArray,
3273 const UBaseType_t uxArraySize,
3274 uint32_t * const pulTotalRunTime )
3276 UBaseType_t uxTask = 0, uxQueue = configMAX_PRIORITIES;
3280 /* Is there a space in the array for each task in the system? */
3281 if( uxArraySize >= uxCurrentNumberOfTasks )
3283 /* Fill in an TaskStatus_t structure with information on each
3284 * task in the Ready state. */
3288 uxTask += prvListTasksWithinSingleList( &( pxTaskStatusArray[ uxTask ] ), &( pxReadyTasksLists[ uxQueue ] ), eReady );
3289 } while( uxQueue > ( UBaseType_t ) tskIDLE_PRIORITY ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */
3291 /* Fill in an TaskStatus_t structure with information on each
3292 * task in the Blocked state. */
3293 uxTask += prvListTasksWithinSingleList( &( pxTaskStatusArray[ uxTask ] ), ( List_t * ) pxDelayedTaskList, eBlocked );
3294 uxTask += prvListTasksWithinSingleList( &( pxTaskStatusArray[ uxTask ] ), ( List_t * ) pxOverflowDelayedTaskList, eBlocked );
3296 #if ( INCLUDE_vTaskDelete == 1 )
3298 /* Fill in an TaskStatus_t structure with information on
3299 * each task that has been deleted but not yet cleaned up. */
3300 uxTask += prvListTasksWithinSingleList( &( pxTaskStatusArray[ uxTask ] ), &xTasksWaitingTermination, eDeleted );
3304 #if ( INCLUDE_vTaskSuspend == 1 )
3306 /* Fill in an TaskStatus_t structure with information on
3307 * each task in the Suspended state. */
3308 uxTask += prvListTasksWithinSingleList( &( pxTaskStatusArray[ uxTask ] ), &xSuspendedTaskList, eSuspended );
3312 #if ( configGENERATE_RUN_TIME_STATS == 1 )
3314 if( pulTotalRunTime != NULL )
3316 #ifdef portALT_GET_RUN_TIME_COUNTER_VALUE
3317 portALT_GET_RUN_TIME_COUNTER_VALUE( ( *pulTotalRunTime ) );
3319 *pulTotalRunTime = portGET_RUN_TIME_COUNTER_VALUE();
3323 #else /* if ( configGENERATE_RUN_TIME_STATS == 1 ) */
3325 if( pulTotalRunTime != NULL )
3327 *pulTotalRunTime = 0;
3330 #endif /* if ( configGENERATE_RUN_TIME_STATS == 1 ) */
3334 mtCOVERAGE_TEST_MARKER();
3337 ( void ) xTaskResumeAll();
3342 #endif /* configUSE_TRACE_FACILITY */
3343 /*----------------------------------------------------------*/
3345 #if ( INCLUDE_xTaskGetIdleTaskHandle == 1 )
3347 TaskHandle_t * xTaskGetIdleTaskHandle( void )
3349 /* If xTaskGetIdleTaskHandle() is called before the scheduler has been
3350 * started, then xIdleTaskHandle will be NULL. */
3351 configASSERT( ( xIdleTaskHandle != NULL ) );
3352 return &( xIdleTaskHandle[ 0 ] );
3355 #endif /* INCLUDE_xTaskGetIdleTaskHandle */
3356 /*----------------------------------------------------------*/
3358 /* This conditional compilation should use inequality to 0, not equality to 1.
3359 * This is to ensure vTaskStepTick() is available when user defined low power mode
3360 * implementations require configUSE_TICKLESS_IDLE to be set to a value other than
3362 #if ( configUSE_TICKLESS_IDLE != 0 )
3364 void vTaskStepTick( const TickType_t xTicksToJump )
3366 /* Correct the tick count value after a period during which the tick
3367 * was suppressed. Note this does *not* call the tick hook function for
3368 * each stepped tick. */
3369 configASSERT( ( xTickCount + xTicksToJump ) <= xNextTaskUnblockTime );
3370 xTickCount += xTicksToJump;
3371 traceINCREASE_TICK_COUNT( xTicksToJump );
3374 #endif /* configUSE_TICKLESS_IDLE */
3375 /*----------------------------------------------------------*/
3377 BaseType_t xTaskCatchUpTicks( TickType_t xTicksToCatchUp )
3379 BaseType_t xYieldOccurred;
3381 /* Must not be called with the scheduler suspended as the implementation
3382 * relies on xPendedTicks being wound down to 0 in xTaskResumeAll(). */
3383 configASSERT( uxSchedulerSuspended == 0 );
3385 /* Use xPendedTicks to mimic xTicksToCatchUp number of ticks occurring when
3386 * the scheduler is suspended so the ticks are executed in xTaskResumeAll(). */
3388 xPendedTicks += xTicksToCatchUp;
3389 xYieldOccurred = xTaskResumeAll();
3391 return xYieldOccurred;
3393 /*----------------------------------------------------------*/
3395 #if ( INCLUDE_xTaskAbortDelay == 1 )
3397 BaseType_t xTaskAbortDelay( TaskHandle_t xTask )
3399 TCB_t * pxTCB = xTask;
3402 configASSERT( pxTCB );
3406 /* A task can only be prematurely removed from the Blocked state if
3407 * it is actually in the Blocked state. */
3408 if( eTaskGetState( xTask ) == eBlocked )
3412 /* Remove the reference to the task from the blocked list. An
3413 * interrupt won't touch the xStateListItem because the
3414 * scheduler is suspended. */
3415 ( void ) uxListRemove( &( pxTCB->xStateListItem ) );
3417 /* Is the task waiting on an event also? If so remove it from
3418 * the event list too. Interrupts can touch the event list item,
3419 * even though the scheduler is suspended, so a critical section
3421 taskENTER_CRITICAL();
3423 if( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) != NULL )
3425 ( void ) uxListRemove( &( pxTCB->xEventListItem ) );
3427 /* This lets the task know it was forcibly removed from the
3428 * blocked state so it should not re-evaluate its block time and
3429 * then block again. */
3430 pxTCB->ucDelayAborted = pdTRUE;
3434 mtCOVERAGE_TEST_MARKER();
3437 taskEXIT_CRITICAL();
3439 /* Place the unblocked task into the appropriate ready list. */
3440 prvAddTaskToReadyList( pxTCB );
3442 /* A task being unblocked cannot cause an immediate context
3443 * switch if preemption is turned off. */
3444 #if ( configUSE_PREEMPTION == 1 )
3446 taskENTER_CRITICAL();
3448 prvYieldForTask( pxTCB, pdFALSE );
3450 taskEXIT_CRITICAL();
3452 #endif /* configUSE_PREEMPTION */
3459 ( void ) xTaskResumeAll();
3464 #endif /* INCLUDE_xTaskAbortDelay */
3465 /*----------------------------------------------------------*/
3467 BaseType_t xTaskIncrementTick( void )
3470 TickType_t xItemValue;
3471 BaseType_t xSwitchRequired = pdFALSE;
3473 #if ( configUSE_PREEMPTION == 1 )
3475 BaseType_t xCoreYieldList[ configNUM_CORES ] = { pdFALSE };
3476 #endif /* configUSE_PREEMPTION */
3478 taskENTER_CRITICAL();
3480 /* Called by the portable layer each time a tick interrupt occurs.
3481 * Increments the tick then checks to see if the new tick value will cause any
3482 * tasks to be unblocked. */
3483 traceTASK_INCREMENT_TICK( xTickCount );
3485 /* Tick increment should occur on every kernel timer event. Core 0 has the
3486 * responsibility to increment the tick, or increment the pended ticks if the
3487 * scheduler is suspended. If pended ticks is greater than zero, the core that
3488 * calls xTaskResumeAll has the responsibility to increment the tick. */
3489 if( uxSchedulerSuspended == ( UBaseType_t ) pdFALSE )
3491 /* Minor optimisation. The tick count cannot change in this
3493 const TickType_t xConstTickCount = xTickCount + ( TickType_t ) 1;
3495 /* Increment the RTOS tick, switching the delayed and overflowed
3496 * delayed lists if it wraps to 0. */
3497 xTickCount = xConstTickCount;
3499 if( xConstTickCount == ( TickType_t ) 0U ) /*lint !e774 'if' does not always evaluate to false as it is looking for an overflow. */
3501 taskSWITCH_DELAYED_LISTS();
3505 mtCOVERAGE_TEST_MARKER();
3508 /* See if this tick has made a timeout expire. Tasks are stored in
3509 * the queue in the order of their wake time - meaning once one task
3510 * has been found whose block time has not expired there is no need to
3511 * look any further down the list. */
3512 if( xConstTickCount >= xNextTaskUnblockTime )
3516 if( listLIST_IS_EMPTY( pxDelayedTaskList ) != pdFALSE )
3518 /* The delayed list is empty. Set xNextTaskUnblockTime
3519 * to the maximum possible value so it is extremely
3521 * if( xTickCount >= xNextTaskUnblockTime ) test will pass
3522 * next time through. */
3523 xNextTaskUnblockTime = portMAX_DELAY; /*lint !e961 MISRA exception as the casts are only redundant for some ports. */
3528 /* The delayed list is not empty, get the value of the
3529 * item at the head of the delayed list. This is the time
3530 * at which the task at the head of the delayed list must
3531 * be removed from the Blocked state. */
3532 pxTCB = listGET_OWNER_OF_HEAD_ENTRY( pxDelayedTaskList ); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */
3533 xItemValue = listGET_LIST_ITEM_VALUE( &( pxTCB->xStateListItem ) );
3535 if( xConstTickCount < xItemValue )
3537 /* It is not time to unblock this item yet, but the
3538 * item value is the time at which the task at the head
3539 * of the blocked list must be removed from the Blocked
3540 * state - so record the item value in
3541 * xNextTaskUnblockTime. */
3542 xNextTaskUnblockTime = xItemValue;
3543 break; /*lint !e9011 Code structure here is deemed easier to understand with multiple breaks. */
3547 mtCOVERAGE_TEST_MARKER();
3550 /* It is time to remove the item from the Blocked state. */
3551 ( void ) uxListRemove( &( pxTCB->xStateListItem ) );
3553 /* Is the task waiting on an event also? If so remove
3554 * it from the event list. */
3555 if( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) != NULL )
3557 ( void ) uxListRemove( &( pxTCB->xEventListItem ) );
3561 mtCOVERAGE_TEST_MARKER();
3564 /* Place the unblocked task into the appropriate ready
3566 prvAddTaskToReadyList( pxTCB );
3568 /* A task being unblocked cannot cause an immediate
3569 * context switch if preemption is turned off. */
3570 #if ( configUSE_PREEMPTION == 1 )
3572 prvYieldForTask( pxTCB, pdTRUE );
3574 #endif /* configUSE_PREEMPTION */
3579 /* Tasks of equal priority to the currently running task will share
3580 * processing time (time slice) if preemption is on, and the application
3581 * writer has not explicitly turned time slicing off. */
3582 #if ( ( configUSE_PREEMPTION == 1 ) && ( configUSE_TIME_SLICING == 1 ) )
3584 /* TODO: If there are fewer "non-IDLE" READY tasks than cores, do not
3585 * force a context switch that would just shuffle tasks around cores */
3586 /* TODO: There are certainly better ways of doing this that would reduce
3587 * the number of interrupts and also potentially help prevent tasks from
3588 * moving between cores as often. This, however, works for now. */
3589 for( x = ( UBaseType_t ) 0; x < ( UBaseType_t ) configNUM_CORES; x++ )
3591 if( listCURRENT_LIST_LENGTH( &( pxReadyTasksLists[ pxCurrentTCBs[ x ]->uxPriority ] ) ) > ( UBaseType_t ) 1 )
3593 xCoreYieldList[ x ] = pdTRUE;
3597 mtCOVERAGE_TEST_MARKER();
3601 #endif /* ( ( configUSE_PREEMPTION == 1 ) && ( configUSE_TIME_SLICING == 1 ) ) */
3603 #if ( configUSE_TICK_HOOK == 1 )
3605 /* Guard against the tick hook being called when the pended tick
3606 * count is being unwound (when the scheduler is being unlocked). */
3607 if( xPendedTicks == ( TickType_t ) 0 )
3609 vApplicationTickHook();
3613 mtCOVERAGE_TEST_MARKER();
3616 #endif /* configUSE_TICK_HOOK */
3618 #if ( configUSE_PREEMPTION == 1 )
3620 for( x = ( UBaseType_t ) 0; x < ( UBaseType_t ) configNUM_CORES; x++ )
3622 if( xYieldPendings[ x ] != pdFALSE )
3624 xCoreYieldList[ x ] = pdTRUE;
3628 mtCOVERAGE_TEST_MARKER();
3632 #endif /* configUSE_PREEMPTION */
3634 #if ( configUSE_PREEMPTION == 1 )
3638 xCoreID = portGET_CORE_ID();
3640 for( x = ( UBaseType_t ) 0; x < ( UBaseType_t ) configNUM_CORES; x++ )
3642 #if ( configUSE_TASK_PREEMPTION_DISABLE == 1 )
3643 if( pxCurrentTCBs[ x ]->xPreemptionDisable == pdFALSE )
3646 if( xCoreYieldList[ x ] != pdFALSE )
3650 xSwitchRequired = pdTRUE;
3659 mtCOVERAGE_TEST_MARKER();
3664 #endif /* configUSE_PREEMPTION */
3670 /* The tick hook gets called at regular intervals, even if the
3671 * scheduler is locked. */
3672 #if ( configUSE_TICK_HOOK == 1 )
3674 vApplicationTickHook();
3679 taskEXIT_CRITICAL();
3681 return xSwitchRequired;
3683 /*-----------------------------------------------------------*/
3685 #if ( configUSE_APPLICATION_TASK_TAG == 1 )
3687 void vTaskSetApplicationTaskTag( TaskHandle_t xTask,
3688 TaskHookFunction_t pxHookFunction )
3692 /* If xTask is NULL then it is the task hook of the calling task that is
3696 xTCB = ( TCB_t * ) pxCurrentTCB;
3703 /* Save the hook function in the TCB. A critical section is required as
3704 * the value can be accessed from an interrupt. */
3705 taskENTER_CRITICAL();
3707 xTCB->pxTaskTag = pxHookFunction;
3709 taskEXIT_CRITICAL();
3712 #endif /* configUSE_APPLICATION_TASK_TAG */
3713 /*-----------------------------------------------------------*/
3715 #if ( configUSE_APPLICATION_TASK_TAG == 1 )
3717 TaskHookFunction_t xTaskGetApplicationTaskTag( TaskHandle_t xTask )
3720 TaskHookFunction_t xReturn;
3722 /* If xTask is NULL then set the calling task's hook. */
3723 pxTCB = prvGetTCBFromHandle( xTask );
3725 /* Save the hook function in the TCB. A critical section is required as
3726 * the value can be accessed from an interrupt. */
3727 taskENTER_CRITICAL();
3729 xReturn = pxTCB->pxTaskTag;
3731 taskEXIT_CRITICAL();
3736 #endif /* configUSE_APPLICATION_TASK_TAG */
3737 /*-----------------------------------------------------------*/
3739 #if ( configUSE_APPLICATION_TASK_TAG == 1 )
3741 TaskHookFunction_t xTaskGetApplicationTaskTagFromISR( TaskHandle_t xTask )
3744 TaskHookFunction_t xReturn;
3745 UBaseType_t uxSavedInterruptStatus;
3747 /* If xTask is NULL then set the calling task's hook. */
3748 pxTCB = prvGetTCBFromHandle( xTask );
3750 /* Save the hook function in the TCB. A critical section is required as
3751 * the value can be accessed from an interrupt. */
3752 uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR();
3754 xReturn = pxTCB->pxTaskTag;
3756 portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus );
3761 #endif /* configUSE_APPLICATION_TASK_TAG */
3762 /*-----------------------------------------------------------*/
3764 #if ( configUSE_APPLICATION_TASK_TAG == 1 )
3766 BaseType_t xTaskCallApplicationTaskHook( TaskHandle_t xTask,
3767 void * pvParameter )
3772 /* If xTask is NULL then we are calling our own task hook. */
3775 xTCB = pxCurrentTCB;
3782 if( xTCB->pxTaskTag != NULL )
3784 xReturn = xTCB->pxTaskTag( pvParameter );
3794 #endif /* configUSE_APPLICATION_TASK_TAG */
3795 /*-----------------------------------------------------------*/
3797 void vTaskSwitchContext( BaseType_t xCoreID )
3799 /* Acquire both locks:
3800 * - The ISR lock protects the ready list from simultaneous access by
3801 * both other ISRs and tasks.
3802 * - We also take the task lock to pause here in case another core has
3803 * suspended the scheduler. We don't want to simply set xYieldPending
3804 * and move on if another core suspended the scheduler. We should only
3805 * do that if the current core has suspended the scheduler. */
3807 portGET_TASK_LOCK(); /* Must always acquire the task lock first */
3810 /* vTaskSwitchContext() must never be called from within a critical section.
3811 * This is not necessarily true for vanilla FreeRTOS, but it is for this SMP port. */
3812 configASSERT( pxCurrentTCB->uxCriticalNesting == 0 );
3814 if( uxSchedulerSuspended != ( UBaseType_t ) pdFALSE )
3816 /* The scheduler is currently suspended - do not allow a context
3818 xYieldPendings[ xCoreID ] = pdTRUE;
3822 xYieldPendings[ xCoreID ] = pdFALSE;
3823 traceTASK_SWITCHED_OUT();
3825 #if ( configGENERATE_RUN_TIME_STATS == 1 )
3827 #ifdef portALT_GET_RUN_TIME_COUNTER_VALUE
3828 portALT_GET_RUN_TIME_COUNTER_VALUE( ulTotalRunTime );
3830 ulTotalRunTime = portGET_RUN_TIME_COUNTER_VALUE();
3833 /* Add the amount of time the task has been running to the
3834 * accumulated time so far. The time the task started running was
3835 * stored in ulTaskSwitchedInTime. Note that there is no overflow
3836 * protection here so count values are only valid until the timer
3837 * overflows. The guard against negative values is to protect
3838 * against suspect run time stat counter implementations - which
3839 * are provided by the application, not the kernel. */
3840 if( ulTotalRunTime > ulTaskSwitchedInTime )
3842 pxCurrentTCB->ulRunTimeCounter += ( ulTotalRunTime - ulTaskSwitchedInTime );
3846 mtCOVERAGE_TEST_MARKER();
3849 ulTaskSwitchedInTime = ulTotalRunTime;
3851 #endif /* configGENERATE_RUN_TIME_STATS */
3853 /* Check for stack overflow, if configured. */
3854 taskCHECK_FOR_STACK_OVERFLOW();
3856 /* Before the currently running task is switched out, save its errno. */
3857 #if ( configUSE_POSIX_ERRNO == 1 )
3859 pxCurrentTCB->iTaskErrno = FreeRTOS_errno;
3863 /* Select a new task to run using either the generic C or port
3864 * optimised asm code. */
3865 ( void ) prvSelectHighestPriorityTask( xCoreID );
3866 traceTASK_SWITCHED_IN();
3868 /* After the new task is switched in, update the global errno. */
3869 #if ( configUSE_POSIX_ERRNO == 1 )
3871 FreeRTOS_errno = pxCurrentTCB->iTaskErrno;
3875 #if ( configUSE_NEWLIB_REENTRANT == 1 )
3877 /* Switch Newlib's _impure_ptr variable to point to the _reent
3878 * structure specific to this task.
3879 * See the third party link http://www.nadler.com/embedded/newlibAndFreeRTOS.html
3880 * for additional information. */
3881 _impure_ptr = &( pxCurrentTCB->xNewLib_reent );
3883 #endif /* configUSE_NEWLIB_REENTRANT */
3886 portRELEASE_ISR_LOCK();
3887 portRELEASE_TASK_LOCK();
3889 /*-----------------------------------------------------------*/
3891 void vTaskPlaceOnEventList( List_t * const pxEventList,
3892 const TickType_t xTicksToWait )
3894 configASSERT( pxEventList );
3896 /* THIS FUNCTION MUST BE CALLED WITH EITHER INTERRUPTS DISABLED OR THE
3897 * SCHEDULER SUSPENDED AND THE QUEUE BEING ACCESSED LOCKED. */
3899 /* Place the event list item of the TCB in the appropriate event list.
3900 * This is placed in the list in priority order so the highest priority task
3901 * is the first to be woken by the event. The queue that contains the event
3902 * list is locked, preventing simultaneous access from interrupts. */
3903 vListInsert( pxEventList, &( pxCurrentTCB->xEventListItem ) );
3905 prvAddCurrentTaskToDelayedList( xTicksToWait, pdTRUE );
3907 /*-----------------------------------------------------------*/
3909 void vTaskPlaceOnUnorderedEventList( List_t * pxEventList,
3910 const TickType_t xItemValue,
3911 const TickType_t xTicksToWait )
3913 configASSERT( pxEventList );
3915 /* THIS FUNCTION MUST BE CALLED WITH THE SCHEDULER SUSPENDED. It is used by
3916 * the event groups implementation. */
3917 configASSERT( uxSchedulerSuspended != 0 );
3919 /* Store the item value in the event list item. It is safe to access the
3920 * event list item here as interrupts won't access the event list item of a
3921 * task that is not in the Blocked state. */
3922 listSET_LIST_ITEM_VALUE( &( pxCurrentTCB->xEventListItem ), xItemValue | taskEVENT_LIST_ITEM_VALUE_IN_USE );
3924 /* Place the event list item of the TCB at the end of the appropriate event
3925 * list. It is safe to access the event list here because it is part of an
3926 * event group implementation - and interrupts don't access event groups
3927 * directly (instead they access them indirectly by pending function calls to
3928 * the task level). */
3929 vListInsertEnd( pxEventList, &( pxCurrentTCB->xEventListItem ) );
3931 prvAddCurrentTaskToDelayedList( xTicksToWait, pdTRUE );
3933 /*-----------------------------------------------------------*/
3935 #if ( configUSE_TIMERS == 1 )
3937 void vTaskPlaceOnEventListRestricted( List_t * const pxEventList,
3938 TickType_t xTicksToWait,
3939 const BaseType_t xWaitIndefinitely )
3941 configASSERT( pxEventList );
3943 /* This function should not be called by application code hence the
3944 * 'Restricted' in its name. It is not part of the public API. It is
3945 * designed for use by kernel code, and has special calling requirements -
3946 * it should be called with the scheduler suspended. */
3949 /* Place the event list item of the TCB in the appropriate event list.
3950 * In this case it is assume that this is the only task that is going to
3951 * be waiting on this event list, so the faster vListInsertEnd() function
3952 * can be used in place of vListInsert. */
3953 vListInsertEnd( pxEventList, &( pxCurrentTCB->xEventListItem ) );
3955 /* If the task should block indefinitely then set the block time to a
3956 * value that will be recognised as an indefinite delay inside the
3957 * prvAddCurrentTaskToDelayedList() function. */
3958 if( xWaitIndefinitely != pdFALSE )
3960 xTicksToWait = portMAX_DELAY;
3963 traceTASK_DELAY_UNTIL( ( xTickCount + xTicksToWait ) );
3964 prvAddCurrentTaskToDelayedList( xTicksToWait, xWaitIndefinitely );
3967 #endif /* configUSE_TIMERS */
3968 /*-----------------------------------------------------------*/
3970 BaseType_t xTaskRemoveFromEventList( const List_t * const pxEventList )
3972 TCB_t * pxUnblockedTCB;
3975 /* THIS FUNCTION MUST BE CALLED FROM A CRITICAL SECTION. It can also be
3976 * called from a critical section within an ISR. */
3978 /* The event list is sorted in priority order, so the first in the list can
3979 * be removed as it is known to be the highest priority. Remove the TCB from
3980 * the delayed list, and add it to the ready list.
3982 * If an event is for a queue that is locked then this function will never
3983 * get called - the lock count on the queue will get modified instead. This
3984 * means exclusive access to the event list is guaranteed here.
3986 * This function assumes that a check has already been made to ensure that
3987 * pxEventList is not empty. */
3988 pxUnblockedTCB = listGET_OWNER_OF_HEAD_ENTRY( pxEventList ); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */
3989 configASSERT( pxUnblockedTCB );
3990 ( void ) uxListRemove( &( pxUnblockedTCB->xEventListItem ) );
3992 if( uxSchedulerSuspended == ( UBaseType_t ) pdFALSE )
3994 ( void ) uxListRemove( &( pxUnblockedTCB->xStateListItem ) );
3995 prvAddTaskToReadyList( pxUnblockedTCB );
3997 #if ( configUSE_TICKLESS_IDLE != 0 )
3999 /* If a task is blocked on a kernel object then xNextTaskUnblockTime
4000 * might be set to the blocked task's time out time. If the task is
4001 * unblocked for a reason other than a timeout xNextTaskUnblockTime is
4002 * normally left unchanged, because it is automatically reset to a new
4003 * value when the tick count equals xNextTaskUnblockTime. However if
4004 * tickless idling is used it might be more important to enter sleep mode
4005 * at the earliest possible time - so reset xNextTaskUnblockTime here to
4006 * ensure it is updated at the earliest possible time. */
4007 prvResetNextTaskUnblockTime();
4013 /* The delayed and ready lists cannot be accessed, so hold this task
4014 * pending until the scheduler is resumed. */
4015 vListInsertEnd( &( xPendingReadyList ), &( pxUnblockedTCB->xEventListItem ) );
4019 #if ( configUSE_PREEMPTION == 1 )
4020 prvYieldForTask( pxUnblockedTCB, pdFALSE );
4022 if( xYieldPendings[ portGET_CORE_ID() ] != pdFALSE )
4030 /*-----------------------------------------------------------*/
4032 void vTaskRemoveFromUnorderedEventList( ListItem_t * pxEventListItem,
4033 const TickType_t xItemValue )
4035 TCB_t * pxUnblockedTCB;
4037 /* THIS FUNCTION MUST BE CALLED WITH THE SCHEDULER SUSPENDED. It is used by
4038 * the event flags implementation. */
4039 configASSERT( uxSchedulerSuspended != pdFALSE );
4041 /* Store the new item value in the event list. */
4042 listSET_LIST_ITEM_VALUE( pxEventListItem, xItemValue | taskEVENT_LIST_ITEM_VALUE_IN_USE );
4044 /* Remove the event list form the event flag. Interrupts do not access
4046 pxUnblockedTCB = listGET_LIST_ITEM_OWNER( pxEventListItem ); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */
4047 configASSERT( pxUnblockedTCB );
4048 ( void ) uxListRemove( pxEventListItem );
4050 #if ( configUSE_TICKLESS_IDLE != 0 )
4052 /* If a task is blocked on a kernel object then xNextTaskUnblockTime
4053 * might be set to the blocked task's time out time. If the task is
4054 * unblocked for a reason other than a timeout xNextTaskUnblockTime is
4055 * normally left unchanged, because it is automatically reset to a new
4056 * value when the tick count equals xNextTaskUnblockTime. However if
4057 * tickless idling is used it might be more important to enter sleep mode
4058 * at the earliest possible time - so reset xNextTaskUnblockTime here to
4059 * ensure it is updated at the earliest possible time. */
4060 prvResetNextTaskUnblockTime();
4064 /* Remove the task from the delayed list and add it to the ready list. The
4065 * scheduler is suspended so interrupts will not be accessing the ready
4067 ( void ) uxListRemove( &( pxUnblockedTCB->xStateListItem ) );
4068 prvAddTaskToReadyList( pxUnblockedTCB );
4070 #if ( configUSE_PREEMPTION == 1 )
4071 taskENTER_CRITICAL();
4073 prvYieldForTask( pxUnblockedTCB, pdFALSE );
4075 taskEXIT_CRITICAL();
4078 /*-----------------------------------------------------------*/
4080 void vTaskSetTimeOutState( TimeOut_t * const pxTimeOut )
4082 configASSERT( pxTimeOut );
4083 taskENTER_CRITICAL();
4085 pxTimeOut->xOverflowCount = xNumOfOverflows;
4086 pxTimeOut->xTimeOnEntering = xTickCount;
4088 taskEXIT_CRITICAL();
4090 /*-----------------------------------------------------------*/
4092 void vTaskInternalSetTimeOutState( TimeOut_t * const pxTimeOut )
4094 /* For internal use only as it does not use a critical section. */
4095 pxTimeOut->xOverflowCount = xNumOfOverflows;
4096 pxTimeOut->xTimeOnEntering = xTickCount;
4098 /*-----------------------------------------------------------*/
4100 BaseType_t xTaskCheckForTimeOut( TimeOut_t * const pxTimeOut,
4101 TickType_t * const pxTicksToWait )
4105 configASSERT( pxTimeOut );
4106 configASSERT( pxTicksToWait );
4108 taskENTER_CRITICAL();
4110 /* Minor optimisation. The tick count cannot change in this block. */
4111 const TickType_t xConstTickCount = xTickCount;
4112 const TickType_t xElapsedTime = xConstTickCount - pxTimeOut->xTimeOnEntering;
4114 #if ( INCLUDE_xTaskAbortDelay == 1 )
4115 if( pxCurrentTCB->ucDelayAborted != ( uint8_t ) pdFALSE )
4117 /* The delay was aborted, which is not the same as a time out,
4118 * but has the same result. */
4119 pxCurrentTCB->ucDelayAborted = pdFALSE;
4125 #if ( INCLUDE_vTaskSuspend == 1 )
4126 if( *pxTicksToWait == portMAX_DELAY )
4128 /* If INCLUDE_vTaskSuspend is set to 1 and the block time
4129 * specified is the maximum block time then the task should block
4130 * indefinitely, and therefore never time out. */
4136 if( ( xNumOfOverflows != pxTimeOut->xOverflowCount ) && ( xConstTickCount >= pxTimeOut->xTimeOnEntering ) ) /*lint !e525 Indentation preferred as is to make code within pre-processor directives clearer. */
4138 /* The tick count is greater than the time at which
4139 * vTaskSetTimeout() was called, but has also overflowed since
4140 * vTaskSetTimeOut() was called. It must have wrapped all the way
4141 * around and gone past again. This passed since vTaskSetTimeout()
4144 *pxTicksToWait = ( TickType_t ) 0;
4146 else if( xElapsedTime < *pxTicksToWait ) /*lint !e961 Explicit casting is only redundant with some compilers, whereas others require it to prevent integer conversion errors. */
4148 /* Not a genuine timeout. Adjust parameters for time remaining. */
4149 *pxTicksToWait -= xElapsedTime;
4150 vTaskInternalSetTimeOutState( pxTimeOut );
4155 *pxTicksToWait = ( TickType_t ) 0;
4159 taskEXIT_CRITICAL();
4163 /*-----------------------------------------------------------*/
4165 void vTaskMissedYield( void )
4167 /* Must be called from within a critical section */
4168 xYieldPendings[ portGET_CORE_ID() ] = pdTRUE;
4170 /*-----------------------------------------------------------*/
4172 #if ( configUSE_TRACE_FACILITY == 1 )
4174 UBaseType_t uxTaskGetTaskNumber( TaskHandle_t xTask )
4176 UBaseType_t uxReturn;
4177 TCB_t const * pxTCB;
4182 uxReturn = pxTCB->uxTaskNumber;
4192 #endif /* configUSE_TRACE_FACILITY */
4193 /*-----------------------------------------------------------*/
4195 #if ( configUSE_TRACE_FACILITY == 1 )
4197 void vTaskSetTaskNumber( TaskHandle_t xTask,
4198 const UBaseType_t uxHandle )
4205 pxTCB->uxTaskNumber = uxHandle;
4209 #endif /* configUSE_TRACE_FACILITY */
4212 * -----------------------------------------------------------
4213 * The MinimalIdle task.
4214 * ----------------------------------------------------------
4216 * The minimal idle task is used for all the additional Cores in a SMP system.
4217 * There must be only 1 idle task and the rest are minimal idle tasks.
4219 * @todo additional conditional compiles to remove this function.
4222 #if ( configNUM_CORES > 1 )
4223 static portTASK_FUNCTION( prvMinimalIdleTask, pvParameters )
4229 #if ( configUSE_PREEMPTION == 0 )
4231 /* If we are not using preemption we keep forcing a task switch to
4232 * see if any other task has become available. If we are using
4233 * preemption we don't need to do this as any task becoming available
4234 * will automatically get the processor anyway. */
4237 #endif /* configUSE_PREEMPTION */
4239 #if ( ( configUSE_PREEMPTION == 1 ) && ( configIDLE_SHOULD_YIELD == 1 ) )
4241 /* When using preemption tasks of equal priority will be
4242 * timesliced. If a task that is sharing the idle priority is ready
4243 * to run then the idle task should yield before the end of the
4246 * A critical region is not required here as we are just reading from
4247 * the list, and an occasional incorrect value will not matter. If
4248 * the ready list at the idle priority contains one more task than the
4249 * number of idle tasks, which is equal to the configured numbers of cores
4250 * then a task other than the idle task is ready to execute. */
4251 if( listCURRENT_LIST_LENGTH( &( pxReadyTasksLists[ tskIDLE_PRIORITY ] ) ) > ( UBaseType_t ) configNUM_CORES )
4257 mtCOVERAGE_TEST_MARKER();
4260 #endif /* ( ( configUSE_PREEMPTION == 1 ) && ( configIDLE_SHOULD_YIELD == 1 ) ) */
4262 #if ( configUSE_MINIMAL_IDLE_HOOK == 1 )
4264 extern void vApplicationMinimalIdleHook( void );
4266 /* Call the user defined function from within the idle task. This
4267 * allows the application designer to add background functionality
4268 * without the overhead of a separate task.
4270 * This hook is intended to manage core activity such as disabling cores that go idle.
4272 * NOTE: vApplicationMinimalIdleHook() MUST NOT, UNDER ANY CIRCUMSTANCES,
4273 * CALL A FUNCTION THAT MIGHT BLOCK. */
4274 vApplicationMinimalIdleHook();
4276 #endif /* configUSE_MINIMAL_IDLE_HOOK */
4279 #endif /* if ( configNUM_CORES > 1 ) */
4282 * -----------------------------------------------------------
4284 * ----------------------------------------------------------
4288 static portTASK_FUNCTION( prvIdleTask, pvParameters )
4290 /* Stop warnings. */
4291 ( void ) pvParameters;
4293 /** THIS IS THE RTOS IDLE TASK - WHICH IS CREATED AUTOMATICALLY WHEN THE
4294 * SCHEDULER IS STARTED. **/
4296 /* In case a task that has a secure context deletes itself, in which case
4297 * the idle task is responsible for deleting the task's secure context, if
4299 portALLOCATE_SECURE_CONTEXT( configMINIMAL_SECURE_STACK_SIZE );
4301 /* All cores start up in the idle task. This initial yield gets the application
4307 /* See if any tasks have deleted themselves - if so then the idle task
4308 * is responsible for freeing the deleted task's TCB and stack. */
4309 prvCheckTasksWaitingTermination();
4311 #if ( configUSE_PREEMPTION == 0 )
4313 /* If we are not using preemption we keep forcing a task switch to
4314 * see if any other task has become available. If we are using
4315 * preemption we don't need to do this as any task becoming available
4316 * will automatically get the processor anyway. */
4319 #endif /* configUSE_PREEMPTION */
4321 #if ( ( configUSE_PREEMPTION == 1 ) && ( configIDLE_SHOULD_YIELD == 1 ) )
4323 /* When using preemption tasks of equal priority will be
4324 * timesliced. If a task that is sharing the idle priority is ready
4325 * to run then the idle task should yield before the end of the
4328 * A critical region is not required here as we are just reading from
4329 * the list, and an occasional incorrect value will not matter. If
4330 * the ready list at the idle priority contains one more task than the
4331 * number of idle tasks, which is equal to the configured numbers of cores
4332 * then a task other than the idle task is ready to execute. */
4333 if( listCURRENT_LIST_LENGTH( &( pxReadyTasksLists[ tskIDLE_PRIORITY ] ) ) > ( UBaseType_t ) configNUM_CORES )
4339 mtCOVERAGE_TEST_MARKER();
4342 #endif /* ( ( configUSE_PREEMPTION == 1 ) && ( configIDLE_SHOULD_YIELD == 1 ) ) */
4344 #if ( configUSE_IDLE_HOOK == 1 )
4346 extern void vApplicationIdleHook( void );
4348 /* Call the user defined function from within the idle task. This
4349 * allows the application designer to add background functionality
4350 * without the overhead of a separate task.
4352 * NOTE: vApplicationIdleHook() MUST NOT, UNDER ANY CIRCUMSTANCES,
4353 * CALL A FUNCTION THAT MIGHT BLOCK. */
4354 vApplicationIdleHook();
4356 #endif /* configUSE_IDLE_HOOK */
4358 /* This conditional compilation should use inequality to 0, not equality
4359 * to 1. This is to ensure portSUPPRESS_TICKS_AND_SLEEP() is called when
4360 * user defined low power mode implementations require
4361 * configUSE_TICKLESS_IDLE to be set to a value other than 1. */
4362 #if ( configUSE_TICKLESS_IDLE != 0 )
4364 TickType_t xExpectedIdleTime;
4366 /* It is not desirable to suspend then resume the scheduler on
4367 * each iteration of the idle task. Therefore, a preliminary
4368 * test of the expected idle time is performed without the
4369 * scheduler suspended. The result here is not necessarily
4371 xExpectedIdleTime = prvGetExpectedIdleTime();
4373 if( xExpectedIdleTime >= configEXPECTED_IDLE_TIME_BEFORE_SLEEP )
4377 /* Now the scheduler is suspended, the expected idle
4378 * time can be sampled again, and this time its value can
4380 configASSERT( xNextTaskUnblockTime >= xTickCount );
4381 xExpectedIdleTime = prvGetExpectedIdleTime();
4383 /* Define the following macro to set xExpectedIdleTime to 0
4384 * if the application does not want
4385 * portSUPPRESS_TICKS_AND_SLEEP() to be called. */
4386 configPRE_SUPPRESS_TICKS_AND_SLEEP_PROCESSING( xExpectedIdleTime );
4388 if( xExpectedIdleTime >= configEXPECTED_IDLE_TIME_BEFORE_SLEEP )
4390 traceLOW_POWER_IDLE_BEGIN();
4391 portSUPPRESS_TICKS_AND_SLEEP( xExpectedIdleTime );
4392 traceLOW_POWER_IDLE_END();
4396 mtCOVERAGE_TEST_MARKER();
4399 ( void ) xTaskResumeAll();
4403 mtCOVERAGE_TEST_MARKER();
4406 #endif /* configUSE_TICKLESS_IDLE */
4408 #if ( configUSE_MINIMAL_IDLE_HOOK == 1 )
4410 extern void vApplicationMinimalIdleHook( void );
4412 /* Call the user defined function from within the idle task. This
4413 * allows the application designer to add background functionality
4414 * without the overhead of a separate task.
4416 * This hook is intended to manage core activity such as disabling cores that go idle.
4418 * NOTE: vApplicationMinimalIdleHook() MUST NOT, UNDER ANY CIRCUMSTANCES,
4419 * CALL A FUNCTION THAT MIGHT BLOCK. */
4420 vApplicationMinimalIdleHook();
4422 #endif /* configUSE_MINIMAL_IDLE_HOOK */
4425 /*-----------------------------------------------------------*/
4427 #if ( configUSE_TICKLESS_IDLE != 0 )
4429 eSleepModeStatus eTaskConfirmSleepModeStatus( void )
4431 /* The idle task exists in addition to the application tasks. */
4432 const UBaseType_t uxNonApplicationTasks = 1;
4433 eSleepModeStatus eReturn = eStandardSleep;
4435 /* This function must be called from a critical section. */
4437 if( listCURRENT_LIST_LENGTH( &xPendingReadyList ) != 0 )
4439 /* A task was made ready while the scheduler was suspended. */
4440 eReturn = eAbortSleep;
4442 else if( xYieldPending != pdFALSE )
4444 /* A yield was pended while the scheduler was suspended. */
4445 eReturn = eAbortSleep;
4447 else if( xPendedTicks != 0 )
4449 /* A tick interrupt has already occurred but was held pending
4450 * because the scheduler is suspended. */
4451 eReturn = eAbortSleep;
4455 /* If all the tasks are in the suspended list (which might mean they
4456 * have an infinite block time rather than actually being suspended)
4457 * then it is safe to turn all clocks off and just wait for external
4459 if( listCURRENT_LIST_LENGTH( &xSuspendedTaskList ) == ( uxCurrentNumberOfTasks - uxNonApplicationTasks ) )
4461 eReturn = eNoTasksWaitingTimeout;
4465 mtCOVERAGE_TEST_MARKER();
4472 #endif /* configUSE_TICKLESS_IDLE */
4473 /*-----------------------------------------------------------*/
4475 #if ( configNUM_THREAD_LOCAL_STORAGE_POINTERS != 0 )
4477 void vTaskSetThreadLocalStoragePointer( TaskHandle_t xTaskToSet,
4483 if( xIndex < configNUM_THREAD_LOCAL_STORAGE_POINTERS )
4485 pxTCB = prvGetTCBFromHandle( xTaskToSet );
4486 configASSERT( pxTCB != NULL );
4487 pxTCB->pvThreadLocalStoragePointers[ xIndex ] = pvValue;
4491 #endif /* configNUM_THREAD_LOCAL_STORAGE_POINTERS */
4492 /*-----------------------------------------------------------*/
4494 #if ( configNUM_THREAD_LOCAL_STORAGE_POINTERS != 0 )
4496 void * pvTaskGetThreadLocalStoragePointer( TaskHandle_t xTaskToQuery,
4499 void * pvReturn = NULL;
4502 if( xIndex < configNUM_THREAD_LOCAL_STORAGE_POINTERS )
4504 pxTCB = prvGetTCBFromHandle( xTaskToQuery );
4505 pvReturn = pxTCB->pvThreadLocalStoragePointers[ xIndex ];
4515 #endif /* configNUM_THREAD_LOCAL_STORAGE_POINTERS */
4516 /*-----------------------------------------------------------*/
4518 #if ( portUSING_MPU_WRAPPERS == 1 )
4520 void vTaskAllocateMPURegions( TaskHandle_t xTaskToModify,
4521 const MemoryRegion_t * const xRegions )
4525 /* If null is passed in here then we are modifying the MPU settings of
4526 * the calling task. */
4527 pxTCB = prvGetTCBFromHandle( xTaskToModify );
4529 vPortStoreTaskMPUSettings( &( pxTCB->xMPUSettings ), xRegions, NULL, 0 );
4532 #endif /* portUSING_MPU_WRAPPERS */
4533 /*-----------------------------------------------------------*/
4535 static void prvInitialiseTaskLists( void )
4537 UBaseType_t uxPriority;
4539 for( uxPriority = ( UBaseType_t ) 0U; uxPriority < ( UBaseType_t ) configMAX_PRIORITIES; uxPriority++ )
4541 vListInitialise( &( pxReadyTasksLists[ uxPriority ] ) );
4544 vListInitialise( &xDelayedTaskList1 );
4545 vListInitialise( &xDelayedTaskList2 );
4546 vListInitialise( &xPendingReadyList );
4548 #if ( INCLUDE_vTaskDelete == 1 )
4550 vListInitialise( &xTasksWaitingTermination );
4552 #endif /* INCLUDE_vTaskDelete */
4554 #if ( INCLUDE_vTaskSuspend == 1 )
4556 vListInitialise( &xSuspendedTaskList );
4558 #endif /* INCLUDE_vTaskSuspend */
4560 /* Start with pxDelayedTaskList using list1 and the pxOverflowDelayedTaskList
4562 pxDelayedTaskList = &xDelayedTaskList1;
4563 pxOverflowDelayedTaskList = &xDelayedTaskList2;
4565 /*-----------------------------------------------------------*/
4567 static void prvCheckTasksWaitingTermination( void )
4569 /** THIS FUNCTION IS CALLED FROM THE RTOS IDLE TASK **/
4571 #if ( INCLUDE_vTaskDelete == 1 )
4575 /* uxDeletedTasksWaitingCleanUp is used to prevent taskENTER_CRITICAL()
4576 * being called too often in the idle task. */
4577 while( uxDeletedTasksWaitingCleanUp > ( UBaseType_t ) 0U )
4579 taskENTER_CRITICAL();
4581 /* Since we are SMP, multiple idles can be running simultaneously
4582 * and we need to check that other idles did not cleanup while we were
4583 * waiting to enter the critical section */
4584 if( uxDeletedTasksWaitingCleanUp > ( UBaseType_t ) 0U )
4586 pxTCB = listGET_OWNER_OF_HEAD_ENTRY( ( &xTasksWaitingTermination ) ); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */
4588 if( pxTCB->xTaskRunState == taskTASK_NOT_RUNNING )
4590 ( void ) uxListRemove( &( pxTCB->xStateListItem ) );
4591 --uxCurrentNumberOfTasks;
4592 --uxDeletedTasksWaitingCleanUp;
4593 prvDeleteTCB( pxTCB );
4597 /* The TCB to be deleted still has not yet been switched out
4598 * by the scheduler, so we will just exit this loop early and
4599 * try again next time. */
4600 taskEXIT_CRITICAL();
4605 taskEXIT_CRITICAL();
4608 #endif /* INCLUDE_vTaskDelete */
4610 /*-----------------------------------------------------------*/
4612 #if ( configUSE_TRACE_FACILITY == 1 )
4614 void vTaskGetInfo( TaskHandle_t xTask,
4615 TaskStatus_t * pxTaskStatus,
4616 BaseType_t xGetFreeStackSpace,
4621 /* xTask is NULL then get the state of the calling task. */
4622 pxTCB = prvGetTCBFromHandle( xTask );
4624 pxTaskStatus->xHandle = ( TaskHandle_t ) pxTCB;
4625 pxTaskStatus->pcTaskName = ( const char * ) &( pxTCB->pcTaskName[ 0 ] );
4626 pxTaskStatus->uxCurrentPriority = pxTCB->uxPriority;
4627 pxTaskStatus->pxStackBase = pxTCB->pxStack;
4628 pxTaskStatus->xTaskNumber = pxTCB->uxTCBNumber;
4630 #if ( configUSE_MUTEXES == 1 )
4632 pxTaskStatus->uxBasePriority = pxTCB->uxBasePriority;
4636 pxTaskStatus->uxBasePriority = 0;
4640 #if ( configGENERATE_RUN_TIME_STATS == 1 )
4642 pxTaskStatus->ulRunTimeCounter = pxTCB->ulRunTimeCounter;
4646 pxTaskStatus->ulRunTimeCounter = 0;
4650 /* Obtaining the task state is a little fiddly, so is only done if the
4651 * value of eState passed into this function is eInvalid - otherwise the
4652 * state is just set to whatever is passed in. */
4653 if( eState != eInvalid )
4655 if( taskTASK_IS_RUNNING( pxTCB->xTaskRunState ) )
4657 pxTaskStatus->eCurrentState = eRunning;
4661 pxTaskStatus->eCurrentState = eState;
4663 #if ( INCLUDE_vTaskSuspend == 1 )
4665 /* If the task is in the suspended list then there is a
4666 * chance it is actually just blocked indefinitely - so really
4667 * it should be reported as being in the Blocked state. */
4668 if( eState == eSuspended )
4672 if( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) != NULL )
4674 pxTaskStatus->eCurrentState = eBlocked;
4677 ( void ) xTaskResumeAll();
4680 #endif /* INCLUDE_vTaskSuspend */
4685 pxTaskStatus->eCurrentState = eTaskGetState( pxTCB );
4688 /* Obtaining the stack space takes some time, so the xGetFreeStackSpace
4689 * parameter is provided to allow it to be skipped. */
4690 if( xGetFreeStackSpace != pdFALSE )
4692 #if ( portSTACK_GROWTH > 0 )
4694 pxTaskStatus->usStackHighWaterMark = prvTaskCheckFreeStackSpace( ( uint8_t * ) pxTCB->pxEndOfStack );
4698 pxTaskStatus->usStackHighWaterMark = prvTaskCheckFreeStackSpace( ( uint8_t * ) pxTCB->pxStack );
4704 pxTaskStatus->usStackHighWaterMark = 0;
4708 #endif /* configUSE_TRACE_FACILITY */
4709 /*-----------------------------------------------------------*/
4711 #if ( configUSE_TRACE_FACILITY == 1 )
4713 static UBaseType_t prvListTasksWithinSingleList( TaskStatus_t * pxTaskStatusArray,
4717 configLIST_VOLATILE TCB_t * pxNextTCB, * pxFirstTCB;
4718 UBaseType_t uxTask = 0;
4720 if( listCURRENT_LIST_LENGTH( pxList ) > ( UBaseType_t ) 0 )
4722 listGET_OWNER_OF_NEXT_ENTRY( pxFirstTCB, pxList ); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */
4724 /* Populate an TaskStatus_t structure within the
4725 * pxTaskStatusArray array for each task that is referenced from
4726 * pxList. See the definition of TaskStatus_t in task.h for the
4727 * meaning of each TaskStatus_t structure member. */
4730 listGET_OWNER_OF_NEXT_ENTRY( pxNextTCB, pxList ); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */
4731 vTaskGetInfo( ( TaskHandle_t ) pxNextTCB, &( pxTaskStatusArray[ uxTask ] ), pdTRUE, eState );
4733 } while( pxNextTCB != pxFirstTCB );
4737 mtCOVERAGE_TEST_MARKER();
4743 #endif /* configUSE_TRACE_FACILITY */
4744 /*-----------------------------------------------------------*/
4746 #if ( ( configUSE_TRACE_FACILITY == 1 ) || ( INCLUDE_uxTaskGetStackHighWaterMark == 1 ) || ( INCLUDE_uxTaskGetStackHighWaterMark2 == 1 ) )
4748 static configSTACK_DEPTH_TYPE prvTaskCheckFreeStackSpace( const uint8_t * pucStackByte )
4750 uint32_t ulCount = 0U;
4752 while( *pucStackByte == ( uint8_t ) tskSTACK_FILL_BYTE )
4754 pucStackByte -= portSTACK_GROWTH;
4758 ulCount /= ( uint32_t ) sizeof( StackType_t ); /*lint !e961 Casting is not redundant on smaller architectures. */
4760 return ( configSTACK_DEPTH_TYPE ) ulCount;
4763 #endif /* ( ( configUSE_TRACE_FACILITY == 1 ) || ( INCLUDE_uxTaskGetStackHighWaterMark == 1 ) || ( INCLUDE_uxTaskGetStackHighWaterMark2 == 1 ) ) */
4764 /*-----------------------------------------------------------*/
4766 #if ( INCLUDE_uxTaskGetStackHighWaterMark2 == 1 )
4768 /* uxTaskGetStackHighWaterMark() and uxTaskGetStackHighWaterMark2() are the
4769 * same except for their return type. Using configSTACK_DEPTH_TYPE allows the
4770 * user to determine the return type. It gets around the problem of the value
4771 * overflowing on 8-bit types without breaking backward compatibility for
4772 * applications that expect an 8-bit return type. */
4773 configSTACK_DEPTH_TYPE uxTaskGetStackHighWaterMark2( TaskHandle_t xTask )
4776 uint8_t * pucEndOfStack;
4777 configSTACK_DEPTH_TYPE uxReturn;
4779 /* uxTaskGetStackHighWaterMark() and uxTaskGetStackHighWaterMark2() are
4780 * the same except for their return type. Using configSTACK_DEPTH_TYPE
4781 * allows the user to determine the return type. It gets around the
4782 * problem of the value overflowing on 8-bit types without breaking
4783 * backward compatibility for applications that expect an 8-bit return
4786 pxTCB = prvGetTCBFromHandle( xTask );
4788 #if portSTACK_GROWTH < 0
4790 pucEndOfStack = ( uint8_t * ) pxTCB->pxStack;
4794 pucEndOfStack = ( uint8_t * ) pxTCB->pxEndOfStack;
4798 uxReturn = prvTaskCheckFreeStackSpace( pucEndOfStack );
4803 #endif /* INCLUDE_uxTaskGetStackHighWaterMark2 */
4804 /*-----------------------------------------------------------*/
4806 #if ( INCLUDE_uxTaskGetStackHighWaterMark == 1 )
4808 UBaseType_t uxTaskGetStackHighWaterMark( TaskHandle_t xTask )
4811 uint8_t * pucEndOfStack;
4812 UBaseType_t uxReturn;
4814 pxTCB = prvGetTCBFromHandle( xTask );
4816 #if portSTACK_GROWTH < 0
4818 pucEndOfStack = ( uint8_t * ) pxTCB->pxStack;
4822 pucEndOfStack = ( uint8_t * ) pxTCB->pxEndOfStack;
4826 uxReturn = ( UBaseType_t ) prvTaskCheckFreeStackSpace( pucEndOfStack );
4831 #endif /* INCLUDE_uxTaskGetStackHighWaterMark */
4832 /*-----------------------------------------------------------*/
4834 #if ( INCLUDE_vTaskDelete == 1 )
4836 static void prvDeleteTCB( TCB_t * pxTCB )
4838 /* This call is required specifically for the TriCore port. It must be
4839 * above the vPortFree() calls. The call is also used by ports/demos that
4840 * want to allocate and clean RAM statically. */
4841 portCLEAN_UP_TCB( pxTCB );
4843 /* Free up the memory allocated by the scheduler for the task. It is up
4844 * to the task to free any memory allocated at the application level.
4845 * See the third party link http://www.nadler.com/embedded/newlibAndFreeRTOS.html
4846 * for additional information. */
4847 #if ( configUSE_NEWLIB_REENTRANT == 1 )
4849 _reclaim_reent( &( pxTCB->xNewLib_reent ) );
4851 #endif /* configUSE_NEWLIB_REENTRANT */
4853 #if ( ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 0 ) && ( portUSING_MPU_WRAPPERS == 0 ) )
4855 /* The task can only have been allocated dynamically - free both
4856 * the stack and TCB. */
4857 vPortFreeStack( pxTCB->pxStack );
4860 #elif ( tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE != 0 ) /*lint !e731 !e9029 Macro has been consolidated for readability reasons. */
4862 /* The task could have been allocated statically or dynamically, so
4863 * check what was statically allocated before trying to free the
4865 if( pxTCB->ucStaticallyAllocated == tskDYNAMICALLY_ALLOCATED_STACK_AND_TCB )
4867 /* Both the stack and TCB were allocated dynamically, so both
4869 vPortFreeStack( pxTCB->pxStack );
4872 else if( pxTCB->ucStaticallyAllocated == tskSTATICALLY_ALLOCATED_STACK_ONLY )
4874 /* Only the stack was statically allocated, so the TCB is the
4875 * only memory that must be freed. */
4880 /* Neither the stack nor the TCB were allocated dynamically, so
4881 * nothing needs to be freed. */
4882 configASSERT( pxTCB->ucStaticallyAllocated == tskSTATICALLY_ALLOCATED_STACK_AND_TCB );
4883 mtCOVERAGE_TEST_MARKER();
4886 #endif /* configSUPPORT_DYNAMIC_ALLOCATION */
4889 #endif /* INCLUDE_vTaskDelete */
4890 /*-----------------------------------------------------------*/
4892 static void prvResetNextTaskUnblockTime( void )
4894 if( listLIST_IS_EMPTY( pxDelayedTaskList ) != pdFALSE )
4896 /* The new current delayed list is empty. Set xNextTaskUnblockTime to
4897 * the maximum possible value so it is extremely unlikely that the
4898 * if( xTickCount >= xNextTaskUnblockTime ) test will pass until
4899 * there is an item in the delayed list. */
4900 xNextTaskUnblockTime = portMAX_DELAY;
4904 /* The new current delayed list is not empty, get the value of
4905 * the item at the head of the delayed list. This is the time at
4906 * which the task at the head of the delayed list should be removed
4907 * from the Blocked state. */
4908 xNextTaskUnblockTime = listGET_ITEM_VALUE_OF_HEAD_ENTRY( pxDelayedTaskList );
4911 /*-----------------------------------------------------------*/
4913 #if ( ( INCLUDE_xTaskGetCurrentTaskHandle == 1 ) || ( configUSE_MUTEXES == 1 ) )
4915 TaskHandle_t xTaskGetCurrentTaskHandle( void )
4917 TaskHandle_t xReturn;
4920 ulState = portDISABLE_INTERRUPTS();
4921 xReturn = pxCurrentTCBs[ portGET_CORE_ID() ];
4922 portRESTORE_INTERRUPTS( ulState );
4927 TaskHandle_t xTaskGetCurrentTaskHandleCPU( UBaseType_t xCoreID )
4929 TaskHandle_t xReturn = NULL;
4931 if( taskVALID_CORE_ID( xCoreID ) != pdFALSE )
4933 xReturn = pxCurrentTCBs[ xCoreID ];
4939 #endif /* ( ( INCLUDE_xTaskGetCurrentTaskHandle == 1 ) || ( configUSE_MUTEXES == 1 ) ) */
4940 /*-----------------------------------------------------------*/
4942 #if ( ( INCLUDE_xTaskGetSchedulerState == 1 ) || ( configUSE_TIMERS == 1 ) )
4944 BaseType_t xTaskGetSchedulerState( void )
4948 if( xSchedulerRunning == pdFALSE )
4950 xReturn = taskSCHEDULER_NOT_STARTED;
4954 taskENTER_CRITICAL();
4956 if( uxSchedulerSuspended == ( UBaseType_t ) pdFALSE )
4958 xReturn = taskSCHEDULER_RUNNING;
4962 xReturn = taskSCHEDULER_SUSPENDED;
4965 taskEXIT_CRITICAL();
4971 #endif /* ( ( INCLUDE_xTaskGetSchedulerState == 1 ) || ( configUSE_TIMERS == 1 ) ) */
4972 /*-----------------------------------------------------------*/
4974 #if ( configUSE_MUTEXES == 1 )
4976 BaseType_t xTaskPriorityInherit( TaskHandle_t const pxMutexHolder )
4978 TCB_t * const pxMutexHolderTCB = pxMutexHolder;
4979 BaseType_t xReturn = pdFALSE;
4981 /* If the mutex was given back by an interrupt while the queue was
4982 * locked then the mutex holder might now be NULL. _RB_ Is this still
4983 * needed as interrupts can no longer use mutexes? */
4984 if( pxMutexHolder != NULL )
4986 /* If the holder of the mutex has a priority below the priority of
4987 * the task attempting to obtain the mutex then it will temporarily
4988 * inherit the priority of the task attempting to obtain the mutex. */
4989 if( pxMutexHolderTCB->uxPriority < pxCurrentTCB->uxPriority )
4991 /* Adjust the mutex holder state to account for its new
4992 * priority. Only reset the event list item value if the value is
4993 * not being used for anything else. */
4994 if( ( listGET_LIST_ITEM_VALUE( &( pxMutexHolderTCB->xEventListItem ) ) & taskEVENT_LIST_ITEM_VALUE_IN_USE ) == 0UL )
4996 listSET_LIST_ITEM_VALUE( &( pxMutexHolderTCB->xEventListItem ), ( TickType_t ) configMAX_PRIORITIES - ( TickType_t ) pxCurrentTCB->uxPriority ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */
5000 mtCOVERAGE_TEST_MARKER();
5003 /* If the task being modified is in the ready state it will need
5004 * to be moved into a new list. */
5005 if( listIS_CONTAINED_WITHIN( &( pxReadyTasksLists[ pxMutexHolderTCB->uxPriority ] ), &( pxMutexHolderTCB->xStateListItem ) ) != pdFALSE )
5007 if( uxListRemove( &( pxMutexHolderTCB->xStateListItem ) ) == ( UBaseType_t ) 0 )
5009 /* It is known that the task is in its ready list so
5010 * there is no need to check again and the port level
5011 * reset macro can be called directly. */
5012 portRESET_READY_PRIORITY( pxMutexHolderTCB->uxPriority, uxTopReadyPriority );
5016 mtCOVERAGE_TEST_MARKER();
5019 /* Inherit the priority before being moved into the new list. */
5020 pxMutexHolderTCB->uxPriority = pxCurrentTCB->uxPriority;
5021 prvAddTaskToReadyList( pxMutexHolderTCB );
5025 /* Just inherit the priority. */
5026 pxMutexHolderTCB->uxPriority = pxCurrentTCB->uxPriority;
5029 traceTASK_PRIORITY_INHERIT( pxMutexHolderTCB, pxCurrentTCB->uxPriority );
5031 /* Inheritance occurred. */
5036 if( pxMutexHolderTCB->uxBasePriority < pxCurrentTCB->uxPriority )
5038 /* The base priority of the mutex holder is lower than the
5039 * priority of the task attempting to take the mutex, but the
5040 * current priority of the mutex holder is not lower than the
5041 * priority of the task attempting to take the mutex.
5042 * Therefore the mutex holder must have already inherited a
5043 * priority, but inheritance would have occurred if that had
5044 * not been the case. */
5049 mtCOVERAGE_TEST_MARKER();
5055 mtCOVERAGE_TEST_MARKER();
5061 #endif /* configUSE_MUTEXES */
5062 /*-----------------------------------------------------------*/
5064 #if ( configUSE_MUTEXES == 1 )
5066 BaseType_t xTaskPriorityDisinherit( TaskHandle_t const pxMutexHolder )
5068 TCB_t * const pxTCB = pxMutexHolder;
5069 BaseType_t xReturn = pdFALSE;
5071 if( pxMutexHolder != NULL )
5073 /* A task can only have an inherited priority if it holds the mutex.
5074 * If the mutex is held by a task then it cannot be given from an
5075 * interrupt, and if a mutex is given by the holding task then it must
5076 * be the running state task. */
5077 configASSERT( pxTCB == pxCurrentTCB );
5078 configASSERT( pxTCB->uxMutexesHeld );
5079 ( pxTCB->uxMutexesHeld )--;
5081 /* Has the holder of the mutex inherited the priority of another
5083 if( pxTCB->uxPriority != pxTCB->uxBasePriority )
5085 /* Only disinherit if no other mutexes are held. */
5086 if( pxTCB->uxMutexesHeld == ( UBaseType_t ) 0 )
5088 /* A task can only have an inherited priority if it holds
5089 * the mutex. If the mutex is held by a task then it cannot be
5090 * given from an interrupt, and if a mutex is given by the
5091 * holding task then it must be the running state task. Remove
5092 * the holding task from the ready list. */
5093 if( uxListRemove( &( pxTCB->xStateListItem ) ) == ( UBaseType_t ) 0 )
5095 portRESET_READY_PRIORITY( pxTCB->uxPriority, uxTopReadyPriority );
5099 mtCOVERAGE_TEST_MARKER();
5102 /* Disinherit the priority before adding the task into the
5103 * new ready list. */
5104 traceTASK_PRIORITY_DISINHERIT( pxTCB, pxTCB->uxBasePriority );
5105 pxTCB->uxPriority = pxTCB->uxBasePriority;
5107 /* Reset the event list item value. It cannot be in use for
5108 * any other purpose if this task is running, and it must be
5109 * running to give back the mutex. */
5110 listSET_LIST_ITEM_VALUE( &( pxTCB->xEventListItem ), ( TickType_t ) configMAX_PRIORITIES - ( TickType_t ) pxTCB->uxPriority ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */
5111 prvAddTaskToReadyList( pxTCB );
5113 /* Return true to indicate that a context switch is required.
5114 * This is only actually required in the corner case whereby
5115 * multiple mutexes were held and the mutexes were given back
5116 * in an order different to that in which they were taken.
5117 * If a context switch did not occur when the first mutex was
5118 * returned, even if a task was waiting on it, then a context
5119 * switch should occur when the last mutex is returned whether
5120 * a task is waiting on it or not. */
5125 mtCOVERAGE_TEST_MARKER();
5130 mtCOVERAGE_TEST_MARKER();
5135 mtCOVERAGE_TEST_MARKER();
5141 #endif /* configUSE_MUTEXES */
5142 /*-----------------------------------------------------------*/
5144 #if ( configUSE_MUTEXES == 1 )
5146 void vTaskPriorityDisinheritAfterTimeout( TaskHandle_t const pxMutexHolder,
5147 UBaseType_t uxHighestPriorityWaitingTask )
5149 TCB_t * const pxTCB = pxMutexHolder;
5150 UBaseType_t uxPriorityUsedOnEntry, uxPriorityToUse;
5151 const UBaseType_t uxOnlyOneMutexHeld = ( UBaseType_t ) 1;
5153 if( pxMutexHolder != NULL )
5155 /* If pxMutexHolder is not NULL then the holder must hold at least
5157 configASSERT( pxTCB->uxMutexesHeld );
5159 /* Determine the priority to which the priority of the task that
5160 * holds the mutex should be set. This will be the greater of the
5161 * holding task's base priority and the priority of the highest
5162 * priority task that is waiting to obtain the mutex. */
5163 if( pxTCB->uxBasePriority < uxHighestPriorityWaitingTask )
5165 uxPriorityToUse = uxHighestPriorityWaitingTask;
5169 uxPriorityToUse = pxTCB->uxBasePriority;
5172 /* Does the priority need to change? */
5173 if( pxTCB->uxPriority != uxPriorityToUse )
5175 /* Only disinherit if no other mutexes are held. This is a
5176 * simplification in the priority inheritance implementation. If
5177 * the task that holds the mutex is also holding other mutexes then
5178 * the other mutexes may have caused the priority inheritance. */
5179 if( pxTCB->uxMutexesHeld == uxOnlyOneMutexHeld )
5181 /* If a task has timed out because it already holds the
5182 * mutex it was trying to obtain then it cannot of inherited
5183 * its own priority. */
5184 configASSERT( pxTCB != pxCurrentTCB );
5186 /* Disinherit the priority, remembering the previous
5187 * priority to facilitate determining the subject task's
5189 traceTASK_PRIORITY_DISINHERIT( pxTCB, uxPriorityToUse );
5190 uxPriorityUsedOnEntry = pxTCB->uxPriority;
5191 pxTCB->uxPriority = uxPriorityToUse;
5193 /* Only reset the event list item value if the value is not
5194 * being used for anything else. */
5195 if( ( listGET_LIST_ITEM_VALUE( &( pxTCB->xEventListItem ) ) & taskEVENT_LIST_ITEM_VALUE_IN_USE ) == 0UL )
5197 listSET_LIST_ITEM_VALUE( &( pxTCB->xEventListItem ), ( TickType_t ) configMAX_PRIORITIES - ( TickType_t ) uxPriorityToUse ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */
5201 mtCOVERAGE_TEST_MARKER();
5204 /* If the running task is not the task that holds the mutex
5205 * then the task that holds the mutex could be in either the
5206 * Ready, Blocked or Suspended states. Only remove the task
5207 * from its current state list if it is in the Ready state as
5208 * the task's priority is going to change and there is one
5209 * Ready list per priority. */
5210 if( listIS_CONTAINED_WITHIN( &( pxReadyTasksLists[ uxPriorityUsedOnEntry ] ), &( pxTCB->xStateListItem ) ) != pdFALSE )
5212 if( uxListRemove( &( pxTCB->xStateListItem ) ) == ( UBaseType_t ) 0 )
5214 /* It is known that the task is in its ready list so
5215 * there is no need to check again and the port level
5216 * reset macro can be called directly. */
5217 portRESET_READY_PRIORITY( pxTCB->uxPriority, uxTopReadyPriority );
5221 mtCOVERAGE_TEST_MARKER();
5224 prvAddTaskToReadyList( pxTCB );
5228 mtCOVERAGE_TEST_MARKER();
5233 mtCOVERAGE_TEST_MARKER();
5238 mtCOVERAGE_TEST_MARKER();
5243 mtCOVERAGE_TEST_MARKER();
5247 #endif /* configUSE_MUTEXES */
5248 /*-----------------------------------------------------------*/
5251 * If not in a critical section then yield immediately.
5252 * Otherwise set xYieldPending to true to wait to
5253 * yield until exiting the critical section.
5255 void vTaskYieldWithinAPI( void )
5257 if( pxCurrentTCB->uxCriticalNesting == 0U )
5263 xYieldPendings[ portGET_CORE_ID() ] = pdTRUE;
5266 /*-----------------------------------------------------------*/
5268 #if ( portCRITICAL_NESTING_IN_TCB == 1 )
5270 void vTaskEnterCritical( void )
5272 portDISABLE_INTERRUPTS();
5274 if( xSchedulerRunning != pdFALSE )
5276 if( pxCurrentTCB->uxCriticalNesting == 0U )
5278 if( portCHECK_IF_IN_ISR() == pdFALSE )
5280 portGET_TASK_LOCK();
5286 ( pxCurrentTCB->uxCriticalNesting )++;
5288 /* This should now be interrupt safe. The only time there would be
5289 * a problem is if this is called before a context switch and
5290 * vTaskExitCritical() is called after pxCurrentTCB changes. Therefore
5291 * this should not be used within vTaskSwitchContext(). */
5293 if( ( uxSchedulerSuspended == 0U ) && ( pxCurrentTCB->uxCriticalNesting == 1U ) )
5295 prvCheckForRunStateChange();
5300 mtCOVERAGE_TEST_MARKER();
5304 #endif /* portCRITICAL_NESTING_IN_TCB */
5305 /*-----------------------------------------------------------*/
5307 #if ( portCRITICAL_NESTING_IN_TCB == 1 )
5309 void vTaskExitCritical( void )
5311 if( xSchedulerRunning != pdFALSE )
5313 /* If pxCurrentTCB->uxCriticalNesting is zero then this function
5314 * does not match a previous call to vTaskEnterCritical(). */
5315 configASSERT( pxCurrentTCB->uxCriticalNesting > 0U );
5317 if( pxCurrentTCB->uxCriticalNesting > 0U )
5319 ( pxCurrentTCB->uxCriticalNesting )--;
5321 if( pxCurrentTCB->uxCriticalNesting == 0U )
5323 portRELEASE_ISR_LOCK();
5325 if( portCHECK_IF_IN_ISR() == pdFALSE )
5327 portRELEASE_TASK_LOCK();
5328 portENABLE_INTERRUPTS();
5330 /* When a task yields in a critical section it just sets
5331 * xYieldPending to true. So now that we have exited the
5332 * critical section check if xYieldPending is true, and
5334 if( xYieldPending != pdFALSE )
5341 /* In an ISR we don't hold the task lock and don't
5342 * need to yield. Yield will happen if necessary when
5343 * the application ISR calls portEND_SWITCHING_ISR() */
5344 mtCOVERAGE_TEST_MARKER();
5349 mtCOVERAGE_TEST_MARKER();
5354 mtCOVERAGE_TEST_MARKER();
5359 mtCOVERAGE_TEST_MARKER();
5363 #endif /* portCRITICAL_NESTING_IN_TCB */
5364 /*-----------------------------------------------------------*/
5366 #if ( ( configUSE_TRACE_FACILITY == 1 ) && ( configUSE_STATS_FORMATTING_FUNCTIONS > 0 ) )
5368 static char * prvWriteNameToBuffer( char * pcBuffer,
5369 const char * pcTaskName )
5373 /* Start by copying the entire string. */
5374 strcpy( pcBuffer, pcTaskName );
5376 /* Pad the end of the string with spaces to ensure columns line up when
5378 for( x = strlen( pcBuffer ); x < ( size_t ) ( configMAX_TASK_NAME_LEN - 1 ); x++ )
5380 pcBuffer[ x ] = ' ';
5384 pcBuffer[ x ] = ( char ) 0x00;
5386 /* Return the new end of string. */
5387 return &( pcBuffer[ x ] );
5390 #endif /* ( configUSE_TRACE_FACILITY == 1 ) && ( configUSE_STATS_FORMATTING_FUNCTIONS > 0 ) */
5391 /*-----------------------------------------------------------*/
5393 #if ( ( configUSE_TRACE_FACILITY == 1 ) && ( configUSE_STATS_FORMATTING_FUNCTIONS > 0 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) )
5395 void vTaskList( char * pcWriteBuffer )
5397 TaskStatus_t * pxTaskStatusArray;
5398 UBaseType_t uxArraySize, x;
5404 * This function is provided for convenience only, and is used by many
5405 * of the demo applications. Do not consider it to be part of the
5408 * vTaskList() calls uxTaskGetSystemState(), then formats part of the
5409 * uxTaskGetSystemState() output into a human readable table that
5410 * displays task: names, states, priority, stack usage and task number.
5411 * Stack usage specified as the number of unused StackType_t words stack can hold
5412 * on top of stack - not the number of bytes.
5414 * vTaskList() has a dependency on the sprintf() C library function that
5415 * might bloat the code size, use a lot of stack, and provide different
5416 * results on different platforms. An alternative, tiny, third party,
5417 * and limited functionality implementation of sprintf() is provided in
5418 * many of the FreeRTOS/Demo sub-directories in a file called
5419 * printf-stdarg.c (note printf-stdarg.c does not provide a full
5420 * snprintf() implementation!).
5422 * It is recommended that production systems call uxTaskGetSystemState()
5423 * directly to get access to raw stats data, rather than indirectly
5424 * through a call to vTaskList().
5428 /* Make sure the write buffer does not contain a string. */
5429 *pcWriteBuffer = ( char ) 0x00;
5431 /* Take a snapshot of the number of tasks in case it changes while this
5432 * function is executing. */
5433 uxArraySize = uxCurrentNumberOfTasks;
5435 /* Allocate an array index for each task. NOTE! if
5436 * configSUPPORT_DYNAMIC_ALLOCATION is set to 0 then pvPortMalloc() will
5437 * equate to NULL. */
5438 pxTaskStatusArray = pvPortMalloc( uxCurrentNumberOfTasks * sizeof( TaskStatus_t ) ); /*lint !e9079 All values returned by pvPortMalloc() have at least the alignment required by the MCU's stack and this allocation allocates a struct that has the alignment requirements of a pointer. */
5440 if( pxTaskStatusArray != NULL )
5442 /* Generate the (binary) data. */
5443 uxArraySize = uxTaskGetSystemState( pxTaskStatusArray, uxArraySize, NULL );
5445 /* Create a human readable table from the binary data. */
5446 for( x = 0; x < uxArraySize; x++ )
5448 switch( pxTaskStatusArray[ x ].eCurrentState )
5451 cStatus = tskRUNNING_CHAR;
5455 cStatus = tskREADY_CHAR;
5459 cStatus = tskBLOCKED_CHAR;
5463 cStatus = tskSUSPENDED_CHAR;
5467 cStatus = tskDELETED_CHAR;
5470 case eInvalid: /* Fall through. */
5471 default: /* Should not get here, but it is included
5472 * to prevent static checking errors. */
5473 cStatus = ( char ) 0x00;
5477 /* Write the task name to the string, padding with spaces so it
5478 * can be printed in tabular form more easily. */
5479 pcWriteBuffer = prvWriteNameToBuffer( pcWriteBuffer, pxTaskStatusArray[ x ].pcTaskName );
5481 /* Write the rest of the string. */
5482 sprintf( pcWriteBuffer, "\t%c\t%u\t%u\t%u\r\n", cStatus, ( unsigned int ) pxTaskStatusArray[ x ].uxCurrentPriority, ( unsigned int ) pxTaskStatusArray[ x ].usStackHighWaterMark, ( unsigned int ) pxTaskStatusArray[ x ].xTaskNumber ); /*lint !e586 sprintf() allowed as this is compiled with many compilers and this is a utility function only - not part of the core kernel implementation. */
5483 pcWriteBuffer += strlen( pcWriteBuffer ); /*lint !e9016 Pointer arithmetic ok on char pointers especially as in this case where it best denotes the intent of the code. */
5486 /* Free the array again. NOTE! If configSUPPORT_DYNAMIC_ALLOCATION
5487 * is 0 then vPortFree() will be #defined to nothing. */
5488 vPortFree( pxTaskStatusArray );
5492 mtCOVERAGE_TEST_MARKER();
5496 #endif /* ( ( configUSE_TRACE_FACILITY == 1 ) && ( configUSE_STATS_FORMATTING_FUNCTIONS > 0 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) */
5497 /*----------------------------------------------------------*/
5499 #if ( ( configGENERATE_RUN_TIME_STATS == 1 ) && ( configUSE_STATS_FORMATTING_FUNCTIONS > 0 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) )
5501 void vTaskGetRunTimeStats( char * pcWriteBuffer )
5503 TaskStatus_t * pxTaskStatusArray;
5504 UBaseType_t uxArraySize, x;
5505 uint32_t ulTotalTime, ulStatsAsPercentage;
5507 #if ( configUSE_TRACE_FACILITY != 1 )
5509 #error configUSE_TRACE_FACILITY must also be set to 1 in FreeRTOSConfig.h to use vTaskGetRunTimeStats().
5516 * This function is provided for convenience only, and is used by many
5517 * of the demo applications. Do not consider it to be part of the
5520 * vTaskGetRunTimeStats() calls uxTaskGetSystemState(), then formats part
5521 * of the uxTaskGetSystemState() output into a human readable table that
5522 * displays the amount of time each task has spent in the Running state
5523 * in both absolute and percentage terms.
5525 * vTaskGetRunTimeStats() has a dependency on the sprintf() C library
5526 * function that might bloat the code size, use a lot of stack, and
5527 * provide different results on different platforms. An alternative,
5528 * tiny, third party, and limited functionality implementation of
5529 * sprintf() is provided in many of the FreeRTOS/Demo sub-directories in
5530 * a file called printf-stdarg.c (note printf-stdarg.c does not provide
5531 * a full snprintf() implementation!).
5533 * It is recommended that production systems call uxTaskGetSystemState()
5534 * directly to get access to raw stats data, rather than indirectly
5535 * through a call to vTaskGetRunTimeStats().
5538 /* Make sure the write buffer does not contain a string. */
5539 *pcWriteBuffer = ( char ) 0x00;
5541 /* Take a snapshot of the number of tasks in case it changes while this
5542 * function is executing. */
5543 uxArraySize = uxCurrentNumberOfTasks;
5545 /* Allocate an array index for each task. NOTE! If
5546 * configSUPPORT_DYNAMIC_ALLOCATION is set to 0 then pvPortMalloc() will
5547 * equate to NULL. */
5548 pxTaskStatusArray = pvPortMalloc( uxCurrentNumberOfTasks * sizeof( TaskStatus_t ) ); /*lint !e9079 All values returned by pvPortMalloc() have at least the alignment required by the MCU's stack and this allocation allocates a struct that has the alignment requirements of a pointer. */
5550 if( pxTaskStatusArray != NULL )
5552 /* Generate the (binary) data. */
5553 uxArraySize = uxTaskGetSystemState( pxTaskStatusArray, uxArraySize, &ulTotalTime );
5555 /* For percentage calculations. */
5556 ulTotalTime /= 100UL;
5558 /* Avoid divide by zero errors. */
5559 if( ulTotalTime > 0UL )
5561 /* Create a human readable table from the binary data. */
5562 for( x = 0; x < uxArraySize; x++ )
5564 /* What percentage of the total run time has the task used?
5565 * This will always be rounded down to the nearest integer.
5566 * ulTotalRunTimeDiv100 has already been divided by 100. */
5567 ulStatsAsPercentage = pxTaskStatusArray[ x ].ulRunTimeCounter / ulTotalTime;
5569 /* Write the task name to the string, padding with
5570 * spaces so it can be printed in tabular form more
5572 pcWriteBuffer = prvWriteNameToBuffer( pcWriteBuffer, pxTaskStatusArray[ x ].pcTaskName );
5574 if( ulStatsAsPercentage > 0UL )
5576 #ifdef portLU_PRINTF_SPECIFIER_REQUIRED
5578 sprintf( pcWriteBuffer, "\t%lu\t\t%lu%%\r\n", pxTaskStatusArray[ x ].ulRunTimeCounter, ulStatsAsPercentage );
5582 /* sizeof( int ) == sizeof( long ) so a smaller
5583 * printf() library can be used. */
5584 sprintf( pcWriteBuffer, "\t%u\t\t%u%%\r\n", ( unsigned int ) pxTaskStatusArray[ x ].ulRunTimeCounter, ( unsigned int ) ulStatsAsPercentage ); /*lint !e586 sprintf() allowed as this is compiled with many compilers and this is a utility function only - not part of the core kernel implementation. */
5590 /* If the percentage is zero here then the task has
5591 * consumed less than 1% of the total run time. */
5592 #ifdef portLU_PRINTF_SPECIFIER_REQUIRED
5594 sprintf( pcWriteBuffer, "\t%lu\t\t<1%%\r\n", pxTaskStatusArray[ x ].ulRunTimeCounter );
5598 /* sizeof( int ) == sizeof( long ) so a smaller
5599 * printf() library can be used. */
5600 sprintf( pcWriteBuffer, "\t%u\t\t<1%%\r\n", ( unsigned int ) pxTaskStatusArray[ x ].ulRunTimeCounter ); /*lint !e586 sprintf() allowed as this is compiled with many compilers and this is a utility function only - not part of the core kernel implementation. */
5605 pcWriteBuffer += strlen( pcWriteBuffer ); /*lint !e9016 Pointer arithmetic ok on char pointers especially as in this case where it best denotes the intent of the code. */
5610 mtCOVERAGE_TEST_MARKER();
5613 /* Free the array again. NOTE! If configSUPPORT_DYNAMIC_ALLOCATION
5614 * is 0 then vPortFree() will be #defined to nothing. */
5615 vPortFree( pxTaskStatusArray );
5619 mtCOVERAGE_TEST_MARKER();
5623 #endif /* ( ( configGENERATE_RUN_TIME_STATS == 1 ) && ( configUSE_STATS_FORMATTING_FUNCTIONS > 0 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) ) */
5624 /*-----------------------------------------------------------*/
5626 TickType_t uxTaskResetEventItemValue( void )
5628 TickType_t uxReturn;
5630 uxReturn = listGET_LIST_ITEM_VALUE( &( pxCurrentTCB->xEventListItem ) );
5632 /* Reset the event list item to its normal value - so it can be used with
5633 * queues and semaphores. */
5634 listSET_LIST_ITEM_VALUE( &( pxCurrentTCB->xEventListItem ), ( ( TickType_t ) configMAX_PRIORITIES - ( TickType_t ) pxCurrentTCB->uxPriority ) ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */
5638 /*-----------------------------------------------------------*/
5640 #if ( configUSE_MUTEXES == 1 )
5642 TaskHandle_t pvTaskIncrementMutexHeldCount( void )
5644 /* If xSemaphoreCreateMutex() is called before any tasks have been created
5645 * then pxCurrentTCB will be NULL. */
5646 if( pxCurrentTCB != NULL )
5648 ( pxCurrentTCB->uxMutexesHeld )++;
5651 return pxCurrentTCB;
5654 #endif /* configUSE_MUTEXES */
5655 /*-----------------------------------------------------------*/
5657 #if ( configUSE_TASK_NOTIFICATIONS == 1 )
5659 uint32_t ulTaskGenericNotifyTake( UBaseType_t uxIndexToWait,
5660 BaseType_t xClearCountOnExit,
5661 TickType_t xTicksToWait )
5665 configASSERT( uxIndexToWait < configTASK_NOTIFICATION_ARRAY_ENTRIES );
5667 taskENTER_CRITICAL();
5669 /* Only block if the notification count is not already non-zero. */
5670 if( pxCurrentTCB->ulNotifiedValue[ uxIndexToWait ] == 0UL )
5672 /* Mark this task as waiting for a notification. */
5673 pxCurrentTCB->ucNotifyState[ uxIndexToWait ] = taskWAITING_NOTIFICATION;
5675 if( xTicksToWait > ( TickType_t ) 0 )
5677 prvAddCurrentTaskToDelayedList( xTicksToWait, pdTRUE );
5678 traceTASK_NOTIFY_TAKE_BLOCK( uxIndexToWait );
5680 /* All ports are written to allow a yield in a critical
5681 * section (some will yield immediately, others wait until the
5682 * critical section exits) - but it is not something that
5683 * application code should ever do. */
5684 vTaskYieldWithinAPI();
5688 mtCOVERAGE_TEST_MARKER();
5693 mtCOVERAGE_TEST_MARKER();
5696 taskEXIT_CRITICAL();
5698 taskENTER_CRITICAL();
5700 traceTASK_NOTIFY_TAKE( uxIndexToWait );
5701 ulReturn = pxCurrentTCB->ulNotifiedValue[ uxIndexToWait ];
5703 if( ulReturn != 0UL )
5705 if( xClearCountOnExit != pdFALSE )
5707 pxCurrentTCB->ulNotifiedValue[ uxIndexToWait ] = 0UL;
5711 pxCurrentTCB->ulNotifiedValue[ uxIndexToWait ] = ulReturn - ( uint32_t ) 1;
5716 mtCOVERAGE_TEST_MARKER();
5719 pxCurrentTCB->ucNotifyState[ uxIndexToWait ] = taskNOT_WAITING_NOTIFICATION;
5721 taskEXIT_CRITICAL();
5726 #endif /* configUSE_TASK_NOTIFICATIONS */
5727 /*-----------------------------------------------------------*/
5729 #if ( configUSE_TASK_NOTIFICATIONS == 1 )
5731 BaseType_t xTaskGenericNotifyWait( UBaseType_t uxIndexToWait,
5732 uint32_t ulBitsToClearOnEntry,
5733 uint32_t ulBitsToClearOnExit,
5734 uint32_t * pulNotificationValue,
5735 TickType_t xTicksToWait )
5739 configASSERT( uxIndexToWait < configTASK_NOTIFICATION_ARRAY_ENTRIES );
5741 taskENTER_CRITICAL();
5743 /* Only block if a notification is not already pending. */
5744 if( pxCurrentTCB->ucNotifyState[ uxIndexToWait ] != taskNOTIFICATION_RECEIVED )
5746 /* Clear bits in the task's notification value as bits may get
5747 * set by the notifying task or interrupt. This can be used to
5748 * clear the value to zero. */
5749 pxCurrentTCB->ulNotifiedValue[ uxIndexToWait ] &= ~ulBitsToClearOnEntry;
5751 /* Mark this task as waiting for a notification. */
5752 pxCurrentTCB->ucNotifyState[ uxIndexToWait ] = taskWAITING_NOTIFICATION;
5754 if( xTicksToWait > ( TickType_t ) 0 )
5756 prvAddCurrentTaskToDelayedList( xTicksToWait, pdTRUE );
5757 traceTASK_NOTIFY_WAIT_BLOCK( uxIndexToWait );
5759 /* All ports are written to allow a yield in a critical
5760 * section (some will yield immediately, others wait until the
5761 * critical section exits) - but it is not something that
5762 * application code should ever do. */
5763 vTaskYieldWithinAPI();
5767 mtCOVERAGE_TEST_MARKER();
5772 mtCOVERAGE_TEST_MARKER();
5775 taskEXIT_CRITICAL();
5777 taskENTER_CRITICAL();
5779 traceTASK_NOTIFY_WAIT( uxIndexToWait );
5781 if( pulNotificationValue != NULL )
5783 /* Output the current notification value, which may or may not
5785 *pulNotificationValue = pxCurrentTCB->ulNotifiedValue[ uxIndexToWait ];
5788 /* If ucNotifyValue is set then either the task never entered the
5789 * blocked state (because a notification was already pending) or the
5790 * task unblocked because of a notification. Otherwise the task
5791 * unblocked because of a timeout. */
5792 if( pxCurrentTCB->ucNotifyState[ uxIndexToWait ] != taskNOTIFICATION_RECEIVED )
5794 /* A notification was not received. */
5799 /* A notification was already pending or a notification was
5800 * received while the task was waiting. */
5801 pxCurrentTCB->ulNotifiedValue[ uxIndexToWait ] &= ~ulBitsToClearOnExit;
5805 pxCurrentTCB->ucNotifyState[ uxIndexToWait ] = taskNOT_WAITING_NOTIFICATION;
5807 taskEXIT_CRITICAL();
5812 #endif /* configUSE_TASK_NOTIFICATIONS */
5813 /*-----------------------------------------------------------*/
5815 #if ( configUSE_TASK_NOTIFICATIONS == 1 )
5817 BaseType_t xTaskGenericNotify( TaskHandle_t xTaskToNotify,
5818 UBaseType_t uxIndexToNotify,
5820 eNotifyAction eAction,
5821 uint32_t * pulPreviousNotificationValue )
5824 BaseType_t xReturn = pdPASS;
5825 uint8_t ucOriginalNotifyState;
5827 configASSERT( uxIndexToNotify < configTASK_NOTIFICATION_ARRAY_ENTRIES );
5828 configASSERT( xTaskToNotify );
5829 pxTCB = xTaskToNotify;
5831 taskENTER_CRITICAL();
5833 if( pulPreviousNotificationValue != NULL )
5835 *pulPreviousNotificationValue = pxTCB->ulNotifiedValue[ uxIndexToNotify ];
5838 ucOriginalNotifyState = pxTCB->ucNotifyState[ uxIndexToNotify ];
5840 pxTCB->ucNotifyState[ uxIndexToNotify ] = taskNOTIFICATION_RECEIVED;
5845 pxTCB->ulNotifiedValue[ uxIndexToNotify ] |= ulValue;
5849 ( pxTCB->ulNotifiedValue[ uxIndexToNotify ] )++;
5852 case eSetValueWithOverwrite:
5853 pxTCB->ulNotifiedValue[ uxIndexToNotify ] = ulValue;
5856 case eSetValueWithoutOverwrite:
5858 if( ucOriginalNotifyState != taskNOTIFICATION_RECEIVED )
5860 pxTCB->ulNotifiedValue[ uxIndexToNotify ] = ulValue;
5864 /* The value could not be written to the task. */
5872 /* The task is being notified without its notify value being
5878 /* Should not get here if all enums are handled.
5879 * Artificially force an assert by testing a value the
5880 * compiler can't assume is const. */
5881 configASSERT( xTickCount == ( TickType_t ) 0 );
5886 traceTASK_NOTIFY( uxIndexToNotify );
5888 /* If the task is in the blocked state specifically to wait for a
5889 * notification then unblock it now. */
5890 if( ucOriginalNotifyState == taskWAITING_NOTIFICATION )
5892 ( void ) uxListRemove( &( pxTCB->xStateListItem ) );
5893 prvAddTaskToReadyList( pxTCB );
5895 /* The task should not have been on an event list. */
5896 configASSERT( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) == NULL );
5898 #if ( configUSE_TICKLESS_IDLE != 0 )
5900 /* If a task is blocked waiting for a notification then
5901 * xNextTaskUnblockTime might be set to the blocked task's time
5902 * out time. If the task is unblocked for a reason other than
5903 * a timeout xNextTaskUnblockTime is normally left unchanged,
5904 * because it will automatically get reset to a new value when
5905 * the tick count equals xNextTaskUnblockTime. However if
5906 * tickless idling is used it might be more important to enter
5907 * sleep mode at the earliest possible time - so reset
5908 * xNextTaskUnblockTime here to ensure it is updated at the
5909 * earliest possible time. */
5910 prvResetNextTaskUnblockTime();
5914 #if ( configUSE_PREEMPTION == 1 )
5916 prvYieldForTask( pxTCB, pdFALSE );
5922 mtCOVERAGE_TEST_MARKER();
5925 taskEXIT_CRITICAL();
5930 #endif /* configUSE_TASK_NOTIFICATIONS */
5931 /*-----------------------------------------------------------*/
5933 #if ( configUSE_TASK_NOTIFICATIONS == 1 )
5935 BaseType_t xTaskGenericNotifyFromISR( TaskHandle_t xTaskToNotify,
5936 UBaseType_t uxIndexToNotify,
5938 eNotifyAction eAction,
5939 uint32_t * pulPreviousNotificationValue,
5940 BaseType_t * pxHigherPriorityTaskWoken )
5943 uint8_t ucOriginalNotifyState;
5944 BaseType_t xReturn = pdPASS;
5945 UBaseType_t uxSavedInterruptStatus;
5947 configASSERT( xTaskToNotify );
5948 configASSERT( uxIndexToNotify < configTASK_NOTIFICATION_ARRAY_ENTRIES );
5950 /* RTOS ports that support interrupt nesting have the concept of a
5951 * maximum system call (or maximum API call) interrupt priority.
5952 * Interrupts that are above the maximum system call priority are keep
5953 * permanently enabled, even when the RTOS kernel is in a critical section,
5954 * but cannot make any calls to FreeRTOS API functions. If configASSERT()
5955 * is defined in FreeRTOSConfig.h then
5956 * portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion
5957 * failure if a FreeRTOS API function is called from an interrupt that has
5958 * been assigned a priority above the configured maximum system call
5959 * priority. Only FreeRTOS functions that end in FromISR can be called
5960 * from interrupts that have been assigned a priority at or (logically)
5961 * below the maximum system call interrupt priority. FreeRTOS maintains a
5962 * separate interrupt safe API to ensure interrupt entry is as fast and as
5963 * simple as possible. More information (albeit Cortex-M specific) is
5964 * provided on the following link:
5965 * https://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html */
5966 portASSERT_IF_INTERRUPT_PRIORITY_INVALID();
5968 pxTCB = xTaskToNotify;
5970 uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR();
5972 if( pulPreviousNotificationValue != NULL )
5974 *pulPreviousNotificationValue = pxTCB->ulNotifiedValue[ uxIndexToNotify ];
5977 ucOriginalNotifyState = pxTCB->ucNotifyState[ uxIndexToNotify ];
5978 pxTCB->ucNotifyState[ uxIndexToNotify ] = taskNOTIFICATION_RECEIVED;
5983 pxTCB->ulNotifiedValue[ uxIndexToNotify ] |= ulValue;
5987 ( pxTCB->ulNotifiedValue[ uxIndexToNotify ] )++;
5990 case eSetValueWithOverwrite:
5991 pxTCB->ulNotifiedValue[ uxIndexToNotify ] = ulValue;
5994 case eSetValueWithoutOverwrite:
5996 if( ucOriginalNotifyState != taskNOTIFICATION_RECEIVED )
5998 pxTCB->ulNotifiedValue[ uxIndexToNotify ] = ulValue;
6002 /* The value could not be written to the task. */
6010 /* The task is being notified without its notify value being
6016 /* Should not get here if all enums are handled.
6017 * Artificially force an assert by testing a value the
6018 * compiler can't assume is const. */
6019 configASSERT( xTickCount == ( TickType_t ) 0 );
6023 traceTASK_NOTIFY_FROM_ISR( uxIndexToNotify );
6025 /* If the task is in the blocked state specifically to wait for a
6026 * notification then unblock it now. */
6027 if( ucOriginalNotifyState == taskWAITING_NOTIFICATION )
6029 /* The task should not have been on an event list. */
6030 configASSERT( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) == NULL );
6032 if( uxSchedulerSuspended == ( UBaseType_t ) pdFALSE )
6034 ( void ) uxListRemove( &( pxTCB->xStateListItem ) );
6035 prvAddTaskToReadyList( pxTCB );
6039 /* The delayed and ready lists cannot be accessed, so hold
6040 * this task pending until the scheduler is resumed. */
6041 vListInsertEnd( &( xPendingReadyList ), &( pxTCB->xEventListItem ) );
6044 #if ( configUSE_PREEMPTION == 1 )
6045 prvYieldForTask( pxTCB, pdFALSE );
6047 if( xYieldPendings[ portGET_CORE_ID() ] == pdTRUE )
6049 if( pxHigherPriorityTaskWoken != NULL )
6051 *pxHigherPriorityTaskWoken = pdTRUE;
6057 portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus );
6062 #endif /* configUSE_TASK_NOTIFICATIONS */
6063 /*-----------------------------------------------------------*/
6065 #if ( configUSE_TASK_NOTIFICATIONS == 1 )
6067 void vTaskGenericNotifyGiveFromISR( TaskHandle_t xTaskToNotify,
6068 UBaseType_t uxIndexToNotify,
6069 BaseType_t * pxHigherPriorityTaskWoken )
6072 uint8_t ucOriginalNotifyState;
6073 UBaseType_t uxSavedInterruptStatus;
6075 configASSERT( xTaskToNotify );
6076 configASSERT( uxIndexToNotify < configTASK_NOTIFICATION_ARRAY_ENTRIES );
6078 /* RTOS ports that support interrupt nesting have the concept of a
6079 * maximum system call (or maximum API call) interrupt priority.
6080 * Interrupts that are above the maximum system call priority are keep
6081 * permanently enabled, even when the RTOS kernel is in a critical section,
6082 * but cannot make any calls to FreeRTOS API functions. If configASSERT()
6083 * is defined in FreeRTOSConfig.h then
6084 * portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion
6085 * failure if a FreeRTOS API function is called from an interrupt that has
6086 * been assigned a priority above the configured maximum system call
6087 * priority. Only FreeRTOS functions that end in FromISR can be called
6088 * from interrupts that have been assigned a priority at or (logically)
6089 * below the maximum system call interrupt priority. FreeRTOS maintains a
6090 * separate interrupt safe API to ensure interrupt entry is as fast and as
6091 * simple as possible. More information (albeit Cortex-M specific) is
6092 * provided on the following link:
6093 * https://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html */
6094 portASSERT_IF_INTERRUPT_PRIORITY_INVALID();
6096 pxTCB = xTaskToNotify;
6098 uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR();
6100 ucOriginalNotifyState = pxTCB->ucNotifyState[ uxIndexToNotify ];
6101 pxTCB->ucNotifyState[ uxIndexToNotify ] = taskNOTIFICATION_RECEIVED;
6103 /* 'Giving' is equivalent to incrementing a count in a counting
6105 ( pxTCB->ulNotifiedValue[ uxIndexToNotify ] )++;
6107 traceTASK_NOTIFY_GIVE_FROM_ISR( uxIndexToNotify );
6109 /* If the task is in the blocked state specifically to wait for a
6110 * notification then unblock it now. */
6111 if( ucOriginalNotifyState == taskWAITING_NOTIFICATION )
6113 /* The task should not have been on an event list. */
6114 configASSERT( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) == NULL );
6116 if( uxSchedulerSuspended == ( UBaseType_t ) pdFALSE )
6118 ( void ) uxListRemove( &( pxTCB->xStateListItem ) );
6119 prvAddTaskToReadyList( pxTCB );
6123 /* The delayed and ready lists cannot be accessed, so hold
6124 * this task pending until the scheduler is resumed. */
6125 vListInsertEnd( &( xPendingReadyList ), &( pxTCB->xEventListItem ) );
6128 #if ( configUSE_PREEMPTION == 1 )
6129 prvYieldForTask( pxTCB, pdFALSE );
6131 if( xYieldPendings[ portGET_CORE_ID() ] == pdTRUE )
6133 if( pxHigherPriorityTaskWoken != NULL )
6135 *pxHigherPriorityTaskWoken = pdTRUE;
6141 portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus );
6144 #endif /* configUSE_TASK_NOTIFICATIONS */
6145 /*-----------------------------------------------------------*/
6147 #if ( configUSE_TASK_NOTIFICATIONS == 1 )
6149 BaseType_t xTaskGenericNotifyStateClear( TaskHandle_t xTask,
6150 UBaseType_t uxIndexToClear )
6155 configASSERT( uxIndexToClear < configTASK_NOTIFICATION_ARRAY_ENTRIES );
6157 /* If null is passed in here then it is the calling task that is having
6158 * its notification state cleared. */
6159 pxTCB = prvGetTCBFromHandle( xTask );
6161 taskENTER_CRITICAL();
6163 if( pxTCB->ucNotifyState[ uxIndexToClear ] == taskNOTIFICATION_RECEIVED )
6165 pxTCB->ucNotifyState[ uxIndexToClear ] = taskNOT_WAITING_NOTIFICATION;
6173 taskEXIT_CRITICAL();
6178 #endif /* configUSE_TASK_NOTIFICATIONS */
6179 /*-----------------------------------------------------------*/
6181 #if ( configUSE_TASK_NOTIFICATIONS == 1 )
6183 uint32_t ulTaskGenericNotifyValueClear( TaskHandle_t xTask,
6184 UBaseType_t uxIndexToClear,
6185 uint32_t ulBitsToClear )
6190 /* If null is passed in here then it is the calling task that is having
6191 * its notification state cleared. */
6192 pxTCB = prvGetTCBFromHandle( xTask );
6194 taskENTER_CRITICAL();
6196 /* Return the notification as it was before the bits were cleared,
6197 * then clear the bit mask. */
6198 ulReturn = pxTCB->ulNotifiedValue[ uxIndexToClear ];
6199 pxTCB->ulNotifiedValue[ uxIndexToClear ] &= ~ulBitsToClear;
6201 taskEXIT_CRITICAL();
6206 #endif /* configUSE_TASK_NOTIFICATIONS */
6207 /*-----------------------------------------------------------*/
6209 #if ( ( configGENERATE_RUN_TIME_STATS == 1 ) && ( INCLUDE_xTaskGetIdleTaskHandle == 1 ) )
6211 uint32_t ulTaskGetIdleRunTimeCounter( void )
6213 uint32_t ulReturn = 0;
6215 for( BaseType_t i = 0; i < configNUM_CORES; i++ )
6217 ulReturn += xIdleTaskHandle[ i ]->ulRunTimeCounter;
6223 #endif /* if ( ( configGENERATE_RUN_TIME_STATS == 1 ) && ( INCLUDE_xTaskGetIdleTaskHandle == 1 ) ) */
6224 /*-----------------------------------------------------------*/
6226 static void prvAddCurrentTaskToDelayedList( TickType_t xTicksToWait,
6227 const BaseType_t xCanBlockIndefinitely )
6229 TickType_t xTimeToWake;
6230 const TickType_t xConstTickCount = xTickCount;
6232 #if ( INCLUDE_xTaskAbortDelay == 1 )
6234 /* About to enter a delayed list, so ensure the ucDelayAborted flag is
6235 * reset to pdFALSE so it can be detected as having been set to pdTRUE
6236 * when the task leaves the Blocked state. */
6237 pxCurrentTCB->ucDelayAborted = pdFALSE;
6241 /* Remove the task from the ready list before adding it to the blocked list
6242 * as the same list item is used for both lists. */
6243 if( uxListRemove( &( pxCurrentTCB->xStateListItem ) ) == ( UBaseType_t ) 0 )
6245 /* The current task must be in a ready list, so there is no need to
6246 * check, and the port reset macro can be called directly. */
6247 portRESET_READY_PRIORITY( pxCurrentTCB->uxPriority, uxTopReadyPriority ); /*lint !e931 pxCurrentTCB cannot change as it is the calling task. pxCurrentTCB->uxPriority and uxTopReadyPriority cannot change as called with scheduler suspended or in a critical section. */
6251 mtCOVERAGE_TEST_MARKER();
6254 #if ( INCLUDE_vTaskSuspend == 1 )
6256 if( ( xTicksToWait == portMAX_DELAY ) && ( xCanBlockIndefinitely != pdFALSE ) )
6258 /* Add the task to the suspended task list instead of a delayed task
6259 * list to ensure it is not woken by a timing event. It will block
6261 vListInsertEnd( &xSuspendedTaskList, &( pxCurrentTCB->xStateListItem ) );
6265 /* Calculate the time at which the task should be woken if the event
6266 * does not occur. This may overflow but this doesn't matter, the
6267 * kernel will manage it correctly. */
6268 xTimeToWake = xConstTickCount + xTicksToWait;
6270 /* The list item will be inserted in wake time order. */
6271 listSET_LIST_ITEM_VALUE( &( pxCurrentTCB->xStateListItem ), xTimeToWake );
6273 if( xTimeToWake < xConstTickCount )
6275 /* Wake time has overflowed. Place this item in the overflow
6277 vListInsert( pxOverflowDelayedTaskList, &( pxCurrentTCB->xStateListItem ) );
6281 /* The wake time has not overflowed, so the current block list
6283 vListInsert( pxDelayedTaskList, &( pxCurrentTCB->xStateListItem ) );
6285 /* If the task entering the blocked state was placed at the
6286 * head of the list of blocked tasks then xNextTaskUnblockTime
6287 * needs to be updated too. */
6288 if( xTimeToWake < xNextTaskUnblockTime )
6290 xNextTaskUnblockTime = xTimeToWake;
6294 mtCOVERAGE_TEST_MARKER();
6299 #else /* INCLUDE_vTaskSuspend */
6301 /* Calculate the time at which the task should be woken if the event
6302 * does not occur. This may overflow but this doesn't matter, the kernel
6303 * will manage it correctly. */
6304 xTimeToWake = xConstTickCount + xTicksToWait;
6306 /* The list item will be inserted in wake time order. */
6307 listSET_LIST_ITEM_VALUE( &( pxCurrentTCB->xStateListItem ), xTimeToWake );
6309 if( xTimeToWake < xConstTickCount )
6311 /* Wake time has overflowed. Place this item in the overflow list. */
6312 vListInsert( pxOverflowDelayedTaskList, &( pxCurrentTCB->xStateListItem ) );
6316 /* The wake time has not overflowed, so the current block list is used. */
6317 vListInsert( pxDelayedTaskList, &( pxCurrentTCB->xStateListItem ) );
6319 /* If the task entering the blocked state was placed at the head of the
6320 * list of blocked tasks then xNextTaskUnblockTime needs to be updated
6322 if( xTimeToWake < xNextTaskUnblockTime )
6324 xNextTaskUnblockTime = xTimeToWake;
6328 mtCOVERAGE_TEST_MARKER();
6332 /* Avoid compiler warning when INCLUDE_vTaskSuspend is not 1. */
6333 ( void ) xCanBlockIndefinitely;
6335 #endif /* INCLUDE_vTaskSuspend */
6338 /* Code below here allows additional code to be inserted into this source file,
6339 * especially where access to file scope functions and data is needed (for example
6340 * when performing module tests). */
6342 #ifdef FREERTOS_MODULE_TEST
6343 #include "tasks_test_access_functions.h"
6347 #if ( configINCLUDE_FREERTOS_TASK_C_ADDITIONS_H == 1 )
6349 #include "freertos_tasks_c_additions.h"
6351 #ifdef FREERTOS_TASKS_C_ADDITIONS_INIT
6352 static void freertos_tasks_c_additions_init( void )
6354 FREERTOS_TASKS_C_ADDITIONS_INIT();
6358 #endif /* if ( configINCLUDE_FREERTOS_TASK_C_ADDITIONS_H == 1 ) */