]> begriffs open source - cmsis-freertos/blob - Demo/Common/Full/dynamic.c
Updated pack to FreeRTOS 10.4.6
[cmsis-freertos] / Demo / Common / Full / dynamic.c
1 /*
2  * FreeRTOS V202111.00
3  * Copyright (C) 2020 Amazon.com, Inc. or its affiliates.  All Rights Reserved.
4  *
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:
11  *
12  * The above copyright notice and this permission notice shall be included in all
13  * copies or substantial portions of the Software.
14  *
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.
21  *
22  * http://www.FreeRTOS.org
23  * http://aws.amazon.com/freertos
24  *
25  * 1 tab == 4 spaces!
26  */
27
28 /**
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
34  * task.
35  *
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
40  * next iteration.
41  *
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
48  * variable.
49  *
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.
55  *
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.
66  *
67  * After a fixed number of iterations the controller task suspends the
68  * continuous count task, and moves on to its second section.
69  *
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.
77  *
78  *
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.
82  *
83  *
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.
87  *
88  * \page Priorities dynamic.c
89  * \ingroup DemoFiles
90  * <HR>
91  */
92
93 /*
94  * Changes from V2.0.0
95  *
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().
100  +
101  + Changes from V3.1.1
102  +
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.
107  */
108
109 #include <stdlib.h>
110
111 /* Scheduler include files. */
112 #include "FreeRTOS.h"
113 #include "task.h"
114 #include "semphr.h"
115
116 /* Demo app include files. */
117 #include "dynamic.h"
118 #include "print.h"
119
120 /* Function that implements the "limited count" task as described above. */
121 static void vLimitedIncrementTask( void * pvParameters );
122
123 /* Function that implements the "continuous count" task as described above. */
124 static void vContinuousIncrementTask( void * pvParameters );
125
126 /* Function that implements the controller task as described above. */
127 static void vCounterControlTask( void * pvParameters );
128
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 );
133
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 );
138
139
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 )
147
148 /*-----------------------------------------------------------*/
149
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;
153
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;
157
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;
161
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;
170
171 /* Queue used by the second test. */
172 QueueHandle_t xSuspendedTestQueue;
173
174 /*-----------------------------------------------------------*/
175
176 /*
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.
179  */
180 void vStartDynamicPriorityTasks( void )
181 {
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 );
190 }
191 /*-----------------------------------------------------------*/
192
193 /*
194  * Just loops around incrementing the shared variable until the limit has been
195  * reached.  Once the limit has been reached it suspends itself.
196  */
197 static void vLimitedIncrementTask( void * pvParameters )
198 {
199     unsigned long * pulCounter;
200
201     /* Take a pointer to the shared variable from the parameters passed into
202      * the task. */
203     pulCounter = ( unsigned long * ) pvParameters;
204
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 );
208
209     for( ; ; )
210     {
211         /* Just count up to a value then suspend. */
212         ( *pulCounter )++;
213
214         if( *pulCounter >= priMAX_COUNT )
215         {
216             vTaskSuspend( NULL );
217         }
218     }
219 }
220 /*-----------------------------------------------------------*/
221
222 /*
223  * Just keep counting the shared variable up.  The control task will suspend
224  * this task when it wants.
225  */
226 static void vContinuousIncrementTask( void * pvParameters )
227 {
228     unsigned long * pulCounter;
229     unsigned portBASE_TYPE uxOurPriority;
230
231     /* Take a pointer to the shared variable from the parameters passed into
232      * the task. */
233     pulCounter = ( unsigned long * ) pvParameters;
234
235     /* Query our priority so we can raise it when exclusive access to the
236      * shared variable is required. */
237     uxOurPriority = uxTaskPriorityGet( NULL );
238
239     for( ; ; )
240     {
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 );
244         ( *pulCounter )++;
245         vTaskPrioritySet( NULL, uxOurPriority );
246
247         #if configUSE_PREEMPTION == 0
248             taskYIELD();
249         #endif
250     }
251 }
252 /*-----------------------------------------------------------*/
253
254 /*
255  * Controller task as described above.
256  */
257 static void vCounterControlTask( void * pvParameters )
258 {
259     unsigned long ulLastCounter;
260     short sLoops;
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";
264
265     /* Just to stop warning messages. */
266     ( void ) pvParameters;
267
268     /* Queue a message for printing to say the task has started. */
269     vPrintDisplayMessage( &pcTaskStartMsg );
270
271     for( ; ; )
272     {
273         /* Start with the counter at zero. */
274         ulCounter = ( unsigned long ) 0;
275
276         /* First section : */
277
278         /* Check the continuous count task is running. */
279         for( sLoops = 0; sLoops < priLOOPS; sLoops++ )
280         {
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 );
286
287             /* Now delay to ensure the other task has processor time. */
288             vTaskDelay( priSLEEP_TIME );
289
290             /* Check the shared variable again.  This time to ensure mutual
291              * exclusion the whole scheduler will be locked.  This is just for
292              * demo purposes! */
293             vTaskSuspendAll();
294             {
295                 if( ulLastCounter == ulCounter )
296                 {
297                     /* The shared variable has not changed.  There is a problem
298                      * with the continuous count task so flag an error. */
299                     sError = pdTRUE;
300                     xTaskResumeAll();
301                     vPrintDisplayMessage( &pcTaskFailMsg );
302                     vTaskSuspendAll();
303                 }
304             }
305             xTaskResumeAll();
306         }
307
308         /* Second section: */
309
310         /* Suspend the continuous counter task so it stops accessing the shared variable. */
311         vTaskSuspend( xContinuousIncrementHandle );
312
313         /* Reset the variable. */
314         ulCounter = ( unsigned long ) 0;
315
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
320          * purposes. */
321         vTaskSuspendAll();
322         vTaskResume( xLimitedIncrementHandle );
323         xTaskResumeAll();
324
325         /* Does the counter variable have the expected value? */
326         if( ulCounter != priMAX_COUNT )
327         {
328             sError = pdTRUE;
329             vPrintDisplayMessage( &pcTaskFailMsg );
330         }
331
332         if( sError == pdFALSE )
333         {
334             /* If no errors have occurred then increment the check variable. */
335             portENTER_CRITICAL();
336             usCheckVariable++;
337             portEXIT_CRITICAL();
338         }
339
340         #if configUSE_PREEMPTION == 0
341             taskYIELD();
342         #endif
343
344         /* Resume the continuous count task and do it all again. */
345         vTaskResume( xContinuousIncrementHandle );
346     }
347 }
348 /*-----------------------------------------------------------*/
349
350 static void vQueueSendWhenSuspendedTask( void * pvParameters )
351 {
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";
355
356     /* Just to stop warning messages. */
357     ( void ) pvParameters;
358
359     /* Queue a message for printing to say the task has started. */
360     vPrintDisplayMessage( &pcTaskStartMsg );
361
362     for( ; ; )
363     {
364         vTaskSuspendAll();
365         {
366             /* We must not block while the scheduler is suspended! */
367             if( xQueueSend( xSuspendedTestQueue, ( void * ) &ulValueToSend, priNO_BLOCK ) != pdTRUE )
368             {
369                 if( xSuspendedQueueSendError == pdFALSE )
370                 {
371                     xTaskResumeAll();
372                     vPrintDisplayMessage( &pcTaskFailMsg );
373                     vTaskSuspendAll();
374                 }
375
376                 xSuspendedQueueSendError = pdTRUE;
377             }
378         }
379         xTaskResumeAll();
380
381         vTaskDelay( priSLEEP_TIME );
382
383         ++ulValueToSend;
384     }
385 }
386 /*-----------------------------------------------------------*/
387
388 static void vQueueReceiveWhenSuspendedTask( void * pvParameters )
389 {
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;
394
395     /* Just to stop warning messages. */
396     ( void ) pvParameters;
397
398     /* Queue a message for printing to say the task has started. */
399     vPrintDisplayMessage( &pcTaskStartMsg );
400
401     for( ; ; )
402     {
403         do
404         {
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
409              * outer call. */
410             vTaskSuspendAll();
411             {
412                 vTaskSuspendAll();
413                 {
414                     xGotValue = xQueueReceive( xSuspendedTestQueue, ( void * ) &ulReceivedValue, priNO_BLOCK );
415                 }
416
417                 if( xTaskResumeAll() )
418                 {
419                     xSuspendedQueueReceiveError = pdTRUE;
420                 }
421             }
422             xTaskResumeAll();
423
424             #if configUSE_PREEMPTION == 0
425                 taskYIELD();
426             #endif
427         } while( xGotValue == pdFALSE );
428
429         if( ulReceivedValue != ulExpectedValue )
430         {
431             if( xSuspendedQueueReceiveError == pdFALSE )
432             {
433                 vPrintDisplayMessage( &pcTaskFailMsg );
434             }
435
436             xSuspendedQueueReceiveError = pdTRUE;
437         }
438
439         ++ulExpectedValue;
440     }
441 }
442 /*-----------------------------------------------------------*/
443
444 static void prvChangePriorityWhenSuspendedTask( void * pvParameters )
445 {
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";
448
449     /* Just to stop warning messages. */
450     ( void ) pvParameters;
451
452     /* Queue a message for printing to say the task has started. */
453     vPrintDisplayMessage( &pcTaskStartMsg );
454
455     for( ; ; )
456     {
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;
460
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 );
464
465         /* Check to ensure the task just resumed has not executed. */
466         portENTER_CRITICAL();
467         {
468             if( ulPrioritySetCounter != ( unsigned long ) 0 )
469             {
470                 xPriorityRaiseWhenSuspendedError = pdTRUE;
471                 vPrintDisplayMessage( &pcTaskFailMsg );
472             }
473         }
474         portEXIT_CRITICAL();
475
476         /* Now try raising the priority while the scheduler is suspended. */
477         vTaskSuspendAll();
478         {
479             vTaskPrioritySet( xChangePriorityWhenSuspendedHandle, ( configMAX_PRIORITIES - 1 ) );
480
481             /* Again, even though the helper task has a priority greater than
482              * ours, it should not have executed yet because the scheduler is
483              * suspended. */
484             portENTER_CRITICAL();
485             {
486                 if( ulPrioritySetCounter != ( unsigned long ) 0 )
487                 {
488                     xPriorityRaiseWhenSuspendedError = pdTRUE;
489                     vPrintDisplayMessage( &pcTaskFailMsg );
490                 }
491             }
492             portEXIT_CRITICAL();
493         }
494         xTaskResumeAll();
495
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.
499          *
500          * We should now always find the counter set to 1. */
501         portENTER_CRITICAL();
502         {
503             if( ulPrioritySetCounter != ( unsigned long ) 1 )
504             {
505                 xPriorityRaiseWhenSuspendedError = pdTRUE;
506                 vPrintDisplayMessage( &pcTaskFailMsg );
507             }
508         }
509         portEXIT_CRITICAL();
510
511         /* Delay until we try this again. */
512         vTaskDelay( priSLEEP_TIME * 2 );
513
514         /* Set the priority of the helper task back ready for the next
515          * execution of this task. */
516         vTaskSuspendAll();
517         vTaskPrioritySet( xChangePriorityWhenSuspendedHandle, tskIDLE_PRIORITY );
518         xTaskResumeAll();
519     }
520 }
521 /*-----------------------------------------------------------*/
522
523 static void prvChangePriorityHelperTask( void * pvParameters )
524 {
525     /* Just to stop warning messages. */
526     ( void ) pvParameters;
527
528     for( ; ; )
529     {
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
534          * executed. */
535         ulPrioritySetCounter++;
536         vTaskSuspend( NULL );
537     }
538 }
539 /*-----------------------------------------------------------*/
540
541 /* Called to check that all the created tasks are still running without error. */
542 portBASE_TYPE xAreDynamicPriorityTasksStillRunning( void )
543 {
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;
548
549     /* Check the tasks are still running by ensuring the check variable
550      * is still incrementing. */
551
552     if( usCheckVariable == usLastTaskCheck )
553     {
554         /* The check has not incremented so an error exists. */
555         xReturn = pdFALSE;
556     }
557
558     if( xSuspendedQueueSendError == pdTRUE )
559     {
560         xReturn = pdFALSE;
561     }
562
563     if( xSuspendedQueueReceiveError == pdTRUE )
564     {
565         xReturn = pdFALSE;
566     }
567
568     if( xPriorityRaiseWhenSuspendedError == pdTRUE )
569     {
570         xReturn = pdFALSE;
571     }
572
573     usLastTaskCheck = usCheckVariable;
574     return xReturn;
575 }