]> begriffs open source - cmsis-freertos/blob - Demo/Common/Minimal/IntSemTest.c
Update cmsis_os2.c
[cmsis-freertos] / Demo / Common / Minimal / IntSemTest.c
1 /*
2     FreeRTOS V9.0.0 - Copyright (C) 2016 Real Time Engineers Ltd.
3     All rights reserved
4
5     VISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION.
6
7     This file is part of the FreeRTOS distribution.
8
9     FreeRTOS is free software; you can redistribute it and/or modify it under
10     the terms of the GNU General Public License (version 2) as published by the
11     Free Software Foundation >>>> AND MODIFIED BY <<<< the FreeRTOS exception.
12
13     ***************************************************************************
14     >>!   NOTE: The modification to the GPL is included to allow you to     !<<
15     >>!   distribute a combined work that includes FreeRTOS without being   !<<
16     >>!   obliged to provide the source code for proprietary components     !<<
17     >>!   outside of the FreeRTOS kernel.                                   !<<
18     ***************************************************************************
19
20     FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANY
21     WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
22     FOR A PARTICULAR PURPOSE.  Full license text is available on the following
23     link: http://www.freertos.org/a00114.html
24
25     ***************************************************************************
26      *                                                                       *
27      *    FreeRTOS provides completely free yet professionally developed,    *
28      *    robust, strictly quality controlled, supported, and cross          *
29      *    platform software that is more than just the market leader, it     *
30      *    is the industry's de facto standard.                               *
31      *                                                                       *
32      *    Help yourself get started quickly while simultaneously helping     *
33      *    to support the FreeRTOS project by purchasing a FreeRTOS           *
34      *    tutorial book, reference manual, or both:                          *
35      *    http://www.FreeRTOS.org/Documentation                              *
36      *                                                                       *
37     ***************************************************************************
38
39     http://www.FreeRTOS.org/FAQHelp.html - Having a problem?  Start by reading
40     the FAQ page "My application does not run, what could be wrong?".  Have you
41     defined configASSERT()?
42
43     http://www.FreeRTOS.org/support - In return for receiving this top quality
44     embedded software for free we request you assist our global community by
45     participating in the support forum.
46
47     http://www.FreeRTOS.org/training - Investing in training allows your team to
48     be as productive as possible as early as possible.  Now you can receive
49     FreeRTOS training directly from Richard Barry, CEO of Real Time Engineers
50     Ltd, and the world's leading authority on the world's leading RTOS.
51
52     http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products,
53     including FreeRTOS+Trace - an indispensable productivity tool, a DOS
54     compatible FAT file system, and our tiny thread aware UDP/IP stack.
55
56     http://www.FreeRTOS.org/labs - Where new FreeRTOS products go to incubate.
57     Come and try FreeRTOS+TCP, our new open source TCP/IP stack for FreeRTOS.
58
59     http://www.OpenRTOS.com - Real Time Engineers ltd. license FreeRTOS to High
60     Integrity Systems ltd. to sell under the OpenRTOS brand.  Low cost OpenRTOS
61     licenses offer ticketed support, indemnification and commercial middleware.
62
63     http://www.SafeRTOS.com - High Integrity Systems also provide a safety
64     engineered and independently SIL3 certified version for use in safety and
65     mission critical applications that require provable dependability.
66
67     1 tab == 4 spaces!
68 */
69
70
71 /*
72  * Demonstrates and tests mutexes being used from an interrupt.
73  */
74
75
76 #include <stdlib.h>
77
78 /* Scheduler include files. */
79 #include "FreeRTOS.h"
80 #include "task.h"
81 #include "semphr.h"
82
83 /* Demo program include files. */
84 #include "IntSemTest.h"
85
86 /*-----------------------------------------------------------*/
87
88 /* The priorities of the test tasks. */
89 #define intsemMASTER_PRIORITY           ( tskIDLE_PRIORITY )
90 #define intsemSLAVE_PRIORITY            ( tskIDLE_PRIORITY + 1 )
91
92 /* The rate at which the tick hook will give the mutex. */
93 #define intsemINTERRUPT_MUTEX_GIVE_PERIOD_MS ( 100 )
94
95 /* A block time of 0 means 'don't block'. */
96 #define intsemNO_BLOCK                          0
97
98 /* The maximum count value for the counting semaphore given from an
99 interrupt. */
100 #define intsemMAX_COUNT                         3
101
102 /*-----------------------------------------------------------*/
103
104 /*
105  * The master is a task that receives a mutex that is given from an interrupt -
106  * although generally mutexes should not be used given in interrupts (and
107  * definitely never taken in an interrupt) there are some circumstances when it
108  * may be desirable.
109  *
110  * The slave task is just used by the master task to force priority inheritance
111  * on a mutex that is shared between the master and the slave - which is a
112  * separate mutex to that given by the interrupt.
113  */
114 static void vInterruptMutexSlaveTask( void *pvParameters );
115 static void vInterruptMutexMasterTask( void *pvParameters );
116
117 /*
118  * A test whereby the master takes the shared and interrupt mutexes in that
119  * order, then gives them back in the same order, ensuring the priority
120  * inheritance is behaving as expected at each step.
121  */
122 static void prvTakeAndGiveInTheSameOrder( void );
123
124 /*
125  * A test whereby the master takes the shared and interrupt mutexes in that
126  * order, then gives them back in the opposite order to which they were taken,
127  * ensuring the priority inheritance is behaving as expected at each step.
128  */
129 static void prvTakeAndGiveInTheOppositeOrder( void );
130
131 /*
132  * A simple task that interacts with an interrupt using a counting semaphore,
133  * primarily for code coverage purposes.
134  */
135 static void vInterruptCountingSemaphoreTask( void *pvParameters );
136
137 /*-----------------------------------------------------------*/
138
139 /* Flag that will be latched to pdTRUE should any unexpected behaviour be
140 detected in any of the tasks. */
141 static volatile BaseType_t xErrorDetected = pdFALSE;
142
143 /* Counters that are incremented on each cycle of a test.  This is used to
144 detect a stalled task - a test that is no longer running. */
145 static volatile uint32_t ulMasterLoops = 0, ulCountingSemaphoreLoops = 0;
146
147 /* Handles of the test tasks that must be accessed from other test tasks. */
148 static TaskHandle_t xSlaveHandle;
149
150 /* A mutex which is given from an interrupt - although generally mutexes should
151 not be used given in interrupts (and definitely never taken in an interrupt)
152 there are some circumstances when it may be desirable. */
153 static SemaphoreHandle_t xISRMutex = NULL;
154
155 /* A counting semaphore which is given from an interrupt. */
156 static SemaphoreHandle_t xISRCountingSemaphore = NULL;
157
158 /* A mutex which is shared between the master and slave tasks - the master
159 does both sharing of this mutex with the slave and receiving a mutex from the
160 interrupt. */
161 static SemaphoreHandle_t xMasterSlaveMutex = NULL;
162
163 /* Flag that allows the master task to control when the interrupt gives or does
164 not give the mutex.  There is no mutual exclusion on this variable, but this is
165 only test code and it should be fine in the 32=bit test environment. */
166 static BaseType_t xOkToGiveMutex = pdFALSE, xOkToGiveCountingSemaphore = pdFALSE;
167
168 /* Used to coordinate timing between tasks and the interrupt. */
169 const TickType_t xInterruptGivePeriod = pdMS_TO_TICKS( intsemINTERRUPT_MUTEX_GIVE_PERIOD_MS );
170
171 /*-----------------------------------------------------------*/
172
173 void vStartInterruptSemaphoreTasks( void )
174 {
175         /* Create the semaphores that are given from an interrupt. */
176         xISRMutex = xSemaphoreCreateMutex();
177         configASSERT( xISRMutex );
178         xISRCountingSemaphore = xSemaphoreCreateCounting( intsemMAX_COUNT, 0 );
179         configASSERT( xISRCountingSemaphore );
180
181         /* Create the mutex that is shared between the master and slave tasks (the
182         master receives a mutex from an interrupt and shares a mutex with the
183         slave. */
184         xMasterSlaveMutex = xSemaphoreCreateMutex();
185         configASSERT( xMasterSlaveMutex );
186
187         /* Create the tasks that share mutexes between then and with interrupts. */
188         xTaskCreate( vInterruptMutexSlaveTask, "IntMuS", configMINIMAL_STACK_SIZE, NULL, intsemSLAVE_PRIORITY, &xSlaveHandle );
189         xTaskCreate( vInterruptMutexMasterTask, "IntMuM", configMINIMAL_STACK_SIZE, NULL, intsemMASTER_PRIORITY, NULL );
190
191         /* Create the task that blocks on the counting semaphore. */
192         xTaskCreate( vInterruptCountingSemaphoreTask, "IntCnt", configMINIMAL_STACK_SIZE, NULL, tskIDLE_PRIORITY, NULL );
193 }
194 /*-----------------------------------------------------------*/
195
196 static void vInterruptMutexMasterTask( void *pvParameters )
197 {
198         /* Just to avoid compiler warnings. */
199         ( void ) pvParameters;
200
201         for( ;; )
202         {
203                 prvTakeAndGiveInTheSameOrder();
204
205                 /* Ensure not to starve out other tests. */
206                 ulMasterLoops++;
207                 vTaskDelay( intsemINTERRUPT_MUTEX_GIVE_PERIOD_MS );
208
209                 prvTakeAndGiveInTheOppositeOrder();
210
211                 /* Ensure not to starve out other tests. */
212                 ulMasterLoops++;
213                 vTaskDelay( intsemINTERRUPT_MUTEX_GIVE_PERIOD_MS );
214         }
215 }
216 /*-----------------------------------------------------------*/
217
218 static void prvTakeAndGiveInTheSameOrder( void )
219 {
220         /* Ensure the slave is suspended, and that this task is running at the
221         lower priority as expected as the start conditions. */
222         #if( INCLUDE_eTaskGetState == 1 )
223         {
224                 configASSERT( eTaskGetState( xSlaveHandle ) == eSuspended );
225         }
226         #endif /* INCLUDE_eTaskGetState */
227
228         if( uxTaskPriorityGet( NULL ) != intsemMASTER_PRIORITY )
229         {
230                 xErrorDetected = pdTRUE;
231         }
232
233         /* Take the semaphore that is shared with the slave. */
234         if( xSemaphoreTake( xMasterSlaveMutex, intsemNO_BLOCK ) != pdPASS )
235         {
236                 xErrorDetected = pdTRUE;
237         }
238
239         /* This task now has the mutex.  Unsuspend the slave so it too
240         attempts to take the mutex. */
241         vTaskResume( xSlaveHandle );
242
243         /* The slave has the higher priority so should now have executed and
244         blocked on the semaphore. */
245         #if( INCLUDE_eTaskGetState == 1 )
246         {
247                 configASSERT( eTaskGetState( xSlaveHandle ) == eBlocked );
248         }
249         #endif /* INCLUDE_eTaskGetState */
250
251         /* This task should now have inherited the priority of the slave
252         task. */
253         if( uxTaskPriorityGet( NULL ) != intsemSLAVE_PRIORITY )
254         {
255                 xErrorDetected = pdTRUE;
256         }
257
258         /* Now wait a little longer than the time between ISR gives to also
259         obtain the ISR mutex. */
260         xOkToGiveMutex = pdTRUE;
261         if( xSemaphoreTake( xISRMutex, ( xInterruptGivePeriod * 2 ) ) != pdPASS )
262         {
263                 xErrorDetected = pdTRUE;
264         }
265         xOkToGiveMutex = pdFALSE;
266
267         /* Attempting to take again immediately should fail as the mutex is
268         already held. */
269         if( xSemaphoreTake( xISRMutex, intsemNO_BLOCK ) != pdFAIL )
270         {
271                 xErrorDetected = pdTRUE;
272         }
273
274         /* Should still be at the priority of the slave task. */
275         if( uxTaskPriorityGet( NULL ) != intsemSLAVE_PRIORITY )
276         {
277                 xErrorDetected = pdTRUE;
278         }
279
280         /* Give back the ISR semaphore to ensure the priority is not
281         disinherited as the shared mutex (which the higher priority task is
282         attempting to obtain) is still held. */
283         if( xSemaphoreGive( xISRMutex ) != pdPASS )
284         {
285                 xErrorDetected = pdTRUE;
286         }
287
288         if( uxTaskPriorityGet( NULL ) != intsemSLAVE_PRIORITY )
289         {
290                 xErrorDetected = pdTRUE;
291         }
292
293         /* Finally give back the shared mutex.  This time the higher priority
294         task should run before this task runs again - so this task should have
295         disinherited the priority and the higher priority task should be in the
296         suspended state again. */
297         if( xSemaphoreGive( xMasterSlaveMutex ) != pdPASS )
298         {
299                 xErrorDetected = pdTRUE;
300         }
301
302         if( uxTaskPriorityGet( NULL ) != intsemMASTER_PRIORITY )
303         {
304                 xErrorDetected = pdTRUE;
305         }
306
307         #if( INCLUDE_eTaskGetState == 1 )
308         {
309                 configASSERT( eTaskGetState( xSlaveHandle ) == eSuspended );
310         }
311         #endif /* INCLUDE_eTaskGetState */
312
313         /* Reset the mutex ready for the next round. */
314         xQueueReset( xISRMutex );
315 }
316 /*-----------------------------------------------------------*/
317
318 static void prvTakeAndGiveInTheOppositeOrder( void )
319 {
320         /* Ensure the slave is suspended, and that this task is running at the
321         lower priority as expected as the start conditions. */
322         #if( INCLUDE_eTaskGetState == 1 )
323         {
324                 configASSERT( eTaskGetState( xSlaveHandle ) == eSuspended );
325         }
326         #endif /* INCLUDE_eTaskGetState */
327
328         if( uxTaskPriorityGet( NULL ) != intsemMASTER_PRIORITY )
329         {
330                 xErrorDetected = pdTRUE;
331         }
332
333         /* Take the semaphore that is shared with the slave. */
334         if( xSemaphoreTake( xMasterSlaveMutex, intsemNO_BLOCK ) != pdPASS )
335         {
336                 xErrorDetected = pdTRUE;
337         }
338
339         /* This task now has the mutex.  Unsuspend the slave so it too
340         attempts to take the mutex. */
341         vTaskResume( xSlaveHandle );
342
343         /* The slave has the higher priority so should now have executed and
344         blocked on the semaphore. */
345         #if( INCLUDE_eTaskGetState == 1 )
346         {
347                 configASSERT( eTaskGetState( xSlaveHandle ) == eBlocked );
348         }
349         #endif /* INCLUDE_eTaskGetState */
350
351         /* This task should now have inherited the priority of the slave
352         task. */
353         if( uxTaskPriorityGet( NULL ) != intsemSLAVE_PRIORITY )
354         {
355                 xErrorDetected = pdTRUE;
356         }
357
358         /* Now wait a little longer than the time between ISR gives to also
359         obtain the ISR mutex. */
360         xOkToGiveMutex = pdTRUE;
361         if( xSemaphoreTake( xISRMutex, ( xInterruptGivePeriod * 2 ) ) != pdPASS )
362         {
363                 xErrorDetected = pdTRUE;
364         }
365         xOkToGiveMutex = pdFALSE;
366
367         /* Attempting to take again immediately should fail as the mutex is
368         already held. */
369         if( xSemaphoreTake( xISRMutex, intsemNO_BLOCK ) != pdFAIL )
370         {
371                 xErrorDetected = pdTRUE;
372         }
373
374         /* Should still be at the priority of the slave task. */
375         if( uxTaskPriorityGet( NULL ) != intsemSLAVE_PRIORITY )
376         {
377                 xErrorDetected = pdTRUE;
378         }
379
380         /* Give back the shared semaphore to ensure the priority is not disinherited
381         as the ISR mutex is still held.  The higher priority slave task should run
382         before this task runs again. */
383         if( xSemaphoreGive( xMasterSlaveMutex ) != pdPASS )
384         {
385                 xErrorDetected = pdTRUE;
386         }
387
388         /* Should still be at the priority of the slave task as this task still
389         holds one semaphore (this is a simplification in the priority inheritance
390         mechanism. */
391         if( uxTaskPriorityGet( NULL ) != intsemSLAVE_PRIORITY )
392         {
393                 xErrorDetected = pdTRUE;
394         }
395
396         /* Give back the ISR semaphore, which should result in the priority being
397         disinherited as it was the last mutex held. */
398         if( xSemaphoreGive( xISRMutex ) != pdPASS )
399         {
400                 xErrorDetected = pdTRUE;
401         }
402
403         if( uxTaskPriorityGet( NULL ) != intsemMASTER_PRIORITY )
404         {
405                 xErrorDetected = pdTRUE;
406         }
407
408         /* Reset the mutex ready for the next round. */
409         xQueueReset( xISRMutex );
410 }
411 /*-----------------------------------------------------------*/
412
413 static void vInterruptMutexSlaveTask( void *pvParameters )
414 {
415         /* Just to avoid compiler warnings. */
416         ( void ) pvParameters;
417
418         for( ;; )
419         {
420                 /* This task starts by suspending itself so when it executes can be
421                 controlled by the master task. */
422                 vTaskSuspend( NULL );
423
424                 /* This task will execute when the master task already holds the mutex.
425                 Attempting to take the mutex will place this task in the Blocked
426                 state. */
427                 if( xSemaphoreTake( xMasterSlaveMutex, portMAX_DELAY ) != pdPASS )
428                 {
429                         xErrorDetected = pdTRUE;
430                 }
431
432                 if( xSemaphoreGive( xMasterSlaveMutex ) != pdPASS )
433                 {
434                         xErrorDetected = pdTRUE;
435                 }
436         }
437 }
438 /*-----------------------------------------------------------*/
439
440 static void vInterruptCountingSemaphoreTask( void *pvParameters )
441 {
442 BaseType_t xCount;
443 const TickType_t xDelay = pdMS_TO_TICKS( intsemINTERRUPT_MUTEX_GIVE_PERIOD_MS ) * ( intsemMAX_COUNT + 1 );
444
445         ( void ) pvParameters;
446
447         for( ;; )
448         {
449                 /* Expect to start with the counting semaphore empty. */
450                 if( uxQueueMessagesWaiting( ( QueueHandle_t ) xISRCountingSemaphore ) != 0 )
451                 {
452                         xErrorDetected = pdTRUE;
453                 }
454
455                 /* Wait until it is expected that the interrupt will have filled the
456                 counting semaphore. */
457                 xOkToGiveCountingSemaphore = pdTRUE;
458                 vTaskDelay( xDelay );
459                 xOkToGiveCountingSemaphore = pdFALSE;
460
461                 /* Now it is expected that the counting semaphore is full. */
462                 if( uxQueueMessagesWaiting( ( QueueHandle_t ) xISRCountingSemaphore ) != intsemMAX_COUNT )
463                 {
464                         xErrorDetected = pdTRUE;
465                 }
466
467                 if( uxQueueSpacesAvailable( ( QueueHandle_t ) xISRCountingSemaphore ) != 0 )
468                 {
469                         xErrorDetected = pdTRUE;
470                 }
471
472                 ulCountingSemaphoreLoops++;
473
474                 /* Expect to be able to take the counting semaphore intsemMAX_COUNT
475                 times.  A block time of 0 is used as the semaphore should already be
476                 there. */
477                 xCount = 0;
478                 while( xSemaphoreTake( xISRCountingSemaphore, 0 ) == pdPASS )
479                 {
480                         xCount++;
481                 }
482
483                 if( xCount != intsemMAX_COUNT )
484                 {
485                         xErrorDetected = pdTRUE;
486                 }
487
488                 /* Now raise the priority of this task so it runs immediately that the
489                 semaphore is given from the interrupt. */
490                 vTaskPrioritySet( NULL, configMAX_PRIORITIES - 1 );
491
492                 /* Block to wait for the semaphore to be given from the interrupt. */
493                 xOkToGiveCountingSemaphore = pdTRUE;
494                 xSemaphoreTake( xISRCountingSemaphore, portMAX_DELAY );
495                 xSemaphoreTake( xISRCountingSemaphore, portMAX_DELAY );
496                 xOkToGiveCountingSemaphore = pdFALSE;
497
498                 /* Reset the priority so as not to disturbe other tests too much. */
499                 vTaskPrioritySet( NULL, tskIDLE_PRIORITY );
500
501                 ulCountingSemaphoreLoops++;
502         }
503 }
504 /*-----------------------------------------------------------*/
505
506 void vInterruptSemaphorePeriodicTest( void )
507 {
508 static TickType_t xLastGiveTime = 0;
509 BaseType_t xHigherPriorityTaskWoken = pdFALSE;
510 TickType_t xTimeNow;
511
512         /* No mutual exclusion on xOkToGiveMutex, but this is only test code (and
513         only executed on a 32-bit architecture) so ignore that in this case. */
514         xTimeNow = xTaskGetTickCountFromISR();
515         if( ( ( TickType_t ) ( xTimeNow - xLastGiveTime ) ) >= pdMS_TO_TICKS( intsemINTERRUPT_MUTEX_GIVE_PERIOD_MS ) )
516         {
517                 configASSERT( xISRMutex );
518                 if( xOkToGiveMutex != pdFALSE )
519                 {
520                         /* Null is used as the second parameter in this give, and non-NULL
521                         in the other gives for code coverage reasons. */
522                         xSemaphoreGiveFromISR( xISRMutex, NULL );
523
524                         /* Second give attempt should fail. */
525                         configASSERT( xSemaphoreGiveFromISR( xISRMutex, &xHigherPriorityTaskWoken ) == pdFAIL );
526                 }
527
528                 if( xOkToGiveCountingSemaphore != pdFALSE )
529                 {
530                         xSemaphoreGiveFromISR( xISRCountingSemaphore, &xHigherPriorityTaskWoken );
531                 }
532                 xLastGiveTime = xTimeNow;
533         }
534
535         /* Remove compiler warnings about the value being set but not used. */
536         ( void ) xHigherPriorityTaskWoken;
537 }
538 /*-----------------------------------------------------------*/
539
540 /* This is called to check that all the created tasks are still running. */
541 BaseType_t xAreInterruptSemaphoreTasksStillRunning( void )
542 {
543 static uint32_t ulLastMasterLoopCounter = 0, ulLastCountingSemaphoreLoops = 0;
544
545         /* If the demo tasks are running then it is expected that the loop counters
546         will have changed since this function was last called. */
547         if( ulLastMasterLoopCounter == ulMasterLoops )
548         {
549                 xErrorDetected = pdTRUE;
550         }
551
552         ulLastMasterLoopCounter = ulMasterLoops;
553
554         if( ulLastCountingSemaphoreLoops == ulCountingSemaphoreLoops )
555         {
556                 xErrorDetected = pdTRUE;
557         }
558
559         ulLastCountingSemaphoreLoops = ulCountingSemaphoreLoops++;
560
561         /* Errors detected in the task itself will have latched xErrorDetected
562         to true. */
563
564         return ( BaseType_t ) !xErrorDetected;
565 }
566
567