]> begriffs open source - cmsis-freertos/blob - Demo/WIN32-MingW/DemosModifiedForLowTickRate/recmutex.c
Updated pack to FreeRTOS 10.4.6
[cmsis-freertos] / Demo / WIN32-MingW / DemosModifiedForLowTickRate / recmutex.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 tasks defined on this page demonstrate the use of recursive mutexes.
30
31         For recursive mutex functionality the created mutex should be created using
32         xSemaphoreCreateRecursiveMutex(), then be manipulated
33         using the xSemaphoreTakeRecursive() and xSemaphoreGiveRecursive() API
34         functions.
35
36         This demo creates three tasks all of which access the same recursive mutex:
37
38         prvRecursiveMutexControllingTask() has the highest priority so executes 
39         first and grabs the mutex.  It then performs some recursive accesses - 
40         between each of which it sleeps for a short period to let the lower 
41         priority tasks execute.  When it has completed its demo functionality
42         it gives the mutex back before suspending itself.
43
44         prvRecursiveMutexBlockingTask() attempts to access the mutex by performing
45         a blocking 'take'.  The blocking task has a lower priority than the 
46         controlling     task so by the time it executes the mutex has already been
47         taken by the controlling task,  causing the blocking task to block.  It 
48         does not unblock until the controlling task has given the mutex back, 
49         and it does not actually run until the controlling task has suspended 
50         itself (due to the relative priorities).  When it eventually does obtain
51         the mutex all it does is give the mutex back prior to also suspending 
52         itself.  At this point both the controlling task and the blocking task are 
53         suspended.
54
55         prvRecursiveMutexPollingTask() runs at the idle priority.  It spins round
56         a tight loop attempting to obtain the mutex with a non-blocking call.  As
57         the lowest priority task it will not successfully obtain the mutex until
58         both the controlling and blocking tasks are suspended.  Once it eventually 
59         does obtain the mutex it first unsuspends both the controlling task and
60         blocking task prior to giving the mutex back - resulting in the polling
61         task temporarily inheriting the controlling tasks priority.
62 */
63
64 /* Scheduler include files. */
65 #include "FreeRTOS.h"
66 #include "task.h"
67 #include "semphr.h"
68
69 /* Demo app include files. */
70 #include "recmutex.h"
71
72 /* Priorities assigned to the three tasks. */
73 #define recmuCONTROLLING_TASK_PRIORITY  ( tskIDLE_PRIORITY + 2 )
74 #define recmuBLOCKING_TASK_PRIORITY             ( tskIDLE_PRIORITY + 1 )
75 #define recmuPOLLING_TASK_PRIORITY              ( tskIDLE_PRIORITY + 0 )
76
77 /* In this version the tick period is very long, so the short delay cannot be
78 for too many ticks, or the check task will execute and find that the recmutex
79 tasks have not completed their functionality and then signal an error.  The
80 delay does however have to be long enough to allow the lower priority tasks
81 a chance of executing - this is basically achieved by reducing the number
82 of times the loop that takes/gives the recursive mutex executes. */
83 #define recmuMAX_COUNT                                  ( 2 )
84 #define recmuSHORT_DELAY                                ( 20 )
85 #define recmuNO_DELAY                                   ( ( TickType_t ) 0 )
86 #define recmuFIVE_TICK_DELAY                    ( ( TickType_t ) 5 )
87
88 /* The three tasks as described at the top of this file. */
89 static void prvRecursiveMutexControllingTask( void *pvParameters );
90 static void prvRecursiveMutexBlockingTask( void *pvParameters );
91 static void prvRecursiveMutexPollingTask( void *pvParameters );
92
93 /* The mutex used by the demo. */
94 static SemaphoreHandle_t xMutex;
95
96 /* Variables used to detect and latch errors. */
97 static volatile portBASE_TYPE xErrorOccurred = pdFALSE, xControllingIsSuspended = pdFALSE, xBlockingIsSuspended = pdFALSE;
98 static volatile unsigned portBASE_TYPE uxControllingCycles = 0, uxBlockingCycles = 0, uxPollingCycles = 0;
99
100 /* Handles of the two higher priority tasks, required so they can be resumed 
101 (unsuspended). */
102 static TaskHandle_t xControllingTaskHandle, xBlockingTaskHandle, xPollingTaskHandle;
103
104 /*-----------------------------------------------------------*/
105
106 void vStartRecursiveMutexTasks( void )
107 {
108         /* Just creates the mutex and the three tasks. */
109
110         xMutex = xSemaphoreCreateRecursiveMutex();
111
112         /* vQueueAddToRegistry() adds the mutex to the registry, if one is
113         in use.  The registry is provided as a means for kernel aware 
114         debuggers to locate mutex and has no purpose if a kernel aware debugger
115         is not being used.  The call to vQueueAddToRegistry() will be removed
116         by the pre-processor if configQUEUE_REGISTRY_SIZE is not defined or is 
117         defined to be less than 1. */
118         vQueueAddToRegistry( ( QueueHandle_t ) xMutex, "Recursive_Mutex" );
119
120
121         if( xMutex != NULL )
122         {
123                 xTaskCreate( prvRecursiveMutexControllingTask, "Rec1Ctrl", configMINIMAL_STACK_SIZE, NULL, recmuCONTROLLING_TASK_PRIORITY, &xControllingTaskHandle );
124         xTaskCreate( prvRecursiveMutexBlockingTask, "Rec2Blck", configMINIMAL_STACK_SIZE, NULL, recmuBLOCKING_TASK_PRIORITY, &xBlockingTaskHandle );
125         xTaskCreate( prvRecursiveMutexPollingTask, "Rec3Poll", configMINIMAL_STACK_SIZE, NULL, recmuPOLLING_TASK_PRIORITY, &xPollingTaskHandle );
126         }
127 }
128 /*-----------------------------------------------------------*/
129
130 static void prvRecursiveMutexControllingTask( void *pvParameters )
131 {
132 unsigned portBASE_TYPE ux;
133
134         /* Just to remove compiler warning. */
135         ( void ) pvParameters;
136
137         for( ;; )
138         {
139                 /* Should not be able to 'give' the mutex, as we have not yet 'taken'
140                 it.   The first time through, the mutex will not have been used yet,
141                 subsequent times through, at this point the mutex will be held by the
142                 polling task. */
143                 if( xSemaphoreGiveRecursive( xMutex ) == pdPASS )
144                 {
145                         xErrorOccurred = pdTRUE;
146                 }
147
148                 for( ux = 0; ux < recmuMAX_COUNT; ux++ )
149                 {
150                         /* We should now be able to take the mutex as many times as
151                         we like.
152                         
153                         The first time through the mutex will be immediately available, on
154                         subsequent times through the mutex will be held by the polling task
155                         at this point and this Take will cause the polling task to inherit
156                         the priority of this task.  In this case the block time must be
157                         long enough to ensure the polling task will execute again before the
158                         block time expires.  If the block time does expire then the error
159                         flag will be set here. */
160                         if( xSemaphoreTakeRecursive( xMutex, recmuFIVE_TICK_DELAY ) != pdPASS )
161                         {
162                                 xErrorOccurred = pdTRUE;
163                         }
164
165                         /* Ensure the other task attempting to access the mutex (and the
166                         other demo tasks) are able to execute to ensure they either block
167                         (where a block time is specified) or return an error (where no 
168                         block time is specified) as the mutex is held by this task. */
169                         vTaskDelay( recmuSHORT_DELAY );
170                 }
171
172                 /* For each time we took the mutex, give it back. */
173                 for( ux = 0; ux < recmuMAX_COUNT; ux++ )
174                 {
175                         /* Ensure the other task attempting to access the mutex (and the
176                         other demo tasks) are able to execute. */
177                         vTaskDelay( recmuSHORT_DELAY );
178
179                         /* We should now be able to give the mutex as many times as we
180                         took it.  When the mutex is available again the Blocking task
181                         should be unblocked but not run because it has a lower priority
182                         than this task.  The polling task should also not run at this point
183                         as it too has a lower priority than this task. */
184                         if( xSemaphoreGiveRecursive( xMutex ) != pdPASS )
185                         {
186                                 xErrorOccurred = pdTRUE;
187                         }
188
189                         #if configUSE_PREEMPTION == 0
190                                 taskYIELD();
191                         #endif
192                 }
193
194                 /* Having given it back the same number of times as it was taken, we
195                 should no longer be the mutex owner, so the next give should fail. */
196                 if( xSemaphoreGiveRecursive( xMutex ) == pdPASS )
197                 {
198                         xErrorOccurred = pdTRUE;
199                 }
200
201                 /* Keep count of the number of cycles this task has performed so a 
202                 stall can be detected. */
203                 uxControllingCycles++;
204
205                 /* Suspend ourselves so the blocking task can execute. */
206                 xControllingIsSuspended = pdTRUE;
207                 vTaskSuspend( NULL );
208                 xControllingIsSuspended = pdFALSE;
209         }
210 }
211 /*-----------------------------------------------------------*/
212
213 static void prvRecursiveMutexBlockingTask( void *pvParameters )
214 {
215         /* Just to remove compiler warning. */
216         ( void ) pvParameters;
217
218         for( ;; )
219         {
220                 /* This task will run while the controlling task is blocked, and the
221                 controlling task will block only once it has the mutex - therefore
222                 this call should block until the controlling task has given up the 
223                 mutex, and not actually execute past this call until the controlling 
224                 task is suspended. */
225                 if( xSemaphoreTakeRecursive( xMutex, portMAX_DELAY ) == pdPASS )
226                 {
227                         if( xControllingIsSuspended != pdTRUE )
228                         {
229                                 /* Did not expect to execute until the controlling task was
230                                 suspended. */
231                                 xErrorOccurred = pdTRUE;
232                         }
233                         else
234                         {
235                                 /* Give the mutex back before suspending ourselves to allow
236                                 the polling task to obtain the mutex. */
237                                 if( xSemaphoreGiveRecursive( xMutex ) != pdPASS )
238                                 {
239                                         xErrorOccurred = pdTRUE;
240                                 }
241
242                                 xBlockingIsSuspended = pdTRUE;
243                                 vTaskSuspend( NULL );
244                                 xBlockingIsSuspended = pdFALSE;
245                         }
246                 }
247                 else
248                 {
249                         /* We should not leave the xSemaphoreTakeRecursive() function
250                         until the mutex was obtained. */
251                         xErrorOccurred = pdTRUE;
252                 }
253
254                 /* The controlling and blocking tasks should be in lock step. */
255                 if( uxControllingCycles != ( uxBlockingCycles + 1 ) )
256                 {
257                         xErrorOccurred = pdTRUE;
258                 }
259
260                 /* Keep count of the number of cycles this task has performed so a 
261                 stall can be detected. */
262                 uxBlockingCycles++;
263         }
264 }
265 /*-----------------------------------------------------------*/
266
267 static void prvRecursiveMutexPollingTask( void *pvParameters )
268 {
269         /* Just to remove compiler warning. */
270         ( void ) pvParameters;
271
272         for( ;; )
273         {
274                 /* Keep attempting to obtain the mutex.  We should only obtain it when
275                 the blocking task has suspended itself, which in turn should only
276                 happen when the controlling task is also suspended. */
277                 if( xSemaphoreTakeRecursive( xMutex, recmuNO_DELAY ) == pdPASS )
278                 {
279                         /* Is the blocking task suspended? */
280                         if( ( xBlockingIsSuspended != pdTRUE ) || ( xControllingIsSuspended != pdTRUE ) )
281                         {
282                                 xErrorOccurred = pdTRUE;
283                         }
284                         else
285                         {
286                                 /* Keep count of the number of cycles this task has performed 
287                                 so a stall can be detected. */
288                                 uxPollingCycles++;
289
290                                 /* We can resume the other tasks here even though they have a
291                                 higher priority than the polling task.  When they execute they
292                                 will attempt to obtain the mutex but fail because the polling
293                                 task is still the mutex holder.  The polling task (this task)
294                                 will then inherit the higher priority.  The Blocking task will
295                                 block indefinitely when it attempts to obtain the mutex, the
296                                 Controlling task will only block for a fixed period and an
297                                 error will be latched if the polling task has not returned the
298                                 mutex by the time this fixed period has expired. */                             
299                                 vTaskResume( xBlockingTaskHandle );
300                                 #if configUSE_PREEMPTION == 0
301                                         taskYIELD();
302                                 #endif
303
304                                 vTaskResume( xControllingTaskHandle );
305                                 #if configUSE_PREEMPTION == 0
306                                         taskYIELD();
307                                 #endif
308
309                                 /* The other two tasks should now have executed and no longer
310                                 be suspended. */
311                                 if( ( xBlockingIsSuspended == pdTRUE ) || ( xControllingIsSuspended == pdTRUE ) )
312                                 {
313                                         xErrorOccurred = pdTRUE;
314                                 }                               
315                         
316                                 /* Release the mutex, disinheriting the higher priority again. */
317                                 if( xSemaphoreGiveRecursive( xMutex ) != pdPASS )
318                                 {
319                                         xErrorOccurred = pdTRUE;
320                                 }
321
322                                 #if configUSE_PREEMPTION == 0
323                                         taskYIELD();
324                                 #endif
325                         }
326                 }
327
328                 #if configUSE_PREEMPTION == 0
329                 {
330                         taskYIELD();
331                 }
332                 #endif
333         }
334 }
335 /*-----------------------------------------------------------*/
336
337 /* This is called to check that all the created tasks are still running. */
338 portBASE_TYPE xAreRecursiveMutexTasksStillRunning( void )
339 {
340 portBASE_TYPE xReturn;
341 static unsigned portBASE_TYPE uxLastControllingCycles = 0, uxLastBlockingCycles = 0, uxLastPollingCycles = 0;
342
343         /* Is the controlling task still cycling? */
344         if( uxLastControllingCycles == uxControllingCycles )
345         {
346                 xErrorOccurred = pdTRUE;
347         }
348         else
349         {
350                 uxLastControllingCycles = uxControllingCycles;
351         }
352
353         /* Is the blocking task still cycling? */
354         if( uxLastBlockingCycles == uxBlockingCycles )
355         {
356                 xErrorOccurred = pdTRUE;
357         }
358         else
359         {
360                 uxLastBlockingCycles = uxBlockingCycles;
361         }
362
363         /* Is the polling task still cycling? */
364         if( uxLastPollingCycles == uxPollingCycles )
365         {
366                 xErrorOccurred = pdTRUE;
367         }
368         else
369         {
370                 uxLastPollingCycles = uxPollingCycles;
371         }
372
373         if( xErrorOccurred == pdTRUE )
374         {
375                 xReturn = pdFAIL;
376         }
377         else
378         {
379                 xReturn = pdTRUE;
380         }
381
382         return xReturn;
383 }
384
385
386
387