changing circuitry to disable RTC, update initialization to match
[fw/openalt] / FreeRTOS / tasks.c
1 /*
2         FreeRTOS.org V4.4.0 - Copyright (C) 2003-2007 Richard Barry.
3
4         This file is part of the FreeRTOS.org distribution.
5
6         FreeRTOS.org is free software; you can redistribute it and/or modify
7         it under the terms of the GNU General Public License as published by
8         the Free Software Foundation; either version 2 of the License, or
9         (at your option) any later version.
10
11         FreeRTOS.org is distributed in the hope that it will be useful,
12         but WITHOUT ANY WARRANTY; without even the implied warranty of
13         MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14         GNU General Public License for more details.
15
16         You should have received a copy of the GNU General Public License
17         along with FreeRTOS.org; if not, write to the Free Software
18         Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19
20         A special exception to the GPL can be applied should you wish to distribute
21         a combined work that includes FreeRTOS.org, without being obliged to provide
22         the source code for any proprietary components.  See the licensing section
23         of http://www.FreeRTOS.org for full details of how and when the exception
24         can be applied.
25
26         ***************************************************************************
27         See http://www.FreeRTOS.org for documentation, latest information, license
28         and contact details.  Please ensure to read the configuration and relevant
29         port sections of the online documentation.
30
31         Also see http://www.SafeRTOS.com for an IEC 61508 compliant version, along
32         with development and support options.
33         ***************************************************************************
34 */
35
36 /*
37 Changes from V1.00:
38         
39         + Call to portRESTORE_CONTEXT has been removed.  The first context
40           switch is now performed within sPortStartScheduler().
41
42 Changes from V1.01:
43
44         + More use of 8bit data types.
45         + Function name prefixes changed where the data type returned has changed.
46         + configUSE_TRACE_FACILITY is no longer defined by default.
47
48 Changes from V1.2.0
49
50         + Introduced ucTopReadyPriority.  This tracks the highest priority ready
51           queue that contains a valid TCB and thus makes the context switch
52           slightly faster.
53
54         + prvAddTaskToReadyQueue() has been made a macro.
55
56 Changes from V1.2.6
57
58         + Added conditional compilation directives.
59         + Extended API.
60         + Rearranged function order.
61         + Creating a task now causes a context switch if the task being created
62           has a higher priority than the calling task - assuming the kernel is
63           running.
64         + vTaskDelete() now only causes a context switch if the calling task is
65           the task being deleted.
66
67 Changes from V2.0.0
68
69         + Allow the type of the tick count to be 16 or 32 bits.
70         + Introduce xPendingReadyList feature to allow the time interrupts have to
71           be disabled to be minimised.
72         + Remove the #if( INCLUDE_vTaskSuspendAll ) statements.  vTaskSuspendAll()
73           is now always included as it is used by the scheduler itself.
74
75 Changes from V2.1.0
76
77         + Bug fix - pxCurrentTCB is now initialised before the call to
78           prvInitializeTaskLists().  Previously pxCurrentTCB could be accessed
79           while null.
80
81 Changed from V2.1.1
82
83         + Change to where lStackSize is declared within sTaskCreate() to prevent
84           compiler warnings with 8051 port.
85
86 Changes from V2.2.0
87
88         + Explicit use of 'signed' qualifier on portCHAR types added.
89         + Changed odd calculation of initial pxTopOfStack value when
90           portSTACK_GROWTH < 0.
91         + Removed pcVersionNumber definition.
92
93 Changes from V2.5.3
94
95         + cTaskResumeAll() modified to ensure it can be called prior to the task
96           lists being initialised.
97
98 Changes from V2.5.5
99
100         + Added API function vTaskDelayUntil().
101         + Added INCLUDE_vTaskDelay conditional compilation.
102
103 Changes from V2.6.0
104
105         + Updated the vWriteTraceToBuffer macro to always be 4 byte aligned so it
106           can be used on ARM architectures.
107         + tskMAX_TASK_NAME_LEN definition replaced with the port specific
108           configMAX_TASK_NAME_LEN definition.
109         + Removed the call to strcpy when copying across the task name into the
110           TCB.
111         + Added ucTasksDeleted variable to prevent vTaskSuspendAll() being called
112           too often in the idle task.
113
114 Changes between V3.0.0 and V2.6.1
115
116         + When resuming the scheduler a yield is performed if either a tick has
117           been missed, or a task is moved from the pending ready list into a ready
118           list.  Previously a yield was not performed on this second condition.
119         + Introduced the type portBASE_TYPE.  This necessitates several API
120           changes.
121         + Removed the sUsingPreemption variable.  The constant defined in
122           portmacro.h is now used directly.
123         + The idle task can now include an optional hook function - and no longer
124           completes its time slice if other tasks with equal priority to it are
125           ready to run.
126         + See the FreeRTOS.org documentation for more information on V2.x.x to
127           V3.x.x modifications.
128
129 Changes from V3.1.1
130
131         + Modified vTaskPrioritySet() and vTaskResume() to allow these functions to
132           be called while the scheduler is suspended.
133         + Corrected the task ordering within event lists.
134
135 Changes from V3.2.0
136
137         + Added function xTaskGetCurrentTaskHandle().
138
139 Changes from V3.2.4
140
141         + Changed the volatile declarations on some variables to reflect the 
142           changes to the list definitions.
143         + Changed the order of the TCB definition so there is commonality between
144           the task control block and a co-routine control block.
145         + Allow the scheduler to be started even if no tasks other than the idle
146           task has been created.  This allows co-routines to run even when no tasks
147           have been created.
148         + The need for a context switch is now signalled if a task woken by an 
149           event has a priority greater or equal to the currently running task.
150           Previously this was only greater than.
151
152 Changes from V4.0.0
153
154         + Added the xMissedYield handling.
155
156 Changes from V4.0.1
157
158         + The function vTaskList() now suspends the scheduler rather than disabling
159           interrupts during the creation of the task list.  
160         + Allow a task to delete itself by passing in its own handle.  Previously 
161           this could only be done by passing in NULL.
162         + The tick hook function is now called only within a tick isr.  Previously
163           it was also called when the tick function was called during the scheduler
164           unlocking process.
165
166 Changes from V4.0.3
167
168         + Extra checks have been placed in vTaskPrioritySet() to avoid unnecessary
169           yields.
170
171 Changed from V4.0.4
172
173         + Bug fix:  The 'value' of the event list item is updated when the priority
174           of a task is changed.  Previously only the priority of the TCB itself was
175           changed.
176         + When resuming a task a check is first made to see if the task is actually
177           suspended.
178         + vTaskPrioritySet() and vTaskResume() no longer use the event list item.
179           This has not been necessary since V4.0.1 when the xMissedYield handling
180           was added.
181         + Implement xTaskResumeFromISR().
182
183 Changes from V4.0.5
184
185         + Added utility functions and xOverflowCount variable to facilitate the
186           queue.c changes.
187
188 Changes from V4.1.2
189         
190         + Tasks that block on events with a timeout of portMAX_DELAY are now
191           blocked indefinitely if configINCLUDE_vTaskSuspend is defined. 
192           Previously portMAX_DELAY was just the longest block time possible.
193
194 Changes from V4.1.3
195
196         + Very small change made to xTaskCheckForTimeout() as a result of the 
197         SafeRTOS testing.  This corrects the case where the function can return an
198         invalid value - but only in an extremely unlikely scenario.
199
200 Changes since V4.3.1:
201
202         + Added xTaskGetSchedulerState() function.
203         + Added prvIsTaskSuspended() to take into account the Occurrence of
204           vTaskResume() or vTaskResumeFromISR() being called passing in the
205           handle of a task that appears in the Suspended list only because it
206           is blocked on an event without a timeout being specified.
207         + Updated xTaskCheckForTimeout() to take into account that tasks blocked
208           using the Suspended list should never time out.
209 */
210
211 #include <stdio.h>
212 #include <stdlib.h>
213 #include <string.h>
214
215 #include "FreeRTOS.h"
216 #include "task.h"
217
218 /*
219  * Macro to define the amount of stack available to the idle task.
220  */
221 #define tskIDLE_STACK_SIZE      configMINIMAL_STACK_SIZE
222
223
224 /*
225  * Default a definitions for backwards compatibility with old
226  * portmacro.h files.
227  */
228 #ifndef configMAX_TASK_NAME_LEN
229         #define configMAX_TASK_NAME_LEN 16
230 #endif
231
232 #ifndef INCLUDE_xTaskGetCurrentTaskHandle
233         #define INCLUDE_xTaskGetCurrentTaskHandle 0
234 #endif
235
236 #ifndef configIDLE_SHOULD_YIELD
237         #define configIDLE_SHOULD_YIELD         1
238 #endif
239
240 #if configMAX_TASK_NAME_LEN < 1
241         #undef configMAX_TASK_NAME_LEN
242         #define configMAX_TASK_NAME_LEN 1
243 #endif
244
245 #ifndef INCLUDE_xTaskResumeFromISR
246         #define INCLUDE_xTaskResumeFromISR 1
247 #endif
248
249 #ifndef INCLUDE_xTaskGetSchedulerState
250         #define INCLUDE_xTaskGetSchedulerState 0
251 #endif
252
253 /*
254  * Task control block.  A task control block (TCB) is allocated to each task,
255  * and stores the context of the task.
256  */
257 typedef struct tskTaskControlBlock
258 {
259         volatile portSTACK_TYPE *pxTopOfStack;          /*< Points to the location of the last item placed on the tasks stack.  THIS MUST BE THE FIRST MEMBER OF THE STRUCT. */
260         xListItem                               xGenericListItem;       /*< List item used to place the TCB in ready and blocked queues. */
261         xListItem                               xEventListItem;         /*< List item used to place the TCB in event lists. */
262         unsigned portBASE_TYPE  uxPriority;                     /*< The priority of the task where 0 is the lowest priority. */
263         portSTACK_TYPE                  *pxStack;                       /*< Points to the start of the stack. */
264         unsigned portBASE_TYPE  uxTCBNumber;            /*< This is used for tracing the scheduler and making debugging easier only. */
265         signed portCHAR                 pcTaskName[ configMAX_TASK_NAME_LEN ];/*< Descriptive name given to the task when created.  Facilitates debugging only. */
266         unsigned portSHORT              usStackDepth;           /*< Total depth of the stack (when empty).  This is defined as the number of variables the stack can hold, not the number of bytes. */
267 } tskTCB;
268
269 /*lint -e956 */
270
271 tskTCB * volatile pxCurrentTCB = NULL;                                  
272
273 /* Lists for ready and blocked tasks. --------------------*/
274
275 static xList pxReadyTasksLists[ configMAX_PRIORITIES ]; /*< Prioritised ready tasks. */
276 static xList xDelayedTaskList1;                                                 /*< Delayed tasks. */
277 static xList xDelayedTaskList2;                                                 /*< Delayed tasks (two lists are used - one for delays that have overflowed the current tick count. */
278 static xList * volatile pxDelayedTaskList;                              /*< Points to the delayed task list currently being used. */
279 static xList * volatile pxOverflowDelayedTaskList;              /*< Points to the delayed task list currently being used to hold tasks that have overflowed the current tick count. */
280 static xList xPendingReadyList;                                                 /*< Tasks that have been readied while the scheduler was suspended.  They will be moved to the ready queue when the scheduler is resumed. */
281
282 #if ( INCLUDE_vTaskDelete == 1 )
283
284         static volatile xList xTasksWaitingTermination;         /*< Tasks that have been deleted - but the their memory not yet freed. */
285         static volatile unsigned portBASE_TYPE uxTasksDeleted = ( unsigned portBASE_TYPE ) 0;
286
287 #endif
288
289 #if ( INCLUDE_vTaskSuspend == 1 )
290
291         static xList xSuspendedTaskList;                                        /*< Tasks that are currently suspended. */
292
293 #endif
294
295 /* File private variables. --------------------------------*/
296 static volatile unsigned portBASE_TYPE uxCurrentNumberOfTasks   = ( unsigned portBASE_TYPE ) 0;
297 static volatile portTickType xTickCount                                                 = ( portTickType ) 0;
298 static unsigned portBASE_TYPE uxTopUsedPriority                                 = tskIDLE_PRIORITY;
299 static volatile unsigned portBASE_TYPE uxTopReadyPriority               = tskIDLE_PRIORITY;
300 static volatile signed portBASE_TYPE xSchedulerRunning                  = pdFALSE;
301 static volatile unsigned portBASE_TYPE uxSchedulerSuspended             = ( unsigned portBASE_TYPE ) pdFALSE;
302 static volatile unsigned portBASE_TYPE uxMissedTicks                    = ( unsigned portBASE_TYPE ) 0;
303 static volatile portBASE_TYPE xMissedYield                                              = ( portBASE_TYPE ) pdFALSE;
304 static volatile portBASE_TYPE xNumOfOverflows                                   = ( portBASE_TYPE ) 0;
305 /* Debugging and trace facilities private variables and macros. ------------*/
306
307 /*
308  * The value used to fill the stack of a task when the task is created.  This
309  * is used purely for checking the high water mark for tasks.
310  */
311 #define tskSTACK_FILL_BYTE      ( 0xa5 )
312
313 /*
314  * Macros used by vListTask to indicate which state a task is in.
315  */
316 #define tskBLOCKED_CHAR         ( ( signed portCHAR ) 'B' )
317 #define tskREADY_CHAR           ( ( signed portCHAR ) 'R' )
318 #define tskDELETED_CHAR         ( ( signed portCHAR ) 'D' )
319 #define tskSUSPENDED_CHAR       ( ( signed portCHAR ) 'S' )
320
321 /*
322  * Macros and private variables used by the trace facility.
323  */
324 #if ( configUSE_TRACE_FACILITY == 1 )
325
326         #define tskSIZE_OF_EACH_TRACE_LINE                      ( ( unsigned portLONG ) ( sizeof( unsigned portLONG ) + sizeof( unsigned portLONG ) ) )
327         static volatile signed portCHAR * volatile pcTraceBuffer;
328         static signed portCHAR *pcTraceBufferStart;
329         static signed portCHAR *pcTraceBufferEnd;
330         static signed portBASE_TYPE xTracing = pdFALSE;
331
332 #endif
333
334 /*
335  * Macro that writes a trace of scheduler activity to a buffer.  This trace
336  * shows which task is running when and is very useful as a debugging tool.
337  * As this macro is called each context switch it is a good idea to undefine
338  * it if not using the facility.
339  */
340 #if ( configUSE_TRACE_FACILITY == 1 )
341
342         #define vWriteTraceToBuffer()                                                                                                                                   \
343         {                                                                                                                                                                                               \
344                 if( xTracing )                                                                                                                                                          \
345                 {                                                                                                                                                                                       \
346                         static unsigned portBASE_TYPE uxPreviousTask = 255;                                                                             \
347                                                                                                                                                                                                         \
348                         if( uxPreviousTask != pxCurrentTCB->uxTCBNumber )                                                                               \
349                         {                                                                                                                                                                               \
350                                 if( ( pcTraceBuffer + tskSIZE_OF_EACH_TRACE_LINE ) < pcTraceBufferEnd )                         \
351                                 {                                                                                                                                                                       \
352                                         uxPreviousTask = pxCurrentTCB->uxTCBNumber;                                                                             \
353                                         *( unsigned portLONG * ) pcTraceBuffer = ( unsigned portLONG ) xTickCount;              \
354                                         pcTraceBuffer += sizeof( unsigned portLONG );                                                                   \
355                                         *( unsigned portLONG * ) pcTraceBuffer = ( unsigned portLONG ) uxPreviousTask;  \
356                                         pcTraceBuffer += sizeof( unsigned portLONG );                                                                   \
357                                 }                                                                                                                                                                       \
358                                 else                                                                                                                                                            \
359                                 {                                                                                                                                                                       \
360                                         xTracing = pdFALSE;                                                                                                                             \
361                                 }                                                                                                                                                                       \
362                         }                                                                                                                                                                               \
363                 }                                                                                                                                                                                       \
364         }
365
366 #else
367
368         #define vWriteTraceToBuffer()
369
370 #endif
371
372
373 /*
374  * Place the task represented by pxTCB into the appropriate ready queue for
375  * the task.  It is inserted at the end of the list.  One quirk of this is
376  * that if the task being inserted is at the same priority as the currently
377  * executing task, then it will only be rescheduled after the currently
378  * executing task has been rescheduled.
379  */
380 #define prvAddTaskToReadyQueue( pxTCB )                                                                                                                                                 \
381 {                                                                                                                                                                                                                               \
382         if( pxTCB->uxPriority > uxTopReadyPriority )                                                                                                                            \
383         {                                                                                                                                                                                                                       \
384                 uxTopReadyPriority = pxTCB->uxPriority;                                                                                                                                 \
385         }                                                                                                                                                                                                                       \
386         vListInsertEnd( ( xList * ) &( pxReadyTasksLists[ pxTCB->uxPriority ] ), &( pxTCB->xGenericListItem ) );        \
387 }               
388
389 /*
390  * Macro that looks at the list of tasks that are currently delayed to see if
391  * any require waking.
392  *
393  * Tasks are stored in the queue in the order of their wake time - meaning
394  * once one tasks has been found whose timer has not expired we need not look
395  * any further down the list.
396  */
397 #define prvCheckDelayedTasks()                                                                                                                                                                          \
398 {                                                                                                                                                                                                                                       \
399 register tskTCB *pxTCB;                                                                                                                                                                                         \
400                                                                                                                                                                                                                                         \
401         while( ( pxTCB = ( tskTCB * ) listGET_OWNER_OF_HEAD_ENTRY( pxDelayedTaskList ) ) != NULL )                                              \
402         {                                                                                                                                                                                                                               \
403                 if( xTickCount < listGET_LIST_ITEM_VALUE( &( pxTCB->xGenericListItem ) ) )                                                                      \
404                 {                                                                                                                                                                                                                       \
405                         break;                                                                                                                                                                                                  \
406                 }                                                                                                                                                                                                                       \
407                 vListRemove( &( pxTCB->xGenericListItem ) );                                                                                                                            \
408                 /* Is the task waiting on an event also? */                                                                                                                                     \
409                 if( pxTCB->xEventListItem.pvContainer )                                                                                                                                         \
410                 {                                                                                                                                                                                                                       \
411                         vListRemove( &( pxTCB->xEventListItem ) );                                                                                                                              \
412                 }                                                                                                                                                                                                                       \
413                 prvAddTaskToReadyQueue( pxTCB );                                                                                                                \
414         }                                                                                                                                                                                                                               \
415 }                                                                                                                                                                                       
416
417 /*
418  * Several functions take an xTaskHandle parameter that can optionally be NULL,
419  * where NULL is used to indicate that the handle of the currently executing
420  * task should be used in place of the parameter.  This macro simply checks to
421  * see if the parameter is NULL and returns a pointer to the appropriate TCB.
422  */
423 #define prvGetTCBFromHandle( pxHandle ) ( ( pxHandle == NULL ) ? ( tskTCB * ) pxCurrentTCB : ( tskTCB * ) pxHandle )
424
425
426 /* File private functions. --------------------------------*/
427
428 /*
429  * Utility to ready a TCB for a given task.  Mainly just copies the parameters
430  * into the TCB structure.
431  */
432 static void prvInitialiseTCBVariables( tskTCB *pxTCB, unsigned portSHORT usStackDepth, const signed portCHAR * const pcName, unsigned portBASE_TYPE uxPriority );
433
434 /*
435  * Utility to ready all the lists used by the scheduler.  This is called
436  * automatically upon the creation of the first task.
437  */
438 static void prvInitialiseTaskLists( void );
439
440 /*
441  * The idle task, which as all tasks is implemented as a never ending loop.
442  * The idle task is automatically created and added to the ready lists upon
443  * creation of the first user task.
444  *
445  * The portTASK_FUNCTION_PROTO() macro is used to allow port/compiler specific
446  * language extensions.  The equivalent prototype for this function is:
447  *
448  * void prvIdleTask( void *pvParameters );
449  *
450  */
451 static portTASK_FUNCTION_PROTO( prvIdleTask, pvParameters );
452
453 /*
454  * Utility to free all memory allocated by the scheduler to hold a TCB,
455  * including the stack pointed to by the TCB.
456  *
457  * This does not free memory allocated by the task itself (i.e. memory
458  * allocated by calls to pvPortMalloc from within the tasks application code).
459  */
460 #if ( ( INCLUDE_vTaskDelete == 1 ) || ( INCLUDE_vTaskCleanUpResources == 1 ) )
461         static void prvDeleteTCB( tskTCB *pxTCB );
462 #endif
463
464 /*
465  * Used only by the idle task.  This checks to see if anything has been placed
466  * in the list of tasks waiting to be deleted.  If so the task is cleaned up
467  * and its TCB deleted.
468  */
469 static void prvCheckTasksWaitingTermination( void );
470
471 /*
472  * Allocates memory from the heap for a TCB and associated stack.  Checks the
473  * allocation was successful.
474  */
475 static tskTCB *prvAllocateTCBAndStack( unsigned portSHORT usStackDepth );
476
477 /*
478  * Called from vTaskList.  vListTasks details all the tasks currently under
479  * control of the scheduler.  The tasks may be in one of a number of lists.
480  * prvListTaskWithinSingleList accepts a list and details the tasks from
481  * within just that list.
482  *
483  * THIS FUNCTION IS INTENDED FOR DEBUGGING ONLY, AND SHOULD NOT BE CALLED FROM
484  * NORMAL APPLICATION CODE.
485  */
486 #if ( configUSE_TRACE_FACILITY == 1 )
487
488         static void prvListTaskWithinSingleList( signed portCHAR *pcWriteBuffer, xList *pxList, signed portCHAR cStatus );
489
490 #endif
491
492 /*
493  * When a task is created, the stack of the task is filled with a known value.
494  * This function determines the 'high water mark' of the task stack by
495  * determining how much of the stack remains at the original preset value.
496  */
497 #if ( configUSE_TRACE_FACILITY == 1 )
498
499         unsigned portSHORT usTaskCheckFreeStackSpace( const unsigned portCHAR *pucStackByte );
500
501 #endif
502
503 /*
504  * Checks that a task being resumed (unsuspended) is actually in the Suspended
505  * state.
506  */
507 #if ( INCLUDE_vTaskSuspend == 1 )
508
509         static portBASE_TYPE prvIsTaskSuspended( const tskTCB * const pxTCB );  
510
511 #endif
512
513 /*lint +e956 */
514
515
516
517
518
519 /*-----------------------------------------------------------
520  * TASK CREATION API documented in task.h
521  *----------------------------------------------------------*/
522
523 signed portBASE_TYPE xTaskCreate( pdTASK_CODE pvTaskCode, const signed portCHAR * const pcName, unsigned portSHORT usStackDepth, void *pvParameters, unsigned portBASE_TYPE uxPriority, xTaskHandle *pxCreatedTask )
524 {
525 signed portBASE_TYPE xReturn;
526 tskTCB * pxNewTCB;
527 static unsigned portBASE_TYPE uxTaskNumber = 0; /*lint !e956 Static is deliberate - this is guarded before use. */
528
529         /* Allocate the memory required by the TCB and stack for the new task.
530         checking that the allocation was successful. */
531         pxNewTCB = prvAllocateTCBAndStack( usStackDepth );
532
533         if( pxNewTCB != NULL )
534         {               
535                 portSTACK_TYPE *pxTopOfStack;
536
537                 /* Setup the newly allocated TCB with the initial state of the task. */
538                 prvInitialiseTCBVariables( pxNewTCB, usStackDepth, pcName, uxPriority );
539
540                 /* Calculate the top of stack address.  This depends on whether the
541                 stack grows from high memory to low (as per the 80x86) or visa versa.
542                 portSTACK_GROWTH is used to make the result positive or negative as
543                 required by the port. */
544                 #if portSTACK_GROWTH < 0
545                 {
546                         pxTopOfStack = pxNewTCB->pxStack + ( pxNewTCB->usStackDepth - 1 );
547                 }
548                 #else
549                 {
550                         pxTopOfStack = pxNewTCB->pxStack;       
551                 }
552                 #endif
553
554                 /* Initialize the TCB stack to look as if the task was already running,
555                 but had been interrupted by the scheduler.  The return address is set
556                 to the start of the task function. Once the stack has been initialised
557                 the     top of stack variable is updated. */
558                 pxNewTCB->pxTopOfStack = pxPortInitialiseStack( pxTopOfStack, pvTaskCode, pvParameters );
559
560                 /* We are going to manipulate the task queues to add this task to a
561                 ready list, so must make sure no interrupts occur. */
562                 portENTER_CRITICAL();
563                 {
564                         uxCurrentNumberOfTasks++;
565                         if( uxCurrentNumberOfTasks == ( unsigned portBASE_TYPE ) 1 )
566                         {
567                                 /* As this is the first task it must also be the current task. */
568                                 pxCurrentTCB =  pxNewTCB;
569
570                                 /* This is the first task to be created so do the preliminary
571                                 initialisation required.  We will not recover if this call
572                                 fails, but we will report the failure. */
573                                 prvInitialiseTaskLists();
574                         }
575                         else
576                         {       
577                                 /* If the scheduler is not already running, make this task the
578                                 current task if it is the highest priority task to be created
579                                 so far. */
580                                 if( xSchedulerRunning == pdFALSE )
581                                 {
582                                         if( pxCurrentTCB->uxPriority <= uxPriority )
583                                         {
584                                                 pxCurrentTCB = pxNewTCB;        
585                                         }
586                                 }
587                         }                               
588
589                         /* Remember the top priority to make context switching faster.  Use
590                         the priority in pxNewTCB as this has been capped to a valid value. */
591                         if( pxNewTCB->uxPriority > uxTopUsedPriority )
592                         {
593                                 uxTopUsedPriority = pxNewTCB->uxPriority;
594                         }
595
596                         /* Add a counter into the TCB for tracing only. */
597                         pxNewTCB->uxTCBNumber = uxTaskNumber;
598                         uxTaskNumber++;
599
600                         prvAddTaskToReadyQueue( pxNewTCB );
601
602                         xReturn = pdPASS;
603                 }
604                 portEXIT_CRITICAL();
605         }
606         else
607         {
608                 xReturn = errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY;
609         }
610
611         if( xReturn == pdPASS )
612         {
613                 if( ( void * ) pxCreatedTask != NULL )
614                 {
615                         /* Pass the TCB out - in an anonymous way.  The calling function/
616                         task can use this as a handle to delete the task later if
617                         required.*/
618                         *pxCreatedTask = ( xTaskHandle ) pxNewTCB;
619                 }
620
621                 if( xSchedulerRunning != pdFALSE )
622                 {
623                         /* If the created task is of a higher priority than the current task
624                         then it should run now. */
625                         if( pxCurrentTCB->uxPriority < uxPriority )
626                         {
627                                 taskYIELD();
628                         }
629                 }
630         }
631
632         return xReturn;
633 }
634 /*-----------------------------------------------------------*/
635
636 #if ( INCLUDE_vTaskDelete == 1 )
637
638         void vTaskDelete( xTaskHandle pxTaskToDelete )
639         {
640         tskTCB *pxTCB;
641
642                 taskENTER_CRITICAL();
643                 {
644                         /* Ensure a yield is performed if the current task is being 
645                         deleted. */
646                         if( pxTaskToDelete == pxCurrentTCB )
647                         {
648                                 pxTaskToDelete = NULL;
649                         }
650
651                         /* If null is passed in here then we are deleting ourselves. */
652                         pxTCB = prvGetTCBFromHandle( pxTaskToDelete );
653
654                         /* Remove task from the ready list and place in the     termination list.
655                         This will stop the task from be scheduled.  The idle task will check
656                         the termination list and free up any memory allocated by the
657                         scheduler for the TCB and stack. */
658                         vListRemove( &( pxTCB->xGenericListItem ) );
659
660                         /* Is the task waiting on an event also? */                                                                                             
661                         if( pxTCB->xEventListItem.pvContainer )
662                         {
663                                 vListRemove( &( pxTCB->xEventListItem ) );
664                         }
665
666                         vListInsertEnd( ( xList * ) &xTasksWaitingTermination, &( pxTCB->xGenericListItem ) );
667
668                         /* Increment the ucTasksDeleted variable so the idle task knows
669                         there is a task that has been deleted and that it should therefore
670                         check the xTasksWaitingTermination list. */
671                         ++uxTasksDeleted;
672                 }
673                 taskEXIT_CRITICAL();
674
675                 /* Force a reschedule if we have just deleted the current task. */
676                 if( xSchedulerRunning != pdFALSE ) 
677                 {
678                         if( ( void * ) pxTaskToDelete == NULL )
679                         {
680                                 taskYIELD();
681                         }
682                 }
683         }
684
685 #endif
686
687
688
689
690
691
692 /*-----------------------------------------------------------
693  * TASK CONTROL API documented in task.h
694  *----------------------------------------------------------*/
695
696 #if ( INCLUDE_vTaskDelayUntil == 1 )
697
698         void vTaskDelayUntil( portTickType *pxPreviousWakeTime, portTickType xTimeIncrement )
699         {
700         portTickType xTimeToWake;
701         portBASE_TYPE xAlreadyYielded, xShouldDelay = pdFALSE;
702
703                 vTaskSuspendAll();
704                 {
705                         /* Generate the tick time at which the task wants to wake. */
706                         xTimeToWake = *pxPreviousWakeTime + xTimeIncrement;
707
708                         if( xTickCount < *pxPreviousWakeTime )
709                         {
710                                 /* The tick count has overflowed since this function was
711                                 lasted called.  In this case the only time we should ever
712                                 actually delay is if the wake time has also     overflowed,
713                                 and the wake time is greater than the tick time.  When this
714                                 is the case it is as if neither time had overflowed. */
715                                 if( ( xTimeToWake < *pxPreviousWakeTime ) && ( xTimeToWake > xTickCount ) )
716                                 {
717                                         xShouldDelay = pdTRUE;
718                                 }
719                         }
720                         else
721                         {
722                                 /* The tick time has not overflowed.  In this case we will
723                                 delay if either the wake time has overflowed, and/or the
724                                 tick time is less than the wake time. */
725                                 if( ( xTimeToWake < *pxPreviousWakeTime ) || ( xTimeToWake > xTickCount ) )
726                                 {
727                                         xShouldDelay = pdTRUE;
728                                 }
729                         }
730
731                         /* Update the wake time ready for the next call. */
732                         *pxPreviousWakeTime = xTimeToWake;
733
734                         if( xShouldDelay )
735                         {
736                                 /* We must remove ourselves from the ready list before adding
737                                 ourselves to the blocked list as the same list item is used for
738                                 both lists. */
739                                 vListRemove( ( xListItem * ) &( pxCurrentTCB->xGenericListItem ) );
740
741                                 /* The list item will be inserted in wake time order. */
742                                 listSET_LIST_ITEM_VALUE( &( pxCurrentTCB->xGenericListItem ), xTimeToWake );
743
744                                 if( xTimeToWake < xTickCount )
745                                 {
746                                         /* Wake time has overflowed.  Place this item in the
747                                         overflow list. */
748                                         vListInsert( ( xList * ) pxOverflowDelayedTaskList, ( xListItem * ) &( pxCurrentTCB->xGenericListItem ) );
749                                 }
750                                 else
751                                 {
752                                         /* The wake time has not overflowed, so we can use the
753                                         current block list. */
754                                         vListInsert( ( xList * ) pxDelayedTaskList, ( xListItem * ) &( pxCurrentTCB->xGenericListItem ) );
755                                 }
756                         }
757                 }
758                 xAlreadyYielded = xTaskResumeAll();
759
760                 /* Force a reschedule if xTaskResumeAll has not already done so, we may
761                 have put ourselves to sleep. */
762                 if( !xAlreadyYielded )
763                 {
764                         taskYIELD();
765                 }
766         }       
767         
768 #endif
769 /*-----------------------------------------------------------*/
770
771 #if ( INCLUDE_vTaskDelay == 1 )
772
773         void vTaskDelay( portTickType xTicksToDelay )
774         {
775         portTickType xTimeToWake;
776         signed portBASE_TYPE xAlreadyYielded = pdFALSE;
777
778                 /* A delay time of zero just forces a reschedule. */
779                 if( xTicksToDelay > ( portTickType ) 0 )
780                 {
781                         vTaskSuspendAll();
782                         {
783                                 /* A task that is removed from the event list while the
784                                 scheduler is suspended will not get placed in the ready
785                                 list or removed from the blocked list until the scheduler
786                                 is resumed.
787                                 
788                                 This task cannot be in an event list as it is the currently
789                                 executing task. */
790
791                                 /* Calculate the time to wake - this may overflow but this is
792                                 not a problem. */
793                                 xTimeToWake = xTickCount + xTicksToDelay;
794
795                                 /* We must remove ourselves from the ready list before adding
796                                 ourselves to the blocked list as the same list item is used for
797                                 both lists. */
798                                 vListRemove( ( xListItem * ) &( pxCurrentTCB->xGenericListItem ) );
799
800                                 /* The list item will be inserted in wake time order. */
801                                 listSET_LIST_ITEM_VALUE( &( pxCurrentTCB->xGenericListItem ), xTimeToWake );
802
803                                 if( xTimeToWake < xTickCount )
804                                 {
805                                         /* Wake time has overflowed.  Place this item in the
806                                         overflow list. */
807                                         vListInsert( ( xList * ) pxOverflowDelayedTaskList, ( xListItem * ) &( pxCurrentTCB->xGenericListItem ) );
808                                 }
809                                 else
810                                 {
811                                         /* The wake time has not overflowed, so we can use the
812                                         current block list. */
813                                         vListInsert( ( xList * ) pxDelayedTaskList, ( xListItem * ) &( pxCurrentTCB->xGenericListItem ) );
814                                 }
815                         }
816                         xAlreadyYielded = xTaskResumeAll();
817                 }
818                 
819                 /* Force a reschedule if xTaskResumeAll has not already done so, we may
820                 have put ourselves to sleep. */
821                 if( !xAlreadyYielded )
822                 {
823                         taskYIELD();
824                 }
825         }
826         
827 #endif
828 /*-----------------------------------------------------------*/
829
830 #if ( INCLUDE_uxTaskPriorityGet == 1 )
831
832         unsigned portBASE_TYPE uxTaskPriorityGet( xTaskHandle pxTask )
833         {
834         tskTCB *pxTCB;
835         unsigned portBASE_TYPE uxReturn;
836
837                 taskENTER_CRITICAL();
838                 {
839                         /* If null is passed in here then we are changing the
840                         priority of the calling function. */
841                         pxTCB = prvGetTCBFromHandle( pxTask );
842                         uxReturn = pxTCB->uxPriority;
843                 }
844                 taskEXIT_CRITICAL();
845
846                 return uxReturn;
847         }
848
849 #endif
850 /*-----------------------------------------------------------*/
851
852 #if ( INCLUDE_vTaskPrioritySet == 1 )
853
854         void vTaskPrioritySet( xTaskHandle pxTask, unsigned portBASE_TYPE uxNewPriority )
855         {
856         tskTCB *pxTCB;
857         unsigned portBASE_TYPE uxCurrentPriority, xYieldRequired = pdFALSE;
858
859                 /* Ensure the new priority is valid. */
860                 if( uxNewPriority >= configMAX_PRIORITIES )
861                 {
862                         uxNewPriority = configMAX_PRIORITIES - 1;
863                 }
864
865                 taskENTER_CRITICAL();
866                 {
867                         /* If null is passed in here then we are changing the
868                         priority of the calling function. */
869                         pxTCB = prvGetTCBFromHandle( pxTask );
870                         uxCurrentPriority = pxTCB->uxPriority;
871
872                         if( uxCurrentPriority != uxNewPriority )
873                         {
874                                 /* The priority change may have readied a task of higher
875                                 priority than the calling task. */
876                                 if( uxNewPriority > pxCurrentTCB->uxPriority ) 
877                                 {
878                                         if( pxTask != NULL )
879                                         {
880                                                 /* The priority of another task is being raised.  If we
881                                                 were raising the priority of the currently running task
882                                                 there would be no need to switch as it must have already
883                                                 been the highest priority task. */
884                                                 xYieldRequired = pdTRUE;
885                                         }
886                                 }
887                                 else if( pxTask == NULL )
888                                 {
889                                         /* Setting our own priority down means there may now be another
890                                         task of higher priority that is ready to execute. */
891                                         xYieldRequired = pdTRUE;
892                                 }
893                         
894                                 pxTCB->uxPriority = uxNewPriority;
895                                 listSET_LIST_ITEM_VALUE( &( pxTCB->xEventListItem ), configMAX_PRIORITIES - ( portTickType ) uxNewPriority );
896
897                                 /* If the task is in the blocked or suspended list we need do
898                                 nothing more than change it's priority variable. However, if
899                                 the task is in a ready list it needs to be removed and placed
900                                 in the queue appropriate to its new priority. */
901                                 if( listIS_CONTAINED_WITHIN( &( pxReadyTasksLists[ uxCurrentPriority ] ), &( pxTCB->xGenericListItem ) ) )
902                                 {
903                                         /* The task is currently in its ready list - remove before adding
904                                         it to it's new ready list.  As we are in a critical section we
905                                         can do this even if the scheduler is suspended. */
906                                         vListRemove( &( pxTCB->xGenericListItem ) );
907                                         prvAddTaskToReadyQueue( pxTCB );
908                                 }                       
909                                 
910                                 if( xYieldRequired == pdTRUE )
911                                 {
912                                         taskYIELD();
913                                 }                               
914                         }
915                 }
916                 taskEXIT_CRITICAL();
917         }
918
919 #endif
920 /*-----------------------------------------------------------*/
921
922 #if ( INCLUDE_vTaskSuspend == 1 )
923
924         void vTaskSuspend( xTaskHandle pxTaskToSuspend )
925         {
926         tskTCB *pxTCB;
927
928                 taskENTER_CRITICAL();
929                 {
930                         /* Ensure a yield is performed if the current task is being 
931                         suspended. */
932                         if( pxTaskToSuspend == pxCurrentTCB )
933                         {
934                                 pxTaskToSuspend = NULL;
935                         }
936
937                         /* If null is passed in here then we are suspending ourselves. */
938                         pxTCB = prvGetTCBFromHandle( pxTaskToSuspend );
939
940                         /* Remove task from the ready/delayed list and place in the     suspended list. */
941                         vListRemove( &( pxTCB->xGenericListItem ) );
942
943                         /* Is the task waiting on an event also? */                                                                                             
944                         if( pxTCB->xEventListItem.pvContainer )
945                         {
946                                 vListRemove( &( pxTCB->xEventListItem ) );
947                         }
948
949                         vListInsertEnd( ( xList * ) &xSuspendedTaskList, &( pxTCB->xGenericListItem ) );
950                 }
951                 taskEXIT_CRITICAL();
952
953                 /* We may have just suspended the current task. */
954                 if( ( void * ) pxTaskToSuspend == NULL )
955                 {
956                         taskYIELD();
957                 }
958         }
959
960 #endif
961 /*-----------------------------------------------------------*/
962
963 #if ( INCLUDE_vTaskSuspend == 1 )
964
965         static portBASE_TYPE prvIsTaskSuspended( const tskTCB * const pxTCB )
966         {
967         portBASE_TYPE xReturn = pdFALSE;
968
969                 /* Is the task we are attempting to resume actually in the
970                 suspended list? */
971                 if( listIS_CONTAINED_WITHIN( &xSuspendedTaskList, &( pxTCB->xGenericListItem ) ) != pdFALSE )
972                 {
973                         /* Has the task already been resumed from within an ISR? */
974                         if( listIS_CONTAINED_WITHIN( &xPendingReadyList, &( pxTCB->xEventListItem ) ) != pdTRUE )
975                         {                       
976                                 /* Is it in the suspended list because it is in the
977                                 Suspended state?  It is possible to be in the suspended
978                                 list because it is blocked on a task with no timeout
979                                 specified. */
980                                 if( listIS_CONTAINED_WITHIN( NULL, &( pxTCB->xEventListItem ) ) == pdTRUE )
981                                 {
982                                         xReturn = pdTRUE;
983                                 }
984                         }
985                 }
986
987                 return xReturn;
988         }
989
990 #endif
991 /*-----------------------------------------------------------*/
992
993 #if ( INCLUDE_vTaskSuspend == 1 )
994
995         void vTaskResume( xTaskHandle pxTaskToResume )
996         {
997         tskTCB *pxTCB;
998
999                 /* Remove the task from whichever list it is currently in, and place
1000                 it in the ready list. */
1001                 pxTCB = ( tskTCB * ) pxTaskToResume;
1002
1003                 /* The parameter cannot be NULL as it is impossible to resume the
1004                 currently executing task. */
1005                 if( pxTCB != NULL )
1006                 {
1007                         taskENTER_CRITICAL();
1008                         {
1009                                 if( prvIsTaskSuspended( pxTCB ) == pdTRUE )
1010                                 {
1011                                         /* As we are in a critical section we can access the ready
1012                                         lists even if the scheduler is suspended. */
1013                                         vListRemove(  &( pxTCB->xGenericListItem ) );
1014                                         prvAddTaskToReadyQueue( pxTCB );
1015
1016                                         /* We may have just resumed a higher priority task. */
1017                                         if( pxTCB->uxPriority >= pxCurrentTCB->uxPriority )
1018                                         {
1019                                                 /* This yield may not cause the task just resumed to run, but
1020                                                 will leave the lists in the correct state for the next yield. */
1021                                                 taskYIELD();
1022                                         }
1023                                 }
1024                         }
1025                         taskEXIT_CRITICAL();
1026                 }
1027         }
1028
1029 #endif
1030
1031 /*-----------------------------------------------------------*/
1032
1033 #if ( ( INCLUDE_xTaskResumeFromISR == 1 ) && ( INCLUDE_vTaskSuspend == 1 ) )
1034
1035         portBASE_TYPE xTaskResumeFromISR( xTaskHandle pxTaskToResume )
1036         {
1037         portBASE_TYPE xYieldRequired = pdFALSE;
1038         tskTCB *pxTCB;
1039
1040                 pxTCB = ( tskTCB * ) pxTaskToResume;
1041
1042                 if( prvIsTaskSuspended( pxTCB ) == pdTRUE )
1043                 {
1044                         if( uxSchedulerSuspended == ( unsigned portBASE_TYPE ) pdFALSE )
1045                         {
1046                                 xYieldRequired = ( pxTCB->uxPriority >= pxCurrentTCB->uxPriority );
1047                                 vListRemove(  &( pxTCB->xGenericListItem ) );   
1048                                 prvAddTaskToReadyQueue( pxTCB );
1049                         }
1050                         else
1051                         {
1052                                 /* We cannot access the delayed or ready lists, so will hold this
1053                                 task pending until the scheduler is resumed, at which point a
1054                                 yield will be preformed if necessary. */
1055                                 vListInsertEnd( ( xList * ) &( xPendingReadyList ), &( pxTCB->xEventListItem ) );
1056                         }
1057                 }
1058
1059                 return xYieldRequired;
1060         }
1061
1062 #endif
1063
1064
1065
1066
1067 /*-----------------------------------------------------------
1068  * PUBLIC SCHEDULER CONTROL documented in task.h
1069  *----------------------------------------------------------*/
1070
1071
1072 void vTaskStartScheduler( void )
1073 {
1074 portBASE_TYPE xReturn;
1075
1076         /* Add the idle task at the lowest priority. */
1077         xReturn = xTaskCreate( prvIdleTask, ( signed portCHAR * ) "IDLE", tskIDLE_STACK_SIZE, ( void * ) NULL, tskIDLE_PRIORITY, ( xTaskHandle * ) NULL );
1078
1079         if( xReturn == pdPASS )
1080         {
1081                 /* Interrupts are turned off here, to ensure a tick does not occur
1082                 before or during the call to xPortStartScheduler().  The stacks of
1083                 the created tasks contain a status word with interrupts switched on
1084                 so interrupts will automatically get re-enabled when the first task
1085                 starts to run.
1086                 
1087                 STEPPING THROUGH HERE USING A DEBUGGER CAN CAUSE BIG PROBLEMS IF THE
1088                 DEBUGGER ALLOWS INTERRUPTS TO BE PROCESSED. */
1089                 portDISABLE_INTERRUPTS();
1090
1091                 xSchedulerRunning = pdTRUE;
1092                 xTickCount = ( portTickType ) 0;
1093
1094                 /* Setting up the timer tick is hardware specific and thus in the
1095                 portable interface. */
1096                 if( xPortStartScheduler() )
1097                 {
1098                         /* Should not reach here as if the scheduler is running the
1099                         function will not return. */
1100                 }
1101                 else
1102                 {
1103                         /* Should only reach here if a task calls xTaskEndScheduler(). */
1104                 }
1105         }
1106 }
1107 /*-----------------------------------------------------------*/
1108
1109 void vTaskEndScheduler( void )
1110 {
1111         /* Stop the scheduler interrupts and call the portable scheduler end
1112         routine so the original ISRs can be restored if necessary.  The port
1113         layer must ensure interrupts enable     bit is left in the correct state. */
1114         portDISABLE_INTERRUPTS();
1115         xSchedulerRunning = pdFALSE;
1116         vPortEndScheduler();
1117 }
1118 /*----------------------------------------------------------*/
1119
1120 void vTaskSuspendAll( void )
1121 {
1122         portENTER_CRITICAL();
1123                 ++uxSchedulerSuspended;
1124         portEXIT_CRITICAL();
1125 }
1126 /*----------------------------------------------------------*/
1127
1128 signed portBASE_TYPE xTaskResumeAll( void )
1129 {
1130 register tskTCB *pxTCB;
1131 signed portBASE_TYPE xAlreadyYielded = pdFALSE;
1132
1133         /* It is possible that an ISR caused a task to be removed from an event
1134         list while the scheduler was suspended.  If this was the case then the
1135         removed task will have been added to the xPendingReadyList.  Once the
1136         scheduler has been resumed it is safe to move all the pending ready
1137         tasks from this list into their appropriate ready list. */
1138         portENTER_CRITICAL();
1139         {
1140                 --uxSchedulerSuspended;
1141
1142                 if( uxSchedulerSuspended == ( unsigned portBASE_TYPE ) pdFALSE )
1143                 {                       
1144                         if( uxCurrentNumberOfTasks > ( unsigned portBASE_TYPE ) 0 )
1145                         {
1146                                 portBASE_TYPE xYieldRequired = pdFALSE;
1147                                 
1148                                 /* Move any readied tasks from the pending list into the
1149                                 appropriate ready list. */
1150                                 while( ( pxTCB = ( tskTCB * ) listGET_OWNER_OF_HEAD_ENTRY(  ( ( xList * ) &xPendingReadyList ) ) ) != NULL )
1151                                 {
1152                                         vListRemove( &( pxTCB->xEventListItem ) );
1153                                         vListRemove( &( pxTCB->xGenericListItem ) );
1154                                         prvAddTaskToReadyQueue( pxTCB );
1155                                         
1156                                         /* If we have moved a task that has a priority higher than
1157                                         the current task then we should yield. */
1158                                         if( pxTCB->uxPriority >= pxCurrentTCB->uxPriority )
1159                                         {
1160                                                 xYieldRequired = pdTRUE;
1161                                         }
1162                                 }
1163
1164                                 /* If any ticks occurred while the scheduler was suspended then
1165                                 they should be processed now.  This ensures the tick count does not
1166                                 slip, and that any delayed tasks are resumed at the correct time. */
1167                                 if( uxMissedTicks > ( unsigned portBASE_TYPE ) 0 )
1168                                 {
1169                                         while( uxMissedTicks > ( unsigned portBASE_TYPE ) 0 )
1170                                         {
1171                                                 vTaskIncrementTick();
1172                                                 --uxMissedTicks;
1173                                         }
1174
1175                                         /* As we have processed some ticks it is appropriate to yield
1176                                         to ensure the highest priority task that is ready to run is
1177                                         the task actually running. */
1178                                         xYieldRequired = pdTRUE;
1179                                 }
1180                                 
1181                                 if( ( xYieldRequired == pdTRUE ) || ( xMissedYield == pdTRUE ) )
1182                                 {
1183                                         xAlreadyYielded = pdTRUE;
1184                                         xMissedYield = pdFALSE;
1185                                         taskYIELD();
1186                                 }
1187                         }
1188                 }
1189         }
1190         portEXIT_CRITICAL();
1191
1192         return xAlreadyYielded;
1193 }
1194
1195
1196
1197
1198
1199
1200 /*-----------------------------------------------------------
1201  * PUBLIC TASK UTILITIES documented in task.h
1202  *----------------------------------------------------------*/
1203
1204
1205
1206 portTickType xTaskGetTickCount( void )
1207 {
1208 portTickType xTicks;
1209
1210         /* Critical section required if running on a 16 bit processor. */
1211         taskENTER_CRITICAL();
1212         {
1213                 xTicks = xTickCount;
1214         }
1215         taskEXIT_CRITICAL();
1216
1217         return xTicks;
1218 }
1219 /*-----------------------------------------------------------*/
1220
1221 unsigned portBASE_TYPE uxTaskGetNumberOfTasks( void )
1222 {
1223 unsigned portBASE_TYPE uxNumberOfTasks;
1224
1225         taskENTER_CRITICAL();
1226                 uxNumberOfTasks = uxCurrentNumberOfTasks;
1227         taskEXIT_CRITICAL();
1228
1229         return uxNumberOfTasks;
1230 }
1231 /*-----------------------------------------------------------*/
1232
1233 #if ( ( configUSE_TRACE_FACILITY == 1 ) && ( INCLUDE_vTaskDelete == 1 ) && ( INCLUDE_vTaskSuspend == 1 ) )
1234
1235         void vTaskList( signed portCHAR *pcWriteBuffer )
1236         {
1237         unsigned portBASE_TYPE uxQueue;
1238
1239                 /* This is a VERY costly function that should be used for debug only.
1240                 It leaves interrupts disabled for a LONG time. */
1241
1242         vTaskSuspendAll();
1243                 {
1244                         /* Run through all the lists that could potentially contain a TCB and
1245                         report the task name, state and stack high water mark. */
1246
1247                         pcWriteBuffer[ 0 ] = ( signed portCHAR ) 0x00;
1248                         strcat( ( portCHAR * ) pcWriteBuffer, ( const portCHAR * ) "\r\n" );
1249
1250                         uxQueue = uxTopUsedPriority + 1;
1251
1252                         do
1253                         {
1254                                 uxQueue--;
1255
1256                                 if( !listLIST_IS_EMPTY( &( pxReadyTasksLists[ uxQueue ] ) ) )
1257                                 {
1258                                         prvListTaskWithinSingleList( pcWriteBuffer, ( xList * ) &( pxReadyTasksLists[ uxQueue ] ), tskREADY_CHAR );                     
1259                                 }
1260                         }while( uxQueue > ( unsigned portSHORT ) tskIDLE_PRIORITY );
1261
1262                         if( !listLIST_IS_EMPTY( pxDelayedTaskList ) )
1263                         {
1264                                 prvListTaskWithinSingleList( pcWriteBuffer, ( xList * ) pxDelayedTaskList, tskBLOCKED_CHAR );
1265                         }
1266
1267                         if( !listLIST_IS_EMPTY( pxOverflowDelayedTaskList ) )
1268                         {
1269                                 prvListTaskWithinSingleList( pcWriteBuffer, ( xList * ) pxOverflowDelayedTaskList, tskBLOCKED_CHAR );
1270                         }
1271
1272                         if( !listLIST_IS_EMPTY( &xTasksWaitingTermination ) )
1273                         {
1274                                 prvListTaskWithinSingleList( pcWriteBuffer, ( xList * ) &xTasksWaitingTermination, tskDELETED_CHAR );
1275                         }
1276
1277                         if( !listLIST_IS_EMPTY( &xSuspendedTaskList ) )
1278                         {
1279                                 prvListTaskWithinSingleList( pcWriteBuffer, ( xList * ) &xSuspendedTaskList, tskSUSPENDED_CHAR );
1280                         }
1281                 }
1282         xTaskResumeAll();
1283         }
1284
1285 #endif
1286 /*----------------------------------------------------------*/
1287
1288 #if ( configUSE_TRACE_FACILITY == 1 )
1289
1290         void vTaskStartTrace( signed portCHAR * pcBuffer, unsigned portLONG ulBufferSize )
1291         {
1292                 portENTER_CRITICAL();
1293                 {
1294                         pcTraceBuffer = ( volatile signed portCHAR * volatile )pcBuffer;
1295                         pcTraceBufferStart = pcBuffer;
1296                         pcTraceBufferEnd = pcBuffer + ( ulBufferSize - tskSIZE_OF_EACH_TRACE_LINE );
1297                         xTracing = pdTRUE;
1298                 }
1299                 portEXIT_CRITICAL();
1300         }
1301
1302 #endif
1303 /*----------------------------------------------------------*/
1304
1305 #if ( configUSE_TRACE_FACILITY == 1 )
1306
1307         unsigned portLONG ulTaskEndTrace( void )
1308         {
1309         unsigned portLONG ulBufferLength;
1310
1311                 portENTER_CRITICAL();
1312                         xTracing = pdFALSE;
1313                 portEXIT_CRITICAL();
1314
1315                 ulBufferLength = ( unsigned portLONG ) ( pcTraceBuffer - pcTraceBufferStart );
1316
1317                 return ulBufferLength;
1318         }
1319
1320 #endif
1321
1322
1323
1324 /*-----------------------------------------------------------
1325  * SCHEDULER INTERNALS AVAILABLE FOR PORTING PURPOSES
1326  * documented in task.h
1327  *----------------------------------------------------------*/
1328
1329
1330 inline void vTaskIncrementTick( void )
1331 {
1332         /* Called by the portable layer each time a tick interrupt occurs.
1333         Increments the tick then checks to see if the new tick value will cause any
1334         tasks to be unblocked. */
1335         if( uxSchedulerSuspended == ( unsigned portBASE_TYPE ) pdFALSE )
1336         {
1337                 ++xTickCount;
1338                 if( xTickCount == ( portTickType ) 0 )
1339                 {
1340                         xList *pxTemp;
1341
1342                         /* Tick count has overflowed so we need to swap the delay lists.  
1343                         If there are any items in pxDelayedTaskList here then there is 
1344                         an error! */
1345                         pxTemp = pxDelayedTaskList;
1346                         pxDelayedTaskList = pxOverflowDelayedTaskList;
1347                         pxOverflowDelayedTaskList = pxTemp;
1348             xNumOfOverflows++;
1349                 }
1350
1351                 /* See if this tick has made a timeout expire. */
1352                 prvCheckDelayedTasks();
1353         }
1354         else
1355         {
1356                 ++uxMissedTicks;
1357
1358                 /* The tick hook gets called at regular intervals, even if the 
1359                 scheduler is locked. */
1360                 #if ( configUSE_TICK_HOOK == 1 )
1361                 {
1362                         extern void vApplicationTickHook( void );
1363
1364                         vApplicationTickHook();
1365                 }
1366                 #endif
1367         }
1368
1369         #if ( configUSE_TICK_HOOK == 1 )
1370         {
1371                 extern void vApplicationTickHook( void );
1372
1373                 /* Guard against the tick hook being called when the missed tick
1374                 count is being unwound (when the scheduler is being unlocked. */
1375                 if( uxMissedTicks == 0 )
1376                 {
1377                         vApplicationTickHook();
1378                 }
1379         }
1380         #endif
1381 }
1382 /*-----------------------------------------------------------*/
1383
1384 #if ( ( INCLUDE_vTaskCleanUpResources == 1 ) && ( INCLUDE_vTaskSuspend == 1 ) )
1385
1386         void vTaskCleanUpResources( void )
1387         {
1388         unsigned portSHORT usQueue;
1389         volatile tskTCB *pxTCB;
1390
1391                 usQueue = ( unsigned portSHORT ) uxTopUsedPriority + ( unsigned portSHORT ) 1;
1392
1393                 /* Remove any TCB's from the ready queues. */
1394                 do
1395                 {
1396                         usQueue--;
1397
1398                         while( !listLIST_IS_EMPTY( &( pxReadyTasksLists[ usQueue ] ) ) )
1399                         {
1400                                 listGET_OWNER_OF_NEXT_ENTRY( pxTCB, &( pxReadyTasksLists[ usQueue ] ) );
1401                                 vListRemove( ( xListItem * ) &( pxTCB->xGenericListItem ) );
1402
1403                                 prvDeleteTCB( ( tskTCB * ) pxTCB );
1404                         }
1405                 }while( usQueue > ( unsigned portSHORT ) tskIDLE_PRIORITY );
1406
1407                 /* Remove any TCB's from the delayed queue. */
1408                 while( !listLIST_IS_EMPTY( &xDelayedTaskList1 ) )
1409                 {
1410                         listGET_OWNER_OF_NEXT_ENTRY( pxTCB, &xDelayedTaskList1 );
1411                         vListRemove( ( xListItem * ) &( pxTCB->xGenericListItem ) );
1412
1413                         prvDeleteTCB( ( tskTCB * ) pxTCB );
1414                 }
1415
1416                 /* Remove any TCB's from the overflow delayed queue. */
1417                 while( !listLIST_IS_EMPTY( &xDelayedTaskList2 ) )
1418                 {
1419                         listGET_OWNER_OF_NEXT_ENTRY( pxTCB, &xDelayedTaskList2 );
1420                         vListRemove( ( xListItem * ) &( pxTCB->xGenericListItem ) );
1421
1422                         prvDeleteTCB( ( tskTCB * ) pxTCB );
1423                 }
1424
1425                 while( !listLIST_IS_EMPTY( &xSuspendedTaskList ) )
1426                 {
1427                         listGET_OWNER_OF_NEXT_ENTRY( pxTCB, &xSuspendedTaskList );
1428                         vListRemove( ( xListItem * ) &( pxTCB->xGenericListItem ) );
1429
1430                         prvDeleteTCB( ( tskTCB * ) pxTCB );
1431                 }               
1432         }
1433
1434 #endif
1435 /*-----------------------------------------------------------*/
1436
1437 void vTaskSwitchContext( void )
1438 {
1439         if( uxSchedulerSuspended != ( unsigned portBASE_TYPE ) pdFALSE )
1440         {
1441                 /* The scheduler is currently suspended - do not allow a context
1442                 switch. */
1443                 xMissedYield = pdTRUE;
1444                 return;
1445         }
1446
1447         /* Find the highest priority queue that contains ready tasks. */
1448         while( listLIST_IS_EMPTY( &( pxReadyTasksLists[ uxTopReadyPriority ] ) ) )
1449         {
1450                 --uxTopReadyPriority;
1451         }
1452
1453         /* listGET_OWNER_OF_NEXT_ENTRY walks through the list, so the tasks of the
1454         same priority get an equal share of the processor time. */
1455         listGET_OWNER_OF_NEXT_ENTRY( pxCurrentTCB, &( pxReadyTasksLists[ uxTopReadyPriority ] ) );
1456         vWriteTraceToBuffer();
1457 }
1458 /*-----------------------------------------------------------*/
1459
1460 void vTaskPlaceOnEventList( xList *pxEventList, portTickType xTicksToWait )
1461 {
1462 portTickType xTimeToWake;
1463
1464         /* THIS FUNCTION MUST BE CALLED WITH INTERRUPTS DISABLED OR THE
1465         SCHEDULER SUSPENDED. */
1466
1467         /* Place the event list item of the TCB in the appropriate event list.
1468         This is placed in the list in priority order so the highest priority task
1469         is the first to be woken by the event. */
1470         vListInsert( ( xList * ) pxEventList, ( xListItem * ) &( pxCurrentTCB->xEventListItem ) );
1471
1472         /* We must remove ourselves from the ready list before adding ourselves
1473         to the blocked list as the same list item is used for both lists.  We have
1474         exclusive access to the ready lists as the scheduler is locked. */
1475         vListRemove( ( xListItem * ) &( pxCurrentTCB->xGenericListItem ) );
1476
1477
1478         #if ( INCLUDE_vTaskSuspend == 1 )
1479         {                        
1480                 if( xTicksToWait == portMAX_DELAY )
1481                 {
1482                         /* Add ourselves to the suspended task list instead of a delayed task
1483                         list to ensure we are not woken by a timing event.  We will block
1484                         indefinitely. */
1485                         vListInsertEnd( ( xList * ) &xSuspendedTaskList, ( xListItem * ) &( pxCurrentTCB->xGenericListItem ) );
1486                 }
1487                 else
1488                 {
1489                         /* Calculate the time at which the task should be woken if the event does
1490                         not occur.  This may overflow but this doesn't matter. */
1491                         xTimeToWake = xTickCount + xTicksToWait;
1492                 
1493                         listSET_LIST_ITEM_VALUE( &( pxCurrentTCB->xGenericListItem ), xTimeToWake );
1494                 
1495                         if( xTimeToWake < xTickCount )
1496                         {
1497                                 /* Wake time has overflowed.  Place this item in the overflow list. */
1498                                 vListInsert( ( xList * ) pxOverflowDelayedTaskList, ( xListItem * ) &( pxCurrentTCB->xGenericListItem ) );
1499                         }
1500                         else
1501                         {
1502                                 /* The wake time has not overflowed, so we can use the current block list. */
1503                                 vListInsert( ( xList * ) pxDelayedTaskList, ( xListItem * ) &( pxCurrentTCB->xGenericListItem ) );
1504                         }
1505                 }
1506         }
1507         #else
1508         {
1509                         /* Calculate the time at which the task should be woken if the event does
1510                         not occur.  This may overflow but this doesn't matter. */
1511                         xTimeToWake = xTickCount + xTicksToWait;
1512                 
1513                         listSET_LIST_ITEM_VALUE( &( pxCurrentTCB->xGenericListItem ), xTimeToWake );
1514                 
1515                         if( xTimeToWake < xTickCount )
1516                         {
1517                                 /* Wake time has overflowed.  Place this item in the overflow list. */
1518                                 vListInsert( ( xList * ) pxOverflowDelayedTaskList, ( xListItem * ) &( pxCurrentTCB->xGenericListItem ) );
1519                         }
1520                         else
1521                         {
1522                                 /* The wake time has not overflowed, so we can use the current block list. */
1523                                 vListInsert( ( xList * ) pxDelayedTaskList, ( xListItem * ) &( pxCurrentTCB->xGenericListItem ) );
1524                         }
1525         }
1526         #endif
1527 }
1528 /*-----------------------------------------------------------*/
1529
1530 signed portBASE_TYPE xTaskRemoveFromEventList( const xList *pxEventList )
1531 {
1532 tskTCB *pxUnblockedTCB;
1533 portBASE_TYPE xReturn;
1534
1535         /* THIS FUNCTION MUST BE CALLED WITH INTERRUPTS DISABLED OR THE
1536         SCHEDULER SUSPENDED.  It can also be called from within an ISR. */
1537
1538         /* The event list is sorted in priority order, so we can remove the
1539         first in the list, remove the TCB from the delayed list, and add
1540         it to the ready list.
1541         
1542         If an event is for a queue that is locked then this function will never
1543         get called - the lock count on the queue will get modified instead.  This
1544         means we can always expect exclusive access to the event list here. */
1545         pxUnblockedTCB = ( tskTCB * ) listGET_OWNER_OF_HEAD_ENTRY( pxEventList );
1546         vListRemove( &( pxUnblockedTCB->xEventListItem ) );
1547
1548         if( uxSchedulerSuspended == ( unsigned portBASE_TYPE ) pdFALSE )
1549         {
1550                 vListRemove( &( pxUnblockedTCB->xGenericListItem ) );
1551                 prvAddTaskToReadyQueue( pxUnblockedTCB );
1552         }
1553         else
1554         {
1555                 /* We cannot access the delayed or ready lists, so will hold this
1556                 task pending until the scheduler is resumed. */
1557                 vListInsertEnd( ( xList * ) &( xPendingReadyList ), &( pxUnblockedTCB->xEventListItem ) );
1558         }
1559
1560         if( pxUnblockedTCB->uxPriority >= pxCurrentTCB->uxPriority )
1561         {
1562                 /* Return true if the task removed from the event list has
1563                 a higher priority than the calling task.  This allows
1564                 the calling task to know if it should force a context
1565                 switch now. */
1566                 xReturn = pdTRUE;
1567         }
1568         else
1569         {
1570                 xReturn = pdFALSE;
1571         }
1572
1573         return xReturn;
1574 }
1575 /*-----------------------------------------------------------*/
1576
1577 void vTaskSetTimeOutState( xTimeOutType *pxTimeOut )
1578 {
1579     pxTimeOut->xOverflowCount = xNumOfOverflows;
1580     pxTimeOut->xTimeOnEntering = xTickCount;
1581 }
1582 /*-----------------------------------------------------------*/
1583
1584 portBASE_TYPE xTaskCheckForTimeOut( xTimeOutType *pxTimeOut, portTickType * const pxTicksToWait )
1585 {
1586 portBASE_TYPE xReturn;
1587
1588         #if ( INCLUDE_vTaskSuspend == 1 )
1589                 /* If INCLUDE_vTaskSuspend is set to 1 and the block time specified is
1590                 the maximum block time then the task should block indefinitely, and
1591                 therefore never time out. */
1592                 if( *pxTicksToWait == portMAX_DELAY )
1593                 {
1594                         xReturn = pdFALSE;
1595                 }
1596                 else /* We are not blocking indefinitely, perform the checks below. */
1597         #endif
1598
1599     if( ( xNumOfOverflows != pxTimeOut->xOverflowCount ) && ( xTickCount >= pxTimeOut->xTimeOnEntering ) )
1600     {
1601         /* The tick count is greater than the time at which vTaskSetTimeout()
1602                 was called, but has also overflowed since vTaskSetTimeOut() was called.
1603         It must have wrapped all the way around and gone past us again. This
1604         passed since vTaskSetTimeout() was called. */
1605         xReturn = pdTRUE;
1606     }
1607     else if( ( xTickCount - pxTimeOut->xTimeOnEntering ) < *pxTicksToWait )
1608     {
1609         /* Not a genuine timeout. Adjust parameters for time remaining. */
1610         *pxTicksToWait -= ( xTickCount - pxTimeOut->xTimeOnEntering );
1611         vTaskSetTimeOutState( pxTimeOut );
1612         xReturn = pdFALSE;
1613     }
1614     else
1615     {
1616         xReturn = pdTRUE;
1617     }
1618
1619     return xReturn;
1620 }
1621 /*-----------------------------------------------------------*/
1622
1623 void vTaskMissedYield( void )
1624 {
1625         xMissedYield = pdTRUE;
1626 }
1627
1628 /*
1629  * -----------------------------------------------------------
1630  * The Idle task.
1631  * ----------------------------------------------------------
1632  *
1633  * The portTASK_FUNCTION() macro is used to allow port/compiler specific
1634  * language extensions.  The equivalent prototype for this function is:
1635  *
1636  * void prvIdleTask( void *pvParameters );
1637  *
1638  */
1639 static portTASK_FUNCTION( prvIdleTask, pvParameters )
1640 {
1641         /* Stop warnings. */
1642         ( void ) pvParameters;
1643
1644         for( ;; )
1645         {
1646                 /* See if any tasks have been deleted. */
1647                 prvCheckTasksWaitingTermination();
1648
1649                 #if ( configUSE_PREEMPTION == 0 )
1650                 {
1651                         /* If we are not using preemption we keep forcing a task switch to
1652                         see if any other task has become available.  If we are using
1653                         preemption we don't need to do this as any task becoming available
1654                         will automatically get the processor anyway. */
1655                         taskYIELD();    
1656                 }
1657                 #endif
1658
1659                 #if ( ( configUSE_PREEMPTION == 1 ) && ( configIDLE_SHOULD_YIELD == 1 ) )
1660                 {
1661                         /* When using preemption tasks of equal priority will be
1662                         timesliced.  If a task that is sharing the idle priority is ready
1663                         to run then the idle task should yield before the end of the
1664                         timeslice.
1665                         
1666                         A critical region is not required here as we are just reading from
1667                         the list, and an occasional incorrect value will not matter.  If
1668                         the ready list at the idle priority contains more than one task
1669                         then a task other than the idle task is ready to execute. */
1670                         if( listCURRENT_LIST_LENGTH( &( pxReadyTasksLists[ tskIDLE_PRIORITY ] ) ) > ( unsigned portBASE_TYPE ) 1 )
1671                         {
1672                                 taskYIELD();
1673                         }
1674                 }
1675                 #endif
1676
1677                 #if ( configUSE_IDLE_HOOK == 1 )
1678                 {
1679                         extern void vApplicationIdleHook( void );
1680
1681                         /* Call the user defined function from within the idle task.  This
1682                         allows the application designer to add background functionality
1683                         without the overhead of a separate task.
1684                         NOTE: vApplicationIdleHook() MUST NOT, UNDER ANY CIRCUMSTANCES,
1685                         CALL A FUNCTION THAT MIGHT BLOCK. */
1686                         vApplicationIdleHook();
1687                 }
1688                 #endif
1689         }
1690 } /*lint !e715 pvParameters is not accessed but all task functions require the same prototype. */
1691
1692
1693
1694
1695
1696
1697
1698 /*-----------------------------------------------------------
1699  * File private functions documented at the top of the file.
1700  *----------------------------------------------------------*/
1701
1702
1703
1704 static void prvInitialiseTCBVariables( tskTCB *pxTCB, unsigned portSHORT usStackDepth, const signed portCHAR * const pcName, unsigned portBASE_TYPE uxPriority )
1705 {
1706         pxTCB->usStackDepth = usStackDepth;
1707
1708         /* Store the function name in the TCB. */
1709         strncpy( ( char * ) pxTCB->pcTaskName, ( const char * ) pcName, ( unsigned portSHORT ) configMAX_TASK_NAME_LEN );
1710         pxTCB->pcTaskName[ ( unsigned portSHORT ) configMAX_TASK_NAME_LEN - ( unsigned portSHORT ) 1 ] = '\0';
1711
1712         /* This is used as an array index so must ensure it's not too large. */
1713         if( uxPriority >= configMAX_PRIORITIES )
1714         {
1715                 uxPriority = configMAX_PRIORITIES - 1;
1716         }
1717
1718         pxTCB->uxPriority = uxPriority;
1719
1720         vListInitialiseItem( &( pxTCB->xGenericListItem ) );
1721         vListInitialiseItem( &( pxTCB->xEventListItem ) );
1722
1723         /* Set the pxTCB as a link back from the xListItem.  This is so we can get
1724         back to the containing TCB from a generic item in a list. */
1725         listSET_LIST_ITEM_OWNER( &( pxTCB->xGenericListItem ), pxTCB );
1726
1727         /* Event lists are always in priority order. */
1728         listSET_LIST_ITEM_VALUE( &( pxTCB->xEventListItem ), configMAX_PRIORITIES - ( portTickType ) uxPriority );
1729         listSET_LIST_ITEM_OWNER( &( pxTCB->xEventListItem ), pxTCB );
1730 }
1731 /*-----------------------------------------------------------*/
1732
1733 static void prvInitialiseTaskLists( void )
1734 {
1735 unsigned portBASE_TYPE uxPriority;
1736
1737         for( uxPriority = 0; uxPriority < configMAX_PRIORITIES; uxPriority++ )
1738         {
1739                 vListInitialise( ( xList * ) &( pxReadyTasksLists[ uxPriority ] ) );
1740         }
1741
1742         vListInitialise( ( xList * ) &xDelayedTaskList1 );
1743         vListInitialise( ( xList * ) &xDelayedTaskList2 );
1744         vListInitialise( ( xList * ) &xPendingReadyList );
1745
1746         #if ( INCLUDE_vTaskDelete == 1 )
1747         {
1748                 vListInitialise( ( xList * ) &xTasksWaitingTermination );
1749         }
1750         #endif
1751
1752         #if ( INCLUDE_vTaskSuspend == 1 )
1753         {
1754                 vListInitialise( ( xList * ) &xSuspendedTaskList );
1755         }
1756         #endif
1757
1758         /* Start with pxDelayedTaskList using list1 and the pxOverflowDelayedTaskList
1759         using list2. */
1760         pxDelayedTaskList = &xDelayedTaskList1;
1761         pxOverflowDelayedTaskList = &xDelayedTaskList2;
1762 }
1763 /*-----------------------------------------------------------*/
1764
1765 static void prvCheckTasksWaitingTermination( void )
1766 {                                                       
1767         #if ( INCLUDE_vTaskDelete == 1 )
1768         {                               
1769                 portBASE_TYPE xListIsEmpty;
1770
1771                 /* ucTasksDeleted is used to prevent vTaskSuspendAll() being called
1772                 too often in the idle task. */
1773                 if( uxTasksDeleted > ( unsigned portBASE_TYPE ) 0 )
1774                 {
1775                         vTaskSuspendAll();
1776                                 xListIsEmpty = listLIST_IS_EMPTY( &xTasksWaitingTermination );                          
1777                         xTaskResumeAll();
1778
1779                         if( !xListIsEmpty )
1780                         {
1781                                 tskTCB *pxTCB;
1782
1783                                 portENTER_CRITICAL();
1784                                 {                       
1785                                         pxTCB = ( tskTCB * ) listGET_OWNER_OF_HEAD_ENTRY( ( ( xList * ) &xTasksWaitingTermination ) );
1786                                         vListRemove( &( pxTCB->xGenericListItem ) );
1787                                         --uxCurrentNumberOfTasks;
1788                                         --uxTasksDeleted;
1789                                 }
1790                                 portEXIT_CRITICAL();
1791
1792                                 prvDeleteTCB( pxTCB );
1793                         }
1794                 }
1795         }
1796         #endif
1797 }
1798 /*-----------------------------------------------------------*/
1799
1800 static tskTCB *prvAllocateTCBAndStack( unsigned portSHORT usStackDepth )
1801 {
1802 tskTCB *pxNewTCB;
1803
1804         /* Allocate space for the TCB.  Where the memory comes from depends on
1805         the implementation of the port malloc function. */
1806         pxNewTCB = ( tskTCB * ) pvPortMalloc( sizeof( tskTCB ) );
1807
1808         if( pxNewTCB != NULL )
1809         {
1810                 /* Allocate space for the stack used by the task being created.
1811                 The base of the stack memory stored in the TCB so the task can
1812                 be deleted later if required. */
1813                 pxNewTCB->pxStack = ( portSTACK_TYPE * ) pvPortMalloc( ( ( size_t )usStackDepth ) * sizeof( portSTACK_TYPE ) );
1814
1815                 if( pxNewTCB->pxStack == NULL )
1816                 {
1817                         /* Could not allocate the stack.  Delete the allocated TCB. */
1818                         vPortFree( pxNewTCB );                  
1819                         pxNewTCB = NULL;                        
1820                 }               
1821                 else
1822                 {
1823                         /* Just to help debugging. */
1824                         memset( pxNewTCB->pxStack, tskSTACK_FILL_BYTE, usStackDepth * sizeof( portSTACK_TYPE ) );
1825                 }
1826         }
1827
1828         return pxNewTCB;
1829 }
1830 /*-----------------------------------------------------------*/
1831
1832 #if ( configUSE_TRACE_FACILITY == 1 )
1833
1834         static void prvListTaskWithinSingleList( signed portCHAR *pcWriteBuffer, xList *pxList, signed portCHAR cStatus )
1835         {
1836         volatile tskTCB *pxNextTCB, *pxFirstTCB;
1837         static portCHAR pcStatusString[ 50 ];
1838         unsigned portSHORT usStackRemaining;
1839
1840                 /* Write the details of all the TCB's in pxList into the buffer. */
1841                 listGET_OWNER_OF_NEXT_ENTRY( pxFirstTCB, pxList );
1842                 do
1843                 {
1844                         listGET_OWNER_OF_NEXT_ENTRY( pxNextTCB, pxList );
1845                         usStackRemaining = usTaskCheckFreeStackSpace( ( unsigned portCHAR * ) pxNextTCB->pxStack );
1846                         sprintf( pcStatusString, ( portCHAR * ) "%s\t\t%c\t%u\t%u\t%u\r\n", pxNextTCB->pcTaskName, cStatus, ( unsigned int ) pxNextTCB->uxPriority, usStackRemaining, ( unsigned int ) pxNextTCB->uxTCBNumber );
1847                         strcat( ( portCHAR * ) pcWriteBuffer, ( portCHAR * ) pcStatusString );
1848
1849                 } while( pxNextTCB != pxFirstTCB );
1850         }
1851
1852 #endif
1853 /*-----------------------------------------------------------*/
1854
1855 #if ( configUSE_TRACE_FACILITY == 1 )
1856         unsigned portSHORT usTaskCheckFreeStackSpace( const unsigned portCHAR *pucStackByte )
1857         {
1858         register unsigned portSHORT usCount = 0;
1859
1860                 while( *pucStackByte == tskSTACK_FILL_BYTE )
1861                 {
1862                         pucStackByte -= portSTACK_GROWTH;
1863                         usCount++;
1864                 }
1865
1866                 usCount /= sizeof( portSTACK_TYPE );
1867
1868                 return usCount;
1869         }
1870 #endif
1871 /*-----------------------------------------------------------*/
1872
1873
1874
1875 #if ( ( INCLUDE_vTaskDelete == 1 ) || ( INCLUDE_vTaskCleanUpResources == 1 ) )
1876
1877         static void prvDeleteTCB( tskTCB *pxTCB )
1878         {
1879                 /* Free up the memory allocated by the scheduler for the task.  It is up to
1880                 the task to free any memory allocated at the application level. */
1881                 vPortFree( pxTCB->pxStack );
1882                 vPortFree( pxTCB );
1883         }
1884
1885 #endif
1886
1887
1888 /*-----------------------------------------------------------*/
1889
1890 #if ( INCLUDE_xTaskGetCurrentTaskHandle == 1 )
1891
1892         xTaskHandle xTaskGetCurrentTaskHandle( void )
1893         {
1894         xTaskHandle xReturn;
1895
1896                 portENTER_CRITICAL();
1897                 {
1898                         xReturn = ( xTaskHandle ) pxCurrentTCB;
1899                 }
1900                 portEXIT_CRITICAL();
1901
1902                 return xReturn;
1903         }
1904
1905 #endif
1906
1907 /*-----------------------------------------------------------*/
1908
1909 #if ( INCLUDE_xTaskGetSchedulerState == 1 )
1910
1911         portBASE_TYPE xTaskGetSchedulerState( void )
1912         {
1913         portBASE_TYPE xReturn;
1914         
1915                 if( xSchedulerRunning == pdFALSE )
1916                 {
1917                         xReturn = taskSCHEDULER_NOT_STARTED;
1918                 }
1919                 else
1920                 {
1921                         if( uxSchedulerSuspended == ( unsigned portBASE_TYPE ) pdFALSE )
1922                         {
1923                                 xReturn = taskSCHEDULER_RUNNING;
1924                         }
1925                         else
1926                         {
1927                                 xReturn = taskSCHEDULER_SUSPENDED;
1928                         }
1929                 }
1930                 
1931                 return xReturn;
1932         }
1933
1934 #endif
1935
1936