FreeRTOS
[armadillo_firmware.git] / FreeRTOS / Common / Full / dynamic.c
blob7fd19f6ea24b6b27b646086e9497eeb0ac0695df
1 /*
2 FreeRTOS V6.0.5 - Copyright (C) 2010 Real Time Engineers Ltd.
4 ***************************************************************************
5 * *
6 * If you are: *
7 * *
8 * + New to FreeRTOS, *
9 * + Wanting to learn FreeRTOS or multitasking in general quickly *
10 * + Looking for basic training, *
11 * + Wanting to improve your FreeRTOS skills and productivity *
12 * *
13 * then take a look at the FreeRTOS eBook *
14 * *
15 * "Using the FreeRTOS Real Time Kernel - a Practical Guide" *
16 * http://www.FreeRTOS.org/Documentation *
17 * *
18 * A pdf reference manual is also available. Both are usually delivered *
19 * to your inbox within 20 minutes to two hours when purchased between 8am *
20 * and 8pm GMT (although please allow up to 24 hours in case of *
21 * exceptional circumstances). Thank you for your support! *
22 * *
23 ***************************************************************************
25 This file is part of the FreeRTOS distribution.
27 FreeRTOS is free software; you can redistribute it and/or modify it under
28 the terms of the GNU General Public License (version 2) as published by the
29 Free Software Foundation AND MODIFIED BY the FreeRTOS exception.
30 ***NOTE*** The exception to the GPL is included to allow you to distribute
31 a combined work that includes FreeRTOS without being obliged to provide the
32 source code for proprietary components outside of the FreeRTOS kernel.
33 FreeRTOS is distributed in the hope that it will be useful, but WITHOUT
34 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
35 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
36 more details. You should have received a copy of the GNU General Public
37 License and the FreeRTOS license exception along with FreeRTOS; if not it
38 can be viewed here: http://www.freertos.org/a00114.html and also obtained
39 by writing to Richard Barry, contact details for whom are available on the
40 FreeRTOS WEB site.
42 1 tab == 4 spaces!
44 http://www.FreeRTOS.org - Documentation, latest information, license and
45 contact details.
47 http://www.SafeRTOS.com - A version that is certified for use in safety
48 critical systems.
50 http://www.OpenRTOS.com - Commercial support, development, porting,
51 licensing and training services.
54 /**
55 * The first test creates three tasks - two counter tasks (one continuous count
56 * and one limited count) and one controller. A "count" variable is shared
57 * between all three tasks. The two counter tasks should never be in a "ready"
58 * state at the same time. The controller task runs at the same priority as
59 * the continuous count task, and at a lower priority than the limited count
60 * task.
62 * One counter task loops indefinitely, incrementing the shared count variable
63 * on each iteration. To ensure it has exclusive access to the variable it
64 * raises it's priority above that of the controller task before each
65 * increment, lowering it again to it's original priority before starting the
66 * next iteration.
68 * The other counter task increments the shared count variable on each
69 * iteration of it's loop until the count has reached a limit of 0xff - at
70 * which point it suspends itself. It will not start a new loop until the
71 * controller task has made it "ready" again by calling vTaskResume ().
72 * This second counter task operates at a higher priority than controller
73 * task so does not need to worry about mutual exclusion of the counter
74 * variable.
76 * The controller task is in two sections. The first section controls and
77 * monitors the continuous count task. When this section is operational the
78 * limited count task is suspended. Likewise, the second section controls
79 * and monitors the limited count task. When this section is operational the
80 * continuous count task is suspended.
82 * In the first section the controller task first takes a copy of the shared
83 * count variable. To ensure mutual exclusion on the count variable it
84 * suspends the continuous count task, resuming it again when the copy has been
85 * taken. The controller task then sleeps for a fixed period - during which
86 * the continuous count task will execute and increment the shared variable.
87 * When the controller task wakes it checks that the continuous count task
88 * has executed by comparing the copy of the shared variable with its current
89 * value. This time, to ensure mutual exclusion, the scheduler itself is
90 * suspended with a call to vTaskSuspendAll (). This is for demonstration
91 * purposes only and is not a recommended technique due to its inefficiency.
93 * After a fixed number of iterations the controller task suspends the
94 * continuous count task, and moves on to its second section.
96 * At the start of the second section the shared variable is cleared to zero.
97 * The limited count task is then woken from it's suspension by a call to
98 * vTaskResume (). As this counter task operates at a higher priority than
99 * the controller task the controller task should not run again until the
100 * shared variable has been counted up to the limited value causing the counter
101 * task to suspend itself. The next line after vTaskResume () is therefore
102 * a check on the shared variable to ensure everything is as expected.
105 * The second test consists of a couple of very simple tasks that post onto a
106 * queue while the scheduler is suspended. This test was added to test parts
107 * of the scheduler not exercised by the first test.
110 * The final set of two tasks implements a third test. This simply raises the
111 * priority of a task while the scheduler is suspended. Again this test was
112 * added to exercise parts of the code not covered by the first test.
114 * \page Priorities dynamic.c
115 * \ingroup DemoFiles
116 * <HR>
120 Changes from V2.0.0
122 + Delay periods are now specified using variables and constants of
123 portTickType rather than unsigned long.
124 + Added a second, simple test that uses the functions
125 vQueueReceiveWhenSuspendedTask() and vQueueSendWhenSuspendedTask().
127 Changes from V3.1.1
129 + Added a third simple test that uses the vTaskPrioritySet() function
130 while the scheduler is suspended.
131 + Modified the controller task slightly to test the calling of
132 vTaskResumeAll() while the scheduler is suspended.
135 #include <stdlib.h>
137 /* Scheduler include files. */
138 #include "FreeRTOS.h"
139 #include "task.h"
140 #include "semphr.h"
142 /* Demo app include files. */
143 #include "dynamic.h"
144 #include "print.h"
146 /* Function that implements the "limited count" task as described above. */
147 static void vLimitedIncrementTask( void * pvParameters );
149 /* Function that implements the "continuous count" task as described above. */
150 static void vContinuousIncrementTask( void * pvParameters );
152 /* Function that implements the controller task as described above. */
153 static void vCounterControlTask( void * pvParameters );
155 /* The simple test functions that check sending and receiving while the
156 scheduler is suspended. */
157 static void vQueueReceiveWhenSuspendedTask( void *pvParameters );
158 static void vQueueSendWhenSuspendedTask( void *pvParameters );
160 /* The simple test functions that check raising and lowering of task priorities
161 while the scheduler is suspended. */
162 static void prvChangePriorityWhenSuspendedTask( void *pvParameters );
163 static void prvChangePriorityHelperTask( void *pvParameters );
166 /* Demo task specific constants. */
167 #define priSTACK_SIZE ( ( unsigned short ) configMINIMAL_STACK_SIZE )
168 #define priSLEEP_TIME ( ( portTickType ) 50 )
169 #define priLOOPS ( 5 )
170 #define priMAX_COUNT ( ( unsigned long ) 0xff )
171 #define priNO_BLOCK ( ( portTickType ) 0 )
172 #define priSUSPENDED_QUEUE_LENGTH ( 1 )
174 /*-----------------------------------------------------------*/
176 /* Handles to the two counter tasks. These could be passed in as parameters
177 to the controller task to prevent them having to be file scope. */
178 static xTaskHandle xContinuousIncrementHandle, xLimitedIncrementHandle, xChangePriorityWhenSuspendedHandle;
180 /* The shared counter variable. This is passed in as a parameter to the two
181 counter variables for demonstration purposes. */
182 static unsigned long ulCounter;
184 /* Variable used in a similar way by the test that checks the raising and
185 lowering of task priorities while the scheduler is suspended. */
186 static unsigned long ulPrioritySetCounter;
188 /* Variables used to check that the tasks are still operating without error.
189 Each complete iteration of the controller task increments this variable
190 provided no errors have been found. The variable maintaining the same value
191 is therefore indication of an error. */
192 static unsigned short usCheckVariable = ( unsigned short ) 0;
193 static portBASE_TYPE xSuspendedQueueSendError = pdFALSE;
194 static portBASE_TYPE xSuspendedQueueReceiveError = pdFALSE;
195 static portBASE_TYPE xPriorityRaiseWhenSuspendedError = pdFALSE;
197 /* Queue used by the second test. */
198 xQueueHandle xSuspendedTestQueue;
200 /*-----------------------------------------------------------*/
202 * Start the seven tasks as described at the top of the file.
203 * Note that the limited count task is given a higher priority.
205 void vStartDynamicPriorityTasks( void )
207 xSuspendedTestQueue = xQueueCreate( priSUSPENDED_QUEUE_LENGTH, sizeof( unsigned long ) );
208 xTaskCreate( vContinuousIncrementTask, "CONT_INC", priSTACK_SIZE, ( void * ) &ulCounter, tskIDLE_PRIORITY, &xContinuousIncrementHandle );
209 xTaskCreate( vLimitedIncrementTask, "LIM_INC", priSTACK_SIZE, ( void * ) &ulCounter, tskIDLE_PRIORITY + 1, &xLimitedIncrementHandle );
210 xTaskCreate( vCounterControlTask, "C_CTRL", priSTACK_SIZE, NULL, tskIDLE_PRIORITY, NULL );
211 xTaskCreate( vQueueSendWhenSuspendedTask, "SUSP_SEND", priSTACK_SIZE, NULL, tskIDLE_PRIORITY, NULL );
212 xTaskCreate( vQueueReceiveWhenSuspendedTask, "SUSP_RECV", priSTACK_SIZE, NULL, tskIDLE_PRIORITY, NULL );
213 xTaskCreate( prvChangePriorityWhenSuspendedTask, "1st_P_CHANGE", priSTACK_SIZE, NULL, tskIDLE_PRIORITY + 1, NULL );
214 xTaskCreate( prvChangePriorityHelperTask, "2nd_P_CHANGE", priSTACK_SIZE, NULL, tskIDLE_PRIORITY, &xChangePriorityWhenSuspendedHandle );
216 /*-----------------------------------------------------------*/
219 * Just loops around incrementing the shared variable until the limit has been
220 * reached. Once the limit has been reached it suspends itself.
222 static void vLimitedIncrementTask( void * pvParameters )
224 unsigned long *pulCounter;
226 /* Take a pointer to the shared variable from the parameters passed into
227 the task. */
228 pulCounter = ( unsigned long * ) pvParameters;
230 /* This will run before the control task, so the first thing it does is
231 suspend - the control task will resume it when ready. */
232 vTaskSuspend( NULL );
234 for( ;; )
236 /* Just count up to a value then suspend. */
237 ( *pulCounter )++;
239 if( *pulCounter >= priMAX_COUNT )
241 vTaskSuspend( NULL );
245 /*-----------------------------------------------------------*/
248 * Just keep counting the shared variable up. The control task will suspend
249 * this task when it wants.
251 static void vContinuousIncrementTask( void * pvParameters )
253 unsigned long *pulCounter;
254 unsigned portBASE_TYPE uxOurPriority;
256 /* Take a pointer to the shared variable from the parameters passed into
257 the task. */
258 pulCounter = ( unsigned long * ) pvParameters;
260 /* Query our priority so we can raise it when exclusive access to the
261 shared variable is required. */
262 uxOurPriority = uxTaskPriorityGet( NULL );
264 for( ;; )
266 /* Raise our priority above the controller task to ensure a context
267 switch does not occur while we are accessing this variable. */
268 vTaskPrioritySet( NULL, uxOurPriority + 1 );
269 ( *pulCounter )++;
270 vTaskPrioritySet( NULL, uxOurPriority );
272 #if configUSE_PREEMPTION == 0
273 taskYIELD();
274 #endif
277 /*-----------------------------------------------------------*/
280 * Controller task as described above.
282 static void vCounterControlTask( void * pvParameters )
284 unsigned long ulLastCounter;
285 short sLoops;
286 short sError = pdFALSE;
287 const char * const pcTaskStartMsg = "Priority manipulation tasks started.\r\n";
288 const char * const pcTaskFailMsg = "Priority manipulation Task Failed\r\n";
290 /* Just to stop warning messages. */
291 ( void ) pvParameters;
293 /* Queue a message for printing to say the task has started. */
294 vPrintDisplayMessage( &pcTaskStartMsg );
296 for( ;; )
298 /* Start with the counter at zero. */
299 ulCounter = ( unsigned long ) 0;
301 /* First section : */
303 /* Check the continuous count task is running. */
304 for( sLoops = 0; sLoops < priLOOPS; sLoops++ )
306 /* Suspend the continuous count task so we can take a mirror of the
307 shared variable without risk of corruption. */
308 vTaskSuspend( xContinuousIncrementHandle );
309 ulLastCounter = ulCounter;
310 vTaskResume( xContinuousIncrementHandle );
312 /* Now delay to ensure the other task has processor time. */
313 vTaskDelay( priSLEEP_TIME );
315 /* Check the shared variable again. This time to ensure mutual
316 exclusion the whole scheduler will be locked. This is just for
317 demo purposes! */
318 vTaskSuspendAll();
320 if( ulLastCounter == ulCounter )
322 /* The shared variable has not changed. There is a problem
323 with the continuous count task so flag an error. */
324 sError = pdTRUE;
325 xTaskResumeAll();
326 vPrintDisplayMessage( &pcTaskFailMsg );
327 vTaskSuspendAll();
330 xTaskResumeAll();
334 /* Second section: */
336 /* Suspend the continuous counter task so it stops accessing the shared variable. */
337 vTaskSuspend( xContinuousIncrementHandle );
339 /* Reset the variable. */
340 ulCounter = ( unsigned long ) 0;
342 /* Resume the limited count task which has a higher priority than us.
343 We should therefore not return from this call until the limited count
344 task has suspended itself with a known value in the counter variable.
345 The scheduler suspension is not necessary but is included for test
346 purposes. */
347 vTaskSuspendAll();
348 vTaskResume( xLimitedIncrementHandle );
349 xTaskResumeAll();
351 /* Does the counter variable have the expected value? */
352 if( ulCounter != priMAX_COUNT )
354 sError = pdTRUE;
355 vPrintDisplayMessage( &pcTaskFailMsg );
358 if( sError == pdFALSE )
360 /* If no errors have occurred then increment the check variable. */
361 portENTER_CRITICAL();
362 usCheckVariable++;
363 portEXIT_CRITICAL();
366 #if configUSE_PREEMPTION == 0
367 taskYIELD();
368 #endif
370 /* Resume the continuous count task and do it all again. */
371 vTaskResume( xContinuousIncrementHandle );
374 /*-----------------------------------------------------------*/
376 static void vQueueSendWhenSuspendedTask( void *pvParameters )
378 static unsigned long ulValueToSend = ( unsigned long ) 0;
379 const char * const pcTaskStartMsg = "Queue send while suspended task started.\r\n";
380 const char * const pcTaskFailMsg = "Queue send while suspended failed.\r\n";
382 /* Just to stop warning messages. */
383 ( void ) pvParameters;
385 /* Queue a message for printing to say the task has started. */
386 vPrintDisplayMessage( &pcTaskStartMsg );
388 for( ;; )
390 vTaskSuspendAll();
392 /* We must not block while the scheduler is suspended! */
393 if( xQueueSend( xSuspendedTestQueue, ( void * ) &ulValueToSend, priNO_BLOCK ) != pdTRUE )
395 if( xSuspendedQueueSendError == pdFALSE )
397 xTaskResumeAll();
398 vPrintDisplayMessage( &pcTaskFailMsg );
399 vTaskSuspendAll();
402 xSuspendedQueueSendError = pdTRUE;
405 xTaskResumeAll();
407 vTaskDelay( priSLEEP_TIME );
409 ++ulValueToSend;
412 /*-----------------------------------------------------------*/
414 static void vQueueReceiveWhenSuspendedTask( void *pvParameters )
416 static unsigned long ulExpectedValue = ( unsigned long ) 0, ulReceivedValue;
417 const char * const pcTaskStartMsg = "Queue receive while suspended task started.\r\n";
418 const char * const pcTaskFailMsg = "Queue receive while suspended failed.\r\n";
419 portBASE_TYPE xGotValue;
421 /* Just to stop warning messages. */
422 ( void ) pvParameters;
424 /* Queue a message for printing to say the task has started. */
425 vPrintDisplayMessage( &pcTaskStartMsg );
427 for( ;; )
431 /* Suspending the scheduler here is fairly pointless and
432 undesirable for a normal application. It is done here purely
433 to test the scheduler. The inner xTaskResumeAll() should
434 never return pdTRUE as the scheduler is still locked by the
435 outer call. */
436 vTaskSuspendAll();
438 vTaskSuspendAll();
440 xGotValue = xQueueReceive( xSuspendedTestQueue, ( void * ) &ulReceivedValue, priNO_BLOCK );
442 if( xTaskResumeAll() )
444 xSuspendedQueueReceiveError = pdTRUE;
447 xTaskResumeAll();
449 #if configUSE_PREEMPTION == 0
450 taskYIELD();
451 #endif
453 } while( xGotValue == pdFALSE );
455 if( ulReceivedValue != ulExpectedValue )
457 if( xSuspendedQueueReceiveError == pdFALSE )
459 vPrintDisplayMessage( &pcTaskFailMsg );
461 xSuspendedQueueReceiveError = pdTRUE;
464 ++ulExpectedValue;
467 /*-----------------------------------------------------------*/
469 static void prvChangePriorityWhenSuspendedTask( void *pvParameters )
471 const char * const pcTaskStartMsg = "Priority change when suspended task started.\r\n";
472 const char * const pcTaskFailMsg = "Priority change when suspended task failed.\r\n";
474 /* Just to stop warning messages. */
475 ( void ) pvParameters;
477 /* Queue a message for printing to say the task has started. */
478 vPrintDisplayMessage( &pcTaskStartMsg );
480 for( ;; )
482 /* Start with the counter at 0 so we know what the counter should be
483 when we check it next. */
484 ulPrioritySetCounter = ( unsigned long ) 0;
486 /* Resume the helper task. At this time it has a priority lower than
487 ours so no context switch should occur. */
488 vTaskResume( xChangePriorityWhenSuspendedHandle );
490 /* Check to ensure the task just resumed has not executed. */
491 portENTER_CRITICAL();
493 if( ulPrioritySetCounter != ( unsigned long ) 0 )
495 xPriorityRaiseWhenSuspendedError = pdTRUE;
496 vPrintDisplayMessage( &pcTaskFailMsg );
499 portEXIT_CRITICAL();
501 /* Now try raising the priority while the scheduler is suspended. */
502 vTaskSuspendAll();
504 vTaskPrioritySet( xChangePriorityWhenSuspendedHandle, ( configMAX_PRIORITIES - 1 ) );
506 /* Again, even though the helper task has a priority greater than
507 ours, it should not have executed yet because the scheduler is
508 suspended. */
509 portENTER_CRITICAL();
511 if( ulPrioritySetCounter != ( unsigned long ) 0 )
513 xPriorityRaiseWhenSuspendedError = pdTRUE;
514 vPrintDisplayMessage( &pcTaskFailMsg );
517 portEXIT_CRITICAL();
519 xTaskResumeAll();
521 /* Now the scheduler has been resumed the helper task should
522 immediately preempt us and execute. When it executes it will increment
523 the ulPrioritySetCounter exactly once before suspending itself.
525 We should now always find the counter set to 1. */
526 portENTER_CRITICAL();
528 if( ulPrioritySetCounter != ( unsigned long ) 1 )
530 xPriorityRaiseWhenSuspendedError = pdTRUE;
531 vPrintDisplayMessage( &pcTaskFailMsg );
534 portEXIT_CRITICAL();
536 /* Delay until we try this again. */
537 vTaskDelay( priSLEEP_TIME * 2 );
539 /* Set the priority of the helper task back ready for the next
540 execution of this task. */
541 vTaskSuspendAll();
542 vTaskPrioritySet( xChangePriorityWhenSuspendedHandle, tskIDLE_PRIORITY );
543 xTaskResumeAll();
546 /*-----------------------------------------------------------*/
548 static void prvChangePriorityHelperTask( void *pvParameters )
550 /* Just to stop warning messages. */
551 ( void ) pvParameters;
553 for( ;; )
555 /* This is the helper task for prvChangePriorityWhenSuspendedTask().
556 It has it's priority raised and lowered. When it runs it simply
557 increments the counter then suspends itself again. This allows
558 prvChangePriorityWhenSuspendedTask() to know how many times it has
559 executed. */
560 ulPrioritySetCounter++;
561 vTaskSuspend( NULL );
564 /*-----------------------------------------------------------*/
566 /* Called to check that all the created tasks are still running without error. */
567 portBASE_TYPE xAreDynamicPriorityTasksStillRunning( void )
569 /* Keep a history of the check variables so we know if it has been incremented
570 since the last call. */
571 static unsigned short usLastTaskCheck = ( unsigned short ) 0;
572 portBASE_TYPE xReturn = pdTRUE;
574 /* Check the tasks are still running by ensuring the check variable
575 is still incrementing. */
577 if( usCheckVariable == usLastTaskCheck )
579 /* The check has not incremented so an error exists. */
580 xReturn = pdFALSE;
583 if( xSuspendedQueueSendError == pdTRUE )
585 xReturn = pdFALSE;
588 if( xSuspendedQueueReceiveError == pdTRUE )
590 xReturn = pdFALSE;
593 if( xPriorityRaiseWhenSuspendedError == pdTRUE )
595 xReturn = pdFALSE;
598 usLastTaskCheck = usCheckVariable;
599 return xReturn;