]> begriffs open source - cmsis-freertos/blob - Demo/Common/Full/semtest.c
Update cmsis_os2.c
[cmsis-freertos] / Demo / Common / Full / semtest.c
1 /*
2     FreeRTOS V9.0.0 - Copyright (C) 2016 Real Time Engineers Ltd.
3     All rights reserved
4
5     VISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION.
6
7     This file is part of the FreeRTOS distribution.
8
9     FreeRTOS is free software; you can redistribute it and/or modify it under
10     the terms of the GNU General Public License (version 2) as published by the
11     Free Software Foundation >>>> AND MODIFIED BY <<<< the FreeRTOS exception.
12
13     ***************************************************************************
14     >>!   NOTE: The modification to the GPL is included to allow you to     !<<
15     >>!   distribute a combined work that includes FreeRTOS without being   !<<
16     >>!   obliged to provide the source code for proprietary components     !<<
17     >>!   outside of the FreeRTOS kernel.                                   !<<
18     ***************************************************************************
19
20     FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANY
21     WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
22     FOR A PARTICULAR PURPOSE.  Full license text is available on the following
23     link: http://www.freertos.org/a00114.html
24
25     ***************************************************************************
26      *                                                                       *
27      *    FreeRTOS provides completely free yet professionally developed,    *
28      *    robust, strictly quality controlled, supported, and cross          *
29      *    platform software that is more than just the market leader, it     *
30      *    is the industry's de facto standard.                               *
31      *                                                                       *
32      *    Help yourself get started quickly while simultaneously helping     *
33      *    to support the FreeRTOS project by purchasing a FreeRTOS           *
34      *    tutorial book, reference manual, or both:                          *
35      *    http://www.FreeRTOS.org/Documentation                              *
36      *                                                                       *
37     ***************************************************************************
38
39     http://www.FreeRTOS.org/FAQHelp.html - Having a problem?  Start by reading
40     the FAQ page "My application does not run, what could be wrong?".  Have you
41     defined configASSERT()?
42
43     http://www.FreeRTOS.org/support - In return for receiving this top quality
44     embedded software for free we request you assist our global community by
45     participating in the support forum.
46
47     http://www.FreeRTOS.org/training - Investing in training allows your team to
48     be as productive as possible as early as possible.  Now you can receive
49     FreeRTOS training directly from Richard Barry, CEO of Real Time Engineers
50     Ltd, and the world's leading authority on the world's leading RTOS.
51
52     http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products,
53     including FreeRTOS+Trace - an indispensable productivity tool, a DOS
54     compatible FAT file system, and our tiny thread aware UDP/IP stack.
55
56     http://www.FreeRTOS.org/labs - Where new FreeRTOS products go to incubate.
57     Come and try FreeRTOS+TCP, our new open source TCP/IP stack for FreeRTOS.
58
59     http://www.OpenRTOS.com - Real Time Engineers ltd. license FreeRTOS to High
60     Integrity Systems ltd. to sell under the OpenRTOS brand.  Low cost OpenRTOS
61     licenses offer ticketed support, indemnification and commercial middleware.
62
63     http://www.SafeRTOS.com - High Integrity Systems also provide a safety
64     engineered and independently SIL3 certified version for use in safety and
65     mission critical applications that require provable dependability.
66
67     1 tab == 4 spaces!
68 */
69
70 /**
71  * Creates two sets of two tasks.  The tasks within a set share a variable, access 
72  * to which is guarded by a semaphore.
73  * 
74  * Each task starts by attempting to obtain the semaphore.  On obtaining a 
75  * semaphore a task checks to ensure that the guarded variable has an expected 
76  * value.  It then clears the variable to zero before counting it back up to the 
77  * expected value in increments of 1.  After each increment the variable is checked 
78  * to ensure it contains the value to which it was just set. When the starting 
79  * value is again reached the task releases the semaphore giving the other task in 
80  * the set a chance to do exactly the same thing.  The starting value is high 
81  * enough to ensure that a tick is likely to occur during the incrementing loop.
82  *
83  * An error is flagged if at any time during the process a shared variable is 
84  * found to have a value other than that expected.  Such an occurrence would 
85  * suggest an error in the mutual exclusion mechanism by which access to the 
86  * variable is restricted.
87  *
88  * The first set of two tasks poll their semaphore.  The second set use blocking 
89  * calls.
90  *
91  * \page SemTestC semtest.c
92  * \ingroup DemoFiles
93  * <HR>
94  */
95
96 /*
97 Changes from V1.2.0:
98
99         + The tasks that operate at the idle priority now use a lower expected
100           count than those running at a higher priority.  This prevents the low
101           priority tasks from signaling an error because they have not been 
102           scheduled enough time for each of them to count the shared variable to
103           the high value.
104
105 Changes from V2.0.0
106
107         + Delay periods are now specified using variables and constants of
108           TickType_t rather than unsigned long.
109
110 Changes from V2.1.1
111
112         + The stack size now uses configMINIMAL_STACK_SIZE.
113         + String constants made file scope to decrease stack depth on 8051 port.
114 */
115
116 #include <stdlib.h>
117
118 /* Scheduler include files. */
119 #include "FreeRTOS.h"
120 #include "task.h"
121 #include "semphr.h"
122
123 /* Demo app include files. */
124 #include "semtest.h"
125 #include "print.h"
126
127 /* The value to which the shared variables are counted. */
128 #define semtstBLOCKING_EXPECTED_VALUE           ( ( unsigned long ) 0xfff )
129 #define semtstNON_BLOCKING_EXPECTED_VALUE       ( ( unsigned long ) 0xff  )
130
131 #define semtstSTACK_SIZE                        configMINIMAL_STACK_SIZE
132
133 #define semtstNUM_TASKS                         ( 4 )
134
135 #define semtstDELAY_FACTOR                      ( ( TickType_t ) 10 )
136
137 /* The task function as described at the top of the file. */
138 static void prvSemaphoreTest( void *pvParameters );
139
140 /* Structure used to pass parameters to each task. */
141 typedef struct SEMAPHORE_PARAMETERS
142 {
143         SemaphoreHandle_t xSemaphore;
144         volatile unsigned long *pulSharedVariable;
145         TickType_t xBlockTime;
146 } xSemaphoreParameters;
147
148 /* Variables used to check that all the tasks are still running without errors. */
149 static volatile short sCheckVariables[ semtstNUM_TASKS ] = { 0 };
150 static volatile short sNextCheckVariable = 0;
151
152 /* Strings to print if USE_STDIO is defined. */
153 const char * const pcPollingSemaphoreTaskError = "Guarded shared variable in unexpected state.\r\n";
154 const char * const pcSemaphoreTaskStart = "Guarded shared variable task started.\r\n";
155
156 /*-----------------------------------------------------------*/
157
158 void vStartSemaphoreTasks( unsigned portBASE_TYPE uxPriority )
159 {
160 xSemaphoreParameters *pxFirstSemaphoreParameters, *pxSecondSemaphoreParameters;
161 const TickType_t xBlockTime = ( TickType_t ) 100;
162
163         /* Create the structure used to pass parameters to the first two tasks. */
164         pxFirstSemaphoreParameters = ( xSemaphoreParameters * ) pvPortMalloc( sizeof( xSemaphoreParameters ) );
165
166         if( pxFirstSemaphoreParameters != NULL )
167         {
168                 /* Create the semaphore used by the first two tasks. */
169                 vSemaphoreCreateBinary( pxFirstSemaphoreParameters->xSemaphore );
170
171                 if( pxFirstSemaphoreParameters->xSemaphore != NULL )
172                 {
173                         /* Create the variable which is to be shared by the first two tasks. */
174                         pxFirstSemaphoreParameters->pulSharedVariable = ( unsigned long * ) pvPortMalloc( sizeof( unsigned long ) );
175
176                         /* Initialise the share variable to the value the tasks expect. */
177                         *( pxFirstSemaphoreParameters->pulSharedVariable ) = semtstNON_BLOCKING_EXPECTED_VALUE;
178
179                         /* The first two tasks do not block on semaphore calls. */
180                         pxFirstSemaphoreParameters->xBlockTime = ( TickType_t ) 0;
181
182                         /* Spawn the first two tasks.  As they poll they operate at the idle priority. */
183                         xTaskCreate( prvSemaphoreTest, "PolSEM1", semtstSTACK_SIZE, ( void * ) pxFirstSemaphoreParameters, tskIDLE_PRIORITY, ( TaskHandle_t * ) NULL );
184                         xTaskCreate( prvSemaphoreTest, "PolSEM2", semtstSTACK_SIZE, ( void * ) pxFirstSemaphoreParameters, tskIDLE_PRIORITY, ( TaskHandle_t * ) NULL );
185                 }
186         }
187
188         /* Do exactly the same to create the second set of tasks, only this time 
189         provide a block time for the semaphore calls. */
190         pxSecondSemaphoreParameters = ( xSemaphoreParameters * ) pvPortMalloc( sizeof( xSemaphoreParameters ) );
191         if( pxSecondSemaphoreParameters != NULL )
192         {
193                 vSemaphoreCreateBinary( pxSecondSemaphoreParameters->xSemaphore );
194
195                 if( pxSecondSemaphoreParameters->xSemaphore != NULL )
196                 {
197                         pxSecondSemaphoreParameters->pulSharedVariable = ( unsigned long * ) pvPortMalloc( sizeof( unsigned long ) );
198                         *( pxSecondSemaphoreParameters->pulSharedVariable ) = semtstBLOCKING_EXPECTED_VALUE;
199                         pxSecondSemaphoreParameters->xBlockTime = xBlockTime / portTICK_PERIOD_MS;
200
201                         xTaskCreate( prvSemaphoreTest, "BlkSEM1", semtstSTACK_SIZE, ( void * ) pxSecondSemaphoreParameters, uxPriority, ( TaskHandle_t * ) NULL );
202                         xTaskCreate( prvSemaphoreTest, "BlkSEM2", semtstSTACK_SIZE, ( void * ) pxSecondSemaphoreParameters, uxPriority, ( TaskHandle_t * ) NULL );
203                 }
204         }
205 }
206 /*-----------------------------------------------------------*/
207
208 static void prvSemaphoreTest( void *pvParameters )
209 {
210 xSemaphoreParameters *pxParameters;
211 volatile unsigned long *pulSharedVariable, ulExpectedValue;
212 unsigned long ulCounter;
213 short sError = pdFALSE, sCheckVariableToUse;
214
215         /* See which check variable to use.  sNextCheckVariable is not semaphore 
216         protected! */
217         portENTER_CRITICAL();
218                 sCheckVariableToUse = sNextCheckVariable;
219                 sNextCheckVariable++;
220         portEXIT_CRITICAL();
221
222         /* Queue a message for printing to say the task has started. */
223         vPrintDisplayMessage( &pcSemaphoreTaskStart );
224
225         /* A structure is passed in as the parameter.  This contains the shared 
226         variable being guarded. */
227         pxParameters = ( xSemaphoreParameters * ) pvParameters;
228         pulSharedVariable = pxParameters->pulSharedVariable;
229
230         /* If we are blocking we use a much higher count to ensure loads of context
231         switches occur during the count. */
232         if( pxParameters->xBlockTime > ( TickType_t ) 0 )
233         {
234                 ulExpectedValue = semtstBLOCKING_EXPECTED_VALUE;
235         }
236         else
237         {
238                 ulExpectedValue = semtstNON_BLOCKING_EXPECTED_VALUE;
239         }
240
241         for( ;; )
242         {
243                 /* Try to obtain the semaphore. */
244                 if( xSemaphoreTake( pxParameters->xSemaphore, pxParameters->xBlockTime ) == pdPASS )
245                 {
246                         /* We have the semaphore and so expect any other tasks using the
247                         shared variable to have left it in the state we expect to find
248                         it. */
249                         if( *pulSharedVariable != ulExpectedValue )
250                         {
251                                 vPrintDisplayMessage( &pcPollingSemaphoreTaskError );
252                                 sError = pdTRUE;
253                         }
254                         
255                         /* Clear the variable, then count it back up to the expected value
256                         before releasing the semaphore.  Would expect a context switch or
257                         two during this time. */
258                         for( ulCounter = ( unsigned long ) 0; ulCounter <= ulExpectedValue; ulCounter++ )
259                         {
260                                 *pulSharedVariable = ulCounter;
261                                 if( *pulSharedVariable != ulCounter )
262                                 {
263                                         if( sError == pdFALSE )
264                                         {
265                                                 vPrintDisplayMessage( &pcPollingSemaphoreTaskError );
266                                         }
267                                         sError = pdTRUE;
268                                 }
269                         }
270
271                         /* Release the semaphore, and if no errors have occurred increment the check
272                         variable. */
273                         if(     xSemaphoreGive( pxParameters->xSemaphore ) == pdFALSE )
274                         {
275                                 vPrintDisplayMessage( &pcPollingSemaphoreTaskError );
276                                 sError = pdTRUE;
277                         }
278
279                         if( sError == pdFALSE )
280                         {
281                                 if( sCheckVariableToUse < semtstNUM_TASKS )
282                                 {
283                                         ( sCheckVariables[ sCheckVariableToUse ] )++;
284                                 }
285                         }
286
287                         /* If we have a block time then we are running at a priority higher
288                         than the idle priority.  This task takes a long time to complete
289                         a cycle (deliberately so to test the guarding) so will be starving
290                         out lower priority tasks.  Block for some time to allow give lower
291                         priority tasks some processor time. */
292                         vTaskDelay( pxParameters->xBlockTime * semtstDELAY_FACTOR );
293                 }
294                 else
295                 {
296                         if( pxParameters->xBlockTime == ( TickType_t ) 0 )
297                         {
298                                 /* We have not got the semaphore yet, so no point using the
299                                 processor.  We are not blocking when attempting to obtain the
300                                 semaphore. */
301                                 taskYIELD();
302                         }
303                 }
304         }
305 }
306 /*-----------------------------------------------------------*/
307
308 /* This is called to check that all the created tasks are still running. */
309 portBASE_TYPE xAreSemaphoreTasksStillRunning( void )
310 {
311 static short sLastCheckVariables[ semtstNUM_TASKS ] = { 0 };
312 portBASE_TYPE xTask, xReturn = pdTRUE;
313
314         for( xTask = 0; xTask < semtstNUM_TASKS; xTask++ )
315         {
316                 if( sLastCheckVariables[ xTask ] == sCheckVariables[ xTask ] )
317                 {
318                         xReturn = pdFALSE;
319                 }
320
321                 sLastCheckVariables[ xTask ] = sCheckVariables[ xTask ];
322         }
323
324         return xReturn;
325 }
326
327