]> begriffs open source - cmsis-freertos/blob - Demo/Common/Minimal/recmutex.c
Updated pack to FreeRTOS 10.4.6
[cmsis-freertos] / Demo / Common / Minimal / 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.  recmuCONTROLLING_TASK_PRIORITY can
73  * be overridden by a definition in FreeRTOSConfig.h. */
74 #ifndef recmuCONTROLLING_TASK_PRIORITY
75     #define recmuCONTROLLING_TASK_PRIORITY               ( tskIDLE_PRIORITY + 2 )
76 #endif
77 #define recmuBLOCKING_TASK_PRIORITY                      ( tskIDLE_PRIORITY + 1 )
78 #define recmuPOLLING_TASK_PRIORITY                       ( tskIDLE_PRIORITY + 0 )
79
80 /* The recursive call depth. */
81 #define recmuMAX_COUNT                                   ( 10 )
82
83 /* Misc. */
84 #define recmuSHORT_DELAY                                 ( pdMS_TO_TICKS( 20 ) )
85 #define recmuNO_DELAY                                    ( ( TickType_t ) 0 )
86 #define recmu15ms_DELAY                                  ( pdMS_TO_TICKS( 15 ) )
87
88 #ifndef recmuRECURSIVE_MUTEX_TEST_TASK_STACK_SIZE
89     #define recmuRECURSIVE_MUTEX_TEST_TASK_STACK_SIZE    configMINIMAL_STACK_SIZE
90 #endif
91
92 /* The three tasks as described at the top of this file. */
93 static void prvRecursiveMutexControllingTask( void * pvParameters );
94 static void prvRecursiveMutexBlockingTask( void * pvParameters );
95 static void prvRecursiveMutexPollingTask( void * pvParameters );
96
97 /* The mutex used by the demo. */
98 static SemaphoreHandle_t xMutex;
99
100 /* Variables used to detect and latch errors. */
101 static volatile BaseType_t xErrorOccurred = pdFALSE, xControllingIsSuspended = pdFALSE, xBlockingIsSuspended = pdFALSE;
102 static volatile UBaseType_t uxControllingCycles = 0, uxBlockingCycles = 0, uxPollingCycles = 0;
103
104 /* Handles of the two higher priority tasks, required so they can be resumed
105  * (unsuspended). */
106 static TaskHandle_t xControllingTaskHandle, xBlockingTaskHandle;
107
108 /*-----------------------------------------------------------*/
109
110 void vStartRecursiveMutexTasks( void )
111 {
112     /* Just creates the mutex and the three tasks. */
113
114     xMutex = xSemaphoreCreateRecursiveMutex();
115
116     if( xMutex != NULL )
117     {
118         /* vQueueAddToRegistry() adds the mutex to the registry, if one is
119          * in use.  The registry is provided as a means for kernel aware
120          * debuggers to locate mutex and has no purpose if a kernel aware debugger
121          * is not being used.  The call to vQueueAddToRegistry() will be removed
122          * by the pre-processor if configQUEUE_REGISTRY_SIZE is not defined or is
123          * defined to be less than 1. */
124         vQueueAddToRegistry( ( QueueHandle_t ) xMutex, "Recursive_Mutex" );
125
126         xTaskCreate( prvRecursiveMutexControllingTask, "Rec1", recmuRECURSIVE_MUTEX_TEST_TASK_STACK_SIZE, NULL, recmuCONTROLLING_TASK_PRIORITY, &xControllingTaskHandle );
127         xTaskCreate( prvRecursiveMutexBlockingTask, "Rec2", recmuRECURSIVE_MUTEX_TEST_TASK_STACK_SIZE, NULL, recmuBLOCKING_TASK_PRIORITY, &xBlockingTaskHandle );
128         xTaskCreate( prvRecursiveMutexPollingTask, "Rec3", recmuRECURSIVE_MUTEX_TEST_TASK_STACK_SIZE, NULL, recmuPOLLING_TASK_PRIORITY, NULL );
129     }
130 }
131 /*-----------------------------------------------------------*/
132
133 static void prvRecursiveMutexControllingTask( void * pvParameters )
134 {
135     UBaseType_t ux;
136
137     /* Just to remove compiler warning. */
138     ( void ) pvParameters;
139
140     for( ; ; )
141     {
142         /* Should not be able to 'give' the mutex, as we have not yet 'taken'
143          * it.   The first time through, the mutex will not have been used yet,
144          * subsequent times through, at this point the mutex will be held by the
145          * polling task. */
146         if( xSemaphoreGiveRecursive( xMutex ) == pdPASS )
147         {
148             xErrorOccurred = pdTRUE;
149         }
150
151         for( ux = 0; ux < recmuMAX_COUNT; ux++ )
152         {
153             /* We should now be able to take the mutex as many times as
154              * we like.
155              *
156              * The first time through the mutex will be immediately available, on
157              * subsequent times through the mutex will be held by the polling task
158              * at this point and this Take will cause the polling task to inherit
159              * the priority of this task.  In this case the block time must be
160              * long enough to ensure the polling task will execute again before the
161              * block time expires.  If the block time does expire then the error
162              * flag will be set here. */
163             if( xSemaphoreTakeRecursive( xMutex, recmu15ms_DELAY ) != pdPASS )
164             {
165                 xErrorOccurred = pdTRUE;
166             }
167
168             /* Ensure the other task attempting to access the mutex (and the
169             * other demo tasks) are able to execute to ensure they either block
170             * (where a block time is specified) or return an error (where no
171             * block time is specified) as the mutex is held by this task. */
172             vTaskDelay( recmuSHORT_DELAY );
173         }
174
175         /* For each time we took the mutex, give it back. */
176         for( ux = 0; ux < recmuMAX_COUNT; ux++ )
177         {
178             /* Ensure the other task attempting to access the mutex (and the
179              * other demo tasks) are able to execute. */
180             vTaskDelay( recmuSHORT_DELAY );
181
182             /* We should now be able to give the mutex as many times as we
183              * took it.  When the mutex is available again the Blocking task
184              * should be unblocked but not run because it has a lower priority
185              * than this task.  The polling task should also not run at this point
186              * as it too has a lower priority than this task. */
187             if( xSemaphoreGiveRecursive( xMutex ) != pdPASS )
188             {
189                 xErrorOccurred = pdTRUE;
190             }
191
192             #if ( configUSE_PREEMPTION == 0 )
193                 taskYIELD();
194             #endif
195         }
196
197         /* Having given it back the same number of times as it was taken, we
198          * should no longer be the mutex owner, so the next give should fail. */
199         if( xSemaphoreGiveRecursive( xMutex ) == pdPASS )
200         {
201             xErrorOccurred = pdTRUE;
202         }
203
204         /* Keep count of the number of cycles this task has performed so a
205          * stall can be detected. */
206         uxControllingCycles++;
207
208         /* Suspend ourselves so the blocking task can execute. */
209         xControllingIsSuspended = pdTRUE;
210         vTaskSuspend( NULL );
211         xControllingIsSuspended = pdFALSE;
212     }
213 }
214 /*-----------------------------------------------------------*/
215
216 static void prvRecursiveMutexBlockingTask( void * pvParameters )
217 {
218     /* Just to remove compiler warning. */
219     ( void ) pvParameters;
220
221     for( ; ; )
222     {
223         /* This task will run while the controlling task is blocked, and the
224          * controlling task will block only once it has the mutex - therefore
225          * this call should block until the controlling task has given up the
226          * mutex, and not actually execute      past this call until the controlling
227          * task is suspended.  portMAX_DELAY - 1 is used instead of portMAX_DELAY
228          * to ensure the task's state is reported as Blocked and not Suspended in
229          * a later call to configASSERT() (within the polling task). */
230         if( xSemaphoreTakeRecursive( xMutex, ( portMAX_DELAY - 1 ) ) == pdPASS )
231         {
232             if( xControllingIsSuspended != pdTRUE )
233             {
234                 /* Did not expect to execute until the controlling task was
235                  * suspended. */
236                 xErrorOccurred = pdTRUE;
237             }
238             else
239             {
240                 /* Give the mutex back before suspending ourselves to allow
241                  * the polling task to obtain the mutex. */
242                 if( xSemaphoreGiveRecursive( xMutex ) != pdPASS )
243                 {
244                     xErrorOccurred = pdTRUE;
245                 }
246
247                 xBlockingIsSuspended = pdTRUE;
248                 vTaskSuspend( NULL );
249                 xBlockingIsSuspended = pdFALSE;
250             }
251         }
252         else
253         {
254             /* We should not leave the xSemaphoreTakeRecursive() function
255              * until the mutex was obtained. */
256             xErrorOccurred = pdTRUE;
257         }
258
259         /* The controlling and blocking tasks should be in lock step. */
260         if( uxControllingCycles != ( UBaseType_t ) ( uxBlockingCycles + 1 ) )
261         {
262             xErrorOccurred = pdTRUE;
263         }
264
265         /* Keep count of the number of cycles this task has performed so a
266          * stall can be detected. */
267         uxBlockingCycles++;
268     }
269 }
270 /*-----------------------------------------------------------*/
271
272 static void prvRecursiveMutexPollingTask( void * pvParameters )
273 {
274     /* Just to remove compiler warning. */
275     ( void ) pvParameters;
276
277     for( ; ; )
278     {
279         /* Keep attempting to obtain the mutex.  It should only be obtained when
280          * the blocking task has suspended itself, which in turn should only
281          * happen when the controlling task is also suspended. */
282         if( xSemaphoreTakeRecursive( xMutex, recmuNO_DELAY ) == pdPASS )
283         {
284             #if ( INCLUDE_eTaskGetState == 1 )
285                 {
286                     configASSERT( eTaskGetState( xControllingTaskHandle ) == eSuspended );
287                     configASSERT( eTaskGetState( xBlockingTaskHandle ) == eSuspended );
288                 }
289             #endif /* INCLUDE_eTaskGetState */
290
291             /* Is the blocking task suspended? */
292             if( ( xBlockingIsSuspended != pdTRUE ) || ( xControllingIsSuspended != pdTRUE ) )
293             {
294                 xErrorOccurred = pdTRUE;
295             }
296             else
297             {
298                 /* Keep count of the number of cycles this task has performed
299                  * so a stall can be detected. */
300                 uxPollingCycles++;
301
302                 /* We can resume the other tasks here even though they have a
303                  * higher priority than the polling task.  When they execute they
304                  * will attempt to obtain the mutex but fail because the polling
305                  * task is still the mutex holder.  The polling task (this task)
306                  * will then inherit the higher priority.  The Blocking task will
307                  * block indefinitely when it attempts to obtain the mutex, the
308                  * Controlling task will only block for a fixed period and an
309                  * error will be latched if the polling task has not returned the
310                  * mutex by the time this fixed period has expired. */
311                 vTaskResume( xBlockingTaskHandle );
312                 #if ( configUSE_PREEMPTION == 0 )
313                     taskYIELD();
314                 #endif
315
316                 vTaskResume( xControllingTaskHandle );
317                 #if ( configUSE_PREEMPTION == 0 )
318                     taskYIELD();
319                 #endif
320
321                 /* The other two tasks should now have executed and no longer
322                  * be suspended. */
323                 if( ( xBlockingIsSuspended == pdTRUE ) || ( xControllingIsSuspended == pdTRUE ) )
324                 {
325                     xErrorOccurred = pdTRUE;
326                 }
327
328                 #if ( INCLUDE_uxTaskPriorityGet == 1 )
329                     {
330                         /* Check priority inherited. */
331                         configASSERT( uxTaskPriorityGet( NULL ) == recmuCONTROLLING_TASK_PRIORITY );
332                     }
333                 #endif /* INCLUDE_uxTaskPriorityGet */
334
335                 #if ( INCLUDE_eTaskGetState == 1 )
336                     {
337                         configASSERT( eTaskGetState( xControllingTaskHandle ) == eBlocked );
338                         configASSERT( eTaskGetState( xBlockingTaskHandle ) == eBlocked );
339                     }
340                 #endif /* INCLUDE_eTaskGetState */
341
342                 /* Release the mutex, disinheriting the higher priority again. */
343                 if( xSemaphoreGiveRecursive( xMutex ) != pdPASS )
344                 {
345                     xErrorOccurred = pdTRUE;
346                 }
347
348                 #if ( INCLUDE_uxTaskPriorityGet == 1 )
349                     {
350                         /* Check priority disinherited. */
351                         configASSERT( uxTaskPriorityGet( NULL ) == recmuPOLLING_TASK_PRIORITY );
352                     }
353                 #endif /* INCLUDE_uxTaskPriorityGet */
354             }
355         }
356
357         #if configUSE_PREEMPTION == 0
358             {
359                 taskYIELD();
360             }
361         #endif
362     }
363 }
364 /*-----------------------------------------------------------*/
365
366 /* This is called to check that all the created tasks are still running. */
367 BaseType_t xAreRecursiveMutexTasksStillRunning( void )
368 {
369     BaseType_t xReturn;
370     static UBaseType_t uxLastControllingCycles = 0, uxLastBlockingCycles = 0, uxLastPollingCycles = 0;
371
372     /* Is the controlling task still cycling? */
373     if( uxLastControllingCycles == uxControllingCycles )
374     {
375         xErrorOccurred = pdTRUE;
376     }
377     else
378     {
379         uxLastControllingCycles = uxControllingCycles;
380     }
381
382     /* Is the blocking task still cycling? */
383     if( uxLastBlockingCycles == uxBlockingCycles )
384     {
385         xErrorOccurred = pdTRUE;
386     }
387     else
388     {
389         uxLastBlockingCycles = uxBlockingCycles;
390     }
391
392     /* Is the polling task still cycling? */
393     if( uxLastPollingCycles == uxPollingCycles )
394     {
395         xErrorOccurred = pdTRUE;
396     }
397     else
398     {
399         uxLastPollingCycles = uxPollingCycles;
400     }
401
402     if( xErrorOccurred == pdTRUE )
403     {
404         xReturn = pdFAIL;
405     }
406     else
407     {
408         xReturn = pdPASS;
409     }
410
411     return xReturn;
412 }