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