]> begriffs open source - freertos/blob - tasks.c
Do not call exit() on MSVC Port when calling vPortEndScheduler (#624)
[freertos] / tasks.c
1 /*
2  * FreeRTOS Kernel <DEVELOPMENT BRANCH>
3  * Copyright (C) 2021 Amazon.com, Inc. or its affiliates.  All Rights Reserved.
4  *
5  * SPDX-License-Identifier: MIT
6  *
7  * Permission is hereby granted, free of charge, to any person obtaining a copy of
8  * this software and associated documentation files (the "Software"), to deal in
9  * the Software without restriction, including without limitation the rights to
10  * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
11  * the Software, and to permit persons to whom the Software is furnished to do so,
12  * subject to the following conditions:
13  *
14  * The above copyright notice and this permission notice shall be included in all
15  * copies or substantial portions of the Software.
16  *
17  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
19  * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
20  * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
21  * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
22  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23  *
24  * https://www.FreeRTOS.org
25  * https://github.com/FreeRTOS
26  *
27  */
28
29 /* Standard includes. */
30 #include <stdlib.h>
31 #include <string.h>
32
33 /* Defining MPU_WRAPPERS_INCLUDED_FROM_API_FILE prevents task.h from redefining
34  * all the API functions to use the MPU wrappers.  That should only be done when
35  * task.h is included from an application file. */
36 #define MPU_WRAPPERS_INCLUDED_FROM_API_FILE
37
38 /* FreeRTOS includes. */
39 #include "FreeRTOS.h"
40 #include "task.h"
41 #include "timers.h"
42 #include "stack_macros.h"
43
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. */
49
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 )
53
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. */
58     #include <stdio.h>
59 #endif /* configUSE_STATS_FORMATTING_FUNCTIONS == 1 ) */
60
61 #if ( configUSE_PREEMPTION == 0 )
62
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()
66 #else
67     #define taskYIELD_IF_USING_PREEMPTION()    portYIELD_WITHIN_API()
68 #endif
69
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 )
74
75 /*
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.
78  */
79 #define tskSTACK_FILL_BYTE                        ( 0xa5U )
80
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 )
85
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
91 #else
92     #define tskSET_NEW_STACKS_TO_KNOWN_VALUE    0
93 #endif
94
95 /*
96  * Macros used by vListTask to indicate which state a task is in.
97  */
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' )
103
104 /*
105  * Some kernel aware debuggers require the data the debugger needs access to to
106  * be global, rather than file scope.
107  */
108 #ifdef portREMOVE_STATIC_QUALIFIER
109     #define static
110 #endif
111
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"
116 #endif
117
118 #if ( configUSE_PORT_OPTIMISED_TASK_SELECTION == 0 )
119
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. */
123
124 /* uxTopReadyPriority holds the priority of the highest priority ready
125  * state task. */
126     #define taskRECORD_READY_PRIORITY( uxPriority ) \
127     {                                               \
128         if( ( uxPriority ) > uxTopReadyPriority )   \
129         {                                           \
130             uxTopReadyPriority = ( uxPriority );    \
131         }                                           \
132     } /* taskRECORD_READY_PRIORITY */
133
134 /*-----------------------------------------------------------*/
135
136     #define taskSELECT_HIGHEST_PRIORITY_TASK()                                \
137     {                                                                         \
138         UBaseType_t uxTopPriority = uxTopReadyPriority;                       \
139                                                                               \
140         /* Find the highest priority queue that contains ready tasks. */      \
141         while( listLIST_IS_EMPTY( &( pxReadyTasksLists[ uxTopPriority ] ) ) ) \
142         {                                                                     \
143             configASSERT( uxTopPriority );                                    \
144             --uxTopPriority;                                                  \
145         }                                                                     \
146                                                                               \
147         /* listGET_OWNER_OF_NEXT_ENTRY indexes through the list, so the tasks of \
148          * the  same priority get an equal share of the processor time. */                    \
149         listGET_OWNER_OF_NEXT_ENTRY( pxCurrentTCB, &( pxReadyTasksLists[ uxTopPriority ] ) ); \
150         uxTopReadyPriority = uxTopPriority;                                                   \
151     } /* taskSELECT_HIGHEST_PRIORITY_TASK */
152
153 /*-----------------------------------------------------------*/
154
155 /* Define away taskRESET_READY_PRIORITY() and portRESET_READY_PRIORITY() as
156  * they are only required when a port optimised method of task selection is
157  * being used. */
158     #define taskRESET_READY_PRIORITY( uxPriority )
159     #define portRESET_READY_PRIORITY( uxPriority, uxTopReadyPriority )
160
161 #else /* configUSE_PORT_OPTIMISED_TASK_SELECTION */
162
163 /* If configUSE_PORT_OPTIMISED_TASK_SELECTION is 1 then task selection is
164  * performed in a way that is tailored to the particular microcontroller
165  * architecture being used. */
166
167 /* A port optimised version is provided.  Call the port defined macros. */
168     #define taskRECORD_READY_PRIORITY( uxPriority )    portRECORD_READY_PRIORITY( ( uxPriority ), uxTopReadyPriority )
169
170 /*-----------------------------------------------------------*/
171
172     #define taskSELECT_HIGHEST_PRIORITY_TASK()                                                  \
173     {                                                                                           \
174         UBaseType_t uxTopPriority;                                                              \
175                                                                                                 \
176         /* Find the highest priority list that contains ready tasks. */                         \
177         portGET_HIGHEST_PRIORITY( uxTopPriority, uxTopReadyPriority );                          \
178         configASSERT( listCURRENT_LIST_LENGTH( &( pxReadyTasksLists[ uxTopPriority ] ) ) > 0 ); \
179         listGET_OWNER_OF_NEXT_ENTRY( pxCurrentTCB, &( pxReadyTasksLists[ uxTopPriority ] ) );   \
180     } /* taskSELECT_HIGHEST_PRIORITY_TASK() */
181
182 /*-----------------------------------------------------------*/
183
184 /* A port optimised version is provided, call it only if the TCB being reset
185  * is being referenced from a ready list.  If it is referenced from a delayed
186  * or suspended list then it won't be in a ready list. */
187     #define taskRESET_READY_PRIORITY( uxPriority )                                                     \
188     {                                                                                                  \
189         if( listCURRENT_LIST_LENGTH( &( pxReadyTasksLists[ ( uxPriority ) ] ) ) == ( UBaseType_t ) 0 ) \
190         {                                                                                              \
191             portRESET_READY_PRIORITY( ( uxPriority ), ( uxTopReadyPriority ) );                        \
192         }                                                                                              \
193     }
194
195 #endif /* configUSE_PORT_OPTIMISED_TASK_SELECTION */
196
197 /*-----------------------------------------------------------*/
198
199 /* pxDelayedTaskList and pxOverflowDelayedTaskList are switched when the tick
200  * count overflows. */
201 #define taskSWITCH_DELAYED_LISTS()                                                \
202     {                                                                             \
203         List_t * pxTemp;                                                          \
204                                                                                   \
205         /* The delayed tasks list should be empty when the lists are switched. */ \
206         configASSERT( ( listLIST_IS_EMPTY( pxDelayedTaskList ) ) );               \
207                                                                                   \
208         pxTemp = pxDelayedTaskList;                                               \
209         pxDelayedTaskList = pxOverflowDelayedTaskList;                            \
210         pxOverflowDelayedTaskList = pxTemp;                                       \
211         xNumOfOverflows++;                                                        \
212         prvResetNextTaskUnblockTime();                                            \
213     }
214
215 /*-----------------------------------------------------------*/
216
217 /*
218  * Place the task represented by pxTCB into the appropriate ready list for
219  * the task.  It is inserted at the end of the list.
220  */
221 #define prvAddTaskToReadyList( pxTCB )                                                                 \
222     traceMOVED_TASK_TO_READY_STATE( pxTCB );                                                           \
223     taskRECORD_READY_PRIORITY( ( pxTCB )->uxPriority );                                                \
224     listINSERT_END( &( pxReadyTasksLists[ ( pxTCB )->uxPriority ] ), &( ( pxTCB )->xStateListItem ) ); \
225     tracePOST_MOVED_TASK_TO_READY_STATE( pxTCB )
226 /*-----------------------------------------------------------*/
227
228 /*
229  * Several functions take a TaskHandle_t parameter that can optionally be NULL,
230  * where NULL is used to indicate that the handle of the currently executing
231  * task should be used in place of the parameter.  This macro simply checks to
232  * see if the parameter is NULL and returns a pointer to the appropriate TCB.
233  */
234 #define prvGetTCBFromHandle( pxHandle )    ( ( ( pxHandle ) == NULL ) ? pxCurrentTCB : ( pxHandle ) )
235
236 /* The item value of the event list item is normally used to hold the priority
237  * of the task to which it belongs (coded to allow it to be held in reverse
238  * priority order).  However, it is occasionally borrowed for other purposes.  It
239  * is important its value is not updated due to a task priority change while it is
240  * being used for another purpose.  The following bit definition is used to inform
241  * the scheduler that the value should not be changed - in which case it is the
242  * responsibility of whichever module is using the value to ensure it gets set back
243  * to its original value when it is released. */
244 #if ( configTICK_TYPE_WIDTH_IN_BITS == TICK_TYPE_WIDTH_16_BITS )
245     #define taskEVENT_LIST_ITEM_VALUE_IN_USE    0x8000U
246 #elif ( configTICK_TYPE_WIDTH_IN_BITS == TICK_TYPE_WIDTH_32_BITS )
247     #define taskEVENT_LIST_ITEM_VALUE_IN_USE    0x80000000UL
248 #elif ( configTICK_TYPE_WIDTH_IN_BITS == TICK_TYPE_WIDTH_64_BITS )
249     #define taskEVENT_LIST_ITEM_VALUE_IN_USE    0x8000000000000000ULL
250 #endif
251
252 /*
253  * Task control block.  A task control block (TCB) is allocated for each task,
254  * and stores task state information, including a pointer to the task's context
255  * (the task's run time environment, including register values)
256  */
257 typedef struct tskTaskControlBlock       /* The old naming convention is used to prevent breaking kernel aware debuggers. */
258 {
259     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. */
260
261     #if ( portUSING_MPU_WRAPPERS == 1 )
262         xMPU_SETTINGS xMPUSettings; /*< The MPU settings are defined as part of the port layer.  THIS MUST BE THE SECOND MEMBER OF THE TCB STRUCT. */
263     #endif
264
265     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 ). */
266     ListItem_t xEventListItem;                  /*< Used to reference a task from an event list. */
267     UBaseType_t uxPriority;                     /*< The priority of the task.  0 is the lowest priority. */
268     StackType_t * pxStack;                      /*< Points to the start of the stack. */
269     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. */
270
271     #if ( ( portSTACK_GROWTH > 0 ) || ( configRECORD_STACK_HIGH_ADDRESS == 1 ) )
272         StackType_t * pxEndOfStack; /*< Points to the highest valid address for the stack. */
273     #endif
274
275     #if ( portCRITICAL_NESTING_IN_TCB == 1 )
276         UBaseType_t uxCriticalNesting; /*< Holds the critical section nesting depth for ports that do not maintain their own count in the port layer. */
277     #endif
278
279     #if ( configUSE_TRACE_FACILITY == 1 )
280         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. */
281         UBaseType_t uxTaskNumber; /*< Stores a number specifically for use by third party trace code. */
282     #endif
283
284     #if ( configUSE_MUTEXES == 1 )
285         UBaseType_t uxBasePriority; /*< The priority last assigned to the task - used by the priority inheritance mechanism. */
286         UBaseType_t uxMutexesHeld;
287     #endif
288
289     #if ( configUSE_APPLICATION_TASK_TAG == 1 )
290         TaskHookFunction_t pxTaskTag;
291     #endif
292
293     #if ( configNUM_THREAD_LOCAL_STORAGE_POINTERS > 0 )
294         void * pvThreadLocalStoragePointers[ configNUM_THREAD_LOCAL_STORAGE_POINTERS ];
295     #endif
296
297     #if ( configGENERATE_RUN_TIME_STATS == 1 )
298         configRUN_TIME_COUNTER_TYPE ulRunTimeCounter; /*< Stores the amount of time the task has spent in the Running state. */
299     #endif
300
301     #if ( ( configUSE_NEWLIB_REENTRANT == 1 ) || ( configUSE_C_RUNTIME_TLS_SUPPORT == 1 ) )
302         configTLS_BLOCK_TYPE xTLSBlock; /*< Memory block used as Thread Local Storage (TLS) Block for the task. */
303     #endif
304
305     #if ( configUSE_TASK_NOTIFICATIONS == 1 )
306         volatile uint32_t ulNotifiedValue[ configTASK_NOTIFICATION_ARRAY_ENTRIES ];
307         volatile uint8_t ucNotifyState[ configTASK_NOTIFICATION_ARRAY_ENTRIES ];
308     #endif
309
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. */
314     #endif
315
316     #if ( INCLUDE_xTaskAbortDelay == 1 )
317         uint8_t ucDelayAborted;
318     #endif
319
320     #if ( configUSE_POSIX_ERRNO == 1 )
321         int iTaskErrno;
322     #endif
323 } tskTCB;
324
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;
328
329 /*lint -save -e956 A manual analysis and inspection has been used to determine
330  * which static variables must be declared volatile. */
331 portDONT_DISCARD PRIVILEGED_DATA TCB_t * volatile pxCurrentTCB = NULL;
332
333 /* Lists for ready and blocked tasks. --------------------
334  * xDelayedTaskList1 and xDelayedTaskList2 could be moved to function scope but
335  * doing so breaks some kernel aware debuggers and debuggers that rely on removing
336  * the static qualifier. */
337 PRIVILEGED_DATA static List_t pxReadyTasksLists[ configMAX_PRIORITIES ]; /*< Prioritised ready tasks. */
338 PRIVILEGED_DATA static List_t xDelayedTaskList1;                         /*< Delayed tasks. */
339 PRIVILEGED_DATA static List_t xDelayedTaskList2;                         /*< Delayed tasks (two lists are used - one for delays that have overflowed the current tick count. */
340 PRIVILEGED_DATA static List_t * volatile pxDelayedTaskList;              /*< Points to the delayed task list currently being used. */
341 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. */
342 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. */
343
344 #if ( INCLUDE_vTaskDelete == 1 )
345
346     PRIVILEGED_DATA static List_t xTasksWaitingTermination; /*< Tasks that have been deleted - but their memory not yet freed. */
347     PRIVILEGED_DATA static volatile UBaseType_t uxDeletedTasksWaitingCleanUp = ( UBaseType_t ) 0U;
348
349 #endif
350
351 #if ( INCLUDE_vTaskSuspend == 1 )
352
353     PRIVILEGED_DATA static List_t xSuspendedTaskList; /*< Tasks that are currently suspended. */
354
355 #endif
356
357 /* Global POSIX errno. Its value is changed upon context switching to match
358  * the errno of the currently running task. */
359 #if ( configUSE_POSIX_ERRNO == 1 )
360     int FreeRTOS_errno = 0;
361 #endif
362
363 /* Other file private variables. --------------------------------*/
364 PRIVILEGED_DATA static volatile UBaseType_t uxCurrentNumberOfTasks = ( UBaseType_t ) 0U;
365 PRIVILEGED_DATA static volatile TickType_t xTickCount = ( TickType_t ) configINITIAL_TICK_COUNT;
366 PRIVILEGED_DATA static volatile UBaseType_t uxTopReadyPriority = tskIDLE_PRIORITY;
367 PRIVILEGED_DATA static volatile BaseType_t xSchedulerRunning = pdFALSE;
368 PRIVILEGED_DATA static volatile TickType_t xPendedTicks = ( TickType_t ) 0U;
369 PRIVILEGED_DATA static volatile BaseType_t xYieldPending = pdFALSE;
370 PRIVILEGED_DATA static volatile BaseType_t xNumOfOverflows = ( BaseType_t ) 0;
371 PRIVILEGED_DATA static UBaseType_t uxTaskNumber = ( UBaseType_t ) 0U;
372 PRIVILEGED_DATA static volatile TickType_t xNextTaskUnblockTime = ( TickType_t ) 0U; /* Initialised to portMAX_DELAY before the scheduler starts. */
373 PRIVILEGED_DATA static TaskHandle_t xIdleTaskHandle = NULL;                          /*< Holds the handle of the idle task.  The idle task is created automatically when the scheduler is started. */
374
375 /* Improve support for OpenOCD. The kernel tracks Ready tasks via priority lists.
376  * For tracking the state of remote threads, OpenOCD uses uxTopUsedPriority
377  * to determine the number of priority lists to read back from the remote target. */
378 const volatile UBaseType_t uxTopUsedPriority = configMAX_PRIORITIES - 1U;
379
380 /* Context switches are held pending while the scheduler is suspended.  Also,
381  * interrupts must not manipulate the xStateListItem of a TCB, or any of the
382  * lists the xStateListItem can be referenced from, if the scheduler is suspended.
383  * If an interrupt needs to unblock a task while the scheduler is suspended then it
384  * moves the task's event list item into the xPendingReadyList, ready for the
385  * kernel to move the task from the pending ready list into the real ready list
386  * when the scheduler is unsuspended.  The pending ready list itself can only be
387  * accessed from a critical section. */
388 PRIVILEGED_DATA static volatile UBaseType_t uxSchedulerSuspended = ( UBaseType_t ) pdFALSE;
389
390 #if ( configGENERATE_RUN_TIME_STATS == 1 )
391
392 /* Do not move these variables to function scope as doing so prevents the
393  * code working with debuggers that need to remove the static qualifier. */
394     PRIVILEGED_DATA static configRUN_TIME_COUNTER_TYPE ulTaskSwitchedInTime = 0UL;    /*< Holds the value of a timer/counter the last time a task was switched in. */
395     PRIVILEGED_DATA static volatile configRUN_TIME_COUNTER_TYPE ulTotalRunTime = 0UL; /*< Holds the total amount of execution time as defined by the run time counter clock. */
396
397 #endif
398
399 /*lint -restore */
400
401 /*-----------------------------------------------------------*/
402
403 /* File private functions. --------------------------------*/
404
405 /**
406  * Utility task that simply returns pdTRUE if the task referenced by xTask is
407  * currently in the Suspended state, or pdFALSE if the task referenced by xTask
408  * is in any other state.
409  */
410 #if ( INCLUDE_vTaskSuspend == 1 )
411
412     static BaseType_t prvTaskIsTaskSuspended( const TaskHandle_t xTask ) PRIVILEGED_FUNCTION;
413
414 #endif /* INCLUDE_vTaskSuspend */
415
416 /*
417  * Utility to ready all the lists used by the scheduler.  This is called
418  * automatically upon the creation of the first task.
419  */
420 static void prvInitialiseTaskLists( void ) PRIVILEGED_FUNCTION;
421
422 /*
423  * The idle task, which as all tasks is implemented as a never ending loop.
424  * The idle task is automatically created and added to the ready lists upon
425  * creation of the first user task.
426  *
427  * The portTASK_FUNCTION_PROTO() macro is used to allow port/compiler specific
428  * language extensions.  The equivalent prototype for this function is:
429  *
430  * void prvIdleTask( void *pvParameters );
431  *
432  */
433 static portTASK_FUNCTION_PROTO( prvIdleTask, pvParameters ) PRIVILEGED_FUNCTION;
434
435 /*
436  * Utility to free all memory allocated by the scheduler to hold a TCB,
437  * including the stack pointed to by the TCB.
438  *
439  * This does not free memory allocated by the task itself (i.e. memory
440  * allocated by calls to pvPortMalloc from within the tasks application code).
441  */
442 #if ( INCLUDE_vTaskDelete == 1 )
443
444     static void prvDeleteTCB( TCB_t * pxTCB ) PRIVILEGED_FUNCTION;
445
446 #endif
447
448 /*
449  * Used only by the idle task.  This checks to see if anything has been placed
450  * in the list of tasks waiting to be deleted.  If so the task is cleaned up
451  * and its TCB deleted.
452  */
453 static void prvCheckTasksWaitingTermination( void ) PRIVILEGED_FUNCTION;
454
455 /*
456  * The currently executing task is entering the Blocked state.  Add the task to
457  * either the current or the overflow delayed task list.
458  */
459 static void prvAddCurrentTaskToDelayedList( TickType_t xTicksToWait,
460                                             const BaseType_t xCanBlockIndefinitely ) PRIVILEGED_FUNCTION;
461
462 /*
463  * Fills an TaskStatus_t structure with information on each task that is
464  * referenced from the pxList list (which may be a ready list, a delayed list,
465  * a suspended list, etc.).
466  *
467  * THIS FUNCTION IS INTENDED FOR DEBUGGING ONLY, AND SHOULD NOT BE CALLED FROM
468  * NORMAL APPLICATION CODE.
469  */
470 #if ( configUSE_TRACE_FACILITY == 1 )
471
472     static UBaseType_t prvListTasksWithinSingleList( TaskStatus_t * pxTaskStatusArray,
473                                                      List_t * pxList,
474                                                      eTaskState eState ) PRIVILEGED_FUNCTION;
475
476 #endif
477
478 /*
479  * Searches pxList for a task with name pcNameToQuery - returning a handle to
480  * the task if it is found, or NULL if the task is not found.
481  */
482 #if ( INCLUDE_xTaskGetHandle == 1 )
483
484     static TCB_t * prvSearchForNameWithinSingleList( List_t * pxList,
485                                                      const char pcNameToQuery[] ) PRIVILEGED_FUNCTION;
486
487 #endif
488
489 /*
490  * When a task is created, the stack of the task is filled with a known value.
491  * This function determines the 'high water mark' of the task stack by
492  * determining how much of the stack remains at the original preset value.
493  */
494 #if ( ( configUSE_TRACE_FACILITY == 1 ) || ( INCLUDE_uxTaskGetStackHighWaterMark == 1 ) || ( INCLUDE_uxTaskGetStackHighWaterMark2 == 1 ) )
495
496     static configSTACK_DEPTH_TYPE prvTaskCheckFreeStackSpace( const uint8_t * pucStackByte ) PRIVILEGED_FUNCTION;
497
498 #endif
499
500 /*
501  * Return the amount of time, in ticks, that will pass before the kernel will
502  * next move a task from the Blocked state to the Running state.
503  *
504  * This conditional compilation should use inequality to 0, not equality to 1.
505  * This is to ensure portSUPPRESS_TICKS_AND_SLEEP() can be called when user
506  * defined low power mode implementations require configUSE_TICKLESS_IDLE to be
507  * set to a value other than 1.
508  */
509 #if ( configUSE_TICKLESS_IDLE != 0 )
510
511     static TickType_t prvGetExpectedIdleTime( void ) PRIVILEGED_FUNCTION;
512
513 #endif
514
515 /*
516  * Set xNextTaskUnblockTime to the time at which the next Blocked state task
517  * will exit the Blocked state.
518  */
519 static void prvResetNextTaskUnblockTime( void ) PRIVILEGED_FUNCTION;
520
521 #if ( configUSE_STATS_FORMATTING_FUNCTIONS > 0 )
522
523 /*
524  * Helper function used to pad task names with spaces when printing out
525  * human readable tables of task information.
526  */
527     static char * prvWriteNameToBuffer( char * pcBuffer,
528                                         const char * pcTaskName ) PRIVILEGED_FUNCTION;
529
530 #endif
531
532 /*
533  * Called after a Task_t structure has been allocated either statically or
534  * dynamically to fill in the structure's members.
535  */
536 static void prvInitialiseNewTask( TaskFunction_t pxTaskCode,
537                                   const char * const pcName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */
538                                   const uint32_t ulStackDepth,
539                                   void * const pvParameters,
540                                   UBaseType_t uxPriority,
541                                   TaskHandle_t * const pxCreatedTask,
542                                   TCB_t * pxNewTCB,
543                                   const MemoryRegion_t * const xRegions ) PRIVILEGED_FUNCTION;
544
545 /*
546  * Called after a new task has been created and initialised to place the task
547  * under the control of the scheduler.
548  */
549 static void prvAddNewTaskToReadyList( TCB_t * pxNewTCB ) PRIVILEGED_FUNCTION;
550
551 /*
552  * freertos_tasks_c_additions_init() should only be called if the user definable
553  * macro FREERTOS_TASKS_C_ADDITIONS_INIT() is defined, as that is the only macro
554  * called by the function.
555  */
556 #ifdef FREERTOS_TASKS_C_ADDITIONS_INIT
557
558     static void freertos_tasks_c_additions_init( void ) PRIVILEGED_FUNCTION;
559
560 #endif
561
562 /*-----------------------------------------------------------*/
563
564 #if ( configSUPPORT_STATIC_ALLOCATION == 1 )
565
566     TaskHandle_t xTaskCreateStatic( TaskFunction_t pxTaskCode,
567                                     const char * const pcName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */
568                                     const uint32_t ulStackDepth,
569                                     void * const pvParameters,
570                                     UBaseType_t uxPriority,
571                                     StackType_t * const puxStackBuffer,
572                                     StaticTask_t * const pxTaskBuffer )
573     {
574         TCB_t * pxNewTCB;
575         TaskHandle_t xReturn;
576
577         configASSERT( puxStackBuffer != NULL );
578         configASSERT( pxTaskBuffer != NULL );
579
580         #if ( configASSERT_DEFINED == 1 )
581         {
582             /* Sanity check that the size of the structure used to declare a
583              * variable of type StaticTask_t equals the size of the real task
584              * structure. */
585             volatile size_t xSize = sizeof( StaticTask_t );
586             configASSERT( xSize == sizeof( TCB_t ) );
587             ( void ) xSize; /* Prevent lint warning when configASSERT() is not used. */
588         }
589         #endif /* configASSERT_DEFINED */
590
591         if( ( pxTaskBuffer != NULL ) && ( puxStackBuffer != NULL ) )
592         {
593             /* The memory used for the task's TCB and stack are passed into this
594              * function - use them. */
595             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. */
596             memset( ( void * ) pxNewTCB, 0x00, sizeof( TCB_t ) );
597             pxNewTCB->pxStack = ( StackType_t * ) puxStackBuffer;
598
599             #if ( tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE != 0 ) /*lint !e731 !e9029 Macro has been consolidated for readability reasons. */
600             {
601                 /* Tasks can be created statically or dynamically, so note this
602                  * task was created statically in case the task is later deleted. */
603                 pxNewTCB->ucStaticallyAllocated = tskSTATICALLY_ALLOCATED_STACK_AND_TCB;
604             }
605             #endif /* tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE */
606
607             prvInitialiseNewTask( pxTaskCode, pcName, ulStackDepth, pvParameters, uxPriority, &xReturn, pxNewTCB, NULL );
608             prvAddNewTaskToReadyList( pxNewTCB );
609         }
610         else
611         {
612             xReturn = NULL;
613         }
614
615         return xReturn;
616     }
617
618 #endif /* SUPPORT_STATIC_ALLOCATION */
619 /*-----------------------------------------------------------*/
620
621 #if ( ( portUSING_MPU_WRAPPERS == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) )
622
623     BaseType_t xTaskCreateRestrictedStatic( const TaskParameters_t * const pxTaskDefinition,
624                                             TaskHandle_t * pxCreatedTask )
625     {
626         TCB_t * pxNewTCB;
627         BaseType_t xReturn = errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY;
628
629         configASSERT( pxTaskDefinition->puxStackBuffer != NULL );
630         configASSERT( pxTaskDefinition->pxTaskBuffer != NULL );
631
632         if( ( pxTaskDefinition->puxStackBuffer != NULL ) && ( pxTaskDefinition->pxTaskBuffer != NULL ) )
633         {
634             /* Allocate space for the TCB.  Where the memory comes from depends
635              * on the implementation of the port malloc function and whether or
636              * not static allocation is being used. */
637             pxNewTCB = ( TCB_t * ) pxTaskDefinition->pxTaskBuffer;
638             memset( ( void * ) pxNewTCB, 0x00, sizeof( TCB_t ) );
639
640             /* Store the stack location in the TCB. */
641             pxNewTCB->pxStack = pxTaskDefinition->puxStackBuffer;
642
643             #if ( tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE != 0 )
644             {
645                 /* Tasks can be created statically or dynamically, so note this
646                  * task was created statically in case the task is later deleted. */
647                 pxNewTCB->ucStaticallyAllocated = tskSTATICALLY_ALLOCATED_STACK_AND_TCB;
648             }
649             #endif /* tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE */
650
651             prvInitialiseNewTask( pxTaskDefinition->pvTaskCode,
652                                   pxTaskDefinition->pcName,
653                                   ( uint32_t ) pxTaskDefinition->usStackDepth,
654                                   pxTaskDefinition->pvParameters,
655                                   pxTaskDefinition->uxPriority,
656                                   pxCreatedTask, pxNewTCB,
657                                   pxTaskDefinition->xRegions );
658
659             prvAddNewTaskToReadyList( pxNewTCB );
660             xReturn = pdPASS;
661         }
662
663         return xReturn;
664     }
665
666 #endif /* ( portUSING_MPU_WRAPPERS == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) */
667 /*-----------------------------------------------------------*/
668
669 #if ( ( portUSING_MPU_WRAPPERS == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) )
670
671     BaseType_t xTaskCreateRestricted( const TaskParameters_t * const pxTaskDefinition,
672                                       TaskHandle_t * pxCreatedTask )
673     {
674         TCB_t * pxNewTCB;
675         BaseType_t xReturn = errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY;
676
677         configASSERT( pxTaskDefinition->puxStackBuffer );
678
679         if( pxTaskDefinition->puxStackBuffer != NULL )
680         {
681             /* Allocate space for the TCB.  Where the memory comes from depends
682              * on the implementation of the port malloc function and whether or
683              * not static allocation is being used. */
684             pxNewTCB = ( TCB_t * ) pvPortMalloc( sizeof( TCB_t ) );
685
686             if( pxNewTCB != NULL )
687             {
688                 memset( ( void * ) pxNewTCB, 0x00, sizeof( TCB_t ) );
689
690                 /* Store the stack location in the TCB. */
691                 pxNewTCB->pxStack = pxTaskDefinition->puxStackBuffer;
692
693                 #if ( tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE != 0 )
694                 {
695                     /* Tasks can be created statically or dynamically, so note
696                      * this task had a statically allocated stack in case it is
697                      * later deleted.  The TCB was allocated dynamically. */
698                     pxNewTCB->ucStaticallyAllocated = tskSTATICALLY_ALLOCATED_STACK_ONLY;
699                 }
700                 #endif /* tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE */
701
702                 prvInitialiseNewTask( pxTaskDefinition->pvTaskCode,
703                                       pxTaskDefinition->pcName,
704                                       ( uint32_t ) pxTaskDefinition->usStackDepth,
705                                       pxTaskDefinition->pvParameters,
706                                       pxTaskDefinition->uxPriority,
707                                       pxCreatedTask, pxNewTCB,
708                                       pxTaskDefinition->xRegions );
709
710                 prvAddNewTaskToReadyList( pxNewTCB );
711                 xReturn = pdPASS;
712             }
713         }
714
715         return xReturn;
716     }
717
718 #endif /* portUSING_MPU_WRAPPERS */
719 /*-----------------------------------------------------------*/
720
721 #if ( configSUPPORT_DYNAMIC_ALLOCATION == 1 )
722
723     BaseType_t xTaskCreate( TaskFunction_t pxTaskCode,
724                             const char * const pcName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */
725                             const configSTACK_DEPTH_TYPE usStackDepth,
726                             void * const pvParameters,
727                             UBaseType_t uxPriority,
728                             TaskHandle_t * const pxCreatedTask )
729     {
730         TCB_t * pxNewTCB;
731         BaseType_t xReturn;
732
733         /* If the stack grows down then allocate the stack then the TCB so the stack
734          * does not grow into the TCB.  Likewise if the stack grows up then allocate
735          * the TCB then the stack. */
736         #if ( portSTACK_GROWTH > 0 )
737         {
738             /* Allocate space for the TCB.  Where the memory comes from depends on
739              * the implementation of the port malloc function and whether or not static
740              * allocation is being used. */
741             pxNewTCB = ( TCB_t * ) pvPortMalloc( sizeof( TCB_t ) );
742
743             if( pxNewTCB != NULL )
744             {
745                 memset( ( void * ) pxNewTCB, 0x00, sizeof( TCB_t ) );
746
747                 /* Allocate space for the stack used by the task being created.
748                  * The base of the stack memory stored in the TCB so the task can
749                  * be deleted later if required. */
750                 pxNewTCB->pxStack = ( StackType_t * ) pvPortMallocStack( ( ( ( size_t ) usStackDepth ) * sizeof( StackType_t ) ) ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */
751
752                 if( pxNewTCB->pxStack == NULL )
753                 {
754                     /* Could not allocate the stack.  Delete the allocated TCB. */
755                     vPortFree( pxNewTCB );
756                     pxNewTCB = NULL;
757                 }
758             }
759         }
760         #else /* portSTACK_GROWTH */
761         {
762             StackType_t * pxStack;
763
764             /* Allocate space for the stack used by the task being created. */
765             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. */
766
767             if( pxStack != NULL )
768             {
769                 /* Allocate space for the TCB. */
770                 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. */
771
772                 if( pxNewTCB != NULL )
773                 {
774                     memset( ( void * ) pxNewTCB, 0x00, sizeof( TCB_t ) );
775
776                     /* Store the stack location in the TCB. */
777                     pxNewTCB->pxStack = pxStack;
778                 }
779                 else
780                 {
781                     /* The stack cannot be used as the TCB was not created.  Free
782                      * it again. */
783                     vPortFreeStack( pxStack );
784                 }
785             }
786             else
787             {
788                 pxNewTCB = NULL;
789             }
790         }
791         #endif /* portSTACK_GROWTH */
792
793         if( pxNewTCB != NULL )
794         {
795             #if ( tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE != 0 ) /*lint !e9029 !e731 Macro has been consolidated for readability reasons. */
796             {
797                 /* Tasks can be created statically or dynamically, so note this
798                  * task was created dynamically in case it is later deleted. */
799                 pxNewTCB->ucStaticallyAllocated = tskDYNAMICALLY_ALLOCATED_STACK_AND_TCB;
800             }
801             #endif /* tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE */
802
803             prvInitialiseNewTask( pxTaskCode, pcName, ( uint32_t ) usStackDepth, pvParameters, uxPriority, pxCreatedTask, pxNewTCB, NULL );
804             prvAddNewTaskToReadyList( pxNewTCB );
805             xReturn = pdPASS;
806         }
807         else
808         {
809             xReturn = errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY;
810         }
811
812         return xReturn;
813     }
814
815 #endif /* configSUPPORT_DYNAMIC_ALLOCATION */
816 /*-----------------------------------------------------------*/
817
818 static void prvInitialiseNewTask( TaskFunction_t pxTaskCode,
819                                   const char * const pcName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */
820                                   const uint32_t ulStackDepth,
821                                   void * const pvParameters,
822                                   UBaseType_t uxPriority,
823                                   TaskHandle_t * const pxCreatedTask,
824                                   TCB_t * pxNewTCB,
825                                   const MemoryRegion_t * const xRegions )
826 {
827     StackType_t * pxTopOfStack;
828     UBaseType_t x;
829
830     #if ( portUSING_MPU_WRAPPERS == 1 )
831         /* Should the task be created in privileged mode? */
832         BaseType_t xRunPrivileged;
833
834         if( ( uxPriority & portPRIVILEGE_BIT ) != 0U )
835         {
836             xRunPrivileged = pdTRUE;
837         }
838         else
839         {
840             xRunPrivileged = pdFALSE;
841         }
842         uxPriority &= ~portPRIVILEGE_BIT;
843     #endif /* portUSING_MPU_WRAPPERS == 1 */
844
845     /* Avoid dependency on memset() if it is not required. */
846     #if ( tskSET_NEW_STACKS_TO_KNOWN_VALUE == 1 )
847     {
848         /* Fill the stack with a known value to assist debugging. */
849         ( void ) memset( pxNewTCB->pxStack, ( int ) tskSTACK_FILL_BYTE, ( size_t ) ulStackDepth * sizeof( StackType_t ) );
850     }
851     #endif /* tskSET_NEW_STACKS_TO_KNOWN_VALUE */
852
853     /* Calculate the top of stack address.  This depends on whether the stack
854      * grows from high memory to low (as per the 80x86) or vice versa.
855      * portSTACK_GROWTH is used to make the result positive or negative as required
856      * by the port. */
857     #if ( portSTACK_GROWTH < 0 )
858     {
859         pxTopOfStack = &( pxNewTCB->pxStack[ ulStackDepth - ( uint32_t ) 1 ] );
860         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(). */
861
862         /* Check the alignment of the calculated top of stack is correct. */
863         configASSERT( ( ( ( portPOINTER_SIZE_TYPE ) pxTopOfStack & ( portPOINTER_SIZE_TYPE ) portBYTE_ALIGNMENT_MASK ) == 0UL ) );
864
865         #if ( configRECORD_STACK_HIGH_ADDRESS == 1 )
866         {
867             /* Also record the stack's high address, which may assist
868              * debugging. */
869             pxNewTCB->pxEndOfStack = pxTopOfStack;
870         }
871         #endif /* configRECORD_STACK_HIGH_ADDRESS */
872     }
873     #else /* portSTACK_GROWTH */
874     {
875         pxTopOfStack = pxNewTCB->pxStack;
876
877         /* Check the alignment of the stack buffer is correct. */
878         configASSERT( ( ( ( portPOINTER_SIZE_TYPE ) pxNewTCB->pxStack & ( portPOINTER_SIZE_TYPE ) portBYTE_ALIGNMENT_MASK ) == 0UL ) );
879
880         /* The other extreme of the stack space is required if stack checking is
881          * performed. */
882         pxNewTCB->pxEndOfStack = pxNewTCB->pxStack + ( ulStackDepth - ( uint32_t ) 1 );
883     }
884     #endif /* portSTACK_GROWTH */
885
886     /* Store the task name in the TCB. */
887     if( pcName != NULL )
888     {
889         for( x = ( UBaseType_t ) 0; x < ( UBaseType_t ) configMAX_TASK_NAME_LEN; x++ )
890         {
891             pxNewTCB->pcTaskName[ x ] = pcName[ x ];
892
893             /* Don't copy all configMAX_TASK_NAME_LEN if the string is shorter than
894              * configMAX_TASK_NAME_LEN characters just in case the memory after the
895              * string is not accessible (extremely unlikely). */
896             if( pcName[ x ] == ( char ) 0x00 )
897             {
898                 break;
899             }
900             else
901             {
902                 mtCOVERAGE_TEST_MARKER();
903             }
904         }
905
906         /* Ensure the name string is terminated in the case that the string length
907          * was greater or equal to configMAX_TASK_NAME_LEN. */
908         pxNewTCB->pcTaskName[ configMAX_TASK_NAME_LEN - 1 ] = '\0';
909     }
910     else
911     {
912         mtCOVERAGE_TEST_MARKER();
913     }
914
915     /* This is used as an array index so must ensure it's not too large. */
916     configASSERT( uxPriority < configMAX_PRIORITIES );
917
918     if( uxPriority >= ( UBaseType_t ) configMAX_PRIORITIES )
919     {
920         uxPriority = ( UBaseType_t ) configMAX_PRIORITIES - ( UBaseType_t ) 1U;
921     }
922     else
923     {
924         mtCOVERAGE_TEST_MARKER();
925     }
926
927     pxNewTCB->uxPriority = uxPriority;
928     #if ( configUSE_MUTEXES == 1 )
929     {
930         pxNewTCB->uxBasePriority = uxPriority;
931     }
932     #endif /* configUSE_MUTEXES */
933
934     vListInitialiseItem( &( pxNewTCB->xStateListItem ) );
935     vListInitialiseItem( &( pxNewTCB->xEventListItem ) );
936
937     /* Set the pxNewTCB as a link back from the ListItem_t.  This is so we can get
938      * back to  the containing TCB from a generic item in a list. */
939     listSET_LIST_ITEM_OWNER( &( pxNewTCB->xStateListItem ), pxNewTCB );
940
941     /* Event lists are always in priority order. */
942     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. */
943     listSET_LIST_ITEM_OWNER( &( pxNewTCB->xEventListItem ), pxNewTCB );
944
945     #if ( portUSING_MPU_WRAPPERS == 1 )
946     {
947         vPortStoreTaskMPUSettings( &( pxNewTCB->xMPUSettings ), xRegions, pxNewTCB->pxStack, ulStackDepth );
948     }
949     #else
950     {
951         /* Avoid compiler warning about unreferenced parameter. */
952         ( void ) xRegions;
953     }
954     #endif
955
956     #if ( ( configUSE_NEWLIB_REENTRANT == 1 ) || ( configUSE_C_RUNTIME_TLS_SUPPORT == 1 ) )
957     {
958         /* Allocate and initialize memory for the task's TLS Block. */
959         configINIT_TLS_BLOCK( pxNewTCB->xTLSBlock );
960     }
961     #endif
962
963     /* Initialize the TCB stack to look as if the task was already running,
964      * but had been interrupted by the scheduler.  The return address is set
965      * to the start of the task function. Once the stack has been initialised
966      * the top of stack variable is updated. */
967     #if ( portUSING_MPU_WRAPPERS == 1 )
968     {
969         /* If the port has capability to detect stack overflow,
970          * pass the stack end address to the stack initialization
971          * function as well. */
972         #if ( portHAS_STACK_OVERFLOW_CHECKING == 1 )
973         {
974             #if ( portSTACK_GROWTH < 0 )
975             {
976                 pxNewTCB->pxTopOfStack = pxPortInitialiseStack( pxTopOfStack, pxNewTCB->pxStack, pxTaskCode, pvParameters, xRunPrivileged );
977             }
978             #else /* portSTACK_GROWTH */
979             {
980                 pxNewTCB->pxTopOfStack = pxPortInitialiseStack( pxTopOfStack, pxNewTCB->pxEndOfStack, pxTaskCode, pvParameters, xRunPrivileged );
981             }
982             #endif /* portSTACK_GROWTH */
983         }
984         #else /* portHAS_STACK_OVERFLOW_CHECKING */
985         {
986             pxNewTCB->pxTopOfStack = pxPortInitialiseStack( pxTopOfStack, pxTaskCode, pvParameters, xRunPrivileged );
987         }
988         #endif /* portHAS_STACK_OVERFLOW_CHECKING */
989     }
990     #else /* portUSING_MPU_WRAPPERS */
991     {
992         /* If the port has capability to detect stack overflow,
993          * pass the stack end address to the stack initialization
994          * function as well. */
995         #if ( portHAS_STACK_OVERFLOW_CHECKING == 1 )
996         {
997             #if ( portSTACK_GROWTH < 0 )
998             {
999                 pxNewTCB->pxTopOfStack = pxPortInitialiseStack( pxTopOfStack, pxNewTCB->pxStack, pxTaskCode, pvParameters );
1000             }
1001             #else /* portSTACK_GROWTH */
1002             {
1003                 pxNewTCB->pxTopOfStack = pxPortInitialiseStack( pxTopOfStack, pxNewTCB->pxEndOfStack, pxTaskCode, pvParameters );
1004             }
1005             #endif /* portSTACK_GROWTH */
1006         }
1007         #else /* portHAS_STACK_OVERFLOW_CHECKING */
1008         {
1009             pxNewTCB->pxTopOfStack = pxPortInitialiseStack( pxTopOfStack, pxTaskCode, pvParameters );
1010         }
1011         #endif /* portHAS_STACK_OVERFLOW_CHECKING */
1012     }
1013     #endif /* portUSING_MPU_WRAPPERS */
1014
1015     if( pxCreatedTask != NULL )
1016     {
1017         /* Pass the handle out in an anonymous way.  The handle can be used to
1018          * change the created task's priority, delete the created task, etc.*/
1019         *pxCreatedTask = ( TaskHandle_t ) pxNewTCB;
1020     }
1021     else
1022     {
1023         mtCOVERAGE_TEST_MARKER();
1024     }
1025 }
1026 /*-----------------------------------------------------------*/
1027
1028 static void prvAddNewTaskToReadyList( TCB_t * pxNewTCB )
1029 {
1030     /* Ensure interrupts don't access the task lists while the lists are being
1031      * updated. */
1032     taskENTER_CRITICAL();
1033     {
1034         uxCurrentNumberOfTasks++;
1035
1036         if( pxCurrentTCB == NULL )
1037         {
1038             /* There are no other tasks, or all the other tasks are in
1039              * the suspended state - make this the current task. */
1040             pxCurrentTCB = pxNewTCB;
1041
1042             if( uxCurrentNumberOfTasks == ( UBaseType_t ) 1 )
1043             {
1044                 /* This is the first task to be created so do the preliminary
1045                  * initialisation required.  We will not recover if this call
1046                  * fails, but we will report the failure. */
1047                 prvInitialiseTaskLists();
1048             }
1049             else
1050             {
1051                 mtCOVERAGE_TEST_MARKER();
1052             }
1053         }
1054         else
1055         {
1056             /* If the scheduler is not already running, make this task the
1057              * current task if it is the highest priority task to be created
1058              * so far. */
1059             if( xSchedulerRunning == pdFALSE )
1060             {
1061                 if( pxCurrentTCB->uxPriority <= pxNewTCB->uxPriority )
1062                 {
1063                     pxCurrentTCB = pxNewTCB;
1064                 }
1065                 else
1066                 {
1067                     mtCOVERAGE_TEST_MARKER();
1068                 }
1069             }
1070             else
1071             {
1072                 mtCOVERAGE_TEST_MARKER();
1073             }
1074         }
1075
1076         uxTaskNumber++;
1077
1078         #if ( configUSE_TRACE_FACILITY == 1 )
1079         {
1080             /* Add a counter into the TCB for tracing only. */
1081             pxNewTCB->uxTCBNumber = uxTaskNumber;
1082         }
1083         #endif /* configUSE_TRACE_FACILITY */
1084         traceTASK_CREATE( pxNewTCB );
1085
1086         prvAddTaskToReadyList( pxNewTCB );
1087
1088         portSETUP_TCB( pxNewTCB );
1089     }
1090     taskEXIT_CRITICAL();
1091
1092     if( xSchedulerRunning != pdFALSE )
1093     {
1094         /* If the created task is of a higher priority than the current task
1095          * then it should run now. */
1096         if( pxCurrentTCB->uxPriority < pxNewTCB->uxPriority )
1097         {
1098             taskYIELD_IF_USING_PREEMPTION();
1099         }
1100         else
1101         {
1102             mtCOVERAGE_TEST_MARKER();
1103         }
1104     }
1105     else
1106     {
1107         mtCOVERAGE_TEST_MARKER();
1108     }
1109 }
1110 /*-----------------------------------------------------------*/
1111
1112 #if ( INCLUDE_vTaskDelete == 1 )
1113
1114     void vTaskDelete( TaskHandle_t xTaskToDelete )
1115     {
1116         TCB_t * pxTCB;
1117
1118         taskENTER_CRITICAL();
1119         {
1120             /* If null is passed in here then it is the calling task that is
1121              * being deleted. */
1122             pxTCB = prvGetTCBFromHandle( xTaskToDelete );
1123
1124             /* Remove task from the ready/delayed list. */
1125             if( uxListRemove( &( pxTCB->xStateListItem ) ) == ( UBaseType_t ) 0 )
1126             {
1127                 taskRESET_READY_PRIORITY( pxTCB->uxPriority );
1128             }
1129             else
1130             {
1131                 mtCOVERAGE_TEST_MARKER();
1132             }
1133
1134             /* Is the task waiting on an event also? */
1135             if( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) != NULL )
1136             {
1137                 ( void ) uxListRemove( &( pxTCB->xEventListItem ) );
1138             }
1139             else
1140             {
1141                 mtCOVERAGE_TEST_MARKER();
1142             }
1143
1144             /* Increment the uxTaskNumber also so kernel aware debuggers can
1145              * detect that the task lists need re-generating.  This is done before
1146              * portPRE_TASK_DELETE_HOOK() as in the Windows port that macro will
1147              * not return. */
1148             uxTaskNumber++;
1149
1150             if( pxTCB == pxCurrentTCB )
1151             {
1152                 /* A task is deleting itself.  This cannot complete within the
1153                  * task itself, as a context switch to another task is required.
1154                  * Place the task in the termination list.  The idle task will
1155                  * check the termination list and free up any memory allocated by
1156                  * the scheduler for the TCB and stack of the deleted task. */
1157                 vListInsertEnd( &xTasksWaitingTermination, &( pxTCB->xStateListItem ) );
1158
1159                 /* Increment the ucTasksDeleted variable so the idle task knows
1160                  * there is a task that has been deleted and that it should therefore
1161                  * check the xTasksWaitingTermination list. */
1162                 ++uxDeletedTasksWaitingCleanUp;
1163
1164                 /* Call the delete hook before portPRE_TASK_DELETE_HOOK() as
1165                  * portPRE_TASK_DELETE_HOOK() does not return in the Win32 port. */
1166                 traceTASK_DELETE( pxTCB );
1167
1168                 /* The pre-delete hook is primarily for the Windows simulator,
1169                  * in which Windows specific clean up operations are performed,
1170                  * after which it is not possible to yield away from this task -
1171                  * hence xYieldPending is used to latch that a context switch is
1172                  * required. */
1173                 portPRE_TASK_DELETE_HOOK( pxTCB, &xYieldPending );
1174             }
1175             else
1176             {
1177                 --uxCurrentNumberOfTasks;
1178                 traceTASK_DELETE( pxTCB );
1179
1180                 /* Reset the next expected unblock time in case it referred to
1181                  * the task that has just been deleted. */
1182                 prvResetNextTaskUnblockTime();
1183             }
1184         }
1185         taskEXIT_CRITICAL();
1186
1187         /* If the task is not deleting itself, call prvDeleteTCB from outside of
1188          * critical section. If a task deletes itself, prvDeleteTCB is called
1189          * from prvCheckTasksWaitingTermination which is called from Idle task. */
1190         if( pxTCB != pxCurrentTCB )
1191         {
1192             prvDeleteTCB( pxTCB );
1193         }
1194
1195         /* Force a reschedule if it is the currently running task that has just
1196          * been deleted. */
1197         if( xSchedulerRunning != pdFALSE )
1198         {
1199             if( pxTCB == pxCurrentTCB )
1200             {
1201                 configASSERT( uxSchedulerSuspended == 0 );
1202                 portYIELD_WITHIN_API();
1203             }
1204             else
1205             {
1206                 mtCOVERAGE_TEST_MARKER();
1207             }
1208         }
1209     }
1210
1211 #endif /* INCLUDE_vTaskDelete */
1212 /*-----------------------------------------------------------*/
1213
1214 #if ( INCLUDE_xTaskDelayUntil == 1 )
1215
1216     BaseType_t xTaskDelayUntil( TickType_t * const pxPreviousWakeTime,
1217                                 const TickType_t xTimeIncrement )
1218     {
1219         TickType_t xTimeToWake;
1220         BaseType_t xAlreadyYielded, xShouldDelay = pdFALSE;
1221
1222         configASSERT( pxPreviousWakeTime );
1223         configASSERT( ( xTimeIncrement > 0U ) );
1224         configASSERT( uxSchedulerSuspended == 0 );
1225
1226         vTaskSuspendAll();
1227         {
1228             /* Minor optimisation.  The tick count cannot change in this
1229              * block. */
1230             const TickType_t xConstTickCount = xTickCount;
1231
1232             /* Generate the tick time at which the task wants to wake. */
1233             xTimeToWake = *pxPreviousWakeTime + xTimeIncrement;
1234
1235             if( xConstTickCount < *pxPreviousWakeTime )
1236             {
1237                 /* The tick count has overflowed since this function was
1238                  * lasted called.  In this case the only time we should ever
1239                  * actually delay is if the wake time has also  overflowed,
1240                  * and the wake time is greater than the tick time.  When this
1241                  * is the case it is as if neither time had overflowed. */
1242                 if( ( xTimeToWake < *pxPreviousWakeTime ) && ( xTimeToWake > xConstTickCount ) )
1243                 {
1244                     xShouldDelay = pdTRUE;
1245                 }
1246                 else
1247                 {
1248                     mtCOVERAGE_TEST_MARKER();
1249                 }
1250             }
1251             else
1252             {
1253                 /* The tick time has not overflowed.  In this case we will
1254                  * delay if either the wake time has overflowed, and/or the
1255                  * tick time is less than the wake time. */
1256                 if( ( xTimeToWake < *pxPreviousWakeTime ) || ( xTimeToWake > xConstTickCount ) )
1257                 {
1258                     xShouldDelay = pdTRUE;
1259                 }
1260                 else
1261                 {
1262                     mtCOVERAGE_TEST_MARKER();
1263                 }
1264             }
1265
1266             /* Update the wake time ready for the next call. */
1267             *pxPreviousWakeTime = xTimeToWake;
1268
1269             if( xShouldDelay != pdFALSE )
1270             {
1271                 traceTASK_DELAY_UNTIL( xTimeToWake );
1272
1273                 /* prvAddCurrentTaskToDelayedList() needs the block time, not
1274                  * the time to wake, so subtract the current tick count. */
1275                 prvAddCurrentTaskToDelayedList( xTimeToWake - xConstTickCount, pdFALSE );
1276             }
1277             else
1278             {
1279                 mtCOVERAGE_TEST_MARKER();
1280             }
1281         }
1282         xAlreadyYielded = xTaskResumeAll();
1283
1284         /* Force a reschedule if xTaskResumeAll has not already done so, we may
1285          * have put ourselves to sleep. */
1286         if( xAlreadyYielded == pdFALSE )
1287         {
1288             portYIELD_WITHIN_API();
1289         }
1290         else
1291         {
1292             mtCOVERAGE_TEST_MARKER();
1293         }
1294
1295         return xShouldDelay;
1296     }
1297
1298 #endif /* INCLUDE_xTaskDelayUntil */
1299 /*-----------------------------------------------------------*/
1300
1301 #if ( INCLUDE_vTaskDelay == 1 )
1302
1303     void vTaskDelay( const TickType_t xTicksToDelay )
1304     {
1305         BaseType_t xAlreadyYielded = pdFALSE;
1306
1307         /* A delay time of zero just forces a reschedule. */
1308         if( xTicksToDelay > ( TickType_t ) 0U )
1309         {
1310             configASSERT( uxSchedulerSuspended == 0 );
1311             vTaskSuspendAll();
1312             {
1313                 traceTASK_DELAY();
1314
1315                 /* A task that is removed from the event list while the
1316                  * scheduler is suspended will not get placed in the ready
1317                  * list or removed from the blocked list until the scheduler
1318                  * is resumed.
1319                  *
1320                  * This task cannot be in an event list as it is the currently
1321                  * executing task. */
1322                 prvAddCurrentTaskToDelayedList( xTicksToDelay, pdFALSE );
1323             }
1324             xAlreadyYielded = xTaskResumeAll();
1325         }
1326         else
1327         {
1328             mtCOVERAGE_TEST_MARKER();
1329         }
1330
1331         /* Force a reschedule if xTaskResumeAll has not already done so, we may
1332          * have put ourselves to sleep. */
1333         if( xAlreadyYielded == pdFALSE )
1334         {
1335             portYIELD_WITHIN_API();
1336         }
1337         else
1338         {
1339             mtCOVERAGE_TEST_MARKER();
1340         }
1341     }
1342
1343 #endif /* INCLUDE_vTaskDelay */
1344 /*-----------------------------------------------------------*/
1345
1346 #if ( ( INCLUDE_eTaskGetState == 1 ) || ( configUSE_TRACE_FACILITY == 1 ) || ( INCLUDE_xTaskAbortDelay == 1 ) )
1347
1348     eTaskState eTaskGetState( TaskHandle_t xTask )
1349     {
1350         eTaskState eReturn;
1351         List_t const * pxStateList;
1352         List_t const * pxDelayedList;
1353         List_t const * pxOverflowedDelayedList;
1354         const TCB_t * const pxTCB = xTask;
1355
1356         configASSERT( pxTCB );
1357
1358         if( pxTCB == pxCurrentTCB )
1359         {
1360             /* The task calling this function is querying its own state. */
1361             eReturn = eRunning;
1362         }
1363         else
1364         {
1365             taskENTER_CRITICAL();
1366             {
1367                 pxStateList = listLIST_ITEM_CONTAINER( &( pxTCB->xStateListItem ) );
1368                 pxDelayedList = pxDelayedTaskList;
1369                 pxOverflowedDelayedList = pxOverflowDelayedTaskList;
1370             }
1371             taskEXIT_CRITICAL();
1372
1373             if( ( pxStateList == pxDelayedList ) || ( pxStateList == pxOverflowedDelayedList ) )
1374             {
1375                 /* The task being queried is referenced from one of the Blocked
1376                  * lists. */
1377                 eReturn = eBlocked;
1378             }
1379
1380             #if ( INCLUDE_vTaskSuspend == 1 )
1381                 else if( pxStateList == &xSuspendedTaskList )
1382                 {
1383                     /* The task being queried is referenced from the suspended
1384                      * list.  Is it genuinely suspended or is it blocked
1385                      * indefinitely? */
1386                     if( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) == NULL )
1387                     {
1388                         #if ( configUSE_TASK_NOTIFICATIONS == 1 )
1389                         {
1390                             BaseType_t x;
1391
1392                             /* The task does not appear on the event list item of
1393                              * and of the RTOS objects, but could still be in the
1394                              * blocked state if it is waiting on its notification
1395                              * rather than waiting on an object.  If not, is
1396                              * suspended. */
1397                             eReturn = eSuspended;
1398
1399                             for( x = 0; x < configTASK_NOTIFICATION_ARRAY_ENTRIES; x++ )
1400                             {
1401                                 if( pxTCB->ucNotifyState[ x ] == taskWAITING_NOTIFICATION )
1402                                 {
1403                                     eReturn = eBlocked;
1404                                     break;
1405                                 }
1406                             }
1407                         }
1408                         #else /* if ( configUSE_TASK_NOTIFICATIONS == 1 ) */
1409                         {
1410                             eReturn = eSuspended;
1411                         }
1412                         #endif /* if ( configUSE_TASK_NOTIFICATIONS == 1 ) */
1413                     }
1414                     else
1415                     {
1416                         eReturn = eBlocked;
1417                     }
1418                 }
1419             #endif /* if ( INCLUDE_vTaskSuspend == 1 ) */
1420
1421             #if ( INCLUDE_vTaskDelete == 1 )
1422                 else if( ( pxStateList == &xTasksWaitingTermination ) || ( pxStateList == NULL ) )
1423                 {
1424                     /* The task being queried is referenced from the deleted
1425                      * tasks list, or it is not referenced from any lists at
1426                      * all. */
1427                     eReturn = eDeleted;
1428                 }
1429             #endif
1430
1431             else /*lint !e525 Negative indentation is intended to make use of pre-processor clearer. */
1432             {
1433                 /* If the task is not in any other state, it must be in the
1434                  * Ready (including pending ready) state. */
1435                 eReturn = eReady;
1436             }
1437         }
1438
1439         return eReturn;
1440     } /*lint !e818 xTask cannot be a pointer to const because it is a typedef. */
1441
1442 #endif /* INCLUDE_eTaskGetState */
1443 /*-----------------------------------------------------------*/
1444
1445 #if ( INCLUDE_uxTaskPriorityGet == 1 )
1446
1447     UBaseType_t uxTaskPriorityGet( const TaskHandle_t xTask )
1448     {
1449         TCB_t const * pxTCB;
1450         UBaseType_t uxReturn;
1451
1452         taskENTER_CRITICAL();
1453         {
1454             /* If null is passed in here then it is the priority of the task
1455              * that called uxTaskPriorityGet() that is being queried. */
1456             pxTCB = prvGetTCBFromHandle( xTask );
1457             uxReturn = pxTCB->uxPriority;
1458         }
1459         taskEXIT_CRITICAL();
1460
1461         return uxReturn;
1462     }
1463
1464 #endif /* INCLUDE_uxTaskPriorityGet */
1465 /*-----------------------------------------------------------*/
1466
1467 #if ( INCLUDE_uxTaskPriorityGet == 1 )
1468
1469     UBaseType_t uxTaskPriorityGetFromISR( const TaskHandle_t xTask )
1470     {
1471         TCB_t const * pxTCB;
1472         UBaseType_t uxReturn, uxSavedInterruptState;
1473
1474         /* RTOS ports that support interrupt nesting have the concept of a
1475          * maximum  system call (or maximum API call) interrupt priority.
1476          * Interrupts that are  above the maximum system call priority are keep
1477          * permanently enabled, even when the RTOS kernel is in a critical section,
1478          * but cannot make any calls to FreeRTOS API functions.  If configASSERT()
1479          * is defined in FreeRTOSConfig.h then
1480          * portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion
1481          * failure if a FreeRTOS API function is called from an interrupt that has
1482          * been assigned a priority above the configured maximum system call
1483          * priority.  Only FreeRTOS functions that end in FromISR can be called
1484          * from interrupts  that have been assigned a priority at or (logically)
1485          * below the maximum system call interrupt priority.  FreeRTOS maintains a
1486          * separate interrupt safe API to ensure interrupt entry is as fast and as
1487          * simple as possible.  More information (albeit Cortex-M specific) is
1488          * provided on the following link:
1489          * https://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html */
1490         portASSERT_IF_INTERRUPT_PRIORITY_INVALID();
1491
1492         uxSavedInterruptState = portSET_INTERRUPT_MASK_FROM_ISR();
1493         {
1494             /* If null is passed in here then it is the priority of the calling
1495              * task that is being queried. */
1496             pxTCB = prvGetTCBFromHandle( xTask );
1497             uxReturn = pxTCB->uxPriority;
1498         }
1499         portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptState );
1500
1501         return uxReturn;
1502     }
1503
1504 #endif /* INCLUDE_uxTaskPriorityGet */
1505 /*-----------------------------------------------------------*/
1506
1507 #if ( INCLUDE_vTaskPrioritySet == 1 )
1508
1509     void vTaskPrioritySet( TaskHandle_t xTask,
1510                            UBaseType_t uxNewPriority )
1511     {
1512         TCB_t * pxTCB;
1513         UBaseType_t uxCurrentBasePriority, uxPriorityUsedOnEntry;
1514         BaseType_t xYieldRequired = pdFALSE;
1515
1516         configASSERT( uxNewPriority < configMAX_PRIORITIES );
1517
1518         /* Ensure the new priority is valid. */
1519         if( uxNewPriority >= ( UBaseType_t ) configMAX_PRIORITIES )
1520         {
1521             uxNewPriority = ( UBaseType_t ) configMAX_PRIORITIES - ( UBaseType_t ) 1U;
1522         }
1523         else
1524         {
1525             mtCOVERAGE_TEST_MARKER();
1526         }
1527
1528         taskENTER_CRITICAL();
1529         {
1530             /* If null is passed in here then it is the priority of the calling
1531              * task that is being changed. */
1532             pxTCB = prvGetTCBFromHandle( xTask );
1533
1534             traceTASK_PRIORITY_SET( pxTCB, uxNewPriority );
1535
1536             #if ( configUSE_MUTEXES == 1 )
1537             {
1538                 uxCurrentBasePriority = pxTCB->uxBasePriority;
1539             }
1540             #else
1541             {
1542                 uxCurrentBasePriority = pxTCB->uxPriority;
1543             }
1544             #endif
1545
1546             if( uxCurrentBasePriority != uxNewPriority )
1547             {
1548                 /* The priority change may have readied a task of higher
1549                  * priority than the calling task. */
1550                 if( uxNewPriority > uxCurrentBasePriority )
1551                 {
1552                     if( pxTCB != pxCurrentTCB )
1553                     {
1554                         /* The priority of a task other than the currently
1555                          * running task is being raised.  Is the priority being
1556                          * raised above that of the running task? */
1557                         if( uxNewPriority > pxCurrentTCB->uxPriority )
1558                         {
1559                             xYieldRequired = pdTRUE;
1560                         }
1561                         else
1562                         {
1563                             mtCOVERAGE_TEST_MARKER();
1564                         }
1565                     }
1566                     else
1567                     {
1568                         /* The priority of the running task is being raised,
1569                          * but the running task must already be the highest
1570                          * priority task able to run so no yield is required. */
1571                     }
1572                 }
1573                 else if( pxTCB == pxCurrentTCB )
1574                 {
1575                     /* Setting the priority of the running task down means
1576                      * there may now be another task of higher priority that
1577                      * is ready to execute. */
1578                     xYieldRequired = pdTRUE;
1579                 }
1580                 else
1581                 {
1582                     /* Setting the priority of any other task down does not
1583                      * require a yield as the running task must be above the
1584                      * new priority of the task being modified. */
1585                 }
1586
1587                 /* Remember the ready list the task might be referenced from
1588                  * before its uxPriority member is changed so the
1589                  * taskRESET_READY_PRIORITY() macro can function correctly. */
1590                 uxPriorityUsedOnEntry = pxTCB->uxPriority;
1591
1592                 #if ( configUSE_MUTEXES == 1 )
1593                 {
1594                     /* Only change the priority being used if the task is not
1595                      * currently using an inherited priority. */
1596                     if( pxTCB->uxBasePriority == pxTCB->uxPriority )
1597                     {
1598                         pxTCB->uxPriority = uxNewPriority;
1599                     }
1600                     else
1601                     {
1602                         mtCOVERAGE_TEST_MARKER();
1603                     }
1604
1605                     /* The base priority gets set whatever. */
1606                     pxTCB->uxBasePriority = uxNewPriority;
1607                 }
1608                 #else /* if ( configUSE_MUTEXES == 1 ) */
1609                 {
1610                     pxTCB->uxPriority = uxNewPriority;
1611                 }
1612                 #endif /* if ( configUSE_MUTEXES == 1 ) */
1613
1614                 /* Only reset the event list item value if the value is not
1615                  * being used for anything else. */
1616                 if( ( listGET_LIST_ITEM_VALUE( &( pxTCB->xEventListItem ) ) & taskEVENT_LIST_ITEM_VALUE_IN_USE ) == 0UL )
1617                 {
1618                     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. */
1619                 }
1620                 else
1621                 {
1622                     mtCOVERAGE_TEST_MARKER();
1623                 }
1624
1625                 /* If the task is in the blocked or suspended list we need do
1626                  * nothing more than change its priority variable. However, if
1627                  * the task is in a ready list it needs to be removed and placed
1628                  * in the list appropriate to its new priority. */
1629                 if( listIS_CONTAINED_WITHIN( &( pxReadyTasksLists[ uxPriorityUsedOnEntry ] ), &( pxTCB->xStateListItem ) ) != pdFALSE )
1630                 {
1631                     /* The task is currently in its ready list - remove before
1632                      * adding it to its new ready list.  As we are in a critical
1633                      * section we can do this even if the scheduler is suspended. */
1634                     if( uxListRemove( &( pxTCB->xStateListItem ) ) == ( UBaseType_t ) 0 )
1635                     {
1636                         /* It is known that the task is in its ready list so
1637                          * there is no need to check again and the port level
1638                          * reset macro can be called directly. */
1639                         portRESET_READY_PRIORITY( uxPriorityUsedOnEntry, uxTopReadyPriority );
1640                     }
1641                     else
1642                     {
1643                         mtCOVERAGE_TEST_MARKER();
1644                     }
1645
1646                     prvAddTaskToReadyList( pxTCB );
1647                 }
1648                 else
1649                 {
1650                     mtCOVERAGE_TEST_MARKER();
1651                 }
1652
1653                 if( xYieldRequired != pdFALSE )
1654                 {
1655                     taskYIELD_IF_USING_PREEMPTION();
1656                 }
1657                 else
1658                 {
1659                     mtCOVERAGE_TEST_MARKER();
1660                 }
1661
1662                 /* Remove compiler warning about unused variables when the port
1663                  * optimised task selection is not being used. */
1664                 ( void ) uxPriorityUsedOnEntry;
1665             }
1666         }
1667         taskEXIT_CRITICAL();
1668     }
1669
1670 #endif /* INCLUDE_vTaskPrioritySet */
1671 /*-----------------------------------------------------------*/
1672
1673 #if ( INCLUDE_vTaskSuspend == 1 )
1674
1675     void vTaskSuspend( TaskHandle_t xTaskToSuspend )
1676     {
1677         TCB_t * pxTCB;
1678
1679         taskENTER_CRITICAL();
1680         {
1681             /* If null is passed in here then it is the running task that is
1682              * being suspended. */
1683             pxTCB = prvGetTCBFromHandle( xTaskToSuspend );
1684
1685             traceTASK_SUSPEND( pxTCB );
1686
1687             /* Remove task from the ready/delayed list and place in the
1688              * suspended list. */
1689             if( uxListRemove( &( pxTCB->xStateListItem ) ) == ( UBaseType_t ) 0 )
1690             {
1691                 taskRESET_READY_PRIORITY( pxTCB->uxPriority );
1692             }
1693             else
1694             {
1695                 mtCOVERAGE_TEST_MARKER();
1696             }
1697
1698             /* Is the task waiting on an event also? */
1699             if( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) != NULL )
1700             {
1701                 ( void ) uxListRemove( &( pxTCB->xEventListItem ) );
1702             }
1703             else
1704             {
1705                 mtCOVERAGE_TEST_MARKER();
1706             }
1707
1708             vListInsertEnd( &xSuspendedTaskList, &( pxTCB->xStateListItem ) );
1709
1710             #if ( configUSE_TASK_NOTIFICATIONS == 1 )
1711             {
1712                 BaseType_t x;
1713
1714                 for( x = 0; x < configTASK_NOTIFICATION_ARRAY_ENTRIES; x++ )
1715                 {
1716                     if( pxTCB->ucNotifyState[ x ] == taskWAITING_NOTIFICATION )
1717                     {
1718                         /* The task was blocked to wait for a notification, but is
1719                          * now suspended, so no notification was received. */
1720                         pxTCB->ucNotifyState[ x ] = taskNOT_WAITING_NOTIFICATION;
1721                     }
1722                 }
1723             }
1724             #endif /* if ( configUSE_TASK_NOTIFICATIONS == 1 ) */
1725         }
1726         taskEXIT_CRITICAL();
1727
1728         if( xSchedulerRunning != pdFALSE )
1729         {
1730             /* Reset the next expected unblock time in case it referred to the
1731              * task that is now in the Suspended state. */
1732             taskENTER_CRITICAL();
1733             {
1734                 prvResetNextTaskUnblockTime();
1735             }
1736             taskEXIT_CRITICAL();
1737         }
1738         else
1739         {
1740             mtCOVERAGE_TEST_MARKER();
1741         }
1742
1743         if( pxTCB == pxCurrentTCB )
1744         {
1745             if( xSchedulerRunning != pdFALSE )
1746             {
1747                 /* The current task has just been suspended. */
1748                 configASSERT( uxSchedulerSuspended == 0 );
1749                 portYIELD_WITHIN_API();
1750             }
1751             else
1752             {
1753                 /* The scheduler is not running, but the task that was pointed
1754                  * to by pxCurrentTCB has just been suspended and pxCurrentTCB
1755                  * must be adjusted to point to a different task. */
1756                 if( listCURRENT_LIST_LENGTH( &xSuspendedTaskList ) == uxCurrentNumberOfTasks ) /*lint !e931 Right has no side effect, just volatile. */
1757                 {
1758                     /* No other tasks are ready, so set pxCurrentTCB back to
1759                      * NULL so when the next task is created pxCurrentTCB will
1760                      * be set to point to it no matter what its relative priority
1761                      * is. */
1762                     pxCurrentTCB = NULL;
1763                 }
1764                 else
1765                 {
1766                     vTaskSwitchContext();
1767                 }
1768             }
1769         }
1770         else
1771         {
1772             mtCOVERAGE_TEST_MARKER();
1773         }
1774     }
1775
1776 #endif /* INCLUDE_vTaskSuspend */
1777 /*-----------------------------------------------------------*/
1778
1779 #if ( INCLUDE_vTaskSuspend == 1 )
1780
1781     static BaseType_t prvTaskIsTaskSuspended( const TaskHandle_t xTask )
1782     {
1783         BaseType_t xReturn = pdFALSE;
1784         const TCB_t * const pxTCB = xTask;
1785
1786         /* Accesses xPendingReadyList so must be called from a critical
1787          * section. */
1788
1789         /* It does not make sense to check if the calling task is suspended. */
1790         configASSERT( xTask );
1791
1792         /* Is the task being resumed actually in the suspended list? */
1793         if( listIS_CONTAINED_WITHIN( &xSuspendedTaskList, &( pxTCB->xStateListItem ) ) != pdFALSE )
1794         {
1795             /* Has the task already been resumed from within an ISR? */
1796             if( listIS_CONTAINED_WITHIN( &xPendingReadyList, &( pxTCB->xEventListItem ) ) == pdFALSE )
1797             {
1798                 /* Is it in the suspended list because it is in the Suspended
1799                  * state, or because is is blocked with no timeout? */
1800                 if( listIS_CONTAINED_WITHIN( NULL, &( pxTCB->xEventListItem ) ) != pdFALSE ) /*lint !e961.  The cast is only redundant when NULL is used. */
1801                 {
1802                     xReturn = pdTRUE;
1803                 }
1804                 else
1805                 {
1806                     mtCOVERAGE_TEST_MARKER();
1807                 }
1808             }
1809             else
1810             {
1811                 mtCOVERAGE_TEST_MARKER();
1812             }
1813         }
1814         else
1815         {
1816             mtCOVERAGE_TEST_MARKER();
1817         }
1818
1819         return xReturn;
1820     } /*lint !e818 xTask cannot be a pointer to const because it is a typedef. */
1821
1822 #endif /* INCLUDE_vTaskSuspend */
1823 /*-----------------------------------------------------------*/
1824
1825 #if ( INCLUDE_vTaskSuspend == 1 )
1826
1827     void vTaskResume( TaskHandle_t xTaskToResume )
1828     {
1829         TCB_t * const pxTCB = xTaskToResume;
1830
1831         /* It does not make sense to resume the calling task. */
1832         configASSERT( xTaskToResume );
1833
1834         /* The parameter cannot be NULL as it is impossible to resume the
1835          * currently executing task. */
1836         if( ( pxTCB != pxCurrentTCB ) && ( pxTCB != NULL ) )
1837         {
1838             taskENTER_CRITICAL();
1839             {
1840                 if( prvTaskIsTaskSuspended( pxTCB ) != pdFALSE )
1841                 {
1842                     traceTASK_RESUME( pxTCB );
1843
1844                     /* The ready list can be accessed even if the scheduler is
1845                      * suspended because this is inside a critical section. */
1846                     ( void ) uxListRemove( &( pxTCB->xStateListItem ) );
1847                     prvAddTaskToReadyList( pxTCB );
1848
1849                     /* A higher priority task may have just been resumed. */
1850                     if( pxTCB->uxPriority > pxCurrentTCB->uxPriority )
1851                     {
1852                         /* This yield may not cause the task just resumed to run,
1853                          * but will leave the lists in the correct state for the
1854                          * next yield. */
1855                         taskYIELD_IF_USING_PREEMPTION();
1856                     }
1857                     else
1858                     {
1859                         mtCOVERAGE_TEST_MARKER();
1860                     }
1861                 }
1862                 else
1863                 {
1864                     mtCOVERAGE_TEST_MARKER();
1865                 }
1866             }
1867             taskEXIT_CRITICAL();
1868         }
1869         else
1870         {
1871             mtCOVERAGE_TEST_MARKER();
1872         }
1873     }
1874
1875 #endif /* INCLUDE_vTaskSuspend */
1876
1877 /*-----------------------------------------------------------*/
1878
1879 #if ( ( INCLUDE_xTaskResumeFromISR == 1 ) && ( INCLUDE_vTaskSuspend == 1 ) )
1880
1881     BaseType_t xTaskResumeFromISR( TaskHandle_t xTaskToResume )
1882     {
1883         BaseType_t xYieldRequired = pdFALSE;
1884         TCB_t * const pxTCB = xTaskToResume;
1885         UBaseType_t uxSavedInterruptStatus;
1886
1887         configASSERT( xTaskToResume );
1888
1889         /* RTOS ports that support interrupt nesting have the concept of a
1890          * maximum  system call (or maximum API call) interrupt priority.
1891          * Interrupts that are  above the maximum system call priority are keep
1892          * permanently enabled, even when the RTOS kernel is in a critical section,
1893          * but cannot make any calls to FreeRTOS API functions.  If configASSERT()
1894          * is defined in FreeRTOSConfig.h then
1895          * portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion
1896          * failure if a FreeRTOS API function is called from an interrupt that has
1897          * been assigned a priority above the configured maximum system call
1898          * priority.  Only FreeRTOS functions that end in FromISR can be called
1899          * from interrupts  that have been assigned a priority at or (logically)
1900          * below the maximum system call interrupt priority.  FreeRTOS maintains a
1901          * separate interrupt safe API to ensure interrupt entry is as fast and as
1902          * simple as possible.  More information (albeit Cortex-M specific) is
1903          * provided on the following link:
1904          * https://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html */
1905         portASSERT_IF_INTERRUPT_PRIORITY_INVALID();
1906
1907         uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR();
1908         {
1909             if( prvTaskIsTaskSuspended( pxTCB ) != pdFALSE )
1910             {
1911                 traceTASK_RESUME_FROM_ISR( pxTCB );
1912
1913                 /* Check the ready lists can be accessed. */
1914                 if( uxSchedulerSuspended == ( UBaseType_t ) pdFALSE )
1915                 {
1916                     /* Ready lists can be accessed so move the task from the
1917                      * suspended list to the ready list directly. */
1918                     if( pxTCB->uxPriority > pxCurrentTCB->uxPriority )
1919                     {
1920                         xYieldRequired = pdTRUE;
1921
1922                         /* Mark that a yield is pending in case the user is not
1923                          * using the return value to initiate a context switch
1924                          * from the ISR using portYIELD_FROM_ISR. */
1925                         xYieldPending = pdTRUE;
1926                     }
1927                     else
1928                     {
1929                         mtCOVERAGE_TEST_MARKER();
1930                     }
1931
1932                     ( void ) uxListRemove( &( pxTCB->xStateListItem ) );
1933                     prvAddTaskToReadyList( pxTCB );
1934                 }
1935                 else
1936                 {
1937                     /* The delayed or ready lists cannot be accessed so the task
1938                      * is held in the pending ready list until the scheduler is
1939                      * unsuspended. */
1940                     vListInsertEnd( &( xPendingReadyList ), &( pxTCB->xEventListItem ) );
1941                 }
1942             }
1943             else
1944             {
1945                 mtCOVERAGE_TEST_MARKER();
1946             }
1947         }
1948         portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus );
1949
1950         return xYieldRequired;
1951     }
1952
1953 #endif /* ( ( INCLUDE_xTaskResumeFromISR == 1 ) && ( INCLUDE_vTaskSuspend == 1 ) ) */
1954 /*-----------------------------------------------------------*/
1955
1956 void vTaskStartScheduler( void )
1957 {
1958     BaseType_t xReturn;
1959
1960     /* Add the idle task at the lowest priority. */
1961     #if ( configSUPPORT_STATIC_ALLOCATION == 1 )
1962     {
1963         StaticTask_t * pxIdleTaskTCBBuffer = NULL;
1964         StackType_t * pxIdleTaskStackBuffer = NULL;
1965         uint32_t ulIdleTaskStackSize;
1966
1967         /* The Idle task is created using user provided RAM - obtain the
1968          * address of the RAM then create the idle task. */
1969         vApplicationGetIdleTaskMemory( &pxIdleTaskTCBBuffer, &pxIdleTaskStackBuffer, &ulIdleTaskStackSize );
1970         xIdleTaskHandle = xTaskCreateStatic( prvIdleTask,
1971                                              configIDLE_TASK_NAME,
1972                                              ulIdleTaskStackSize,
1973                                              ( void * ) NULL,       /*lint !e961.  The cast is not redundant for all compilers. */
1974                                              portPRIVILEGE_BIT,     /* In effect ( tskIDLE_PRIORITY | portPRIVILEGE_BIT ), but tskIDLE_PRIORITY is zero. */
1975                                              pxIdleTaskStackBuffer,
1976                                              pxIdleTaskTCBBuffer ); /*lint !e961 MISRA exception, justified as it is not a redundant explicit cast to all supported compilers. */
1977
1978         if( xIdleTaskHandle != NULL )
1979         {
1980             xReturn = pdPASS;
1981         }
1982         else
1983         {
1984             xReturn = pdFAIL;
1985         }
1986     }
1987     #else /* if ( configSUPPORT_STATIC_ALLOCATION == 1 ) */
1988     {
1989         /* The Idle task is being created using dynamically allocated RAM. */
1990         xReturn = xTaskCreate( prvIdleTask,
1991                                configIDLE_TASK_NAME,
1992                                configMINIMAL_STACK_SIZE,
1993                                ( void * ) NULL,
1994                                portPRIVILEGE_BIT,  /* In effect ( tskIDLE_PRIORITY | portPRIVILEGE_BIT ), but tskIDLE_PRIORITY is zero. */
1995                                &xIdleTaskHandle ); /*lint !e961 MISRA exception, justified as it is not a redundant explicit cast to all supported compilers. */
1996     }
1997     #endif /* configSUPPORT_STATIC_ALLOCATION */
1998
1999     #if ( configUSE_TIMERS == 1 )
2000     {
2001         if( xReturn == pdPASS )
2002         {
2003             xReturn = xTimerCreateTimerTask();
2004         }
2005         else
2006         {
2007             mtCOVERAGE_TEST_MARKER();
2008         }
2009     }
2010     #endif /* configUSE_TIMERS */
2011
2012     if( xReturn == pdPASS )
2013     {
2014         /* freertos_tasks_c_additions_init() should only be called if the user
2015          * definable macro FREERTOS_TASKS_C_ADDITIONS_INIT() is defined, as that is
2016          * the only macro called by the function. */
2017         #ifdef FREERTOS_TASKS_C_ADDITIONS_INIT
2018         {
2019             freertos_tasks_c_additions_init();
2020         }
2021         #endif
2022
2023         /* Interrupts are turned off here, to ensure a tick does not occur
2024          * before or during the call to xPortStartScheduler().  The stacks of
2025          * the created tasks contain a status word with interrupts switched on
2026          * so interrupts will automatically get re-enabled when the first task
2027          * starts to run. */
2028         portDISABLE_INTERRUPTS();
2029
2030         #if ( ( configUSE_NEWLIB_REENTRANT == 1 ) || ( configUSE_C_RUNTIME_TLS_SUPPORT == 1 ) )
2031         {
2032             /* Switch C-Runtime's TLS Block to point to the TLS
2033              * block specific to the task that will run first. */
2034             configSET_TLS_BLOCK( pxCurrentTCB->xTLSBlock );
2035         }
2036         #endif
2037
2038         xNextTaskUnblockTime = portMAX_DELAY;
2039         xSchedulerRunning = pdTRUE;
2040         xTickCount = ( TickType_t ) configINITIAL_TICK_COUNT;
2041
2042         /* If configGENERATE_RUN_TIME_STATS is defined then the following
2043          * macro must be defined to configure the timer/counter used to generate
2044          * the run time counter time base.   NOTE:  If configGENERATE_RUN_TIME_STATS
2045          * is set to 0 and the following line fails to build then ensure you do not
2046          * have portCONFIGURE_TIMER_FOR_RUN_TIME_STATS() defined in your
2047          * FreeRTOSConfig.h file. */
2048         portCONFIGURE_TIMER_FOR_RUN_TIME_STATS();
2049
2050         traceTASK_SWITCHED_IN();
2051
2052         /* Setting up the timer tick is hardware specific and thus in the
2053          * portable interface. */
2054         xPortStartScheduler();
2055
2056         /* In most cases, xPortStartScheduler() will not return. If it
2057          * returns pdTRUE then there was not enough heap memory available
2058          * to create either the Idle or the Timer task. If it returned
2059          * pdFALSE, then the application called xTaskEndScheduler().
2060          * Most ports don't implement xTaskEndScheduler() as there is
2061          * nothing to return to. */
2062     }
2063     else
2064     {
2065         /* This line will only be reached if the kernel could not be started,
2066          * because there was not enough FreeRTOS heap to create the idle task
2067          * or the timer task. */
2068         configASSERT( xReturn != errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY );
2069     }
2070
2071     /* Prevent compiler warnings if INCLUDE_xTaskGetIdleTaskHandle is set to 0,
2072      * meaning xIdleTaskHandle is not used anywhere else. */
2073     ( void ) xIdleTaskHandle;
2074
2075     /* OpenOCD makes use of uxTopUsedPriority for thread debugging. Prevent uxTopUsedPriority
2076      * from getting optimized out as it is no longer used by the kernel. */
2077     ( void ) uxTopUsedPriority;
2078 }
2079 /*-----------------------------------------------------------*/
2080
2081 void vTaskEndScheduler( void )
2082 {
2083     /* Stop the scheduler interrupts and call the portable scheduler end
2084      * routine so the original ISRs can be restored if necessary.  The port
2085      * layer must ensure interrupts enable  bit is left in the correct state. */
2086     portDISABLE_INTERRUPTS();
2087     xSchedulerRunning = pdFALSE;
2088     vPortEndScheduler();
2089 }
2090 /*----------------------------------------------------------*/
2091
2092 void vTaskSuspendAll( void )
2093 {
2094     /* A critical section is not required as the variable is of type
2095      * BaseType_t.  Please read Richard Barry's reply in the following link to a
2096      * post in the FreeRTOS support forum before reporting this as a bug! -
2097      * https://goo.gl/wu4acr */
2098
2099     /* portSOFTWARE_BARRIER() is only implemented for emulated/simulated ports that
2100      * do not otherwise exhibit real time behaviour. */
2101     portSOFTWARE_BARRIER();
2102
2103     /* The scheduler is suspended if uxSchedulerSuspended is non-zero.  An increment
2104      * is used to allow calls to vTaskSuspendAll() to nest. */
2105     ++uxSchedulerSuspended;
2106
2107     /* Enforces ordering for ports and optimised compilers that may otherwise place
2108      * the above increment elsewhere. */
2109     portMEMORY_BARRIER();
2110 }
2111 /*----------------------------------------------------------*/
2112
2113 #if ( configUSE_TICKLESS_IDLE != 0 )
2114
2115     static TickType_t prvGetExpectedIdleTime( void )
2116     {
2117         TickType_t xReturn;
2118         UBaseType_t uxHigherPriorityReadyTasks = pdFALSE;
2119
2120         /* uxHigherPriorityReadyTasks takes care of the case where
2121          * configUSE_PREEMPTION is 0, so there may be tasks above the idle priority
2122          * task that are in the Ready state, even though the idle task is
2123          * running. */
2124         #if ( configUSE_PORT_OPTIMISED_TASK_SELECTION == 0 )
2125         {
2126             if( uxTopReadyPriority > tskIDLE_PRIORITY )
2127             {
2128                 uxHigherPriorityReadyTasks = pdTRUE;
2129             }
2130         }
2131         #else
2132         {
2133             const UBaseType_t uxLeastSignificantBit = ( UBaseType_t ) 0x01;
2134
2135             /* When port optimised task selection is used the uxTopReadyPriority
2136              * variable is used as a bit map.  If bits other than the least
2137              * significant bit are set then there are tasks that have a priority
2138              * above the idle priority that are in the Ready state.  This takes
2139              * care of the case where the co-operative scheduler is in use. */
2140             if( uxTopReadyPriority > uxLeastSignificantBit )
2141             {
2142                 uxHigherPriorityReadyTasks = pdTRUE;
2143             }
2144         }
2145         #endif /* if ( configUSE_PORT_OPTIMISED_TASK_SELECTION == 0 ) */
2146
2147         if( pxCurrentTCB->uxPriority > tskIDLE_PRIORITY )
2148         {
2149             xReturn = 0;
2150         }
2151         else if( listCURRENT_LIST_LENGTH( &( pxReadyTasksLists[ tskIDLE_PRIORITY ] ) ) > 1 )
2152         {
2153             /* There are other idle priority tasks in the ready state.  If
2154              * time slicing is used then the very next tick interrupt must be
2155              * processed. */
2156             xReturn = 0;
2157         }
2158         else if( uxHigherPriorityReadyTasks != pdFALSE )
2159         {
2160             /* There are tasks in the Ready state that have a priority above the
2161              * idle priority.  This path can only be reached if
2162              * configUSE_PREEMPTION is 0. */
2163             xReturn = 0;
2164         }
2165         else
2166         {
2167             xReturn = xNextTaskUnblockTime - xTickCount;
2168         }
2169
2170         return xReturn;
2171     }
2172
2173 #endif /* configUSE_TICKLESS_IDLE */
2174 /*----------------------------------------------------------*/
2175
2176 BaseType_t xTaskResumeAll( void )
2177 {
2178     TCB_t * pxTCB = NULL;
2179     BaseType_t xAlreadyYielded = pdFALSE;
2180
2181     /* If uxSchedulerSuspended is zero then this function does not match a
2182      * previous call to vTaskSuspendAll(). */
2183     configASSERT( uxSchedulerSuspended );
2184
2185     /* It is possible that an ISR caused a task to be removed from an event
2186      * list while the scheduler was suspended.  If this was the case then the
2187      * removed task will have been added to the xPendingReadyList.  Once the
2188      * scheduler has been resumed it is safe to move all the pending ready
2189      * tasks from this list into their appropriate ready list. */
2190     taskENTER_CRITICAL();
2191     {
2192         --uxSchedulerSuspended;
2193
2194         if( uxSchedulerSuspended == ( UBaseType_t ) pdFALSE )
2195         {
2196             if( uxCurrentNumberOfTasks > ( UBaseType_t ) 0U )
2197             {
2198                 /* Move any readied tasks from the pending list into the
2199                  * appropriate ready list. */
2200                 while( listLIST_IS_EMPTY( &xPendingReadyList ) == pdFALSE )
2201                 {
2202                     pxTCB = listGET_OWNER_OF_HEAD_ENTRY( ( &xPendingReadyList ) ); /*lint !e9079 void * is used as this macro is used with timers too.  Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */
2203                     listREMOVE_ITEM( &( pxTCB->xEventListItem ) );
2204                     portMEMORY_BARRIER();
2205                     listREMOVE_ITEM( &( pxTCB->xStateListItem ) );
2206                     prvAddTaskToReadyList( pxTCB );
2207
2208                     /* If the moved task has a priority higher than the current
2209                      * task then a yield must be performed. */
2210                     if( pxTCB->uxPriority > pxCurrentTCB->uxPriority )
2211                     {
2212                         xYieldPending = pdTRUE;
2213                     }
2214                     else
2215                     {
2216                         mtCOVERAGE_TEST_MARKER();
2217                     }
2218                 }
2219
2220                 if( pxTCB != NULL )
2221                 {
2222                     /* A task was unblocked while the scheduler was suspended,
2223                      * which may have prevented the next unblock time from being
2224                      * re-calculated, in which case re-calculate it now.  Mainly
2225                      * important for low power tickless implementations, where
2226                      * this can prevent an unnecessary exit from low power
2227                      * state. */
2228                     prvResetNextTaskUnblockTime();
2229                 }
2230
2231                 /* If any ticks occurred while the scheduler was suspended then
2232                  * they should be processed now.  This ensures the tick count does
2233                  * not  slip, and that any delayed tasks are resumed at the correct
2234                  * time. */
2235                 {
2236                     TickType_t xPendedCounts = xPendedTicks; /* Non-volatile copy. */
2237
2238                     if( xPendedCounts > ( TickType_t ) 0U )
2239                     {
2240                         do
2241                         {
2242                             if( xTaskIncrementTick() != pdFALSE )
2243                             {
2244                                 xYieldPending = pdTRUE;
2245                             }
2246                             else
2247                             {
2248                                 mtCOVERAGE_TEST_MARKER();
2249                             }
2250
2251                             --xPendedCounts;
2252                         } while( xPendedCounts > ( TickType_t ) 0U );
2253
2254                         xPendedTicks = 0;
2255                     }
2256                     else
2257                     {
2258                         mtCOVERAGE_TEST_MARKER();
2259                     }
2260                 }
2261
2262                 if( xYieldPending != pdFALSE )
2263                 {
2264                     #if ( configUSE_PREEMPTION != 0 )
2265                     {
2266                         xAlreadyYielded = pdTRUE;
2267                     }
2268                     #endif
2269                     taskYIELD_IF_USING_PREEMPTION();
2270                 }
2271                 else
2272                 {
2273                     mtCOVERAGE_TEST_MARKER();
2274                 }
2275             }
2276         }
2277         else
2278         {
2279             mtCOVERAGE_TEST_MARKER();
2280         }
2281     }
2282     taskEXIT_CRITICAL();
2283
2284     return xAlreadyYielded;
2285 }
2286 /*-----------------------------------------------------------*/
2287
2288 TickType_t xTaskGetTickCount( void )
2289 {
2290     TickType_t xTicks;
2291
2292     /* Critical section required if running on a 16 bit processor. */
2293     portTICK_TYPE_ENTER_CRITICAL();
2294     {
2295         xTicks = xTickCount;
2296     }
2297     portTICK_TYPE_EXIT_CRITICAL();
2298
2299     return xTicks;
2300 }
2301 /*-----------------------------------------------------------*/
2302
2303 TickType_t xTaskGetTickCountFromISR( void )
2304 {
2305     TickType_t xReturn;
2306     UBaseType_t uxSavedInterruptStatus;
2307
2308     /* RTOS ports that support interrupt nesting have the concept of a maximum
2309      * system call (or maximum API call) interrupt priority.  Interrupts that are
2310      * above the maximum system call priority are kept permanently enabled, even
2311      * when the RTOS kernel is in a critical section, but cannot make any calls to
2312      * FreeRTOS API functions.  If configASSERT() is defined in FreeRTOSConfig.h
2313      * then portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion
2314      * failure if a FreeRTOS API function is called from an interrupt that has been
2315      * assigned a priority above the configured maximum system call priority.
2316      * Only FreeRTOS functions that end in FromISR can be called from interrupts
2317      * that have been assigned a priority at or (logically) below the maximum
2318      * system call  interrupt priority.  FreeRTOS maintains a separate interrupt
2319      * safe API to ensure interrupt entry is as fast and as simple as possible.
2320      * More information (albeit Cortex-M specific) is provided on the following
2321      * link: https://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html */
2322     portASSERT_IF_INTERRUPT_PRIORITY_INVALID();
2323
2324     uxSavedInterruptStatus = portTICK_TYPE_SET_INTERRUPT_MASK_FROM_ISR();
2325     {
2326         xReturn = xTickCount;
2327     }
2328     portTICK_TYPE_CLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus );
2329
2330     return xReturn;
2331 }
2332 /*-----------------------------------------------------------*/
2333
2334 UBaseType_t uxTaskGetNumberOfTasks( void )
2335 {
2336     /* A critical section is not required because the variables are of type
2337      * BaseType_t. */
2338     return uxCurrentNumberOfTasks;
2339 }
2340 /*-----------------------------------------------------------*/
2341
2342 char * pcTaskGetName( TaskHandle_t xTaskToQuery ) /*lint !e971 Unqualified char types are allowed for strings and single characters only. */
2343 {
2344     TCB_t * pxTCB;
2345
2346     /* If null is passed in here then the name of the calling task is being
2347      * queried. */
2348     pxTCB = prvGetTCBFromHandle( xTaskToQuery );
2349     configASSERT( pxTCB );
2350     return &( pxTCB->pcTaskName[ 0 ] );
2351 }
2352 /*-----------------------------------------------------------*/
2353
2354 #if ( INCLUDE_xTaskGetHandle == 1 )
2355
2356     static TCB_t * prvSearchForNameWithinSingleList( List_t * pxList,
2357                                                      const char pcNameToQuery[] )
2358     {
2359         TCB_t * pxNextTCB;
2360         TCB_t * pxFirstTCB;
2361         TCB_t * pxReturn = NULL;
2362         UBaseType_t x;
2363         char cNextChar;
2364         BaseType_t xBreakLoop;
2365
2366         /* This function is called with the scheduler suspended. */
2367
2368         if( listCURRENT_LIST_LENGTH( pxList ) > ( UBaseType_t ) 0 )
2369         {
2370             listGET_OWNER_OF_NEXT_ENTRY( pxFirstTCB, pxList ); /*lint !e9079 void * is used as this macro is used with timers too.  Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */
2371
2372             do
2373             {
2374                 listGET_OWNER_OF_NEXT_ENTRY( pxNextTCB, pxList ); /*lint !e9079 void * is used as this macro is used with timers too.  Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */
2375
2376                 /* Check each character in the name looking for a match or
2377                  * mismatch. */
2378                 xBreakLoop = pdFALSE;
2379
2380                 for( x = ( UBaseType_t ) 0; x < ( UBaseType_t ) configMAX_TASK_NAME_LEN; x++ )
2381                 {
2382                     cNextChar = pxNextTCB->pcTaskName[ x ];
2383
2384                     if( cNextChar != pcNameToQuery[ x ] )
2385                     {
2386                         /* Characters didn't match. */
2387                         xBreakLoop = pdTRUE;
2388                     }
2389                     else if( cNextChar == ( char ) 0x00 )
2390                     {
2391                         /* Both strings terminated, a match must have been
2392                          * found. */
2393                         pxReturn = pxNextTCB;
2394                         xBreakLoop = pdTRUE;
2395                     }
2396                     else
2397                     {
2398                         mtCOVERAGE_TEST_MARKER();
2399                     }
2400
2401                     if( xBreakLoop != pdFALSE )
2402                     {
2403                         break;
2404                     }
2405                 }
2406
2407                 if( pxReturn != NULL )
2408                 {
2409                     /* The handle has been found. */
2410                     break;
2411                 }
2412             } while( pxNextTCB != pxFirstTCB );
2413         }
2414         else
2415         {
2416             mtCOVERAGE_TEST_MARKER();
2417         }
2418
2419         return pxReturn;
2420     }
2421
2422 #endif /* INCLUDE_xTaskGetHandle */
2423 /*-----------------------------------------------------------*/
2424
2425 #if ( INCLUDE_xTaskGetHandle == 1 )
2426
2427     TaskHandle_t xTaskGetHandle( const char * pcNameToQuery ) /*lint !e971 Unqualified char types are allowed for strings and single characters only. */
2428     {
2429         UBaseType_t uxQueue = configMAX_PRIORITIES;
2430         TCB_t * pxTCB;
2431
2432         /* Task names will be truncated to configMAX_TASK_NAME_LEN - 1 bytes. */
2433         configASSERT( strlen( pcNameToQuery ) < configMAX_TASK_NAME_LEN );
2434
2435         vTaskSuspendAll();
2436         {
2437             /* Search the ready lists. */
2438             do
2439             {
2440                 uxQueue--;
2441                 pxTCB = prvSearchForNameWithinSingleList( ( List_t * ) &( pxReadyTasksLists[ uxQueue ] ), pcNameToQuery );
2442
2443                 if( pxTCB != NULL )
2444                 {
2445                     /* Found the handle. */
2446                     break;
2447                 }
2448             } while( uxQueue > ( UBaseType_t ) tskIDLE_PRIORITY ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */
2449
2450             /* Search the delayed lists. */
2451             if( pxTCB == NULL )
2452             {
2453                 pxTCB = prvSearchForNameWithinSingleList( ( List_t * ) pxDelayedTaskList, pcNameToQuery );
2454             }
2455
2456             if( pxTCB == NULL )
2457             {
2458                 pxTCB = prvSearchForNameWithinSingleList( ( List_t * ) pxOverflowDelayedTaskList, pcNameToQuery );
2459             }
2460
2461             #if ( INCLUDE_vTaskSuspend == 1 )
2462             {
2463                 if( pxTCB == NULL )
2464                 {
2465                     /* Search the suspended list. */
2466                     pxTCB = prvSearchForNameWithinSingleList( &xSuspendedTaskList, pcNameToQuery );
2467                 }
2468             }
2469             #endif
2470
2471             #if ( INCLUDE_vTaskDelete == 1 )
2472             {
2473                 if( pxTCB == NULL )
2474                 {
2475                     /* Search the deleted list. */
2476                     pxTCB = prvSearchForNameWithinSingleList( &xTasksWaitingTermination, pcNameToQuery );
2477                 }
2478             }
2479             #endif
2480         }
2481         ( void ) xTaskResumeAll();
2482
2483         return pxTCB;
2484     }
2485
2486 #endif /* INCLUDE_xTaskGetHandle */
2487 /*-----------------------------------------------------------*/
2488
2489 #if ( configUSE_TRACE_FACILITY == 1 )
2490
2491     UBaseType_t uxTaskGetSystemState( TaskStatus_t * const pxTaskStatusArray,
2492                                       const UBaseType_t uxArraySize,
2493                                       configRUN_TIME_COUNTER_TYPE * const pulTotalRunTime )
2494     {
2495         UBaseType_t uxTask = 0, uxQueue = configMAX_PRIORITIES;
2496
2497         vTaskSuspendAll();
2498         {
2499             /* Is there a space in the array for each task in the system? */
2500             if( uxArraySize >= uxCurrentNumberOfTasks )
2501             {
2502                 /* Fill in an TaskStatus_t structure with information on each
2503                  * task in the Ready state. */
2504                 do
2505                 {
2506                     uxQueue--;
2507                     uxTask += prvListTasksWithinSingleList( &( pxTaskStatusArray[ uxTask ] ), &( pxReadyTasksLists[ uxQueue ] ), eReady );
2508                 } while( uxQueue > ( UBaseType_t ) tskIDLE_PRIORITY ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */
2509
2510                 /* Fill in an TaskStatus_t structure with information on each
2511                  * task in the Blocked state. */
2512                 uxTask += prvListTasksWithinSingleList( &( pxTaskStatusArray[ uxTask ] ), ( List_t * ) pxDelayedTaskList, eBlocked );
2513                 uxTask += prvListTasksWithinSingleList( &( pxTaskStatusArray[ uxTask ] ), ( List_t * ) pxOverflowDelayedTaskList, eBlocked );
2514
2515                 #if ( INCLUDE_vTaskDelete == 1 )
2516                 {
2517                     /* Fill in an TaskStatus_t structure with information on
2518                      * each task that has been deleted but not yet cleaned up. */
2519                     uxTask += prvListTasksWithinSingleList( &( pxTaskStatusArray[ uxTask ] ), &xTasksWaitingTermination, eDeleted );
2520                 }
2521                 #endif
2522
2523                 #if ( INCLUDE_vTaskSuspend == 1 )
2524                 {
2525                     /* Fill in an TaskStatus_t structure with information on
2526                      * each task in the Suspended state. */
2527                     uxTask += prvListTasksWithinSingleList( &( pxTaskStatusArray[ uxTask ] ), &xSuspendedTaskList, eSuspended );
2528                 }
2529                 #endif
2530
2531                 #if ( configGENERATE_RUN_TIME_STATS == 1 )
2532                 {
2533                     if( pulTotalRunTime != NULL )
2534                     {
2535                         #ifdef portALT_GET_RUN_TIME_COUNTER_VALUE
2536                             portALT_GET_RUN_TIME_COUNTER_VALUE( ( *pulTotalRunTime ) );
2537                         #else
2538                             *pulTotalRunTime = portGET_RUN_TIME_COUNTER_VALUE();
2539                         #endif
2540                     }
2541                 }
2542                 #else /* if ( configGENERATE_RUN_TIME_STATS == 1 ) */
2543                 {
2544                     if( pulTotalRunTime != NULL )
2545                     {
2546                         *pulTotalRunTime = 0;
2547                     }
2548                 }
2549                 #endif /* if ( configGENERATE_RUN_TIME_STATS == 1 ) */
2550             }
2551             else
2552             {
2553                 mtCOVERAGE_TEST_MARKER();
2554             }
2555         }
2556         ( void ) xTaskResumeAll();
2557
2558         return uxTask;
2559     }
2560
2561 #endif /* configUSE_TRACE_FACILITY */
2562 /*----------------------------------------------------------*/
2563
2564 #if ( INCLUDE_xTaskGetIdleTaskHandle == 1 )
2565
2566     TaskHandle_t xTaskGetIdleTaskHandle( void )
2567     {
2568         /* If xTaskGetIdleTaskHandle() is called before the scheduler has been
2569          * started, then xIdleTaskHandle will be NULL. */
2570         configASSERT( ( xIdleTaskHandle != NULL ) );
2571         return xIdleTaskHandle;
2572     }
2573
2574 #endif /* INCLUDE_xTaskGetIdleTaskHandle */
2575 /*----------------------------------------------------------*/
2576
2577 /* This conditional compilation should use inequality to 0, not equality to 1.
2578  * This is to ensure vTaskStepTick() is available when user defined low power mode
2579  * implementations require configUSE_TICKLESS_IDLE to be set to a value other than
2580  * 1. */
2581 #if ( configUSE_TICKLESS_IDLE != 0 )
2582
2583     void vTaskStepTick( TickType_t xTicksToJump )
2584     {
2585         /* Correct the tick count value after a period during which the tick
2586          * was suppressed.  Note this does *not* call the tick hook function for
2587          * each stepped tick. */
2588         configASSERT( ( xTickCount + xTicksToJump ) <= xNextTaskUnblockTime );
2589
2590         if( ( xTickCount + xTicksToJump ) == xNextTaskUnblockTime )
2591         {
2592             /* Arrange for xTickCount to reach xNextTaskUnblockTime in
2593              * xTaskIncrementTick() when the scheduler resumes.  This ensures
2594              * that any delayed tasks are resumed at the correct time. */
2595             configASSERT( uxSchedulerSuspended );
2596             configASSERT( xTicksToJump != ( TickType_t ) 0 );
2597
2598             /* Prevent the tick interrupt modifying xPendedTicks simultaneously. */
2599             taskENTER_CRITICAL();
2600             {
2601                 xPendedTicks++;
2602             }
2603             taskEXIT_CRITICAL();
2604             xTicksToJump--;
2605         }
2606         else
2607         {
2608             mtCOVERAGE_TEST_MARKER();
2609         }
2610
2611         xTickCount += xTicksToJump;
2612         traceINCREASE_TICK_COUNT( xTicksToJump );
2613     }
2614
2615 #endif /* configUSE_TICKLESS_IDLE */
2616 /*----------------------------------------------------------*/
2617
2618 BaseType_t xTaskCatchUpTicks( TickType_t xTicksToCatchUp )
2619 {
2620     BaseType_t xYieldOccurred;
2621
2622     /* Must not be called with the scheduler suspended as the implementation
2623      * relies on xPendedTicks being wound down to 0 in xTaskResumeAll(). */
2624     configASSERT( uxSchedulerSuspended == 0 );
2625
2626     /* Use xPendedTicks to mimic xTicksToCatchUp number of ticks occurring when
2627      * the scheduler is suspended so the ticks are executed in xTaskResumeAll(). */
2628     vTaskSuspendAll();
2629
2630     /* Prevent the tick interrupt modifying xPendedTicks simultaneously. */
2631     taskENTER_CRITICAL();
2632     {
2633         xPendedTicks += xTicksToCatchUp;
2634     }
2635     taskEXIT_CRITICAL();
2636     xYieldOccurred = xTaskResumeAll();
2637
2638     return xYieldOccurred;
2639 }
2640 /*----------------------------------------------------------*/
2641
2642 #if ( INCLUDE_xTaskAbortDelay == 1 )
2643
2644     BaseType_t xTaskAbortDelay( TaskHandle_t xTask )
2645     {
2646         TCB_t * pxTCB = xTask;
2647         BaseType_t xReturn;
2648
2649         configASSERT( pxTCB );
2650
2651         vTaskSuspendAll();
2652         {
2653             /* A task can only be prematurely removed from the Blocked state if
2654              * it is actually in the Blocked state. */
2655             if( eTaskGetState( xTask ) == eBlocked )
2656             {
2657                 xReturn = pdPASS;
2658
2659                 /* Remove the reference to the task from the blocked list.  An
2660                  * interrupt won't touch the xStateListItem because the
2661                  * scheduler is suspended. */
2662                 ( void ) uxListRemove( &( pxTCB->xStateListItem ) );
2663
2664                 /* Is the task waiting on an event also?  If so remove it from
2665                  * the event list too.  Interrupts can touch the event list item,
2666                  * even though the scheduler is suspended, so a critical section
2667                  * is used. */
2668                 taskENTER_CRITICAL();
2669                 {
2670                     if( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) != NULL )
2671                     {
2672                         ( void ) uxListRemove( &( pxTCB->xEventListItem ) );
2673
2674                         /* This lets the task know it was forcibly removed from the
2675                          * blocked state so it should not re-evaluate its block time and
2676                          * then block again. */
2677                         pxTCB->ucDelayAborted = pdTRUE;
2678                     }
2679                     else
2680                     {
2681                         mtCOVERAGE_TEST_MARKER();
2682                     }
2683                 }
2684                 taskEXIT_CRITICAL();
2685
2686                 /* Place the unblocked task into the appropriate ready list. */
2687                 prvAddTaskToReadyList( pxTCB );
2688
2689                 /* A task being unblocked cannot cause an immediate context
2690                  * switch if preemption is turned off. */
2691                 #if ( configUSE_PREEMPTION == 1 )
2692                 {
2693                     /* Preemption is on, but a context switch should only be
2694                      * performed if the unblocked task has a priority that is
2695                      * higher than the currently executing task. */
2696                     if( pxTCB->uxPriority > pxCurrentTCB->uxPriority )
2697                     {
2698                         /* Pend the yield to be performed when the scheduler
2699                          * is unsuspended. */
2700                         xYieldPending = pdTRUE;
2701                     }
2702                     else
2703                     {
2704                         mtCOVERAGE_TEST_MARKER();
2705                     }
2706                 }
2707                 #endif /* configUSE_PREEMPTION */
2708             }
2709             else
2710             {
2711                 xReturn = pdFAIL;
2712             }
2713         }
2714         ( void ) xTaskResumeAll();
2715
2716         return xReturn;
2717     }
2718
2719 #endif /* INCLUDE_xTaskAbortDelay */
2720 /*----------------------------------------------------------*/
2721
2722 BaseType_t xTaskIncrementTick( void )
2723 {
2724     TCB_t * pxTCB;
2725     TickType_t xItemValue;
2726     BaseType_t xSwitchRequired = pdFALSE;
2727
2728     /* Called by the portable layer each time a tick interrupt occurs.
2729      * Increments the tick then checks to see if the new tick value will cause any
2730      * tasks to be unblocked. */
2731     traceTASK_INCREMENT_TICK( xTickCount );
2732
2733     if( uxSchedulerSuspended == ( UBaseType_t ) pdFALSE )
2734     {
2735         /* Minor optimisation.  The tick count cannot change in this
2736          * block. */
2737         const TickType_t xConstTickCount = xTickCount + ( TickType_t ) 1;
2738
2739         /* Increment the RTOS tick, switching the delayed and overflowed
2740          * delayed lists if it wraps to 0. */
2741         xTickCount = xConstTickCount;
2742
2743         if( xConstTickCount == ( TickType_t ) 0U ) /*lint !e774 'if' does not always evaluate to false as it is looking for an overflow. */
2744         {
2745             taskSWITCH_DELAYED_LISTS();
2746         }
2747         else
2748         {
2749             mtCOVERAGE_TEST_MARKER();
2750         }
2751
2752         /* See if this tick has made a timeout expire.  Tasks are stored in
2753          * the  queue in the order of their wake time - meaning once one task
2754          * has been found whose block time has not expired there is no need to
2755          * look any further down the list. */
2756         if( xConstTickCount >= xNextTaskUnblockTime )
2757         {
2758             for( ; ; )
2759             {
2760                 if( listLIST_IS_EMPTY( pxDelayedTaskList ) != pdFALSE )
2761                 {
2762                     /* The delayed list is empty.  Set xNextTaskUnblockTime
2763                      * to the maximum possible value so it is extremely
2764                      * unlikely that the
2765                      * if( xTickCount >= xNextTaskUnblockTime ) test will pass
2766                      * next time through. */
2767                     xNextTaskUnblockTime = portMAX_DELAY; /*lint !e961 MISRA exception as the casts are only redundant for some ports. */
2768                     break;
2769                 }
2770                 else
2771                 {
2772                     /* The delayed list is not empty, get the value of the
2773                      * item at the head of the delayed list.  This is the time
2774                      * at which the task at the head of the delayed list must
2775                      * be removed from the Blocked state. */
2776                     pxTCB = listGET_OWNER_OF_HEAD_ENTRY( pxDelayedTaskList ); /*lint !e9079 void * is used as this macro is used with timers too.  Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */
2777                     xItemValue = listGET_LIST_ITEM_VALUE( &( pxTCB->xStateListItem ) );
2778
2779                     if( xConstTickCount < xItemValue )
2780                     {
2781                         /* It is not time to unblock this item yet, but the
2782                          * item value is the time at which the task at the head
2783                          * of the blocked list must be removed from the Blocked
2784                          * state -  so record the item value in
2785                          * xNextTaskUnblockTime. */
2786                         xNextTaskUnblockTime = xItemValue;
2787                         break; /*lint !e9011 Code structure here is deemed easier to understand with multiple breaks. */
2788                     }
2789                     else
2790                     {
2791                         mtCOVERAGE_TEST_MARKER();
2792                     }
2793
2794                     /* It is time to remove the item from the Blocked state. */
2795                     listREMOVE_ITEM( &( pxTCB->xStateListItem ) );
2796
2797                     /* Is the task waiting on an event also?  If so remove
2798                      * it from the event list. */
2799                     if( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) != NULL )
2800                     {
2801                         listREMOVE_ITEM( &( pxTCB->xEventListItem ) );
2802                     }
2803                     else
2804                     {
2805                         mtCOVERAGE_TEST_MARKER();
2806                     }
2807
2808                     /* Place the unblocked task into the appropriate ready
2809                      * list. */
2810                     prvAddTaskToReadyList( pxTCB );
2811
2812                     /* A task being unblocked cannot cause an immediate
2813                      * context switch if preemption is turned off. */
2814                     #if ( configUSE_PREEMPTION == 1 )
2815                     {
2816                         /* Preemption is on, but a context switch should
2817                          * only be performed if the unblocked task's
2818                          * priority is higher than the currently executing
2819                          * task.
2820                          * The case of equal priority tasks sharing
2821                          * processing time (which happens when both
2822                          * preemption and time slicing are on) is
2823                          * handled below.*/
2824                         if( pxTCB->uxPriority > pxCurrentTCB->uxPriority )
2825                         {
2826                             xSwitchRequired = pdTRUE;
2827                         }
2828                         else
2829                         {
2830                             mtCOVERAGE_TEST_MARKER();
2831                         }
2832                     }
2833                     #endif /* configUSE_PREEMPTION */
2834                 }
2835             }
2836         }
2837
2838         /* Tasks of equal priority to the currently running task will share
2839          * processing time (time slice) if preemption is on, and the application
2840          * writer has not explicitly turned time slicing off. */
2841         #if ( ( configUSE_PREEMPTION == 1 ) && ( configUSE_TIME_SLICING == 1 ) )
2842         {
2843             if( listCURRENT_LIST_LENGTH( &( pxReadyTasksLists[ pxCurrentTCB->uxPriority ] ) ) > ( UBaseType_t ) 1 )
2844             {
2845                 xSwitchRequired = pdTRUE;
2846             }
2847             else
2848             {
2849                 mtCOVERAGE_TEST_MARKER();
2850             }
2851         }
2852         #endif /* ( ( configUSE_PREEMPTION == 1 ) && ( configUSE_TIME_SLICING == 1 ) ) */
2853
2854         #if ( configUSE_TICK_HOOK == 1 )
2855         {
2856             /* Guard against the tick hook being called when the pended tick
2857              * count is being unwound (when the scheduler is being unlocked). */
2858             if( xPendedTicks == ( TickType_t ) 0 )
2859             {
2860                 vApplicationTickHook();
2861             }
2862             else
2863             {
2864                 mtCOVERAGE_TEST_MARKER();
2865             }
2866         }
2867         #endif /* configUSE_TICK_HOOK */
2868
2869         #if ( configUSE_PREEMPTION == 1 )
2870         {
2871             if( xYieldPending != pdFALSE )
2872             {
2873                 xSwitchRequired = pdTRUE;
2874             }
2875             else
2876             {
2877                 mtCOVERAGE_TEST_MARKER();
2878             }
2879         }
2880         #endif /* configUSE_PREEMPTION */
2881     }
2882     else
2883     {
2884         ++xPendedTicks;
2885
2886         /* The tick hook gets called at regular intervals, even if the
2887          * scheduler is locked. */
2888         #if ( configUSE_TICK_HOOK == 1 )
2889         {
2890             vApplicationTickHook();
2891         }
2892         #endif
2893     }
2894
2895     return xSwitchRequired;
2896 }
2897 /*-----------------------------------------------------------*/
2898
2899 #if ( configUSE_APPLICATION_TASK_TAG == 1 )
2900
2901     void vTaskSetApplicationTaskTag( TaskHandle_t xTask,
2902                                      TaskHookFunction_t pxHookFunction )
2903     {
2904         TCB_t * xTCB;
2905
2906         /* If xTask is NULL then it is the task hook of the calling task that is
2907          * getting set. */
2908         if( xTask == NULL )
2909         {
2910             xTCB = ( TCB_t * ) pxCurrentTCB;
2911         }
2912         else
2913         {
2914             xTCB = xTask;
2915         }
2916
2917         /* Save the hook function in the TCB.  A critical section is required as
2918          * the value can be accessed from an interrupt. */
2919         taskENTER_CRITICAL();
2920         {
2921             xTCB->pxTaskTag = pxHookFunction;
2922         }
2923         taskEXIT_CRITICAL();
2924     }
2925
2926 #endif /* configUSE_APPLICATION_TASK_TAG */
2927 /*-----------------------------------------------------------*/
2928
2929 #if ( configUSE_APPLICATION_TASK_TAG == 1 )
2930
2931     TaskHookFunction_t xTaskGetApplicationTaskTag( TaskHandle_t xTask )
2932     {
2933         TCB_t * pxTCB;
2934         TaskHookFunction_t xReturn;
2935
2936         /* If xTask is NULL then set the calling task's hook. */
2937         pxTCB = prvGetTCBFromHandle( xTask );
2938
2939         /* Save the hook function in the TCB.  A critical section is required as
2940          * the value can be accessed from an interrupt. */
2941         taskENTER_CRITICAL();
2942         {
2943             xReturn = pxTCB->pxTaskTag;
2944         }
2945         taskEXIT_CRITICAL();
2946
2947         return xReturn;
2948     }
2949
2950 #endif /* configUSE_APPLICATION_TASK_TAG */
2951 /*-----------------------------------------------------------*/
2952
2953 #if ( configUSE_APPLICATION_TASK_TAG == 1 )
2954
2955     TaskHookFunction_t xTaskGetApplicationTaskTagFromISR( TaskHandle_t xTask )
2956     {
2957         TCB_t * pxTCB;
2958         TaskHookFunction_t xReturn;
2959         UBaseType_t uxSavedInterruptStatus;
2960
2961         /* If xTask is NULL then set the calling task's hook. */
2962         pxTCB = prvGetTCBFromHandle( xTask );
2963
2964         /* Save the hook function in the TCB.  A critical section is required as
2965          * the value can be accessed from an interrupt. */
2966         uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR();
2967         {
2968             xReturn = pxTCB->pxTaskTag;
2969         }
2970         portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus );
2971
2972         return xReturn;
2973     }
2974
2975 #endif /* configUSE_APPLICATION_TASK_TAG */
2976 /*-----------------------------------------------------------*/
2977
2978 #if ( configUSE_APPLICATION_TASK_TAG == 1 )
2979
2980     BaseType_t xTaskCallApplicationTaskHook( TaskHandle_t xTask,
2981                                              void * pvParameter )
2982     {
2983         TCB_t * xTCB;
2984         BaseType_t xReturn;
2985
2986         /* If xTask is NULL then we are calling our own task hook. */
2987         if( xTask == NULL )
2988         {
2989             xTCB = pxCurrentTCB;
2990         }
2991         else
2992         {
2993             xTCB = xTask;
2994         }
2995
2996         if( xTCB->pxTaskTag != NULL )
2997         {
2998             xReturn = xTCB->pxTaskTag( pvParameter );
2999         }
3000         else
3001         {
3002             xReturn = pdFAIL;
3003         }
3004
3005         return xReturn;
3006     }
3007
3008 #endif /* configUSE_APPLICATION_TASK_TAG */
3009 /*-----------------------------------------------------------*/
3010
3011 void vTaskSwitchContext( void )
3012 {
3013     if( uxSchedulerSuspended != ( UBaseType_t ) pdFALSE )
3014     {
3015         /* The scheduler is currently suspended - do not allow a context
3016          * switch. */
3017         xYieldPending = pdTRUE;
3018     }
3019     else
3020     {
3021         xYieldPending = pdFALSE;
3022         traceTASK_SWITCHED_OUT();
3023
3024         #if ( configGENERATE_RUN_TIME_STATS == 1 )
3025         {
3026             #ifdef portALT_GET_RUN_TIME_COUNTER_VALUE
3027                 portALT_GET_RUN_TIME_COUNTER_VALUE( ulTotalRunTime );
3028             #else
3029                 ulTotalRunTime = portGET_RUN_TIME_COUNTER_VALUE();
3030             #endif
3031
3032             /* Add the amount of time the task has been running to the
3033              * accumulated time so far.  The time the task started running was
3034              * stored in ulTaskSwitchedInTime.  Note that there is no overflow
3035              * protection here so count values are only valid until the timer
3036              * overflows.  The guard against negative values is to protect
3037              * against suspect run time stat counter implementations - which
3038              * are provided by the application, not the kernel. */
3039             if( ulTotalRunTime > ulTaskSwitchedInTime )
3040             {
3041                 pxCurrentTCB->ulRunTimeCounter += ( ulTotalRunTime - ulTaskSwitchedInTime );
3042             }
3043             else
3044             {
3045                 mtCOVERAGE_TEST_MARKER();
3046             }
3047
3048             ulTaskSwitchedInTime = ulTotalRunTime;
3049         }
3050         #endif /* configGENERATE_RUN_TIME_STATS */
3051
3052         /* Check for stack overflow, if configured. */
3053         taskCHECK_FOR_STACK_OVERFLOW();
3054
3055         /* Before the currently running task is switched out, save its errno. */
3056         #if ( configUSE_POSIX_ERRNO == 1 )
3057         {
3058             pxCurrentTCB->iTaskErrno = FreeRTOS_errno;
3059         }
3060         #endif
3061
3062         /* Select a new task to run using either the generic C or port
3063          * optimised asm code. */
3064         taskSELECT_HIGHEST_PRIORITY_TASK(); /*lint !e9079 void * is used as this macro is used with timers too.  Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */
3065         traceTASK_SWITCHED_IN();
3066
3067         /* After the new task is switched in, update the global errno. */
3068         #if ( configUSE_POSIX_ERRNO == 1 )
3069         {
3070             FreeRTOS_errno = pxCurrentTCB->iTaskErrno;
3071         }
3072         #endif
3073
3074         #if ( ( configUSE_NEWLIB_REENTRANT == 1 ) || ( configUSE_C_RUNTIME_TLS_SUPPORT == 1 ) )
3075         {
3076             /* Switch C-Runtime's TLS Block to point to the TLS
3077              * Block specific to this task. */
3078             configSET_TLS_BLOCK( pxCurrentTCB->xTLSBlock );
3079         }
3080         #endif
3081     }
3082 }
3083 /*-----------------------------------------------------------*/
3084
3085 void vTaskPlaceOnEventList( List_t * const pxEventList,
3086                             const TickType_t xTicksToWait )
3087 {
3088     configASSERT( pxEventList );
3089
3090     /* THIS FUNCTION MUST BE CALLED WITH EITHER INTERRUPTS DISABLED OR THE
3091      * SCHEDULER SUSPENDED AND THE QUEUE BEING ACCESSED LOCKED. */
3092
3093     /* Place the event list item of the TCB in the appropriate event list.
3094      * This is placed in the list in priority order so the highest priority task
3095      * is the first to be woken by the event.
3096      *
3097      * Note: Lists are sorted in ascending order by ListItem_t.xItemValue.
3098      * Normally, the xItemValue of a TCB's ListItem_t members is:
3099      *      xItemValue = ( configMAX_PRIORITIES - uxPriority )
3100      * Therefore, the event list is sorted in descending priority order.
3101      *
3102      * The queue that contains the event list is locked, preventing
3103      * simultaneous access from interrupts. */
3104     vListInsert( pxEventList, &( pxCurrentTCB->xEventListItem ) );
3105
3106     prvAddCurrentTaskToDelayedList( xTicksToWait, pdTRUE );
3107 }
3108 /*-----------------------------------------------------------*/
3109
3110 void vTaskPlaceOnUnorderedEventList( List_t * pxEventList,
3111                                      const TickType_t xItemValue,
3112                                      const TickType_t xTicksToWait )
3113 {
3114     configASSERT( pxEventList );
3115
3116     /* THIS FUNCTION MUST BE CALLED WITH THE SCHEDULER SUSPENDED.  It is used by
3117      * the event groups implementation. */
3118     configASSERT( uxSchedulerSuspended != 0 );
3119
3120     /* Store the item value in the event list item.  It is safe to access the
3121      * event list item here as interrupts won't access the event list item of a
3122      * task that is not in the Blocked state. */
3123     listSET_LIST_ITEM_VALUE( &( pxCurrentTCB->xEventListItem ), xItemValue | taskEVENT_LIST_ITEM_VALUE_IN_USE );
3124
3125     /* Place the event list item of the TCB at the end of the appropriate event
3126      * list.  It is safe to access the event list here because it is part of an
3127      * event group implementation - and interrupts don't access event groups
3128      * directly (instead they access them indirectly by pending function calls to
3129      * the task level). */
3130     listINSERT_END( pxEventList, &( pxCurrentTCB->xEventListItem ) );
3131
3132     prvAddCurrentTaskToDelayedList( xTicksToWait, pdTRUE );
3133 }
3134 /*-----------------------------------------------------------*/
3135
3136 #if ( configUSE_TIMERS == 1 )
3137
3138     void vTaskPlaceOnEventListRestricted( List_t * const pxEventList,
3139                                           TickType_t xTicksToWait,
3140                                           const BaseType_t xWaitIndefinitely )
3141     {
3142         configASSERT( pxEventList );
3143
3144         /* This function should not be called by application code hence the
3145          * 'Restricted' in its name.  It is not part of the public API.  It is
3146          * designed for use by kernel code, and has special calling requirements -
3147          * it should be called with the scheduler suspended. */
3148
3149
3150         /* Place the event list item of the TCB in the appropriate event list.
3151          * In this case it is assume that this is the only task that is going to
3152          * be waiting on this event list, so the faster vListInsertEnd() function
3153          * can be used in place of vListInsert. */
3154         listINSERT_END( pxEventList, &( pxCurrentTCB->xEventListItem ) );
3155
3156         /* If the task should block indefinitely then set the block time to a
3157          * value that will be recognised as an indefinite delay inside the
3158          * prvAddCurrentTaskToDelayedList() function. */
3159         if( xWaitIndefinitely != pdFALSE )
3160         {
3161             xTicksToWait = portMAX_DELAY;
3162         }
3163
3164         traceTASK_DELAY_UNTIL( ( xTickCount + xTicksToWait ) );
3165         prvAddCurrentTaskToDelayedList( xTicksToWait, xWaitIndefinitely );
3166     }
3167
3168 #endif /* configUSE_TIMERS */
3169 /*-----------------------------------------------------------*/
3170
3171 BaseType_t xTaskRemoveFromEventList( const List_t * const pxEventList )
3172 {
3173     TCB_t * pxUnblockedTCB;
3174     BaseType_t xReturn;
3175
3176     /* THIS FUNCTION MUST BE CALLED FROM A CRITICAL SECTION.  It can also be
3177      * called from a critical section within an ISR. */
3178
3179     /* The event list is sorted in priority order, so the first in the list can
3180      * be removed as it is known to be the highest priority.  Remove the TCB from
3181      * the delayed list, and add it to the ready list.
3182      *
3183      * If an event is for a queue that is locked then this function will never
3184      * get called - the lock count on the queue will get modified instead.  This
3185      * means exclusive access to the event list is guaranteed here.
3186      *
3187      * This function assumes that a check has already been made to ensure that
3188      * pxEventList is not empty. */
3189     pxUnblockedTCB = listGET_OWNER_OF_HEAD_ENTRY( pxEventList ); /*lint !e9079 void * is used as this macro is used with timers too.  Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */
3190     configASSERT( pxUnblockedTCB );
3191     listREMOVE_ITEM( &( pxUnblockedTCB->xEventListItem ) );
3192
3193     if( uxSchedulerSuspended == ( UBaseType_t ) pdFALSE )
3194     {
3195         listREMOVE_ITEM( &( pxUnblockedTCB->xStateListItem ) );
3196         prvAddTaskToReadyList( pxUnblockedTCB );
3197
3198         #if ( configUSE_TICKLESS_IDLE != 0 )
3199         {
3200             /* If a task is blocked on a kernel object then xNextTaskUnblockTime
3201              * might be set to the blocked task's time out time.  If the task is
3202              * unblocked for a reason other than a timeout xNextTaskUnblockTime is
3203              * normally left unchanged, because it is automatically reset to a new
3204              * value when the tick count equals xNextTaskUnblockTime.  However if
3205              * tickless idling is used it might be more important to enter sleep mode
3206              * at the earliest possible time - so reset xNextTaskUnblockTime here to
3207              * ensure it is updated at the earliest possible time. */
3208             prvResetNextTaskUnblockTime();
3209         }
3210         #endif
3211     }
3212     else
3213     {
3214         /* The delayed and ready lists cannot be accessed, so hold this task
3215          * pending until the scheduler is resumed. */
3216         listINSERT_END( &( xPendingReadyList ), &( pxUnblockedTCB->xEventListItem ) );
3217     }
3218
3219     if( pxUnblockedTCB->uxPriority > pxCurrentTCB->uxPriority )
3220     {
3221         /* Return true if the task removed from the event list has a higher
3222          * priority than the calling task.  This allows the calling task to know if
3223          * it should force a context switch now. */
3224         xReturn = pdTRUE;
3225
3226         /* Mark that a yield is pending in case the user is not using the
3227          * "xHigherPriorityTaskWoken" parameter to an ISR safe FreeRTOS function. */
3228         xYieldPending = pdTRUE;
3229     }
3230     else
3231     {
3232         xReturn = pdFALSE;
3233     }
3234
3235     return xReturn;
3236 }
3237 /*-----------------------------------------------------------*/
3238
3239 void vTaskRemoveFromUnorderedEventList( ListItem_t * pxEventListItem,
3240                                         const TickType_t xItemValue )
3241 {
3242     TCB_t * pxUnblockedTCB;
3243
3244     /* THIS FUNCTION MUST BE CALLED WITH THE SCHEDULER SUSPENDED.  It is used by
3245      * the event flags implementation. */
3246     configASSERT( uxSchedulerSuspended != pdFALSE );
3247
3248     /* Store the new item value in the event list. */
3249     listSET_LIST_ITEM_VALUE( pxEventListItem, xItemValue | taskEVENT_LIST_ITEM_VALUE_IN_USE );
3250
3251     /* Remove the event list form the event flag.  Interrupts do not access
3252      * event flags. */
3253     pxUnblockedTCB = listGET_LIST_ITEM_OWNER( pxEventListItem ); /*lint !e9079 void * is used as this macro is used with timers too.  Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */
3254     configASSERT( pxUnblockedTCB );
3255     listREMOVE_ITEM( pxEventListItem );
3256
3257     #if ( configUSE_TICKLESS_IDLE != 0 )
3258     {
3259         /* If a task is blocked on a kernel object then xNextTaskUnblockTime
3260          * might be set to the blocked task's time out time.  If the task is
3261          * unblocked for a reason other than a timeout xNextTaskUnblockTime is
3262          * normally left unchanged, because it is automatically reset to a new
3263          * value when the tick count equals xNextTaskUnblockTime.  However if
3264          * tickless idling is used it might be more important to enter sleep mode
3265          * at the earliest possible time - so reset xNextTaskUnblockTime here to
3266          * ensure it is updated at the earliest possible time. */
3267         prvResetNextTaskUnblockTime();
3268     }
3269     #endif
3270
3271     /* Remove the task from the delayed list and add it to the ready list.  The
3272      * scheduler is suspended so interrupts will not be accessing the ready
3273      * lists. */
3274     listREMOVE_ITEM( &( pxUnblockedTCB->xStateListItem ) );
3275     prvAddTaskToReadyList( pxUnblockedTCB );
3276
3277     if( pxUnblockedTCB->uxPriority > pxCurrentTCB->uxPriority )
3278     {
3279         /* The unblocked task has a priority above that of the calling task, so
3280          * a context switch is required.  This function is called with the
3281          * scheduler suspended so xYieldPending is set so the context switch
3282          * occurs immediately that the scheduler is resumed (unsuspended). */
3283         xYieldPending = pdTRUE;
3284     }
3285 }
3286 /*-----------------------------------------------------------*/
3287
3288 void vTaskSetTimeOutState( TimeOut_t * const pxTimeOut )
3289 {
3290     configASSERT( pxTimeOut );
3291     taskENTER_CRITICAL();
3292     {
3293         pxTimeOut->xOverflowCount = xNumOfOverflows;
3294         pxTimeOut->xTimeOnEntering = xTickCount;
3295     }
3296     taskEXIT_CRITICAL();
3297 }
3298 /*-----------------------------------------------------------*/
3299
3300 void vTaskInternalSetTimeOutState( TimeOut_t * const pxTimeOut )
3301 {
3302     /* For internal use only as it does not use a critical section. */
3303     pxTimeOut->xOverflowCount = xNumOfOverflows;
3304     pxTimeOut->xTimeOnEntering = xTickCount;
3305 }
3306 /*-----------------------------------------------------------*/
3307
3308 BaseType_t xTaskCheckForTimeOut( TimeOut_t * const pxTimeOut,
3309                                  TickType_t * const pxTicksToWait )
3310 {
3311     BaseType_t xReturn;
3312
3313     configASSERT( pxTimeOut );
3314     configASSERT( pxTicksToWait );
3315
3316     taskENTER_CRITICAL();
3317     {
3318         /* Minor optimisation.  The tick count cannot change in this block. */
3319         const TickType_t xConstTickCount = xTickCount;
3320         const TickType_t xElapsedTime = xConstTickCount - pxTimeOut->xTimeOnEntering;
3321
3322         #if ( INCLUDE_xTaskAbortDelay == 1 )
3323             if( pxCurrentTCB->ucDelayAborted != ( uint8_t ) pdFALSE )
3324             {
3325                 /* The delay was aborted, which is not the same as a time out,
3326                  * but has the same result. */
3327                 pxCurrentTCB->ucDelayAborted = pdFALSE;
3328                 xReturn = pdTRUE;
3329             }
3330             else
3331         #endif
3332
3333         #if ( INCLUDE_vTaskSuspend == 1 )
3334             if( *pxTicksToWait == portMAX_DELAY )
3335             {
3336                 /* If INCLUDE_vTaskSuspend is set to 1 and the block time
3337                  * specified is the maximum block time then the task should block
3338                  * indefinitely, and therefore never time out. */
3339                 xReturn = pdFALSE;
3340             }
3341             else
3342         #endif
3343
3344         if( ( xNumOfOverflows != pxTimeOut->xOverflowCount ) && ( xConstTickCount >= pxTimeOut->xTimeOnEntering ) ) /*lint !e525 Indentation preferred as is to make code within pre-processor directives clearer. */
3345         {
3346             /* The tick count is greater than the time at which
3347              * vTaskSetTimeout() was called, but has also overflowed since
3348              * vTaskSetTimeOut() was called.  It must have wrapped all the way
3349              * around and gone past again. This passed since vTaskSetTimeout()
3350              * was called. */
3351             xReturn = pdTRUE;
3352             *pxTicksToWait = ( TickType_t ) 0;
3353         }
3354         else if( xElapsedTime < *pxTicksToWait ) /*lint !e961 Explicit casting is only redundant with some compilers, whereas others require it to prevent integer conversion errors. */
3355         {
3356             /* Not a genuine timeout. Adjust parameters for time remaining. */
3357             *pxTicksToWait -= xElapsedTime;
3358             vTaskInternalSetTimeOutState( pxTimeOut );
3359             xReturn = pdFALSE;
3360         }
3361         else
3362         {
3363             *pxTicksToWait = ( TickType_t ) 0;
3364             xReturn = pdTRUE;
3365         }
3366     }
3367     taskEXIT_CRITICAL();
3368
3369     return xReturn;
3370 }
3371 /*-----------------------------------------------------------*/
3372
3373 void vTaskMissedYield( void )
3374 {
3375     xYieldPending = pdTRUE;
3376 }
3377 /*-----------------------------------------------------------*/
3378
3379 #if ( configUSE_TRACE_FACILITY == 1 )
3380
3381     UBaseType_t uxTaskGetTaskNumber( TaskHandle_t xTask )
3382     {
3383         UBaseType_t uxReturn;
3384         TCB_t const * pxTCB;
3385
3386         if( xTask != NULL )
3387         {
3388             pxTCB = xTask;
3389             uxReturn = pxTCB->uxTaskNumber;
3390         }
3391         else
3392         {
3393             uxReturn = 0U;
3394         }
3395
3396         return uxReturn;
3397     }
3398
3399 #endif /* configUSE_TRACE_FACILITY */
3400 /*-----------------------------------------------------------*/
3401
3402 #if ( configUSE_TRACE_FACILITY == 1 )
3403
3404     void vTaskSetTaskNumber( TaskHandle_t xTask,
3405                              const UBaseType_t uxHandle )
3406     {
3407         TCB_t * pxTCB;
3408
3409         if( xTask != NULL )
3410         {
3411             pxTCB = xTask;
3412             pxTCB->uxTaskNumber = uxHandle;
3413         }
3414     }
3415
3416 #endif /* configUSE_TRACE_FACILITY */
3417
3418 /*
3419  * -----------------------------------------------------------
3420  * The Idle task.
3421  * ----------------------------------------------------------
3422  *
3423  * The portTASK_FUNCTION() macro is used to allow port/compiler specific
3424  * language extensions.  The equivalent prototype for this function is:
3425  *
3426  * void prvIdleTask( void *pvParameters );
3427  *
3428  */
3429 static portTASK_FUNCTION( prvIdleTask, pvParameters )
3430 {
3431     /* Stop warnings. */
3432     ( void ) pvParameters;
3433
3434     /** THIS IS THE RTOS IDLE TASK - WHICH IS CREATED AUTOMATICALLY WHEN THE
3435      * SCHEDULER IS STARTED. **/
3436
3437     /* In case a task that has a secure context deletes itself, in which case
3438      * the idle task is responsible for deleting the task's secure context, if
3439      * any. */
3440     portALLOCATE_SECURE_CONTEXT( configMINIMAL_SECURE_STACK_SIZE );
3441
3442     for( ; ; )
3443     {
3444         /* See if any tasks have deleted themselves - if so then the idle task
3445          * is responsible for freeing the deleted task's TCB and stack. */
3446         prvCheckTasksWaitingTermination();
3447
3448         #if ( configUSE_PREEMPTION == 0 )
3449         {
3450             /* If we are not using preemption we keep forcing a task switch to
3451              * see if any other task has become available.  If we are using
3452              * preemption we don't need to do this as any task becoming available
3453              * will automatically get the processor anyway. */
3454             taskYIELD();
3455         }
3456         #endif /* configUSE_PREEMPTION */
3457
3458         #if ( ( configUSE_PREEMPTION == 1 ) && ( configIDLE_SHOULD_YIELD == 1 ) )
3459         {
3460             /* When using preemption tasks of equal priority will be
3461              * timesliced.  If a task that is sharing the idle priority is ready
3462              * to run then the idle task should yield before the end of the
3463              * timeslice.
3464              *
3465              * A critical region is not required here as we are just reading from
3466              * the list, and an occasional incorrect value will not matter.  If
3467              * the ready list at the idle priority contains more than one task
3468              * then a task other than the idle task is ready to execute. */
3469             if( listCURRENT_LIST_LENGTH( &( pxReadyTasksLists[ tskIDLE_PRIORITY ] ) ) > ( UBaseType_t ) 1 )
3470             {
3471                 taskYIELD();
3472             }
3473             else
3474             {
3475                 mtCOVERAGE_TEST_MARKER();
3476             }
3477         }
3478         #endif /* ( ( configUSE_PREEMPTION == 1 ) && ( configIDLE_SHOULD_YIELD == 1 ) ) */
3479
3480         #if ( configUSE_IDLE_HOOK == 1 )
3481         {
3482             /* Call the user defined function from within the idle task. */
3483             vApplicationIdleHook();
3484         }
3485         #endif /* configUSE_IDLE_HOOK */
3486
3487         /* This conditional compilation should use inequality to 0, not equality
3488          * to 1.  This is to ensure portSUPPRESS_TICKS_AND_SLEEP() is called when
3489          * user defined low power mode  implementations require
3490          * configUSE_TICKLESS_IDLE to be set to a value other than 1. */
3491         #if ( configUSE_TICKLESS_IDLE != 0 )
3492         {
3493             TickType_t xExpectedIdleTime;
3494
3495             /* It is not desirable to suspend then resume the scheduler on
3496              * each iteration of the idle task.  Therefore, a preliminary
3497              * test of the expected idle time is performed without the
3498              * scheduler suspended.  The result here is not necessarily
3499              * valid. */
3500             xExpectedIdleTime = prvGetExpectedIdleTime();
3501
3502             if( xExpectedIdleTime >= configEXPECTED_IDLE_TIME_BEFORE_SLEEP )
3503             {
3504                 vTaskSuspendAll();
3505                 {
3506                     /* Now the scheduler is suspended, the expected idle
3507                      * time can be sampled again, and this time its value can
3508                      * be used. */
3509                     configASSERT( xNextTaskUnblockTime >= xTickCount );
3510                     xExpectedIdleTime = prvGetExpectedIdleTime();
3511
3512                     /* Define the following macro to set xExpectedIdleTime to 0
3513                      * if the application does not want
3514                      * portSUPPRESS_TICKS_AND_SLEEP() to be called. */
3515                     configPRE_SUPPRESS_TICKS_AND_SLEEP_PROCESSING( xExpectedIdleTime );
3516
3517                     if( xExpectedIdleTime >= configEXPECTED_IDLE_TIME_BEFORE_SLEEP )
3518                     {
3519                         traceLOW_POWER_IDLE_BEGIN();
3520                         portSUPPRESS_TICKS_AND_SLEEP( xExpectedIdleTime );
3521                         traceLOW_POWER_IDLE_END();
3522                     }
3523                     else
3524                     {
3525                         mtCOVERAGE_TEST_MARKER();
3526                     }
3527                 }
3528                 ( void ) xTaskResumeAll();
3529             }
3530             else
3531             {
3532                 mtCOVERAGE_TEST_MARKER();
3533             }
3534         }
3535         #endif /* configUSE_TICKLESS_IDLE */
3536     }
3537 }
3538 /*-----------------------------------------------------------*/
3539
3540 #if ( configUSE_TICKLESS_IDLE != 0 )
3541
3542     eSleepModeStatus eTaskConfirmSleepModeStatus( void )
3543     {
3544         #if ( INCLUDE_vTaskSuspend == 1 )
3545             /* The idle task exists in addition to the application tasks. */
3546             const UBaseType_t uxNonApplicationTasks = 1;
3547         #endif /* INCLUDE_vTaskSuspend */
3548
3549         eSleepModeStatus eReturn = eStandardSleep;
3550
3551         /* This function must be called from a critical section. */
3552
3553         if( listCURRENT_LIST_LENGTH( &xPendingReadyList ) != 0 )
3554         {
3555             /* A task was made ready while the scheduler was suspended. */
3556             eReturn = eAbortSleep;
3557         }
3558         else if( xYieldPending != pdFALSE )
3559         {
3560             /* A yield was pended while the scheduler was suspended. */
3561             eReturn = eAbortSleep;
3562         }
3563         else if( xPendedTicks != 0 )
3564         {
3565             /* A tick interrupt has already occurred but was held pending
3566              * because the scheduler is suspended. */
3567             eReturn = eAbortSleep;
3568         }
3569
3570         #if ( INCLUDE_vTaskSuspend == 1 )
3571             else if( listCURRENT_LIST_LENGTH( &xSuspendedTaskList ) == ( uxCurrentNumberOfTasks - uxNonApplicationTasks ) )
3572             {
3573                 /* If all the tasks are in the suspended list (which might mean they
3574                  * have an infinite block time rather than actually being suspended)
3575                  * then it is safe to turn all clocks off and just wait for external
3576                  * interrupts. */
3577                 eReturn = eNoTasksWaitingTimeout;
3578             }
3579         #endif /* INCLUDE_vTaskSuspend */
3580         else
3581         {
3582             mtCOVERAGE_TEST_MARKER();
3583         }
3584
3585         return eReturn;
3586     }
3587
3588 #endif /* configUSE_TICKLESS_IDLE */
3589 /*-----------------------------------------------------------*/
3590
3591 #if ( configNUM_THREAD_LOCAL_STORAGE_POINTERS != 0 )
3592
3593     void vTaskSetThreadLocalStoragePointer( TaskHandle_t xTaskToSet,
3594                                             BaseType_t xIndex,
3595                                             void * pvValue )
3596     {
3597         TCB_t * pxTCB;
3598
3599         if( ( xIndex >= 0 ) &&
3600             ( xIndex < configNUM_THREAD_LOCAL_STORAGE_POINTERS ) )
3601         {
3602             pxTCB = prvGetTCBFromHandle( xTaskToSet );
3603             configASSERT( pxTCB != NULL );
3604             pxTCB->pvThreadLocalStoragePointers[ xIndex ] = pvValue;
3605         }
3606     }
3607
3608 #endif /* configNUM_THREAD_LOCAL_STORAGE_POINTERS */
3609 /*-----------------------------------------------------------*/
3610
3611 #if ( configNUM_THREAD_LOCAL_STORAGE_POINTERS != 0 )
3612
3613     void * pvTaskGetThreadLocalStoragePointer( TaskHandle_t xTaskToQuery,
3614                                                BaseType_t xIndex )
3615     {
3616         void * pvReturn = NULL;
3617         TCB_t * pxTCB;
3618
3619         if( ( xIndex >= 0 ) &&
3620             ( xIndex < configNUM_THREAD_LOCAL_STORAGE_POINTERS ) )
3621         {
3622             pxTCB = prvGetTCBFromHandle( xTaskToQuery );
3623             pvReturn = pxTCB->pvThreadLocalStoragePointers[ xIndex ];
3624         }
3625         else
3626         {
3627             pvReturn = NULL;
3628         }
3629
3630         return pvReturn;
3631     }
3632
3633 #endif /* configNUM_THREAD_LOCAL_STORAGE_POINTERS */
3634 /*-----------------------------------------------------------*/
3635
3636 #if ( portUSING_MPU_WRAPPERS == 1 )
3637
3638     void vTaskAllocateMPURegions( TaskHandle_t xTaskToModify,
3639                                   const MemoryRegion_t * const xRegions )
3640     {
3641         TCB_t * pxTCB;
3642
3643         /* If null is passed in here then we are modifying the MPU settings of
3644          * the calling task. */
3645         pxTCB = prvGetTCBFromHandle( xTaskToModify );
3646
3647         vPortStoreTaskMPUSettings( &( pxTCB->xMPUSettings ), xRegions, NULL, 0 );
3648     }
3649
3650 #endif /* portUSING_MPU_WRAPPERS */
3651 /*-----------------------------------------------------------*/
3652
3653 static void prvInitialiseTaskLists( void )
3654 {
3655     UBaseType_t uxPriority;
3656
3657     for( uxPriority = ( UBaseType_t ) 0U; uxPriority < ( UBaseType_t ) configMAX_PRIORITIES; uxPriority++ )
3658     {
3659         vListInitialise( &( pxReadyTasksLists[ uxPriority ] ) );
3660     }
3661
3662     vListInitialise( &xDelayedTaskList1 );
3663     vListInitialise( &xDelayedTaskList2 );
3664     vListInitialise( &xPendingReadyList );
3665
3666     #if ( INCLUDE_vTaskDelete == 1 )
3667     {
3668         vListInitialise( &xTasksWaitingTermination );
3669     }
3670     #endif /* INCLUDE_vTaskDelete */
3671
3672     #if ( INCLUDE_vTaskSuspend == 1 )
3673     {
3674         vListInitialise( &xSuspendedTaskList );
3675     }
3676     #endif /* INCLUDE_vTaskSuspend */
3677
3678     /* Start with pxDelayedTaskList using list1 and the pxOverflowDelayedTaskList
3679      * using list2. */
3680     pxDelayedTaskList = &xDelayedTaskList1;
3681     pxOverflowDelayedTaskList = &xDelayedTaskList2;
3682 }
3683 /*-----------------------------------------------------------*/
3684
3685 static void prvCheckTasksWaitingTermination( void )
3686 {
3687     /** THIS FUNCTION IS CALLED FROM THE RTOS IDLE TASK **/
3688
3689     #if ( INCLUDE_vTaskDelete == 1 )
3690     {
3691         TCB_t * pxTCB;
3692
3693         /* uxDeletedTasksWaitingCleanUp is used to prevent taskENTER_CRITICAL()
3694          * being called too often in the idle task. */
3695         while( uxDeletedTasksWaitingCleanUp > ( UBaseType_t ) 0U )
3696         {
3697             taskENTER_CRITICAL();
3698             {
3699                 pxTCB = listGET_OWNER_OF_HEAD_ENTRY( ( &xTasksWaitingTermination ) ); /*lint !e9079 void * is used as this macro is used with timers too.  Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */
3700                 ( void ) uxListRemove( &( pxTCB->xStateListItem ) );
3701                 --uxCurrentNumberOfTasks;
3702                 --uxDeletedTasksWaitingCleanUp;
3703             }
3704             taskEXIT_CRITICAL();
3705
3706             prvDeleteTCB( pxTCB );
3707         }
3708     }
3709     #endif /* INCLUDE_vTaskDelete */
3710 }
3711 /*-----------------------------------------------------------*/
3712
3713 #if ( configUSE_TRACE_FACILITY == 1 )
3714
3715     void vTaskGetInfo( TaskHandle_t xTask,
3716                        TaskStatus_t * pxTaskStatus,
3717                        BaseType_t xGetFreeStackSpace,
3718                        eTaskState eState )
3719     {
3720         TCB_t * pxTCB;
3721
3722         /* xTask is NULL then get the state of the calling task. */
3723         pxTCB = prvGetTCBFromHandle( xTask );
3724
3725         pxTaskStatus->xHandle = ( TaskHandle_t ) pxTCB;
3726         pxTaskStatus->pcTaskName = ( const char * ) &( pxTCB->pcTaskName[ 0 ] );
3727         pxTaskStatus->uxCurrentPriority = pxTCB->uxPriority;
3728         pxTaskStatus->pxStackBase = pxTCB->pxStack;
3729         #if ( ( portSTACK_GROWTH > 0 ) && ( configRECORD_STACK_HIGH_ADDRESS == 1 ) )
3730             pxTaskStatus->pxTopOfStack = pxTCB->pxTopOfStack;
3731             pxTaskStatus->pxEndOfStack = pxTCB->pxEndOfStack;
3732         #endif
3733         pxTaskStatus->xTaskNumber = pxTCB->uxTCBNumber;
3734
3735         #if ( configUSE_MUTEXES == 1 )
3736         {
3737             pxTaskStatus->uxBasePriority = pxTCB->uxBasePriority;
3738         }
3739         #else
3740         {
3741             pxTaskStatus->uxBasePriority = 0;
3742         }
3743         #endif
3744
3745         #if ( configGENERATE_RUN_TIME_STATS == 1 )
3746         {
3747             pxTaskStatus->ulRunTimeCounter = pxTCB->ulRunTimeCounter;
3748         }
3749         #else
3750         {
3751             pxTaskStatus->ulRunTimeCounter = ( configRUN_TIME_COUNTER_TYPE ) 0;
3752         }
3753         #endif
3754
3755         /* Obtaining the task state is a little fiddly, so is only done if the
3756          * value of eState passed into this function is eInvalid - otherwise the
3757          * state is just set to whatever is passed in. */
3758         if( eState != eInvalid )
3759         {
3760             if( pxTCB == pxCurrentTCB )
3761             {
3762                 pxTaskStatus->eCurrentState = eRunning;
3763             }
3764             else
3765             {
3766                 pxTaskStatus->eCurrentState = eState;
3767
3768                 #if ( INCLUDE_vTaskSuspend == 1 )
3769                 {
3770                     /* If the task is in the suspended list then there is a
3771                      *  chance it is actually just blocked indefinitely - so really
3772                      *  it should be reported as being in the Blocked state. */
3773                     if( eState == eSuspended )
3774                     {
3775                         vTaskSuspendAll();
3776                         {
3777                             if( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) != NULL )
3778                             {
3779                                 pxTaskStatus->eCurrentState = eBlocked;
3780                             }
3781                         }
3782                         ( void ) xTaskResumeAll();
3783                     }
3784                 }
3785                 #endif /* INCLUDE_vTaskSuspend */
3786             }
3787         }
3788         else
3789         {
3790             pxTaskStatus->eCurrentState = eTaskGetState( pxTCB );
3791         }
3792
3793         /* Obtaining the stack space takes some time, so the xGetFreeStackSpace
3794          * parameter is provided to allow it to be skipped. */
3795         if( xGetFreeStackSpace != pdFALSE )
3796         {
3797             #if ( portSTACK_GROWTH > 0 )
3798             {
3799                 pxTaskStatus->usStackHighWaterMark = prvTaskCheckFreeStackSpace( ( uint8_t * ) pxTCB->pxEndOfStack );
3800             }
3801             #else
3802             {
3803                 pxTaskStatus->usStackHighWaterMark = prvTaskCheckFreeStackSpace( ( uint8_t * ) pxTCB->pxStack );
3804             }
3805             #endif
3806         }
3807         else
3808         {
3809             pxTaskStatus->usStackHighWaterMark = 0;
3810         }
3811     }
3812
3813 #endif /* configUSE_TRACE_FACILITY */
3814 /*-----------------------------------------------------------*/
3815
3816 #if ( configUSE_TRACE_FACILITY == 1 )
3817
3818     static UBaseType_t prvListTasksWithinSingleList( TaskStatus_t * pxTaskStatusArray,
3819                                                      List_t * pxList,
3820                                                      eTaskState eState )
3821     {
3822         configLIST_VOLATILE TCB_t * pxNextTCB;
3823         configLIST_VOLATILE TCB_t * pxFirstTCB;
3824         UBaseType_t uxTask = 0;
3825
3826         if( listCURRENT_LIST_LENGTH( pxList ) > ( UBaseType_t ) 0 )
3827         {
3828             listGET_OWNER_OF_NEXT_ENTRY( pxFirstTCB, pxList ); /*lint !e9079 void * is used as this macro is used with timers too.  Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */
3829
3830             /* Populate an TaskStatus_t structure within the
3831              * pxTaskStatusArray array for each task that is referenced from
3832              * pxList.  See the definition of TaskStatus_t in task.h for the
3833              * meaning of each TaskStatus_t structure member. */
3834             do
3835             {
3836                 listGET_OWNER_OF_NEXT_ENTRY( pxNextTCB, pxList ); /*lint !e9079 void * is used as this macro is used with timers too.  Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */
3837                 vTaskGetInfo( ( TaskHandle_t ) pxNextTCB, &( pxTaskStatusArray[ uxTask ] ), pdTRUE, eState );
3838                 uxTask++;
3839             } while( pxNextTCB != pxFirstTCB );
3840         }
3841         else
3842         {
3843             mtCOVERAGE_TEST_MARKER();
3844         }
3845
3846         return uxTask;
3847     }
3848
3849 #endif /* configUSE_TRACE_FACILITY */
3850 /*-----------------------------------------------------------*/
3851
3852 #if ( ( configUSE_TRACE_FACILITY == 1 ) || ( INCLUDE_uxTaskGetStackHighWaterMark == 1 ) || ( INCLUDE_uxTaskGetStackHighWaterMark2 == 1 ) )
3853
3854     static configSTACK_DEPTH_TYPE prvTaskCheckFreeStackSpace( const uint8_t * pucStackByte )
3855     {
3856         uint32_t ulCount = 0U;
3857
3858         while( *pucStackByte == ( uint8_t ) tskSTACK_FILL_BYTE )
3859         {
3860             pucStackByte -= portSTACK_GROWTH;
3861             ulCount++;
3862         }
3863
3864         ulCount /= ( uint32_t ) sizeof( StackType_t ); /*lint !e961 Casting is not redundant on smaller architectures. */
3865
3866         return ( configSTACK_DEPTH_TYPE ) ulCount;
3867     }
3868
3869 #endif /* ( ( configUSE_TRACE_FACILITY == 1 ) || ( INCLUDE_uxTaskGetStackHighWaterMark == 1 ) || ( INCLUDE_uxTaskGetStackHighWaterMark2 == 1 ) ) */
3870 /*-----------------------------------------------------------*/
3871
3872 #if ( INCLUDE_uxTaskGetStackHighWaterMark2 == 1 )
3873
3874 /* uxTaskGetStackHighWaterMark() and uxTaskGetStackHighWaterMark2() are the
3875  * same except for their return type.  Using configSTACK_DEPTH_TYPE allows the
3876  * user to determine the return type.  It gets around the problem of the value
3877  * overflowing on 8-bit types without breaking backward compatibility for
3878  * applications that expect an 8-bit return type. */
3879     configSTACK_DEPTH_TYPE uxTaskGetStackHighWaterMark2( TaskHandle_t xTask )
3880     {
3881         TCB_t * pxTCB;
3882         uint8_t * pucEndOfStack;
3883         configSTACK_DEPTH_TYPE uxReturn;
3884
3885         /* uxTaskGetStackHighWaterMark() and uxTaskGetStackHighWaterMark2() are
3886          * the same except for their return type.  Using configSTACK_DEPTH_TYPE
3887          * allows the user to determine the return type.  It gets around the
3888          * problem of the value overflowing on 8-bit types without breaking
3889          * backward compatibility for applications that expect an 8-bit return
3890          * type. */
3891
3892         pxTCB = prvGetTCBFromHandle( xTask );
3893
3894         #if portSTACK_GROWTH < 0
3895         {
3896             pucEndOfStack = ( uint8_t * ) pxTCB->pxStack;
3897         }
3898         #else
3899         {
3900             pucEndOfStack = ( uint8_t * ) pxTCB->pxEndOfStack;
3901         }
3902         #endif
3903
3904         uxReturn = prvTaskCheckFreeStackSpace( pucEndOfStack );
3905
3906         return uxReturn;
3907     }
3908
3909 #endif /* INCLUDE_uxTaskGetStackHighWaterMark2 */
3910 /*-----------------------------------------------------------*/
3911
3912 #if ( INCLUDE_uxTaskGetStackHighWaterMark == 1 )
3913
3914     UBaseType_t uxTaskGetStackHighWaterMark( TaskHandle_t xTask )
3915     {
3916         TCB_t * pxTCB;
3917         uint8_t * pucEndOfStack;
3918         UBaseType_t uxReturn;
3919
3920         pxTCB = prvGetTCBFromHandle( xTask );
3921
3922         #if portSTACK_GROWTH < 0
3923         {
3924             pucEndOfStack = ( uint8_t * ) pxTCB->pxStack;
3925         }
3926         #else
3927         {
3928             pucEndOfStack = ( uint8_t * ) pxTCB->pxEndOfStack;
3929         }
3930         #endif
3931
3932         uxReturn = ( UBaseType_t ) prvTaskCheckFreeStackSpace( pucEndOfStack );
3933
3934         return uxReturn;
3935     }
3936
3937 #endif /* INCLUDE_uxTaskGetStackHighWaterMark */
3938 /*-----------------------------------------------------------*/
3939
3940 #if ( INCLUDE_vTaskDelete == 1 )
3941
3942     static void prvDeleteTCB( TCB_t * pxTCB )
3943     {
3944         /* This call is required specifically for the TriCore port.  It must be
3945          * above the vPortFree() calls.  The call is also used by ports/demos that
3946          * want to allocate and clean RAM statically. */
3947         portCLEAN_UP_TCB( pxTCB );
3948
3949         #if ( ( configUSE_NEWLIB_REENTRANT == 1 ) || ( configUSE_C_RUNTIME_TLS_SUPPORT == 1 ) )
3950         {
3951             /* Free up the memory allocated for the task's TLS Block. */
3952             configDEINIT_TLS_BLOCK( pxCurrentTCB->xTLSBlock );
3953         }
3954         #endif
3955
3956         #if ( ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 0 ) && ( portUSING_MPU_WRAPPERS == 0 ) )
3957         {
3958             /* The task can only have been allocated dynamically - free both
3959              * the stack and TCB. */
3960             vPortFreeStack( pxTCB->pxStack );
3961             vPortFree( pxTCB );
3962         }
3963         #elif ( tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE != 0 ) /*lint !e731 !e9029 Macro has been consolidated for readability reasons. */
3964         {
3965             /* The task could have been allocated statically or dynamically, so
3966              * check what was statically allocated before trying to free the
3967              * memory. */
3968             if( pxTCB->ucStaticallyAllocated == tskDYNAMICALLY_ALLOCATED_STACK_AND_TCB )
3969             {
3970                 /* Both the stack and TCB were allocated dynamically, so both
3971                  * must be freed. */
3972                 vPortFreeStack( pxTCB->pxStack );
3973                 vPortFree( pxTCB );
3974             }
3975             else if( pxTCB->ucStaticallyAllocated == tskSTATICALLY_ALLOCATED_STACK_ONLY )
3976             {
3977                 /* Only the stack was statically allocated, so the TCB is the
3978                  * only memory that must be freed. */
3979                 vPortFree( pxTCB );
3980             }
3981             else
3982             {
3983                 /* Neither the stack nor the TCB were allocated dynamically, so
3984                  * nothing needs to be freed. */
3985                 configASSERT( pxTCB->ucStaticallyAllocated == tskSTATICALLY_ALLOCATED_STACK_AND_TCB );
3986                 mtCOVERAGE_TEST_MARKER();
3987             }
3988         }
3989         #endif /* configSUPPORT_DYNAMIC_ALLOCATION */
3990     }
3991
3992 #endif /* INCLUDE_vTaskDelete */
3993 /*-----------------------------------------------------------*/
3994
3995 static void prvResetNextTaskUnblockTime( void )
3996 {
3997     if( listLIST_IS_EMPTY( pxDelayedTaskList ) != pdFALSE )
3998     {
3999         /* The new current delayed list is empty.  Set xNextTaskUnblockTime to
4000          * the maximum possible value so it is  extremely unlikely that the
4001          * if( xTickCount >= xNextTaskUnblockTime ) test will pass until
4002          * there is an item in the delayed list. */
4003         xNextTaskUnblockTime = portMAX_DELAY;
4004     }
4005     else
4006     {
4007         /* The new current delayed list is not empty, get the value of
4008          * the item at the head of the delayed list.  This is the time at
4009          * which the task at the head of the delayed list should be removed
4010          * from the Blocked state. */
4011         xNextTaskUnblockTime = listGET_ITEM_VALUE_OF_HEAD_ENTRY( pxDelayedTaskList );
4012     }
4013 }
4014 /*-----------------------------------------------------------*/
4015
4016 #if ( ( INCLUDE_xTaskGetCurrentTaskHandle == 1 ) || ( configUSE_MUTEXES == 1 ) )
4017
4018     TaskHandle_t xTaskGetCurrentTaskHandle( void )
4019     {
4020         TaskHandle_t xReturn;
4021
4022         /* A critical section is not required as this is not called from
4023          * an interrupt and the current TCB will always be the same for any
4024          * individual execution thread. */
4025         xReturn = pxCurrentTCB;
4026
4027         return xReturn;
4028     }
4029
4030 #endif /* ( ( INCLUDE_xTaskGetCurrentTaskHandle == 1 ) || ( configUSE_MUTEXES == 1 ) ) */
4031 /*-----------------------------------------------------------*/
4032
4033 #if ( ( INCLUDE_xTaskGetSchedulerState == 1 ) || ( configUSE_TIMERS == 1 ) )
4034
4035     BaseType_t xTaskGetSchedulerState( void )
4036     {
4037         BaseType_t xReturn;
4038
4039         if( xSchedulerRunning == pdFALSE )
4040         {
4041             xReturn = taskSCHEDULER_NOT_STARTED;
4042         }
4043         else
4044         {
4045             if( uxSchedulerSuspended == ( UBaseType_t ) pdFALSE )
4046             {
4047                 xReturn = taskSCHEDULER_RUNNING;
4048             }
4049             else
4050             {
4051                 xReturn = taskSCHEDULER_SUSPENDED;
4052             }
4053         }
4054
4055         return xReturn;
4056     }
4057
4058 #endif /* ( ( INCLUDE_xTaskGetSchedulerState == 1 ) || ( configUSE_TIMERS == 1 ) ) */
4059 /*-----------------------------------------------------------*/
4060
4061 #if ( configUSE_MUTEXES == 1 )
4062
4063     BaseType_t xTaskPriorityInherit( TaskHandle_t const pxMutexHolder )
4064     {
4065         TCB_t * const pxMutexHolderTCB = pxMutexHolder;
4066         BaseType_t xReturn = pdFALSE;
4067
4068         /* If the mutex was given back by an interrupt while the queue was
4069          * locked then the mutex holder might now be NULL.  _RB_ Is this still
4070          * needed as interrupts can no longer use mutexes? */
4071         if( pxMutexHolder != NULL )
4072         {
4073             /* If the holder of the mutex has a priority below the priority of
4074              * the task attempting to obtain the mutex then it will temporarily
4075              * inherit the priority of the task attempting to obtain the mutex. */
4076             if( pxMutexHolderTCB->uxPriority < pxCurrentTCB->uxPriority )
4077             {
4078                 /* Adjust the mutex holder state to account for its new
4079                  * priority.  Only reset the event list item value if the value is
4080                  * not being used for anything else. */
4081                 if( ( listGET_LIST_ITEM_VALUE( &( pxMutexHolderTCB->xEventListItem ) ) & taskEVENT_LIST_ITEM_VALUE_IN_USE ) == 0UL )
4082                 {
4083                     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. */
4084                 }
4085                 else
4086                 {
4087                     mtCOVERAGE_TEST_MARKER();
4088                 }
4089
4090                 /* If the task being modified is in the ready state it will need
4091                  * to be moved into a new list. */
4092                 if( listIS_CONTAINED_WITHIN( &( pxReadyTasksLists[ pxMutexHolderTCB->uxPriority ] ), &( pxMutexHolderTCB->xStateListItem ) ) != pdFALSE )
4093                 {
4094                     if( uxListRemove( &( pxMutexHolderTCB->xStateListItem ) ) == ( UBaseType_t ) 0 )
4095                     {
4096                         /* It is known that the task is in its ready list so
4097                          * there is no need to check again and the port level
4098                          * reset macro can be called directly. */
4099                         portRESET_READY_PRIORITY( pxMutexHolderTCB->uxPriority, uxTopReadyPriority );
4100                     }
4101                     else
4102                     {
4103                         mtCOVERAGE_TEST_MARKER();
4104                     }
4105
4106                     /* Inherit the priority before being moved into the new list. */
4107                     pxMutexHolderTCB->uxPriority = pxCurrentTCB->uxPriority;
4108                     prvAddTaskToReadyList( pxMutexHolderTCB );
4109                 }
4110                 else
4111                 {
4112                     /* Just inherit the priority. */
4113                     pxMutexHolderTCB->uxPriority = pxCurrentTCB->uxPriority;
4114                 }
4115
4116                 traceTASK_PRIORITY_INHERIT( pxMutexHolderTCB, pxCurrentTCB->uxPriority );
4117
4118                 /* Inheritance occurred. */
4119                 xReturn = pdTRUE;
4120             }
4121             else
4122             {
4123                 if( pxMutexHolderTCB->uxBasePriority < pxCurrentTCB->uxPriority )
4124                 {
4125                     /* The base priority of the mutex holder is lower than the
4126                      * priority of the task attempting to take the mutex, but the
4127                      * current priority of the mutex holder is not lower than the
4128                      * priority of the task attempting to take the mutex.
4129                      * Therefore the mutex holder must have already inherited a
4130                      * priority, but inheritance would have occurred if that had
4131                      * not been the case. */
4132                     xReturn = pdTRUE;
4133                 }
4134                 else
4135                 {
4136                     mtCOVERAGE_TEST_MARKER();
4137                 }
4138             }
4139         }
4140         else
4141         {
4142             mtCOVERAGE_TEST_MARKER();
4143         }
4144
4145         return xReturn;
4146     }
4147
4148 #endif /* configUSE_MUTEXES */
4149 /*-----------------------------------------------------------*/
4150
4151 #if ( configUSE_MUTEXES == 1 )
4152
4153     BaseType_t xTaskPriorityDisinherit( TaskHandle_t const pxMutexHolder )
4154     {
4155         TCB_t * const pxTCB = pxMutexHolder;
4156         BaseType_t xReturn = pdFALSE;
4157
4158         if( pxMutexHolder != NULL )
4159         {
4160             /* A task can only have an inherited priority if it holds the mutex.
4161              * If the mutex is held by a task then it cannot be given from an
4162              * interrupt, and if a mutex is given by the holding task then it must
4163              * be the running state task. */
4164             configASSERT( pxTCB == pxCurrentTCB );
4165             configASSERT( pxTCB->uxMutexesHeld );
4166             ( pxTCB->uxMutexesHeld )--;
4167
4168             /* Has the holder of the mutex inherited the priority of another
4169              * task? */
4170             if( pxTCB->uxPriority != pxTCB->uxBasePriority )
4171             {
4172                 /* Only disinherit if no other mutexes are held. */
4173                 if( pxTCB->uxMutexesHeld == ( UBaseType_t ) 0 )
4174                 {
4175                     /* A task can only have an inherited priority if it holds
4176                      * the mutex.  If the mutex is held by a task then it cannot be
4177                      * given from an interrupt, and if a mutex is given by the
4178                      * holding task then it must be the running state task.  Remove
4179                      * the holding task from the ready list. */
4180                     if( uxListRemove( &( pxTCB->xStateListItem ) ) == ( UBaseType_t ) 0 )
4181                     {
4182                         portRESET_READY_PRIORITY( pxTCB->uxPriority, uxTopReadyPriority );
4183                     }
4184                     else
4185                     {
4186                         mtCOVERAGE_TEST_MARKER();
4187                     }
4188
4189                     /* Disinherit the priority before adding the task into the
4190                      * new  ready list. */
4191                     traceTASK_PRIORITY_DISINHERIT( pxTCB, pxTCB->uxBasePriority );
4192                     pxTCB->uxPriority = pxTCB->uxBasePriority;
4193
4194                     /* Reset the event list item value.  It cannot be in use for
4195                      * any other purpose if this task is running, and it must be
4196                      * running to give back the mutex. */
4197                     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. */
4198                     prvAddTaskToReadyList( pxTCB );
4199
4200                     /* Return true to indicate that a context switch is required.
4201                      * This is only actually required in the corner case whereby
4202                      * multiple mutexes were held and the mutexes were given back
4203                      * in an order different to that in which they were taken.
4204                      * If a context switch did not occur when the first mutex was
4205                      * returned, even if a task was waiting on it, then a context
4206                      * switch should occur when the last mutex is returned whether
4207                      * a task is waiting on it or not. */
4208                     xReturn = pdTRUE;
4209                 }
4210                 else
4211                 {
4212                     mtCOVERAGE_TEST_MARKER();
4213                 }
4214             }
4215             else
4216             {
4217                 mtCOVERAGE_TEST_MARKER();
4218             }
4219         }
4220         else
4221         {
4222             mtCOVERAGE_TEST_MARKER();
4223         }
4224
4225         return xReturn;
4226     }
4227
4228 #endif /* configUSE_MUTEXES */
4229 /*-----------------------------------------------------------*/
4230
4231 #if ( configUSE_MUTEXES == 1 )
4232
4233     void vTaskPriorityDisinheritAfterTimeout( TaskHandle_t const pxMutexHolder,
4234                                               UBaseType_t uxHighestPriorityWaitingTask )
4235     {
4236         TCB_t * const pxTCB = pxMutexHolder;
4237         UBaseType_t uxPriorityUsedOnEntry, uxPriorityToUse;
4238         const UBaseType_t uxOnlyOneMutexHeld = ( UBaseType_t ) 1;
4239
4240         if( pxMutexHolder != NULL )
4241         {
4242             /* If pxMutexHolder is not NULL then the holder must hold at least
4243              * one mutex. */
4244             configASSERT( pxTCB->uxMutexesHeld );
4245
4246             /* Determine the priority to which the priority of the task that
4247              * holds the mutex should be set.  This will be the greater of the
4248              * holding task's base priority and the priority of the highest
4249              * priority task that is waiting to obtain the mutex. */
4250             if( pxTCB->uxBasePriority < uxHighestPriorityWaitingTask )
4251             {
4252                 uxPriorityToUse = uxHighestPriorityWaitingTask;
4253             }
4254             else
4255             {
4256                 uxPriorityToUse = pxTCB->uxBasePriority;
4257             }
4258
4259             /* Does the priority need to change? */
4260             if( pxTCB->uxPriority != uxPriorityToUse )
4261             {
4262                 /* Only disinherit if no other mutexes are held.  This is a
4263                  * simplification in the priority inheritance implementation.  If
4264                  * the task that holds the mutex is also holding other mutexes then
4265                  * the other mutexes may have caused the priority inheritance. */
4266                 if( pxTCB->uxMutexesHeld == uxOnlyOneMutexHeld )
4267                 {
4268                     /* If a task has timed out because it already holds the
4269                      * mutex it was trying to obtain then it cannot of inherited
4270                      * its own priority. */
4271                     configASSERT( pxTCB != pxCurrentTCB );
4272
4273                     /* Disinherit the priority, remembering the previous
4274                      * priority to facilitate determining the subject task's
4275                      * state. */
4276                     traceTASK_PRIORITY_DISINHERIT( pxTCB, uxPriorityToUse );
4277                     uxPriorityUsedOnEntry = pxTCB->uxPriority;
4278                     pxTCB->uxPriority = uxPriorityToUse;
4279
4280                     /* Only reset the event list item value if the value is not
4281                      * being used for anything else. */
4282                     if( ( listGET_LIST_ITEM_VALUE( &( pxTCB->xEventListItem ) ) & taskEVENT_LIST_ITEM_VALUE_IN_USE ) == 0UL )
4283                     {
4284                         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. */
4285                     }
4286                     else
4287                     {
4288                         mtCOVERAGE_TEST_MARKER();
4289                     }
4290
4291                     /* If the running task is not the task that holds the mutex
4292                      * then the task that holds the mutex could be in either the
4293                      * Ready, Blocked or Suspended states.  Only remove the task
4294                      * from its current state list if it is in the Ready state as
4295                      * the task's priority is going to change and there is one
4296                      * Ready list per priority. */
4297                     if( listIS_CONTAINED_WITHIN( &( pxReadyTasksLists[ uxPriorityUsedOnEntry ] ), &( pxTCB->xStateListItem ) ) != pdFALSE )
4298                     {
4299                         if( uxListRemove( &( pxTCB->xStateListItem ) ) == ( UBaseType_t ) 0 )
4300                         {
4301                             /* It is known that the task is in its ready list so
4302                              * there is no need to check again and the port level
4303                              * reset macro can be called directly. */
4304                             portRESET_READY_PRIORITY( pxTCB->uxPriority, uxTopReadyPriority );
4305                         }
4306                         else
4307                         {
4308                             mtCOVERAGE_TEST_MARKER();
4309                         }
4310
4311                         prvAddTaskToReadyList( pxTCB );
4312                     }
4313                     else
4314                     {
4315                         mtCOVERAGE_TEST_MARKER();
4316                     }
4317                 }
4318                 else
4319                 {
4320                     mtCOVERAGE_TEST_MARKER();
4321                 }
4322             }
4323             else
4324             {
4325                 mtCOVERAGE_TEST_MARKER();
4326             }
4327         }
4328         else
4329         {
4330             mtCOVERAGE_TEST_MARKER();
4331         }
4332     }
4333
4334 #endif /* configUSE_MUTEXES */
4335 /*-----------------------------------------------------------*/
4336
4337 #if ( portCRITICAL_NESTING_IN_TCB == 1 )
4338
4339     void vTaskEnterCritical( void )
4340     {
4341         portDISABLE_INTERRUPTS();
4342
4343         if( xSchedulerRunning != pdFALSE )
4344         {
4345             ( pxCurrentTCB->uxCriticalNesting )++;
4346
4347             /* This is not the interrupt safe version of the enter critical
4348              * function so  assert() if it is being called from an interrupt
4349              * context.  Only API functions that end in "FromISR" can be used in an
4350              * interrupt.  Only assert if the critical nesting count is 1 to
4351              * protect against recursive calls if the assert function also uses a
4352              * critical section. */
4353             if( pxCurrentTCB->uxCriticalNesting == 1 )
4354             {
4355                 portASSERT_IF_IN_ISR();
4356             }
4357         }
4358         else
4359         {
4360             mtCOVERAGE_TEST_MARKER();
4361         }
4362     }
4363
4364 #endif /* portCRITICAL_NESTING_IN_TCB */
4365 /*-----------------------------------------------------------*/
4366
4367 #if ( portCRITICAL_NESTING_IN_TCB == 1 )
4368
4369     void vTaskExitCritical( void )
4370     {
4371         if( xSchedulerRunning != pdFALSE )
4372         {
4373             if( pxCurrentTCB->uxCriticalNesting > 0U )
4374             {
4375                 ( pxCurrentTCB->uxCriticalNesting )--;
4376
4377                 if( pxCurrentTCB->uxCriticalNesting == 0U )
4378                 {
4379                     portENABLE_INTERRUPTS();
4380                 }
4381                 else
4382                 {
4383                     mtCOVERAGE_TEST_MARKER();
4384                 }
4385             }
4386             else
4387             {
4388                 mtCOVERAGE_TEST_MARKER();
4389             }
4390         }
4391         else
4392         {
4393             mtCOVERAGE_TEST_MARKER();
4394         }
4395     }
4396
4397 #endif /* portCRITICAL_NESTING_IN_TCB */
4398 /*-----------------------------------------------------------*/
4399
4400 #if ( configUSE_STATS_FORMATTING_FUNCTIONS > 0 )
4401
4402     static char * prvWriteNameToBuffer( char * pcBuffer,
4403                                         const char * pcTaskName )
4404     {
4405         size_t x;
4406
4407         /* Start by copying the entire string. */
4408         strcpy( pcBuffer, pcTaskName );
4409
4410         /* Pad the end of the string with spaces to ensure columns line up when
4411          * printed out. */
4412         for( x = strlen( pcBuffer ); x < ( size_t ) ( configMAX_TASK_NAME_LEN - 1 ); x++ )
4413         {
4414             pcBuffer[ x ] = ' ';
4415         }
4416
4417         /* Terminate. */
4418         pcBuffer[ x ] = ( char ) 0x00;
4419
4420         /* Return the new end of string. */
4421         return &( pcBuffer[ x ] );
4422     }
4423
4424 #endif /* ( configUSE_STATS_FORMATTING_FUNCTIONS > 0 ) */
4425 /*-----------------------------------------------------------*/
4426
4427 #if ( ( configUSE_TRACE_FACILITY == 1 ) && ( configUSE_STATS_FORMATTING_FUNCTIONS > 0 ) )
4428
4429     void vTaskList( char * pcWriteBuffer )
4430     {
4431         TaskStatus_t * pxTaskStatusArray;
4432         UBaseType_t uxArraySize, x;
4433         char cStatus;
4434
4435         /*
4436          * PLEASE NOTE:
4437          *
4438          * This function is provided for convenience only, and is used by many
4439          * of the demo applications.  Do not consider it to be part of the
4440          * scheduler.
4441          *
4442          * vTaskList() calls uxTaskGetSystemState(), then formats part of the
4443          * uxTaskGetSystemState() output into a human readable table that
4444          * displays task: names, states, priority, stack usage and task number.
4445          * Stack usage specified as the number of unused StackType_t words stack can hold
4446          * on top of stack - not the number of bytes.
4447          *
4448          * vTaskList() has a dependency on the sprintf() C library function that
4449          * might bloat the code size, use a lot of stack, and provide different
4450          * results on different platforms.  An alternative, tiny, third party,
4451          * and limited functionality implementation of sprintf() is provided in
4452          * many of the FreeRTOS/Demo sub-directories in a file called
4453          * printf-stdarg.c (note printf-stdarg.c does not provide a full
4454          * snprintf() implementation!).
4455          *
4456          * It is recommended that production systems call uxTaskGetSystemState()
4457          * directly to get access to raw stats data, rather than indirectly
4458          * through a call to vTaskList().
4459          */
4460
4461
4462         /* Make sure the write buffer does not contain a string. */
4463         *pcWriteBuffer = ( char ) 0x00;
4464
4465         /* Take a snapshot of the number of tasks in case it changes while this
4466          * function is executing. */
4467         uxArraySize = uxCurrentNumberOfTasks;
4468
4469         /* Allocate an array index for each task.  NOTE!  if
4470          * configSUPPORT_DYNAMIC_ALLOCATION is set to 0 then pvPortMalloc() will
4471          * equate to NULL. */
4472         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. */
4473
4474         if( pxTaskStatusArray != NULL )
4475         {
4476             /* Generate the (binary) data. */
4477             uxArraySize = uxTaskGetSystemState( pxTaskStatusArray, uxArraySize, NULL );
4478
4479             /* Create a human readable table from the binary data. */
4480             for( x = 0; x < uxArraySize; x++ )
4481             {
4482                 switch( pxTaskStatusArray[ x ].eCurrentState )
4483                 {
4484                     case eRunning:
4485                         cStatus = tskRUNNING_CHAR;
4486                         break;
4487
4488                     case eReady:
4489                         cStatus = tskREADY_CHAR;
4490                         break;
4491
4492                     case eBlocked:
4493                         cStatus = tskBLOCKED_CHAR;
4494                         break;
4495
4496                     case eSuspended:
4497                         cStatus = tskSUSPENDED_CHAR;
4498                         break;
4499
4500                     case eDeleted:
4501                         cStatus = tskDELETED_CHAR;
4502                         break;
4503
4504                     case eInvalid: /* Fall through. */
4505                     default:       /* Should not get here, but it is included
4506                                     * to prevent static checking errors. */
4507                         cStatus = ( char ) 0x00;
4508                         break;
4509                 }
4510
4511                 /* Write the task name to the string, padding with spaces so it
4512                  * can be printed in tabular form more easily. */
4513                 pcWriteBuffer = prvWriteNameToBuffer( pcWriteBuffer, pxTaskStatusArray[ x ].pcTaskName );
4514
4515                 /* Write the rest of the string. */
4516                 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. */
4517                 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. */
4518             }
4519
4520             /* Free the array again.  NOTE!  If configSUPPORT_DYNAMIC_ALLOCATION
4521              * is 0 then vPortFree() will be #defined to nothing. */
4522             vPortFree( pxTaskStatusArray );
4523         }
4524         else
4525         {
4526             mtCOVERAGE_TEST_MARKER();
4527         }
4528     }
4529
4530 #endif /* ( ( configUSE_TRACE_FACILITY == 1 ) && ( configUSE_STATS_FORMATTING_FUNCTIONS > 0 ) ) */
4531 /*----------------------------------------------------------*/
4532
4533 #if ( ( configGENERATE_RUN_TIME_STATS == 1 ) && ( configUSE_STATS_FORMATTING_FUNCTIONS > 0 ) && ( configUSE_TRACE_FACILITY == 1 ) )
4534
4535     void vTaskGetRunTimeStats( char * pcWriteBuffer )
4536     {
4537         TaskStatus_t * pxTaskStatusArray;
4538         UBaseType_t uxArraySize, x;
4539         configRUN_TIME_COUNTER_TYPE ulTotalTime, ulStatsAsPercentage;
4540
4541         /*
4542          * PLEASE NOTE:
4543          *
4544          * This function is provided for convenience only, and is used by many
4545          * of the demo applications.  Do not consider it to be part of the
4546          * scheduler.
4547          *
4548          * vTaskGetRunTimeStats() calls uxTaskGetSystemState(), then formats part
4549          * of the uxTaskGetSystemState() output into a human readable table that
4550          * displays the amount of time each task has spent in the Running state
4551          * in both absolute and percentage terms.
4552          *
4553          * vTaskGetRunTimeStats() has a dependency on the sprintf() C library
4554          * function that might bloat the code size, use a lot of stack, and
4555          * provide different results on different platforms.  An alternative,
4556          * tiny, third party, and limited functionality implementation of
4557          * sprintf() is provided in many of the FreeRTOS/Demo sub-directories in
4558          * a file called printf-stdarg.c (note printf-stdarg.c does not provide
4559          * a full snprintf() implementation!).
4560          *
4561          * It is recommended that production systems call uxTaskGetSystemState()
4562          * directly to get access to raw stats data, rather than indirectly
4563          * through a call to vTaskGetRunTimeStats().
4564          */
4565
4566         /* Make sure the write buffer does not contain a string. */
4567         *pcWriteBuffer = ( char ) 0x00;
4568
4569         /* Take a snapshot of the number of tasks in case it changes while this
4570          * function is executing. */
4571         uxArraySize = uxCurrentNumberOfTasks;
4572
4573         /* Allocate an array index for each task.  NOTE!  If
4574          * configSUPPORT_DYNAMIC_ALLOCATION is set to 0 then pvPortMalloc() will
4575          * equate to NULL. */
4576         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. */
4577
4578         if( pxTaskStatusArray != NULL )
4579         {
4580             /* Generate the (binary) data. */
4581             uxArraySize = uxTaskGetSystemState( pxTaskStatusArray, uxArraySize, &ulTotalTime );
4582
4583             /* For percentage calculations. */
4584             ulTotalTime /= 100UL;
4585
4586             /* Avoid divide by zero errors. */
4587             if( ulTotalTime > 0UL )
4588             {
4589                 /* Create a human readable table from the binary data. */
4590                 for( x = 0; x < uxArraySize; x++ )
4591                 {
4592                     /* What percentage of the total run time has the task used?
4593                      * This will always be rounded down to the nearest integer.
4594                      * ulTotalRunTime has already been divided by 100. */
4595                     ulStatsAsPercentage = pxTaskStatusArray[ x ].ulRunTimeCounter / ulTotalTime;
4596
4597                     /* Write the task name to the string, padding with
4598                      * spaces so it can be printed in tabular form more
4599                      * easily. */
4600                     pcWriteBuffer = prvWriteNameToBuffer( pcWriteBuffer, pxTaskStatusArray[ x ].pcTaskName );
4601
4602                     if( ulStatsAsPercentage > 0UL )
4603                     {
4604                         #ifdef portLU_PRINTF_SPECIFIER_REQUIRED
4605                         {
4606                             sprintf( pcWriteBuffer, "\t%lu\t\t%lu%%\r\n", pxTaskStatusArray[ x ].ulRunTimeCounter, ulStatsAsPercentage );
4607                         }
4608                         #else
4609                         {
4610                             /* sizeof( int ) == sizeof( long ) so a smaller
4611                              * printf() library can be used. */
4612                             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. */
4613                         }
4614                         #endif
4615                     }
4616                     else
4617                     {
4618                         /* If the percentage is zero here then the task has
4619                          * consumed less than 1% of the total run time. */
4620                         #ifdef portLU_PRINTF_SPECIFIER_REQUIRED
4621                         {
4622                             sprintf( pcWriteBuffer, "\t%lu\t\t<1%%\r\n", pxTaskStatusArray[ x ].ulRunTimeCounter );
4623                         }
4624                         #else
4625                         {
4626                             /* sizeof( int ) == sizeof( long ) so a smaller
4627                              * printf() library can be used. */
4628                             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. */
4629                         }
4630                         #endif
4631                     }
4632
4633                     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. */
4634                 }
4635             }
4636             else
4637             {
4638                 mtCOVERAGE_TEST_MARKER();
4639             }
4640
4641             /* Free the array again.  NOTE!  If configSUPPORT_DYNAMIC_ALLOCATION
4642              * is 0 then vPortFree() will be #defined to nothing. */
4643             vPortFree( pxTaskStatusArray );
4644         }
4645         else
4646         {
4647             mtCOVERAGE_TEST_MARKER();
4648         }
4649     }
4650
4651 #endif /* ( ( configGENERATE_RUN_TIME_STATS == 1 ) && ( configUSE_STATS_FORMATTING_FUNCTIONS > 0 ) ) */
4652 /*-----------------------------------------------------------*/
4653
4654 TickType_t uxTaskResetEventItemValue( void )
4655 {
4656     TickType_t uxReturn;
4657
4658     uxReturn = listGET_LIST_ITEM_VALUE( &( pxCurrentTCB->xEventListItem ) );
4659
4660     /* Reset the event list item to its normal value - so it can be used with
4661      * queues and semaphores. */
4662     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. */
4663
4664     return uxReturn;
4665 }
4666 /*-----------------------------------------------------------*/
4667
4668 #if ( configUSE_MUTEXES == 1 )
4669
4670     TaskHandle_t pvTaskIncrementMutexHeldCount( void )
4671     {
4672         /* If xSemaphoreCreateMutex() is called before any tasks have been created
4673          * then pxCurrentTCB will be NULL. */
4674         if( pxCurrentTCB != NULL )
4675         {
4676             ( pxCurrentTCB->uxMutexesHeld )++;
4677         }
4678
4679         return pxCurrentTCB;
4680     }
4681
4682 #endif /* configUSE_MUTEXES */
4683 /*-----------------------------------------------------------*/
4684
4685 #if ( configUSE_TASK_NOTIFICATIONS == 1 )
4686
4687     uint32_t ulTaskGenericNotifyTake( UBaseType_t uxIndexToWait,
4688                                       BaseType_t xClearCountOnExit,
4689                                       TickType_t xTicksToWait )
4690     {
4691         uint32_t ulReturn;
4692
4693         configASSERT( uxIndexToWait < configTASK_NOTIFICATION_ARRAY_ENTRIES );
4694
4695         taskENTER_CRITICAL();
4696         {
4697             /* Only block if the notification count is not already non-zero. */
4698             if( pxCurrentTCB->ulNotifiedValue[ uxIndexToWait ] == 0UL )
4699             {
4700                 /* Mark this task as waiting for a notification. */
4701                 pxCurrentTCB->ucNotifyState[ uxIndexToWait ] = taskWAITING_NOTIFICATION;
4702
4703                 if( xTicksToWait > ( TickType_t ) 0 )
4704                 {
4705                     prvAddCurrentTaskToDelayedList( xTicksToWait, pdTRUE );
4706                     traceTASK_NOTIFY_TAKE_BLOCK( uxIndexToWait );
4707
4708                     /* All ports are written to allow a yield in a critical
4709                      * section (some will yield immediately, others wait until the
4710                      * critical section exits) - but it is not something that
4711                      * application code should ever do. */
4712                     portYIELD_WITHIN_API();
4713                 }
4714                 else
4715                 {
4716                     mtCOVERAGE_TEST_MARKER();
4717                 }
4718             }
4719             else
4720             {
4721                 mtCOVERAGE_TEST_MARKER();
4722             }
4723         }
4724         taskEXIT_CRITICAL();
4725
4726         taskENTER_CRITICAL();
4727         {
4728             traceTASK_NOTIFY_TAKE( uxIndexToWait );
4729             ulReturn = pxCurrentTCB->ulNotifiedValue[ uxIndexToWait ];
4730
4731             if( ulReturn != 0UL )
4732             {
4733                 if( xClearCountOnExit != pdFALSE )
4734                 {
4735                     pxCurrentTCB->ulNotifiedValue[ uxIndexToWait ] = 0UL;
4736                 }
4737                 else
4738                 {
4739                     pxCurrentTCB->ulNotifiedValue[ uxIndexToWait ] = ulReturn - ( uint32_t ) 1;
4740                 }
4741             }
4742             else
4743             {
4744                 mtCOVERAGE_TEST_MARKER();
4745             }
4746
4747             pxCurrentTCB->ucNotifyState[ uxIndexToWait ] = taskNOT_WAITING_NOTIFICATION;
4748         }
4749         taskEXIT_CRITICAL();
4750
4751         return ulReturn;
4752     }
4753
4754 #endif /* configUSE_TASK_NOTIFICATIONS */
4755 /*-----------------------------------------------------------*/
4756
4757 #if ( configUSE_TASK_NOTIFICATIONS == 1 )
4758
4759     BaseType_t xTaskGenericNotifyWait( UBaseType_t uxIndexToWait,
4760                                        uint32_t ulBitsToClearOnEntry,
4761                                        uint32_t ulBitsToClearOnExit,
4762                                        uint32_t * pulNotificationValue,
4763                                        TickType_t xTicksToWait )
4764     {
4765         BaseType_t xReturn;
4766
4767         configASSERT( uxIndexToWait < configTASK_NOTIFICATION_ARRAY_ENTRIES );
4768
4769         taskENTER_CRITICAL();
4770         {
4771             /* Only block if a notification is not already pending. */
4772             if( pxCurrentTCB->ucNotifyState[ uxIndexToWait ] != taskNOTIFICATION_RECEIVED )
4773             {
4774                 /* Clear bits in the task's notification value as bits may get
4775                  * set  by the notifying task or interrupt.  This can be used to
4776                  * clear the value to zero. */
4777                 pxCurrentTCB->ulNotifiedValue[ uxIndexToWait ] &= ~ulBitsToClearOnEntry;
4778
4779                 /* Mark this task as waiting for a notification. */
4780                 pxCurrentTCB->ucNotifyState[ uxIndexToWait ] = taskWAITING_NOTIFICATION;
4781
4782                 if( xTicksToWait > ( TickType_t ) 0 )
4783                 {
4784                     prvAddCurrentTaskToDelayedList( xTicksToWait, pdTRUE );
4785                     traceTASK_NOTIFY_WAIT_BLOCK( uxIndexToWait );
4786
4787                     /* All ports are written to allow a yield in a critical
4788                      * section (some will yield immediately, others wait until the
4789                      * critical section exits) - but it is not something that
4790                      * application code should ever do. */
4791                     portYIELD_WITHIN_API();
4792                 }
4793                 else
4794                 {
4795                     mtCOVERAGE_TEST_MARKER();
4796                 }
4797             }
4798             else
4799             {
4800                 mtCOVERAGE_TEST_MARKER();
4801             }
4802         }
4803         taskEXIT_CRITICAL();
4804
4805         taskENTER_CRITICAL();
4806         {
4807             traceTASK_NOTIFY_WAIT( uxIndexToWait );
4808
4809             if( pulNotificationValue != NULL )
4810             {
4811                 /* Output the current notification value, which may or may not
4812                  * have changed. */
4813                 *pulNotificationValue = pxCurrentTCB->ulNotifiedValue[ uxIndexToWait ];
4814             }
4815
4816             /* If ucNotifyValue is set then either the task never entered the
4817              * blocked state (because a notification was already pending) or the
4818              * task unblocked because of a notification.  Otherwise the task
4819              * unblocked because of a timeout. */
4820             if( pxCurrentTCB->ucNotifyState[ uxIndexToWait ] != taskNOTIFICATION_RECEIVED )
4821             {
4822                 /* A notification was not received. */
4823                 xReturn = pdFALSE;
4824             }
4825             else
4826             {
4827                 /* A notification was already pending or a notification was
4828                  * received while the task was waiting. */
4829                 pxCurrentTCB->ulNotifiedValue[ uxIndexToWait ] &= ~ulBitsToClearOnExit;
4830                 xReturn = pdTRUE;
4831             }
4832
4833             pxCurrentTCB->ucNotifyState[ uxIndexToWait ] = taskNOT_WAITING_NOTIFICATION;
4834         }
4835         taskEXIT_CRITICAL();
4836
4837         return xReturn;
4838     }
4839
4840 #endif /* configUSE_TASK_NOTIFICATIONS */
4841 /*-----------------------------------------------------------*/
4842
4843 #if ( configUSE_TASK_NOTIFICATIONS == 1 )
4844
4845     BaseType_t xTaskGenericNotify( TaskHandle_t xTaskToNotify,
4846                                    UBaseType_t uxIndexToNotify,
4847                                    uint32_t ulValue,
4848                                    eNotifyAction eAction,
4849                                    uint32_t * pulPreviousNotificationValue )
4850     {
4851         TCB_t * pxTCB;
4852         BaseType_t xReturn = pdPASS;
4853         uint8_t ucOriginalNotifyState;
4854
4855         configASSERT( uxIndexToNotify < configTASK_NOTIFICATION_ARRAY_ENTRIES );
4856         configASSERT( xTaskToNotify );
4857         pxTCB = xTaskToNotify;
4858
4859         taskENTER_CRITICAL();
4860         {
4861             if( pulPreviousNotificationValue != NULL )
4862             {
4863                 *pulPreviousNotificationValue = pxTCB->ulNotifiedValue[ uxIndexToNotify ];
4864             }
4865
4866             ucOriginalNotifyState = pxTCB->ucNotifyState[ uxIndexToNotify ];
4867
4868             pxTCB->ucNotifyState[ uxIndexToNotify ] = taskNOTIFICATION_RECEIVED;
4869
4870             switch( eAction )
4871             {
4872                 case eSetBits:
4873                     pxTCB->ulNotifiedValue[ uxIndexToNotify ] |= ulValue;
4874                     break;
4875
4876                 case eIncrement:
4877                     ( pxTCB->ulNotifiedValue[ uxIndexToNotify ] )++;
4878                     break;
4879
4880                 case eSetValueWithOverwrite:
4881                     pxTCB->ulNotifiedValue[ uxIndexToNotify ] = ulValue;
4882                     break;
4883
4884                 case eSetValueWithoutOverwrite:
4885
4886                     if( ucOriginalNotifyState != taskNOTIFICATION_RECEIVED )
4887                     {
4888                         pxTCB->ulNotifiedValue[ uxIndexToNotify ] = ulValue;
4889                     }
4890                     else
4891                     {
4892                         /* The value could not be written to the task. */
4893                         xReturn = pdFAIL;
4894                     }
4895
4896                     break;
4897
4898                 case eNoAction:
4899
4900                     /* The task is being notified without its notify value being
4901                      * updated. */
4902                     break;
4903
4904                 default:
4905
4906                     /* Should not get here if all enums are handled.
4907                      * Artificially force an assert by testing a value the
4908                      * compiler can't assume is const. */
4909                     configASSERT( xTickCount == ( TickType_t ) 0 );
4910
4911                     break;
4912             }
4913
4914             traceTASK_NOTIFY( uxIndexToNotify );
4915
4916             /* If the task is in the blocked state specifically to wait for a
4917              * notification then unblock it now. */
4918             if( ucOriginalNotifyState == taskWAITING_NOTIFICATION )
4919             {
4920                 listREMOVE_ITEM( &( pxTCB->xStateListItem ) );
4921                 prvAddTaskToReadyList( pxTCB );
4922
4923                 /* The task should not have been on an event list. */
4924                 configASSERT( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) == NULL );
4925
4926                 #if ( configUSE_TICKLESS_IDLE != 0 )
4927                 {
4928                     /* If a task is blocked waiting for a notification then
4929                      * xNextTaskUnblockTime might be set to the blocked task's time
4930                      * out time.  If the task is unblocked for a reason other than
4931                      * a timeout xNextTaskUnblockTime is normally left unchanged,
4932                      * because it will automatically get reset to a new value when
4933                      * the tick count equals xNextTaskUnblockTime.  However if
4934                      * tickless idling is used it might be more important to enter
4935                      * sleep mode at the earliest possible time - so reset
4936                      * xNextTaskUnblockTime here to ensure it is updated at the
4937                      * earliest possible time. */
4938                     prvResetNextTaskUnblockTime();
4939                 }
4940                 #endif
4941
4942                 if( pxTCB->uxPriority > pxCurrentTCB->uxPriority )
4943                 {
4944                     /* The notified task has a priority above the currently
4945                      * executing task so a yield is required. */
4946                     taskYIELD_IF_USING_PREEMPTION();
4947                 }
4948                 else
4949                 {
4950                     mtCOVERAGE_TEST_MARKER();
4951                 }
4952             }
4953             else
4954             {
4955                 mtCOVERAGE_TEST_MARKER();
4956             }
4957         }
4958         taskEXIT_CRITICAL();
4959
4960         return xReturn;
4961     }
4962
4963 #endif /* configUSE_TASK_NOTIFICATIONS */
4964 /*-----------------------------------------------------------*/
4965
4966 #if ( configUSE_TASK_NOTIFICATIONS == 1 )
4967
4968     BaseType_t xTaskGenericNotifyFromISR( TaskHandle_t xTaskToNotify,
4969                                           UBaseType_t uxIndexToNotify,
4970                                           uint32_t ulValue,
4971                                           eNotifyAction eAction,
4972                                           uint32_t * pulPreviousNotificationValue,
4973                                           BaseType_t * pxHigherPriorityTaskWoken )
4974     {
4975         TCB_t * pxTCB;
4976         uint8_t ucOriginalNotifyState;
4977         BaseType_t xReturn = pdPASS;
4978         UBaseType_t uxSavedInterruptStatus;
4979
4980         configASSERT( xTaskToNotify );
4981         configASSERT( uxIndexToNotify < configTASK_NOTIFICATION_ARRAY_ENTRIES );
4982
4983         /* RTOS ports that support interrupt nesting have the concept of a
4984          * maximum  system call (or maximum API call) interrupt priority.
4985          * Interrupts that are  above the maximum system call priority are keep
4986          * permanently enabled, even when the RTOS kernel is in a critical section,
4987          * but cannot make any calls to FreeRTOS API functions.  If configASSERT()
4988          * is defined in FreeRTOSConfig.h then
4989          * portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion
4990          * failure if a FreeRTOS API function is called from an interrupt that has
4991          * been assigned a priority above the configured maximum system call
4992          * priority.  Only FreeRTOS functions that end in FromISR can be called
4993          * from interrupts  that have been assigned a priority at or (logically)
4994          * below the maximum system call interrupt priority.  FreeRTOS maintains a
4995          * separate interrupt safe API to ensure interrupt entry is as fast and as
4996          * simple as possible.  More information (albeit Cortex-M specific) is
4997          * provided on the following link:
4998          * https://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html */
4999         portASSERT_IF_INTERRUPT_PRIORITY_INVALID();
5000
5001         pxTCB = xTaskToNotify;
5002
5003         uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR();
5004         {
5005             if( pulPreviousNotificationValue != NULL )
5006             {
5007                 *pulPreviousNotificationValue = pxTCB->ulNotifiedValue[ uxIndexToNotify ];
5008             }
5009
5010             ucOriginalNotifyState = pxTCB->ucNotifyState[ uxIndexToNotify ];
5011             pxTCB->ucNotifyState[ uxIndexToNotify ] = taskNOTIFICATION_RECEIVED;
5012
5013             switch( eAction )
5014             {
5015                 case eSetBits:
5016                     pxTCB->ulNotifiedValue[ uxIndexToNotify ] |= ulValue;
5017                     break;
5018
5019                 case eIncrement:
5020                     ( pxTCB->ulNotifiedValue[ uxIndexToNotify ] )++;
5021                     break;
5022
5023                 case eSetValueWithOverwrite:
5024                     pxTCB->ulNotifiedValue[ uxIndexToNotify ] = ulValue;
5025                     break;
5026
5027                 case eSetValueWithoutOverwrite:
5028
5029                     if( ucOriginalNotifyState != taskNOTIFICATION_RECEIVED )
5030                     {
5031                         pxTCB->ulNotifiedValue[ uxIndexToNotify ] = ulValue;
5032                     }
5033                     else
5034                     {
5035                         /* The value could not be written to the task. */
5036                         xReturn = pdFAIL;
5037                     }
5038
5039                     break;
5040
5041                 case eNoAction:
5042
5043                     /* The task is being notified without its notify value being
5044                      * updated. */
5045                     break;
5046
5047                 default:
5048
5049                     /* Should not get here if all enums are handled.
5050                      * Artificially force an assert by testing a value the
5051                      * compiler can't assume is const. */
5052                     configASSERT( xTickCount == ( TickType_t ) 0 );
5053                     break;
5054             }
5055
5056             traceTASK_NOTIFY_FROM_ISR( uxIndexToNotify );
5057
5058             /* If the task is in the blocked state specifically to wait for a
5059              * notification then unblock it now. */
5060             if( ucOriginalNotifyState == taskWAITING_NOTIFICATION )
5061             {
5062                 /* The task should not have been on an event list. */
5063                 configASSERT( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) == NULL );
5064
5065                 if( uxSchedulerSuspended == ( UBaseType_t ) pdFALSE )
5066                 {
5067                     listREMOVE_ITEM( &( pxTCB->xStateListItem ) );
5068                     prvAddTaskToReadyList( pxTCB );
5069                 }
5070                 else
5071                 {
5072                     /* The delayed and ready lists cannot be accessed, so hold
5073                      * this task pending until the scheduler is resumed. */
5074                     listINSERT_END( &( xPendingReadyList ), &( pxTCB->xEventListItem ) );
5075                 }
5076
5077                 if( pxTCB->uxPriority > pxCurrentTCB->uxPriority )
5078                 {
5079                     /* The notified task has a priority above the currently
5080                      * executing task so a yield is required. */
5081                     if( pxHigherPriorityTaskWoken != NULL )
5082                     {
5083                         *pxHigherPriorityTaskWoken = pdTRUE;
5084                     }
5085
5086                     /* Mark that a yield is pending in case the user is not
5087                      * using the "xHigherPriorityTaskWoken" parameter to an ISR
5088                      * safe FreeRTOS function. */
5089                     xYieldPending = pdTRUE;
5090                 }
5091                 else
5092                 {
5093                     mtCOVERAGE_TEST_MARKER();
5094                 }
5095             }
5096         }
5097         portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus );
5098
5099         return xReturn;
5100     }
5101
5102 #endif /* configUSE_TASK_NOTIFICATIONS */
5103 /*-----------------------------------------------------------*/
5104
5105 #if ( configUSE_TASK_NOTIFICATIONS == 1 )
5106
5107     void vTaskGenericNotifyGiveFromISR( TaskHandle_t xTaskToNotify,
5108                                         UBaseType_t uxIndexToNotify,
5109                                         BaseType_t * pxHigherPriorityTaskWoken )
5110     {
5111         TCB_t * pxTCB;
5112         uint8_t ucOriginalNotifyState;
5113         UBaseType_t uxSavedInterruptStatus;
5114
5115         configASSERT( xTaskToNotify );
5116         configASSERT( uxIndexToNotify < configTASK_NOTIFICATION_ARRAY_ENTRIES );
5117
5118         /* RTOS ports that support interrupt nesting have the concept of a
5119          * maximum  system call (or maximum API call) interrupt priority.
5120          * Interrupts that are  above the maximum system call priority are keep
5121          * permanently enabled, even when the RTOS kernel is in a critical section,
5122          * but cannot make any calls to FreeRTOS API functions.  If configASSERT()
5123          * is defined in FreeRTOSConfig.h then
5124          * portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion
5125          * failure if a FreeRTOS API function is called from an interrupt that has
5126          * been assigned a priority above the configured maximum system call
5127          * priority.  Only FreeRTOS functions that end in FromISR can be called
5128          * from interrupts  that have been assigned a priority at or (logically)
5129          * below the maximum system call interrupt priority.  FreeRTOS maintains a
5130          * separate interrupt safe API to ensure interrupt entry is as fast and as
5131          * simple as possible.  More information (albeit Cortex-M specific) is
5132          * provided on the following link:
5133          * https://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html */
5134         portASSERT_IF_INTERRUPT_PRIORITY_INVALID();
5135
5136         pxTCB = xTaskToNotify;
5137
5138         uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR();
5139         {
5140             ucOriginalNotifyState = pxTCB->ucNotifyState[ uxIndexToNotify ];
5141             pxTCB->ucNotifyState[ uxIndexToNotify ] = taskNOTIFICATION_RECEIVED;
5142
5143             /* 'Giving' is equivalent to incrementing a count in a counting
5144              * semaphore. */
5145             ( pxTCB->ulNotifiedValue[ uxIndexToNotify ] )++;
5146
5147             traceTASK_NOTIFY_GIVE_FROM_ISR( uxIndexToNotify );
5148
5149             /* If the task is in the blocked state specifically to wait for a
5150              * notification then unblock it now. */
5151             if( ucOriginalNotifyState == taskWAITING_NOTIFICATION )
5152             {
5153                 /* The task should not have been on an event list. */
5154                 configASSERT( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) == NULL );
5155
5156                 if( uxSchedulerSuspended == ( UBaseType_t ) pdFALSE )
5157                 {
5158                     listREMOVE_ITEM( &( pxTCB->xStateListItem ) );
5159                     prvAddTaskToReadyList( pxTCB );
5160                 }
5161                 else
5162                 {
5163                     /* The delayed and ready lists cannot be accessed, so hold
5164                      * this task pending until the scheduler is resumed. */
5165                     listINSERT_END( &( xPendingReadyList ), &( pxTCB->xEventListItem ) );
5166                 }
5167
5168                 if( pxTCB->uxPriority > pxCurrentTCB->uxPriority )
5169                 {
5170                     /* The notified task has a priority above the currently
5171                      * executing task so a yield is required. */
5172                     if( pxHigherPriorityTaskWoken != NULL )
5173                     {
5174                         *pxHigherPriorityTaskWoken = pdTRUE;
5175                     }
5176
5177                     /* Mark that a yield is pending in case the user is not
5178                      * using the "xHigherPriorityTaskWoken" parameter in an ISR
5179                      * safe FreeRTOS function. */
5180                     xYieldPending = pdTRUE;
5181                 }
5182                 else
5183                 {
5184                     mtCOVERAGE_TEST_MARKER();
5185                 }
5186             }
5187         }
5188         portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus );
5189     }
5190
5191 #endif /* configUSE_TASK_NOTIFICATIONS */
5192 /*-----------------------------------------------------------*/
5193
5194 #if ( configUSE_TASK_NOTIFICATIONS == 1 )
5195
5196     BaseType_t xTaskGenericNotifyStateClear( TaskHandle_t xTask,
5197                                              UBaseType_t uxIndexToClear )
5198     {
5199         TCB_t * pxTCB;
5200         BaseType_t xReturn;
5201
5202         configASSERT( uxIndexToClear < configTASK_NOTIFICATION_ARRAY_ENTRIES );
5203
5204         /* If null is passed in here then it is the calling task that is having
5205          * its notification state cleared. */
5206         pxTCB = prvGetTCBFromHandle( xTask );
5207
5208         taskENTER_CRITICAL();
5209         {
5210             if( pxTCB->ucNotifyState[ uxIndexToClear ] == taskNOTIFICATION_RECEIVED )
5211             {
5212                 pxTCB->ucNotifyState[ uxIndexToClear ] = taskNOT_WAITING_NOTIFICATION;
5213                 xReturn = pdPASS;
5214             }
5215             else
5216             {
5217                 xReturn = pdFAIL;
5218             }
5219         }
5220         taskEXIT_CRITICAL();
5221
5222         return xReturn;
5223     }
5224
5225 #endif /* configUSE_TASK_NOTIFICATIONS */
5226 /*-----------------------------------------------------------*/
5227
5228 #if ( configUSE_TASK_NOTIFICATIONS == 1 )
5229
5230     uint32_t ulTaskGenericNotifyValueClear( TaskHandle_t xTask,
5231                                             UBaseType_t uxIndexToClear,
5232                                             uint32_t ulBitsToClear )
5233     {
5234         TCB_t * pxTCB;
5235         uint32_t ulReturn;
5236
5237         /* If null is passed in here then it is the calling task that is having
5238          * its notification state cleared. */
5239         pxTCB = prvGetTCBFromHandle( xTask );
5240
5241         taskENTER_CRITICAL();
5242         {
5243             /* Return the notification as it was before the bits were cleared,
5244              * then clear the bit mask. */
5245             ulReturn = pxTCB->ulNotifiedValue[ uxIndexToClear ];
5246             pxTCB->ulNotifiedValue[ uxIndexToClear ] &= ~ulBitsToClear;
5247         }
5248         taskEXIT_CRITICAL();
5249
5250         return ulReturn;
5251     }
5252
5253 #endif /* configUSE_TASK_NOTIFICATIONS */
5254 /*-----------------------------------------------------------*/
5255
5256 #if ( configGENERATE_RUN_TIME_STATS == 1 )
5257
5258     configRUN_TIME_COUNTER_TYPE ulTaskGetRunTimeCounter( const TaskHandle_t xTask )
5259     {
5260         return xTask->ulRunTimeCounter;
5261     }
5262
5263 #endif
5264 /*-----------------------------------------------------------*/
5265
5266 #if ( configGENERATE_RUN_TIME_STATS == 1 )
5267
5268     configRUN_TIME_COUNTER_TYPE ulTaskGetRunTimePercent( const TaskHandle_t xTask )
5269     {
5270         configRUN_TIME_COUNTER_TYPE ulTotalTime, ulReturn;
5271
5272         ulTotalTime = portGET_RUN_TIME_COUNTER_VALUE();
5273
5274         /* For percentage calculations. */
5275         ulTotalTime /= ( configRUN_TIME_COUNTER_TYPE ) 100;
5276
5277         /* Avoid divide by zero errors. */
5278         if( ulTotalTime > ( configRUN_TIME_COUNTER_TYPE ) 0 )
5279         {
5280             ulReturn = xTask->ulRunTimeCounter / ulTotalTime;
5281         }
5282         else
5283         {
5284             ulReturn = 0;
5285         }
5286
5287         return ulReturn;
5288     }
5289
5290 #endif /* if ( configGENERATE_RUN_TIME_STATS == 1 ) */
5291 /*-----------------------------------------------------------*/
5292
5293 #if ( configGENERATE_RUN_TIME_STATS == 1 )
5294
5295     configRUN_TIME_COUNTER_TYPE ulTaskGetIdleRunTimeCounter( void )
5296     {
5297         return ulTaskGetRunTimeCounter( xIdleTaskHandle );
5298     }
5299
5300 #endif
5301 /*-----------------------------------------------------------*/
5302
5303 #if ( configGENERATE_RUN_TIME_STATS == 1 )
5304
5305     configRUN_TIME_COUNTER_TYPE ulTaskGetIdleRunTimePercent( void )
5306     {
5307         return ulTaskGetRunTimePercent( xIdleTaskHandle );
5308     }
5309
5310 #endif
5311 /*-----------------------------------------------------------*/
5312
5313 static void prvAddCurrentTaskToDelayedList( TickType_t xTicksToWait,
5314                                             const BaseType_t xCanBlockIndefinitely )
5315 {
5316     TickType_t xTimeToWake;
5317     const TickType_t xConstTickCount = xTickCount;
5318
5319     #if ( INCLUDE_xTaskAbortDelay == 1 )
5320     {
5321         /* About to enter a delayed list, so ensure the ucDelayAborted flag is
5322          * reset to pdFALSE so it can be detected as having been set to pdTRUE
5323          * when the task leaves the Blocked state. */
5324         pxCurrentTCB->ucDelayAborted = pdFALSE;
5325     }
5326     #endif
5327
5328     /* Remove the task from the ready list before adding it to the blocked list
5329      * as the same list item is used for both lists. */
5330     if( uxListRemove( &( pxCurrentTCB->xStateListItem ) ) == ( UBaseType_t ) 0 )
5331     {
5332         /* The current task must be in a ready list, so there is no need to
5333          * check, and the port reset macro can be called directly. */
5334         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. */
5335     }
5336     else
5337     {
5338         mtCOVERAGE_TEST_MARKER();
5339     }
5340
5341     #if ( INCLUDE_vTaskSuspend == 1 )
5342     {
5343         if( ( xTicksToWait == portMAX_DELAY ) && ( xCanBlockIndefinitely != pdFALSE ) )
5344         {
5345             /* Add the task to the suspended task list instead of a delayed task
5346              * list to ensure it is not woken by a timing event.  It will block
5347              * indefinitely. */
5348             listINSERT_END( &xSuspendedTaskList, &( pxCurrentTCB->xStateListItem ) );
5349         }
5350         else
5351         {
5352             /* Calculate the time at which the task should be woken if the event
5353              * does not occur.  This may overflow but this doesn't matter, the
5354              * kernel will manage it correctly. */
5355             xTimeToWake = xConstTickCount + xTicksToWait;
5356
5357             /* The list item will be inserted in wake time order. */
5358             listSET_LIST_ITEM_VALUE( &( pxCurrentTCB->xStateListItem ), xTimeToWake );
5359
5360             if( xTimeToWake < xConstTickCount )
5361             {
5362                 /* Wake time has overflowed.  Place this item in the overflow
5363                  * list. */
5364                 vListInsert( pxOverflowDelayedTaskList, &( pxCurrentTCB->xStateListItem ) );
5365             }
5366             else
5367             {
5368                 /* The wake time has not overflowed, so the current block list
5369                  * is used. */
5370                 vListInsert( pxDelayedTaskList, &( pxCurrentTCB->xStateListItem ) );
5371
5372                 /* If the task entering the blocked state was placed at the
5373                  * head of the list of blocked tasks then xNextTaskUnblockTime
5374                  * needs to be updated too. */
5375                 if( xTimeToWake < xNextTaskUnblockTime )
5376                 {
5377                     xNextTaskUnblockTime = xTimeToWake;
5378                 }
5379                 else
5380                 {
5381                     mtCOVERAGE_TEST_MARKER();
5382                 }
5383             }
5384         }
5385     }
5386     #else /* INCLUDE_vTaskSuspend */
5387     {
5388         /* Calculate the time at which the task should be woken if the event
5389          * does not occur.  This may overflow but this doesn't matter, the kernel
5390          * will manage it correctly. */
5391         xTimeToWake = xConstTickCount + xTicksToWait;
5392
5393         /* The list item will be inserted in wake time order. */
5394         listSET_LIST_ITEM_VALUE( &( pxCurrentTCB->xStateListItem ), xTimeToWake );
5395
5396         if( xTimeToWake < xConstTickCount )
5397         {
5398             /* Wake time has overflowed.  Place this item in the overflow list. */
5399             vListInsert( pxOverflowDelayedTaskList, &( pxCurrentTCB->xStateListItem ) );
5400         }
5401         else
5402         {
5403             /* The wake time has not overflowed, so the current block list is used. */
5404             vListInsert( pxDelayedTaskList, &( pxCurrentTCB->xStateListItem ) );
5405
5406             /* If the task entering the blocked state was placed at the head of the
5407              * list of blocked tasks then xNextTaskUnblockTime needs to be updated
5408              * too. */
5409             if( xTimeToWake < xNextTaskUnblockTime )
5410             {
5411                 xNextTaskUnblockTime = xTimeToWake;
5412             }
5413             else
5414             {
5415                 mtCOVERAGE_TEST_MARKER();
5416             }
5417         }
5418
5419         /* Avoid compiler warning when INCLUDE_vTaskSuspend is not 1. */
5420         ( void ) xCanBlockIndefinitely;
5421     }
5422     #endif /* INCLUDE_vTaskSuspend */
5423 }
5424
5425 /* Code below here allows additional code to be inserted into this source file,
5426  * especially where access to file scope functions and data is needed (for example
5427  * when performing module tests). */
5428
5429 #ifdef FREERTOS_MODULE_TEST
5430     #include "tasks_test_access_functions.h"
5431 #endif
5432
5433
5434 #if ( configINCLUDE_FREERTOS_TASK_C_ADDITIONS_H == 1 )
5435
5436     #include "freertos_tasks_c_additions.h"
5437
5438     #ifdef FREERTOS_TASKS_C_ADDITIONS_INIT
5439         static void freertos_tasks_c_additions_init( void )
5440         {
5441             FREERTOS_TASKS_C_ADDITIONS_INIT();
5442         }
5443     #endif
5444
5445 #endif /* if ( configINCLUDE_FREERTOS_TASK_C_ADDITIONS_H == 1 ) */