3 * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
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:
12 * The above copyright notice and this permission notice shall be included in all
13 * copies or substantial portions of the Software.
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.
22 * http://www.FreeRTOS.org
23 * http://aws.amazon.com/freertos
29 * The tasks defined on this page demonstrate the use of recursive mutexes.
31 * For recursive mutex functionality the created mutex should be created using
32 * xSemaphoreCreateRecursiveMutex(), then be manipulated
33 * using the xSemaphoreTakeRecursive() and xSemaphoreGiveRecursive() API
36 * This demo creates three tasks all of which access the same recursive mutex:
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.
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
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.
64 /* Scheduler include files. */
69 /* Demo app include files. */
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 )
77 #define recmuBLOCKING_TASK_PRIORITY ( tskIDLE_PRIORITY + 1 )
78 #define recmuPOLLING_TASK_PRIORITY ( tskIDLE_PRIORITY + 0 )
80 /* The recursive call depth. */
81 #define recmuMAX_COUNT ( 10 )
84 #define recmuSHORT_DELAY ( pdMS_TO_TICKS( 20 ) )
85 #define recmuNO_DELAY ( ( TickType_t ) 0 )
86 #define recmu15ms_DELAY ( pdMS_TO_TICKS( 15 ) )
88 #ifndef recmuRECURSIVE_MUTEX_TEST_TASK_STACK_SIZE
89 #define recmuRECURSIVE_MUTEX_TEST_TASK_STACK_SIZE configMINIMAL_STACK_SIZE
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 );
97 /* The mutex used by the demo. */
98 static SemaphoreHandle_t xMutex;
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;
104 /* Handles of the two higher priority tasks, required so they can be resumed
106 static TaskHandle_t xControllingTaskHandle, xBlockingTaskHandle;
108 /*-----------------------------------------------------------*/
110 void vStartRecursiveMutexTasks( void )
112 /* Just creates the mutex and the three tasks. */
114 xMutex = xSemaphoreCreateRecursiveMutex();
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" );
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 );
131 /*-----------------------------------------------------------*/
133 static void prvRecursiveMutexControllingTask( void * pvParameters )
137 /* Just to remove compiler warning. */
138 ( void ) pvParameters;
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
146 if( xSemaphoreGiveRecursive( xMutex ) == pdPASS )
148 xErrorOccurred = pdTRUE;
151 for( ux = 0; ux < recmuMAX_COUNT; ux++ )
153 /* We should now be able to take the mutex as many times as
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 )
165 xErrorOccurred = pdTRUE;
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 );
175 /* For each time we took the mutex, give it back. */
176 for( ux = 0; ux < recmuMAX_COUNT; ux++ )
178 /* Ensure the other task attempting to access the mutex (and the
179 * other demo tasks) are able to execute. */
180 vTaskDelay( recmuSHORT_DELAY );
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 )
189 xErrorOccurred = pdTRUE;
192 #if ( configUSE_PREEMPTION == 0 )
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 )
201 xErrorOccurred = pdTRUE;
204 /* Keep count of the number of cycles this task has performed so a
205 * stall can be detected. */
206 uxControllingCycles++;
208 /* Suspend ourselves so the blocking task can execute. */
209 xControllingIsSuspended = pdTRUE;
210 vTaskSuspend( NULL );
211 xControllingIsSuspended = pdFALSE;
214 /*-----------------------------------------------------------*/
216 static void prvRecursiveMutexBlockingTask( void * pvParameters )
218 /* Just to remove compiler warning. */
219 ( void ) pvParameters;
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 )
232 if( xControllingIsSuspended != pdTRUE )
234 /* Did not expect to execute until the controlling task was
236 xErrorOccurred = pdTRUE;
240 /* Give the mutex back before suspending ourselves to allow
241 * the polling task to obtain the mutex. */
242 if( xSemaphoreGiveRecursive( xMutex ) != pdPASS )
244 xErrorOccurred = pdTRUE;
247 xBlockingIsSuspended = pdTRUE;
248 vTaskSuspend( NULL );
249 xBlockingIsSuspended = pdFALSE;
254 /* We should not leave the xSemaphoreTakeRecursive() function
255 * until the mutex was obtained. */
256 xErrorOccurred = pdTRUE;
259 /* The controlling and blocking tasks should be in lock step. */
260 if( uxControllingCycles != ( UBaseType_t ) ( uxBlockingCycles + 1 ) )
262 xErrorOccurred = pdTRUE;
265 /* Keep count of the number of cycles this task has performed so a
266 * stall can be detected. */
270 /*-----------------------------------------------------------*/
272 static void prvRecursiveMutexPollingTask( void * pvParameters )
274 /* Just to remove compiler warning. */
275 ( void ) pvParameters;
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 )
284 #if ( INCLUDE_eTaskGetState == 1 )
286 configASSERT( eTaskGetState( xControllingTaskHandle ) == eSuspended );
287 configASSERT( eTaskGetState( xBlockingTaskHandle ) == eSuspended );
289 #endif /* INCLUDE_eTaskGetState */
291 /* Is the blocking task suspended? */
292 if( ( xBlockingIsSuspended != pdTRUE ) || ( xControllingIsSuspended != pdTRUE ) )
294 xErrorOccurred = pdTRUE;
298 /* Keep count of the number of cycles this task has performed
299 * so a stall can be detected. */
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 )
316 vTaskResume( xControllingTaskHandle );
317 #if ( configUSE_PREEMPTION == 0 )
321 /* The other two tasks should now have executed and no longer
323 if( ( xBlockingIsSuspended == pdTRUE ) || ( xControllingIsSuspended == pdTRUE ) )
325 xErrorOccurred = pdTRUE;
328 #if ( INCLUDE_uxTaskPriorityGet == 1 )
330 /* Check priority inherited. */
331 configASSERT( uxTaskPriorityGet( NULL ) == recmuCONTROLLING_TASK_PRIORITY );
333 #endif /* INCLUDE_uxTaskPriorityGet */
335 #if ( INCLUDE_eTaskGetState == 1 )
337 configASSERT( eTaskGetState( xControllingTaskHandle ) == eBlocked );
338 configASSERT( eTaskGetState( xBlockingTaskHandle ) == eBlocked );
340 #endif /* INCLUDE_eTaskGetState */
342 /* Release the mutex, disinheriting the higher priority again. */
343 if( xSemaphoreGiveRecursive( xMutex ) != pdPASS )
345 xErrorOccurred = pdTRUE;
348 #if ( INCLUDE_uxTaskPriorityGet == 1 )
350 /* Check priority disinherited. */
351 configASSERT( uxTaskPriorityGet( NULL ) == recmuPOLLING_TASK_PRIORITY );
353 #endif /* INCLUDE_uxTaskPriorityGet */
357 #if configUSE_PREEMPTION == 0
364 /*-----------------------------------------------------------*/
366 /* This is called to check that all the created tasks are still running. */
367 BaseType_t xAreRecursiveMutexTasksStillRunning( void )
370 static UBaseType_t uxLastControllingCycles = 0, uxLastBlockingCycles = 0, uxLastPollingCycles = 0;
372 /* Is the controlling task still cycling? */
373 if( uxLastControllingCycles == uxControllingCycles )
375 xErrorOccurred = pdTRUE;
379 uxLastControllingCycles = uxControllingCycles;
382 /* Is the blocking task still cycling? */
383 if( uxLastBlockingCycles == uxBlockingCycles )
385 xErrorOccurred = pdTRUE;
389 uxLastBlockingCycles = uxBlockingCycles;
392 /* Is the polling task still cycling? */
393 if( uxLastPollingCycles == uxPollingCycles )
395 xErrorOccurred = pdTRUE;
399 uxLastPollingCycles = uxPollingCycles;
402 if( xErrorOccurred == pdTRUE )