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