3 * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
5 * Permission is hereby granted, free of charge, to any person obtaining a copy of
6 * this software and associated documentation files (the "Software"), to deal in
7 * the Software without restriction, including without limitation the rights to
8 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
9 * the Software, and to permit persons to whom the Software is furnished to do so,
10 * subject to the following conditions:
12 * The above copyright notice and this permission notice shall be included in all
13 * copies or substantial portions of the Software.
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
17 * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
18 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
19 * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
20 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 * http://www.FreeRTOS.org
23 * http://aws.amazon.com/freertos
29 * The first test creates three tasks - two counter tasks (one continuous count
30 * and one limited count) and one controller. A "count" variable is shared
31 * between all three tasks. The two counter tasks should never be in a "ready"
32 * state at the same time. The controller task runs at the same priority as
33 * the continuous count task, and at a lower priority than the limited count
36 * One counter task loops indefinitely, incrementing the shared count variable
37 * on each iteration. To ensure it has exclusive access to the variable it
38 * raises it's priority above that of the controller task before each
39 * increment, lowering it again to it's original priority before starting the
42 * The other counter task increments the shared count variable on each
43 * iteration of it's loop until the count has reached a limit of 0xff - at
44 * which point it suspends itself. It will not start a new loop until the
45 * controller task has made it "ready" again by calling vTaskResume ().
46 * This second counter task operates at a higher priority than controller
47 * task so does not need to worry about mutual exclusion of the counter
50 * The controller task is in two sections. The first section controls and
51 * monitors the continuous count task. When this section is operational the
52 * limited count task is suspended. Likewise, the second section controls
53 * and monitors the limited count task. When this section is operational the
54 * continuous count task is suspended.
56 * In the first section the controller task first takes a copy of the shared
57 * count variable. To ensure mutual exclusion on the count variable it
58 * suspends the continuous count task, resuming it again when the copy has been
59 * taken. The controller task then sleeps for a fixed period - during which
60 * the continuous count task will execute and increment the shared variable.
61 * When the controller task wakes it checks that the continuous count task
62 * has executed by comparing the copy of the shared variable with its current
63 * value. This time, to ensure mutual exclusion, the scheduler itself is
64 * suspended with a call to vTaskSuspendAll (). This is for demonstration
65 * purposes only and is not a recommended technique due to its inefficiency.
67 * After a fixed number of iterations the controller task suspends the
68 * continuous count task, and moves on to its second section.
70 * At the start of the second section the shared variable is cleared to zero.
71 * The limited count task is then woken from it's suspension by a call to
72 * vTaskResume (). As this counter task operates at a higher priority than
73 * the controller task the controller task should not run again until the
74 * shared variable has been counted up to the limited value causing the counter
75 * task to suspend itself. The next line after vTaskResume () is therefore
76 * a check on the shared variable to ensure everything is as expected.
79 * The second test consists of a couple of very simple tasks that post onto a
80 * queue while the scheduler is suspended. This test was added to test parts
81 * of the scheduler not exercised by the first test.
84 * The final set of two tasks implements a third test. This simply raises the
85 * priority of a task while the scheduler is suspended. Again this test was
86 * added to exercise parts of the code not covered by the first test.
88 * \page Priorities dynamic.c
96 + Delay periods are now specified using variables and constants of
97 + TickType_t rather than unsigned long.
98 + Added a second, simple test that uses the functions
99 + vQueueReceiveWhenSuspendedTask() and vQueueSendWhenSuspendedTask().
101 + Changes from V3.1.1
103 + Added a third simple test that uses the vTaskPrioritySet() function
104 + while the scheduler is suspended.
105 + Modified the controller task slightly to test the calling of
106 + vTaskResumeAll() while the scheduler is suspended.
111 /* Scheduler include files. */
112 #include "FreeRTOS.h"
116 /* Demo app include files. */
120 /* Function that implements the "limited count" task as described above. */
121 static void vLimitedIncrementTask( void * pvParameters );
123 /* Function that implements the "continuous count" task as described above. */
124 static void vContinuousIncrementTask( void * pvParameters );
126 /* Function that implements the controller task as described above. */
127 static void vCounterControlTask( void * pvParameters );
129 /* The simple test functions that check sending and receiving while the
130 * scheduler is suspended. */
131 static void vQueueReceiveWhenSuspendedTask( void * pvParameters );
132 static void vQueueSendWhenSuspendedTask( void * pvParameters );
134 /* The simple test functions that check raising and lowering of task priorities
135 * while the scheduler is suspended. */
136 static void prvChangePriorityWhenSuspendedTask( void * pvParameters );
137 static void prvChangePriorityHelperTask( void * pvParameters );
140 /* Demo task specific constants. */
141 #define priSTACK_SIZE ( ( unsigned short ) configMINIMAL_STACK_SIZE )
142 #define priSLEEP_TIME ( ( TickType_t ) 50 )
143 #define priLOOPS ( 5 )
144 #define priMAX_COUNT ( ( unsigned long ) 0xff )
145 #define priNO_BLOCK ( ( TickType_t ) 0 )
146 #define priSUSPENDED_QUEUE_LENGTH ( 1 )
148 /*-----------------------------------------------------------*/
150 /* Handles to the two counter tasks. These could be passed in as parameters
151 * to the controller task to prevent them having to be file scope. */
152 static TaskHandle_t xContinuousIncrementHandle, xLimitedIncrementHandle, xChangePriorityWhenSuspendedHandle;
154 /* The shared counter variable. This is passed in as a parameter to the two
155 * counter variables for demonstration purposes. */
156 static unsigned long ulCounter;
158 /* Variable used in a similar way by the test that checks the raising and
159 * lowering of task priorities while the scheduler is suspended. */
160 static unsigned long ulPrioritySetCounter;
162 /* Variables used to check that the tasks are still operating without error.
163 * Each complete iteration of the controller task increments this variable
164 * provided no errors have been found. The variable maintaining the same value
165 * is therefore indication of an error. */
166 static unsigned short usCheckVariable = ( unsigned short ) 0;
167 static portBASE_TYPE xSuspendedQueueSendError = pdFALSE;
168 static portBASE_TYPE xSuspendedQueueReceiveError = pdFALSE;
169 static portBASE_TYPE xPriorityRaiseWhenSuspendedError = pdFALSE;
171 /* Queue used by the second test. */
172 QueueHandle_t xSuspendedTestQueue;
174 /*-----------------------------------------------------------*/
177 * Start the seven tasks as described at the top of the file.
178 * Note that the limited count task is given a higher priority.
180 void vStartDynamicPriorityTasks( void )
182 xSuspendedTestQueue = xQueueCreate( priSUSPENDED_QUEUE_LENGTH, sizeof( unsigned long ) );
183 xTaskCreate( vContinuousIncrementTask, "CONT_INC", priSTACK_SIZE, ( void * ) &ulCounter, tskIDLE_PRIORITY, &xContinuousIncrementHandle );
184 xTaskCreate( vLimitedIncrementTask, "LIM_INC", priSTACK_SIZE, ( void * ) &ulCounter, tskIDLE_PRIORITY + 1, &xLimitedIncrementHandle );
185 xTaskCreate( vCounterControlTask, "C_CTRL", priSTACK_SIZE, NULL, tskIDLE_PRIORITY, NULL );
186 xTaskCreate( vQueueSendWhenSuspendedTask, "SUSP_SEND", priSTACK_SIZE, NULL, tskIDLE_PRIORITY, NULL );
187 xTaskCreate( vQueueReceiveWhenSuspendedTask, "SUSP_RECV", priSTACK_SIZE, NULL, tskIDLE_PRIORITY, NULL );
188 xTaskCreate( prvChangePriorityWhenSuspendedTask, "1st_P_CHANGE", priSTACK_SIZE, NULL, tskIDLE_PRIORITY + 1, NULL );
189 xTaskCreate( prvChangePriorityHelperTask, "2nd_P_CHANGE", priSTACK_SIZE, NULL, tskIDLE_PRIORITY, &xChangePriorityWhenSuspendedHandle );
191 /*-----------------------------------------------------------*/
194 * Just loops around incrementing the shared variable until the limit has been
195 * reached. Once the limit has been reached it suspends itself.
197 static void vLimitedIncrementTask( void * pvParameters )
199 unsigned long * pulCounter;
201 /* Take a pointer to the shared variable from the parameters passed into
203 pulCounter = ( unsigned long * ) pvParameters;
205 /* This will run before the control task, so the first thing it does is
206 * suspend - the control task will resume it when ready. */
207 vTaskSuspend( NULL );
211 /* Just count up to a value then suspend. */
214 if( *pulCounter >= priMAX_COUNT )
216 vTaskSuspend( NULL );
220 /*-----------------------------------------------------------*/
223 * Just keep counting the shared variable up. The control task will suspend
224 * this task when it wants.
226 static void vContinuousIncrementTask( void * pvParameters )
228 unsigned long * pulCounter;
229 unsigned portBASE_TYPE uxOurPriority;
231 /* Take a pointer to the shared variable from the parameters passed into
233 pulCounter = ( unsigned long * ) pvParameters;
235 /* Query our priority so we can raise it when exclusive access to the
236 * shared variable is required. */
237 uxOurPriority = uxTaskPriorityGet( NULL );
241 /* Raise our priority above the controller task to ensure a context
242 * switch does not occur while we are accessing this variable. */
243 vTaskPrioritySet( NULL, uxOurPriority + 1 );
245 vTaskPrioritySet( NULL, uxOurPriority );
247 #if configUSE_PREEMPTION == 0
252 /*-----------------------------------------------------------*/
255 * Controller task as described above.
257 static void vCounterControlTask( void * pvParameters )
259 unsigned long ulLastCounter;
261 short sError = pdFALSE;
262 const char * const pcTaskStartMsg = "Priority manipulation tasks started.\r\n";
263 const char * const pcTaskFailMsg = "Priority manipulation Task Failed\r\n";
265 /* Just to stop warning messages. */
266 ( void ) pvParameters;
268 /* Queue a message for printing to say the task has started. */
269 vPrintDisplayMessage( &pcTaskStartMsg );
273 /* Start with the counter at zero. */
274 ulCounter = ( unsigned long ) 0;
276 /* First section : */
278 /* Check the continuous count task is running. */
279 for( sLoops = 0; sLoops < priLOOPS; sLoops++ )
281 /* Suspend the continuous count task so we can take a mirror of the
282 * shared variable without risk of corruption. */
283 vTaskSuspend( xContinuousIncrementHandle );
284 ulLastCounter = ulCounter;
285 vTaskResume( xContinuousIncrementHandle );
287 /* Now delay to ensure the other task has processor time. */
288 vTaskDelay( priSLEEP_TIME );
290 /* Check the shared variable again. This time to ensure mutual
291 * exclusion the whole scheduler will be locked. This is just for
295 if( ulLastCounter == ulCounter )
297 /* The shared variable has not changed. There is a problem
298 * with the continuous count task so flag an error. */
301 vPrintDisplayMessage( &pcTaskFailMsg );
308 /* Second section: */
310 /* Suspend the continuous counter task so it stops accessing the shared variable. */
311 vTaskSuspend( xContinuousIncrementHandle );
313 /* Reset the variable. */
314 ulCounter = ( unsigned long ) 0;
316 /* Resume the limited count task which has a higher priority than us.
317 * We should therefore not return from this call until the limited count
318 * task has suspended itself with a known value in the counter variable.
319 * The scheduler suspension is not necessary but is included for test
322 vTaskResume( xLimitedIncrementHandle );
325 /* Does the counter variable have the expected value? */
326 if( ulCounter != priMAX_COUNT )
329 vPrintDisplayMessage( &pcTaskFailMsg );
332 if( sError == pdFALSE )
334 /* If no errors have occurred then increment the check variable. */
335 portENTER_CRITICAL();
340 #if configUSE_PREEMPTION == 0
344 /* Resume the continuous count task and do it all again. */
345 vTaskResume( xContinuousIncrementHandle );
348 /*-----------------------------------------------------------*/
350 static void vQueueSendWhenSuspendedTask( void * pvParameters )
352 static unsigned long ulValueToSend = ( unsigned long ) 0;
353 const char * const pcTaskStartMsg = "Queue send while suspended task started.\r\n";
354 const char * const pcTaskFailMsg = "Queue send while suspended failed.\r\n";
356 /* Just to stop warning messages. */
357 ( void ) pvParameters;
359 /* Queue a message for printing to say the task has started. */
360 vPrintDisplayMessage( &pcTaskStartMsg );
366 /* We must not block while the scheduler is suspended! */
367 if( xQueueSend( xSuspendedTestQueue, ( void * ) &ulValueToSend, priNO_BLOCK ) != pdTRUE )
369 if( xSuspendedQueueSendError == pdFALSE )
372 vPrintDisplayMessage( &pcTaskFailMsg );
376 xSuspendedQueueSendError = pdTRUE;
381 vTaskDelay( priSLEEP_TIME );
386 /*-----------------------------------------------------------*/
388 static void vQueueReceiveWhenSuspendedTask( void * pvParameters )
390 static unsigned long ulExpectedValue = ( unsigned long ) 0, ulReceivedValue;
391 const char * const pcTaskStartMsg = "Queue receive while suspended task started.\r\n";
392 const char * const pcTaskFailMsg = "Queue receive while suspended failed.\r\n";
393 portBASE_TYPE xGotValue;
395 /* Just to stop warning messages. */
396 ( void ) pvParameters;
398 /* Queue a message for printing to say the task has started. */
399 vPrintDisplayMessage( &pcTaskStartMsg );
405 /* Suspending the scheduler here is fairly pointless and
406 * undesirable for a normal application. It is done here purely
407 * to test the scheduler. The inner xTaskResumeAll() should
408 * never return pdTRUE as the scheduler is still locked by the
414 xGotValue = xQueueReceive( xSuspendedTestQueue, ( void * ) &ulReceivedValue, priNO_BLOCK );
417 if( xTaskResumeAll() )
419 xSuspendedQueueReceiveError = pdTRUE;
424 #if configUSE_PREEMPTION == 0
427 } while( xGotValue == pdFALSE );
429 if( ulReceivedValue != ulExpectedValue )
431 if( xSuspendedQueueReceiveError == pdFALSE )
433 vPrintDisplayMessage( &pcTaskFailMsg );
436 xSuspendedQueueReceiveError = pdTRUE;
442 /*-----------------------------------------------------------*/
444 static void prvChangePriorityWhenSuspendedTask( void * pvParameters )
446 const char * const pcTaskStartMsg = "Priority change when suspended task started.\r\n";
447 const char * const pcTaskFailMsg = "Priority change when suspended task failed.\r\n";
449 /* Just to stop warning messages. */
450 ( void ) pvParameters;
452 /* Queue a message for printing to say the task has started. */
453 vPrintDisplayMessage( &pcTaskStartMsg );
457 /* Start with the counter at 0 so we know what the counter should be
458 * when we check it next. */
459 ulPrioritySetCounter = ( unsigned long ) 0;
461 /* Resume the helper task. At this time it has a priority lower than
462 * ours so no context switch should occur. */
463 vTaskResume( xChangePriorityWhenSuspendedHandle );
465 /* Check to ensure the task just resumed has not executed. */
466 portENTER_CRITICAL();
468 if( ulPrioritySetCounter != ( unsigned long ) 0 )
470 xPriorityRaiseWhenSuspendedError = pdTRUE;
471 vPrintDisplayMessage( &pcTaskFailMsg );
476 /* Now try raising the priority while the scheduler is suspended. */
479 vTaskPrioritySet( xChangePriorityWhenSuspendedHandle, ( configMAX_PRIORITIES - 1 ) );
481 /* Again, even though the helper task has a priority greater than
482 * ours, it should not have executed yet because the scheduler is
484 portENTER_CRITICAL();
486 if( ulPrioritySetCounter != ( unsigned long ) 0 )
488 xPriorityRaiseWhenSuspendedError = pdTRUE;
489 vPrintDisplayMessage( &pcTaskFailMsg );
496 /* Now the scheduler has been resumed the helper task should
497 * immediately preempt us and execute. When it executes it will increment
498 * the ulPrioritySetCounter exactly once before suspending itself.
500 * We should now always find the counter set to 1. */
501 portENTER_CRITICAL();
503 if( ulPrioritySetCounter != ( unsigned long ) 1 )
505 xPriorityRaiseWhenSuspendedError = pdTRUE;
506 vPrintDisplayMessage( &pcTaskFailMsg );
511 /* Delay until we try this again. */
512 vTaskDelay( priSLEEP_TIME * 2 );
514 /* Set the priority of the helper task back ready for the next
515 * execution of this task. */
517 vTaskPrioritySet( xChangePriorityWhenSuspendedHandle, tskIDLE_PRIORITY );
521 /*-----------------------------------------------------------*/
523 static void prvChangePriorityHelperTask( void * pvParameters )
525 /* Just to stop warning messages. */
526 ( void ) pvParameters;
530 /* This is the helper task for prvChangePriorityWhenSuspendedTask().
531 * It has it's priority raised and lowered. When it runs it simply
532 * increments the counter then suspends itself again. This allows
533 * prvChangePriorityWhenSuspendedTask() to know how many times it has
535 ulPrioritySetCounter++;
536 vTaskSuspend( NULL );
539 /*-----------------------------------------------------------*/
541 /* Called to check that all the created tasks are still running without error. */
542 portBASE_TYPE xAreDynamicPriorityTasksStillRunning( void )
544 /* Keep a history of the check variables so we know if it has been incremented
545 * since the last call. */
546 static unsigned short usLastTaskCheck = ( unsigned short ) 0;
547 portBASE_TYPE xReturn = pdTRUE;
549 /* Check the tasks are still running by ensuring the check variable
550 * is still incrementing. */
552 if( usCheckVariable == usLastTaskCheck )
554 /* The check has not incremented so an error exists. */
558 if( xSuspendedQueueSendError == pdTRUE )
563 if( xSuspendedQueueReceiveError == pdTRUE )
568 if( xPriorityRaiseWhenSuspendedError == pdTRUE )
573 usLastTaskCheck = usCheckVariable;