]> git.sur5r.net Git - freertos/blob - FreeRTOS/Demo/WIN32-MSVC/DemosModifiedForLowTickRate/recmutex.c
386906a7b3efaac3c1093c5e4d9c29d365746f1b
[freertos] / FreeRTOS / Demo / WIN32-MSVC / DemosModifiedForLowTickRate / recmutex.c
1 /*\r
2     FreeRTOS V7.5.0 - Copyright (C) 2013 Real Time Engineers Ltd.\r
3 \r
4     VISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION.\r
5 \r
6     ***************************************************************************\r
7      *                                                                       *\r
8      *    FreeRTOS provides completely free yet professionally developed,    *\r
9      *    robust, strictly quality controlled, supported, and cross          *\r
10      *    platform software that has become a de facto standard.             *\r
11      *                                                                       *\r
12      *    Help yourself get started quickly and support the FreeRTOS         *\r
13      *    project by purchasing a FreeRTOS tutorial book, reference          *\r
14      *    manual, or both from: http://www.FreeRTOS.org/Documentation        *\r
15      *                                                                       *\r
16      *    Thank you!                                                         *\r
17      *                                                                       *\r
18     ***************************************************************************\r
19 \r
20     This file is part of the FreeRTOS distribution.\r
21 \r
22     FreeRTOS is free software; you can redistribute it and/or modify it under\r
23     the terms of the GNU General Public License (version 2) as published by the\r
24     Free Software Foundation >>!AND MODIFIED BY!<< the FreeRTOS exception.\r
25 \r
26     >>! NOTE: The modification to the GPL is included to allow you to distribute\r
27     >>! a combined work that includes FreeRTOS without being obliged to provide\r
28     >>! the source code for proprietary components outside of the FreeRTOS\r
29     >>! kernel.\r
30 \r
31     FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANY\r
32     WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\r
33     FOR A PARTICULAR PURPOSE.  Full license text is available from the following\r
34     link: http://www.freertos.org/a00114.html\r
35 \r
36     1 tab == 4 spaces!\r
37 \r
38     ***************************************************************************\r
39      *                                                                       *\r
40      *    Having a problem?  Start by reading the FAQ "My application does   *\r
41      *    not run, what could be wrong?"                                     *\r
42      *                                                                       *\r
43      *    http://www.FreeRTOS.org/FAQHelp.html                               *\r
44      *                                                                       *\r
45     ***************************************************************************\r
46 \r
47     http://www.FreeRTOS.org - Documentation, books, training, latest versions,\r
48     license and Real Time Engineers Ltd. contact details.\r
49 \r
50     http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products,\r
51     including FreeRTOS+Trace - an indispensable productivity tool, a DOS\r
52     compatible FAT file system, and our tiny thread aware UDP/IP stack.\r
53 \r
54     http://www.OpenRTOS.com - Real Time Engineers ltd license FreeRTOS to High\r
55     Integrity Systems to sell under the OpenRTOS brand.  Low cost OpenRTOS\r
56     licenses offer ticketed support, indemnification and middleware.\r
57 \r
58     http://www.SafeRTOS.com - High Integrity Systems also provide a safety\r
59     engineered and independently SIL3 certified version for use in safety and\r
60     mission critical applications that require provable dependability.\r
61 \r
62     1 tab == 4 spaces!\r
63 */\r
64 \r
65 /*\r
66         The tasks defined on this page demonstrate the use of recursive mutexes.\r
67 \r
68         For recursive mutex functionality the created mutex should be created using\r
69         xSemaphoreCreateRecursiveMutex(), then be manipulated\r
70         using the xSemaphoreTakeRecursive() and xSemaphoreGiveRecursive() API\r
71         functions.\r
72 \r
73         This demo creates three tasks all of which access the same recursive mutex:\r
74 \r
75         prvRecursiveMutexControllingTask() has the highest priority so executes \r
76         first and grabs the mutex.  It then performs some recursive accesses - \r
77         between each of which it sleeps for a short period to let the lower \r
78         priority tasks execute.  When it has completed its demo functionality\r
79         it gives the mutex back before suspending itself.\r
80 \r
81         prvRecursiveMutexBlockingTask() attempts to access the mutex by performing\r
82         a blocking 'take'.  The blocking task has a lower priority than the \r
83         controlling     task so by the time it executes the mutex has already been\r
84         taken by the controlling task,  causing the blocking task to block.  It \r
85         does not unblock until the controlling task has given the mutex back, \r
86         and it does not actually run until the controlling task has suspended \r
87         itself (due to the relative priorities).  When it eventually does obtain\r
88         the mutex all it does is give the mutex back prior to also suspending \r
89         itself.  At this point both the controlling task and the blocking task are \r
90         suspended.\r
91 \r
92         prvRecursiveMutexPollingTask() runs at the idle priority.  It spins round\r
93         a tight loop attempting to obtain the mutex with a non-blocking call.  As\r
94         the lowest priority task it will not successfully obtain the mutex until\r
95         both the controlling and blocking tasks are suspended.  Once it eventually \r
96         does obtain the mutex it first unsuspends both the controlling task and\r
97         blocking task prior to giving the mutex back - resulting in the polling\r
98         task temporarily inheriting the controlling tasks priority.\r
99 */\r
100 \r
101 /* Scheduler include files. */\r
102 #include "FreeRTOS.h"\r
103 #include "task.h"\r
104 #include "semphr.h"\r
105 \r
106 /* Demo app include files. */\r
107 #include "recmutex.h"\r
108 \r
109 /* Priorities assigned to the three tasks. */\r
110 #define recmuCONTROLLING_TASK_PRIORITY  ( tskIDLE_PRIORITY + 2 )\r
111 #define recmuBLOCKING_TASK_PRIORITY             ( tskIDLE_PRIORITY + 1 )\r
112 #define recmuPOLLING_TASK_PRIORITY              ( tskIDLE_PRIORITY + 0 )\r
113 \r
114 /* In this version the tick period is very long, so the short delay cannot be\r
115 for too many ticks, or the check task will execute and find that the recmutex\r
116 tasks have not completed their functionality and then signal an error.  The\r
117 delay does however have to be long enough to allow the lower priority tasks\r
118 a chance of executing - this is basically achieved by reducing the number\r
119 of times the loop that takes/gives the recursive mutex executes. */\r
120 #define recmuMAX_COUNT                                  ( 2 )\r
121 #define recmuSHORT_DELAY                                ( 20 )\r
122 #define recmuNO_DELAY                                   ( ( portTickType ) 0 )\r
123 #define recmuFIVE_TICK_DELAY                    ( ( portTickType ) 5 )\r
124 \r
125 /* The three tasks as described at the top of this file. */\r
126 static void prvRecursiveMutexControllingTask( void *pvParameters );\r
127 static void prvRecursiveMutexBlockingTask( void *pvParameters );\r
128 static void prvRecursiveMutexPollingTask( void *pvParameters );\r
129 \r
130 /* The mutex used by the demo. */\r
131 static xSemaphoreHandle xMutex;\r
132 \r
133 /* Variables used to detect and latch errors. */\r
134 static volatile portBASE_TYPE xErrorOccurred = pdFALSE, xControllingIsSuspended = pdFALSE, xBlockingIsSuspended = pdFALSE;\r
135 static volatile unsigned portBASE_TYPE uxControllingCycles = 0, uxBlockingCycles = 0, uxPollingCycles = 0;\r
136 \r
137 /* Handles of the two higher priority tasks, required so they can be resumed \r
138 (unsuspended). */\r
139 static xTaskHandle xControllingTaskHandle, xBlockingTaskHandle;\r
140 \r
141 /*-----------------------------------------------------------*/\r
142 \r
143 void vStartRecursiveMutexTasks( void )\r
144 {\r
145         /* Just creates the mutex and the three tasks. */\r
146 \r
147         xMutex = xSemaphoreCreateRecursiveMutex();\r
148 \r
149         /* vQueueAddToRegistry() adds the mutex to the registry, if one is\r
150         in use.  The registry is provided as a means for kernel aware \r
151         debuggers to locate mutex and has no purpose if a kernel aware debugger\r
152         is not being used.  The call to vQueueAddToRegistry() will be removed\r
153         by the pre-processor if configQUEUE_REGISTRY_SIZE is not defined or is \r
154         defined to be less than 1. */\r
155         vQueueAddToRegistry( ( xQueueHandle ) xMutex, ( signed portCHAR * ) "Recursive_Mutex" );\r
156 \r
157 \r
158         if( xMutex != NULL )\r
159         {\r
160                 xTaskCreate( prvRecursiveMutexControllingTask, ( signed portCHAR * ) "Rec1Ctrl", configMINIMAL_STACK_SIZE, NULL, recmuCONTROLLING_TASK_PRIORITY, &xControllingTaskHandle );\r
161         xTaskCreate( prvRecursiveMutexBlockingTask, ( signed portCHAR * ) "Rec2Blck", configMINIMAL_STACK_SIZE, NULL, recmuBLOCKING_TASK_PRIORITY, &xBlockingTaskHandle );\r
162         xTaskCreate( prvRecursiveMutexPollingTask, ( signed portCHAR * ) "Rec3Poll", configMINIMAL_STACK_SIZE, NULL, recmuPOLLING_TASK_PRIORITY, NULL );\r
163         }\r
164 }\r
165 /*-----------------------------------------------------------*/\r
166 \r
167 static void prvRecursiveMutexControllingTask( void *pvParameters )\r
168 {\r
169 unsigned portBASE_TYPE ux;\r
170 \r
171         /* Just to remove compiler warning. */\r
172         ( void ) pvParameters;\r
173 \r
174         for( ;; )\r
175         {\r
176                 /* Should not be able to 'give' the mutex, as we have not yet 'taken'\r
177                 it.   The first time through, the mutex will not have been used yet,\r
178                 subsequent times through, at this point the mutex will be held by the\r
179                 polling task. */\r
180                 if( xSemaphoreGiveRecursive( xMutex ) == pdPASS )\r
181                 {\r
182                         xErrorOccurred = pdTRUE;\r
183                 }\r
184 \r
185                 for( ux = 0; ux < recmuMAX_COUNT; ux++ )\r
186                 {\r
187                         /* We should now be able to take the mutex as many times as\r
188                         we like.\r
189                         \r
190                         The first time through the mutex will be immediately available, on\r
191                         subsequent times through the mutex will be held by the polling task\r
192                         at this point and this Take will cause the polling task to inherit\r
193                         the priority of this task.  In this case the block time must be\r
194                         long enough to ensure the polling task will execute again before the\r
195                         block time expires.  If the block time does expire then the error\r
196                         flag will be set here. */\r
197                         if( xSemaphoreTakeRecursive( xMutex, recmuFIVE_TICK_DELAY ) != pdPASS )\r
198                         {\r
199                                 xErrorOccurred = pdTRUE;\r
200                         }\r
201 \r
202                         /* Ensure the other task attempting to access the mutex (and the\r
203                         other demo tasks) are able to execute to ensure they either block\r
204                         (where a block time is specified) or return an error (where no \r
205                         block time is specified) as the mutex is held by this task. */\r
206                         vTaskDelay( recmuSHORT_DELAY );\r
207                 }\r
208 \r
209                 /* For each time we took the mutex, give it back. */\r
210                 for( ux = 0; ux < recmuMAX_COUNT; ux++ )\r
211                 {\r
212                         /* Ensure the other task attempting to access the mutex (and the\r
213                         other demo tasks) are able to execute. */\r
214                         vTaskDelay( recmuSHORT_DELAY );\r
215 \r
216                         /* We should now be able to give the mutex as many times as we\r
217                         took it.  When the mutex is available again the Blocking task\r
218                         should be unblocked but not run because it has a lower priority\r
219                         than this task.  The polling task should also not run at this point\r
220                         as it too has a lower priority than this task. */\r
221                         if( xSemaphoreGiveRecursive( xMutex ) != pdPASS )\r
222                         {\r
223                                 xErrorOccurred = pdTRUE;\r
224                         }\r
225                 }\r
226 \r
227                 /* Having given it back the same number of times as it was taken, we\r
228                 should no longer be the mutex owner, so the next give should fail. */\r
229                 if( xSemaphoreGiveRecursive( xMutex ) == pdPASS )\r
230                 {\r
231                         xErrorOccurred = pdTRUE;\r
232                 }\r
233 \r
234                 /* Keep count of the number of cycles this task has performed so a \r
235                 stall can be detected. */\r
236                 uxControllingCycles++;\r
237 \r
238                 /* Suspend ourselves so the blocking task can execute. */\r
239                 xControllingIsSuspended = pdTRUE;\r
240                 vTaskSuspend( NULL );\r
241                 xControllingIsSuspended = pdFALSE;\r
242         }\r
243 }\r
244 /*-----------------------------------------------------------*/\r
245 \r
246 static void prvRecursiveMutexBlockingTask( void *pvParameters )\r
247 {\r
248         /* Just to remove compiler warning. */\r
249         ( void ) pvParameters;\r
250 \r
251         for( ;; )\r
252         {\r
253                 /* This task will run while the controlling task is blocked, and the\r
254                 controlling task will block only once it has the mutex - therefore\r
255                 this call should block until the controlling task has given up the \r
256                 mutex, and not actually execute past this call until the controlling \r
257                 task is suspended. */\r
258                 if( xSemaphoreTakeRecursive( xMutex, portMAX_DELAY ) == pdPASS )\r
259                 {\r
260                         if( xControllingIsSuspended != pdTRUE )\r
261                         {\r
262                                 /* Did not expect to execute until the controlling task was\r
263                                 suspended. */\r
264                                 xErrorOccurred = pdTRUE;\r
265                         }\r
266                         else\r
267                         {\r
268                                 /* Give the mutex back before suspending ourselves to allow\r
269                                 the polling task to obtain the mutex. */\r
270                                 if( xSemaphoreGiveRecursive( xMutex ) != pdPASS )\r
271                                 {\r
272                                         xErrorOccurred = pdTRUE;\r
273                                 }\r
274 \r
275                                 xBlockingIsSuspended = pdTRUE;\r
276                                 vTaskSuspend( NULL );\r
277                                 xBlockingIsSuspended = pdFALSE;\r
278                         }\r
279                 }\r
280                 else\r
281                 {\r
282                         /* We should not leave the xSemaphoreTakeRecursive() function\r
283                         until the mutex was obtained. */\r
284                         xErrorOccurred = pdTRUE;\r
285                 }\r
286 \r
287                 /* The controlling and blocking tasks should be in lock step. */\r
288                 if( uxControllingCycles != ( uxBlockingCycles + 1 ) )\r
289                 {\r
290                         xErrorOccurred = pdTRUE;\r
291                 }\r
292 \r
293                 /* Keep count of the number of cycles this task has performed so a \r
294                 stall can be detected. */\r
295                 uxBlockingCycles++;\r
296         }\r
297 }\r
298 /*-----------------------------------------------------------*/\r
299 \r
300 static void prvRecursiveMutexPollingTask( void *pvParameters )\r
301 {\r
302         /* Just to remove compiler warning. */\r
303         ( void ) pvParameters;\r
304 \r
305         for( ;; )\r
306         {\r
307                 /* Keep attempting to obtain the mutex.  We should only obtain it when\r
308                 the blocking task has suspended itself, which in turn should only\r
309                 happen when the controlling task is also suspended. */\r
310                 if( xSemaphoreTakeRecursive( xMutex, recmuNO_DELAY ) == pdPASS )\r
311                 {\r
312                         /* Is the blocking task suspended? */\r
313                         if( ( xBlockingIsSuspended != pdTRUE ) || ( xControllingIsSuspended != pdTRUE ) )\r
314                         {\r
315                                 xErrorOccurred = pdTRUE;\r
316                         }\r
317                         else\r
318                         {\r
319                                 /* Keep count of the number of cycles this task has performed \r
320                                 so a stall can be detected. */\r
321                                 uxPollingCycles++;\r
322 \r
323                                 /* We can resume the other tasks here even though they have a\r
324                                 higher priority than the polling task.  When they execute they\r
325                                 will attempt to obtain the mutex but fail because the polling\r
326                                 task is still the mutex holder.  The polling task (this task)\r
327                                 will then inherit the higher priority.  The Blocking task will\r
328                                 block indefinitely when it attempts to obtain the mutex, the\r
329                                 Controlling task will only block for a fixed period and an\r
330                                 error will be latched if the polling task has not returned the\r
331                                 mutex by the time this fixed period has expired. */\r
332                                 vTaskResume( xBlockingTaskHandle );\r
333                 vTaskResume( xControllingTaskHandle );\r
334                         \r
335                                 /* The other two tasks should now have executed and no longer\r
336                                 be suspended. */\r
337                                 if( ( xBlockingIsSuspended == pdTRUE ) || ( xControllingIsSuspended == pdTRUE ) )\r
338                                 {\r
339                                         xErrorOccurred = pdTRUE;\r
340                                 }                               \r
341                         \r
342                                 /* Release the mutex, disinheriting the higher priority again. */\r
343                                 if( xSemaphoreGiveRecursive( xMutex ) != pdPASS )\r
344                                 {\r
345                                         xErrorOccurred = pdTRUE;\r
346                                 }\r
347                         }\r
348                 }\r
349 \r
350                 #if configUSE_PREEMPTION == 0\r
351                 {\r
352                         taskYIELD();\r
353                 }\r
354                 #endif\r
355         }\r
356 }\r
357 /*-----------------------------------------------------------*/\r
358 \r
359 /* This is called to check that all the created tasks are still running. */\r
360 portBASE_TYPE xAreRecursiveMutexTasksStillRunning( void )\r
361 {\r
362 portBASE_TYPE xReturn;\r
363 static unsigned portBASE_TYPE uxLastControllingCycles = 0, uxLastBlockingCycles = 0, uxLastPollingCycles = 0;\r
364 \r
365         /* Is the controlling task still cycling? */\r
366         if( uxLastControllingCycles == uxControllingCycles )\r
367         {\r
368                 xErrorOccurred = pdTRUE;\r
369         }\r
370         else\r
371         {\r
372                 uxLastControllingCycles = uxControllingCycles;\r
373         }\r
374 \r
375         /* Is the blocking task still cycling? */\r
376         if( uxLastBlockingCycles == uxBlockingCycles )\r
377         {\r
378                 xErrorOccurred = pdTRUE;\r
379         }\r
380         else\r
381         {\r
382                 uxLastBlockingCycles = uxBlockingCycles;\r
383         }\r
384 \r
385         /* Is the polling task still cycling? */\r
386         if( uxLastPollingCycles == uxPollingCycles )\r
387         {\r
388                 xErrorOccurred = pdTRUE;\r
389         }\r
390         else\r
391         {\r
392                 uxLastPollingCycles = uxPollingCycles;\r
393         }\r
394 \r
395         if( xErrorOccurred == pdTRUE )\r
396         {\r
397                 xReturn = pdFAIL;\r
398         }\r
399         else\r
400         {\r
401                 xReturn = pdTRUE;\r
402         }\r
403 \r
404         return xReturn;\r
405 }\r
406 \r
407 \r
408 \r
409 \r