1 /*
2  * FreeRTOS Kernel V11.1.0
3  * Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
4  *
5  * SPDX-License-Identifier: MIT
6  *
7  * Permission is hereby granted, free of charge, to any person obtaining a copy of
8  * this software and associated documentation files (the "Software"), to deal in
9  * the Software without restriction, including without limitation the rights to
10  * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
11  * the Software, and to permit persons to whom the Software is furnished to do so,
12  * subject to the following conditions:
13  *
14  * The above copyright notice and this permission notice shall be included in all
15  * copies or substantial portions of the Software.
16  *
17  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
19  * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
20  * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
21  * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
22  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23  *
24  * https://www.FreeRTOS.org
25  * https://github.com/FreeRTOS
26  *
27  */
28 
29 #include "FreeRTOS.h"
30 #include "task.h"
31 #include "croutine.h"
32 
33 /* Remove the whole file if co-routines are not being used. */
34 #if ( configUSE_CO_ROUTINES != 0 )
35 
36 /*
37  * Some kernel aware debuggers require data to be viewed to be global, rather
38  * than file scope.
39  */
40     #ifdef portREMOVE_STATIC_QUALIFIER
41         #define static
42     #endif
43 
44 
45 /* Lists for ready and blocked co-routines. --------------------*/
46     static List_t pxReadyCoRoutineLists[ configMAX_CO_ROUTINE_PRIORITIES ]; /**< Prioritised ready co-routines. */
47     static List_t xDelayedCoRoutineList1;                                   /**< Delayed co-routines. */
48     static List_t xDelayedCoRoutineList2;                                   /**< Delayed co-routines (two lists are used - one for delays that have overflowed the current tick count. */
49     static List_t * pxDelayedCoRoutineList = NULL;                          /**< Points to the delayed co-routine list currently being used. */
50     static List_t * pxOverflowDelayedCoRoutineList = NULL;                  /**< Points to the delayed co-routine list currently being used to hold co-routines that have overflowed the current tick count. */
51     static List_t xPendingReadyCoRoutineList;                               /**< Holds co-routines that have been readied by an external event.  They cannot be added directly to the ready lists as the ready lists cannot be accessed by interrupts. */
52 
53 /* Other file private variables. --------------------------------*/
54     CRCB_t * pxCurrentCoRoutine = NULL;
55     static UBaseType_t uxTopCoRoutineReadyPriority = ( UBaseType_t ) 0U;
56     static TickType_t xCoRoutineTickCount = ( TickType_t ) 0U;
57     static TickType_t xLastTickCount = ( TickType_t ) 0U;
58     static TickType_t xPassedTicks = ( TickType_t ) 0U;
59 
60 /* The initial state of the co-routine when it is created. */
61     #define corINITIAL_STATE    ( 0 )
62 
63 /*
64  * Place the co-routine represented by pxCRCB into the appropriate ready queue
65  * for the priority.  It is inserted at the end of the list.
66  *
67  * This macro accesses the co-routine ready lists and therefore must not be
68  * used from within an ISR.
69  */
70     #define prvAddCoRoutineToReadyQueue( pxCRCB )                                                                               \
71     do {                                                                                                                        \
72         if( ( pxCRCB )->uxPriority > uxTopCoRoutineReadyPriority )                                                              \
73         {                                                                                                                       \
74             uxTopCoRoutineReadyPriority = ( pxCRCB )->uxPriority;                                                               \
75         }                                                                                                                       \
76         vListInsertEnd( ( List_t * ) &( pxReadyCoRoutineLists[ ( pxCRCB )->uxPriority ] ), &( ( pxCRCB )->xGenericListItem ) ); \
77     } while( 0 )
78 
79 /*
80  * Utility to ready all the lists used by the scheduler.  This is called
81  * automatically upon the creation of the first co-routine.
82  */
83     static void prvInitialiseCoRoutineLists( void );
84 
85 /*
86  * Co-routines that are readied by an interrupt cannot be placed directly into
87  * the ready lists (there is no mutual exclusion).  Instead they are placed in
88  * in the pending ready list in order that they can later be moved to the ready
89  * list by the co-routine scheduler.
90  */
91     static void prvCheckPendingReadyList( void );
92 
93 /*
94  * Macro that looks at the list of co-routines that are currently delayed to
95  * see if any require waking.
96  *
97  * Co-routines are stored in the queue in the order of their wake time -
98  * meaning once one co-routine has been found whose timer has not expired
99  * we need not look any further down the list.
100  */
101     static void prvCheckDelayedList( void );
102 
103 /*-----------------------------------------------------------*/
104 
xCoRoutineCreate(crCOROUTINE_CODE pxCoRoutineCode,UBaseType_t uxPriority,UBaseType_t uxIndex)105     BaseType_t xCoRoutineCreate( crCOROUTINE_CODE pxCoRoutineCode,
106                                  UBaseType_t uxPriority,
107                                  UBaseType_t uxIndex )
108     {
109         BaseType_t xReturn;
110         CRCB_t * pxCoRoutine;
111 
112         traceENTER_xCoRoutineCreate( pxCoRoutineCode, uxPriority, uxIndex );
113 
114         /* Allocate the memory that will store the co-routine control block. */
115         /* MISRA Ref 11.5.1 [Malloc memory assignment] */
116         /* More details at: https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/MISRA.md#rule-115 */
117         /* coverity[misra_c_2012_rule_11_5_violation] */
118         pxCoRoutine = ( CRCB_t * ) pvPortMalloc( sizeof( CRCB_t ) );
119 
120         if( pxCoRoutine )
121         {
122             /* If pxCurrentCoRoutine is NULL then this is the first co-routine to
123             * be created and the co-routine data structures need initialising. */
124             if( pxCurrentCoRoutine == NULL )
125             {
126                 pxCurrentCoRoutine = pxCoRoutine;
127                 prvInitialiseCoRoutineLists();
128             }
129 
130             /* Check the priority is within limits. */
131             if( uxPriority >= configMAX_CO_ROUTINE_PRIORITIES )
132             {
133                 uxPriority = configMAX_CO_ROUTINE_PRIORITIES - 1;
134             }
135 
136             /* Fill out the co-routine control block from the function parameters. */
137             pxCoRoutine->uxState = corINITIAL_STATE;
138             pxCoRoutine->uxPriority = uxPriority;
139             pxCoRoutine->uxIndex = uxIndex;
140             pxCoRoutine->pxCoRoutineFunction = pxCoRoutineCode;
141 
142             /* Initialise all the other co-routine control block parameters. */
143             vListInitialiseItem( &( pxCoRoutine->xGenericListItem ) );
144             vListInitialiseItem( &( pxCoRoutine->xEventListItem ) );
145 
146             /* Set the co-routine control block as a link back from the ListItem_t.
147              * This is so we can get back to the containing CRCB from a generic item
148              * in a list. */
149             listSET_LIST_ITEM_OWNER( &( pxCoRoutine->xGenericListItem ), pxCoRoutine );
150             listSET_LIST_ITEM_OWNER( &( pxCoRoutine->xEventListItem ), pxCoRoutine );
151 
152             /* Event lists are always in priority order. */
153             listSET_LIST_ITEM_VALUE( &( pxCoRoutine->xEventListItem ), ( ( TickType_t ) configMAX_CO_ROUTINE_PRIORITIES - ( TickType_t ) uxPriority ) );
154 
155             /* Now the co-routine has been initialised it can be added to the ready
156              * list at the correct priority. */
157             prvAddCoRoutineToReadyQueue( pxCoRoutine );
158 
159             xReturn = pdPASS;
160         }
161         else
162         {
163             xReturn = errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY;
164         }
165 
166         traceRETURN_xCoRoutineCreate( xReturn );
167 
168         return xReturn;
169     }
170 /*-----------------------------------------------------------*/
171 
vCoRoutineAddToDelayedList(TickType_t xTicksToDelay,List_t * pxEventList)172     void vCoRoutineAddToDelayedList( TickType_t xTicksToDelay,
173                                      List_t * pxEventList )
174     {
175         TickType_t xTimeToWake;
176 
177         traceENTER_vCoRoutineAddToDelayedList( xTicksToDelay, pxEventList );
178 
179         /* Calculate the time to wake - this may overflow but this is
180          * not a problem. */
181         xTimeToWake = xCoRoutineTickCount + xTicksToDelay;
182 
183         /* We must remove ourselves from the ready list before adding
184          * ourselves to the blocked list as the same list item is used for
185          * both lists. */
186         ( void ) uxListRemove( ( ListItem_t * ) &( pxCurrentCoRoutine->xGenericListItem ) );
187 
188         /* The list item will be inserted in wake time order. */
189         listSET_LIST_ITEM_VALUE( &( pxCurrentCoRoutine->xGenericListItem ), xTimeToWake );
190 
191         if( xTimeToWake < xCoRoutineTickCount )
192         {
193             /* Wake time has overflowed.  Place this item in the
194              * overflow list. */
195             vListInsert( ( List_t * ) pxOverflowDelayedCoRoutineList, ( ListItem_t * ) &( pxCurrentCoRoutine->xGenericListItem ) );
196         }
197         else
198         {
199             /* The wake time has not overflowed, so we can use the
200              * current block list. */
201             vListInsert( ( List_t * ) pxDelayedCoRoutineList, ( ListItem_t * ) &( pxCurrentCoRoutine->xGenericListItem ) );
202         }
203 
204         if( pxEventList )
205         {
206             /* Also add the co-routine to an event list.  If this is done then the
207              * function must be called with interrupts disabled. */
208             vListInsert( pxEventList, &( pxCurrentCoRoutine->xEventListItem ) );
209         }
210 
211         traceRETURN_vCoRoutineAddToDelayedList();
212     }
213 /*-----------------------------------------------------------*/
214 
prvCheckPendingReadyList(void)215     static void prvCheckPendingReadyList( void )
216     {
217         /* Are there any co-routines waiting to get moved to the ready list?  These
218          * are co-routines that have been readied by an ISR.  The ISR cannot access
219          * the ready lists itself. */
220         while( listLIST_IS_EMPTY( &xPendingReadyCoRoutineList ) == pdFALSE )
221         {
222             CRCB_t * pxUnblockedCRCB;
223 
224             /* The pending ready list can be accessed by an ISR. */
225             portDISABLE_INTERRUPTS();
226             {
227                 pxUnblockedCRCB = ( CRCB_t * ) listGET_OWNER_OF_HEAD_ENTRY( ( &xPendingReadyCoRoutineList ) );
228                 ( void ) uxListRemove( &( pxUnblockedCRCB->xEventListItem ) );
229             }
230             portENABLE_INTERRUPTS();
231 
232             ( void ) uxListRemove( &( pxUnblockedCRCB->xGenericListItem ) );
233             prvAddCoRoutineToReadyQueue( pxUnblockedCRCB );
234         }
235     }
236 /*-----------------------------------------------------------*/
237 
prvCheckDelayedList(void)238     static void prvCheckDelayedList( void )
239     {
240         CRCB_t * pxCRCB;
241 
242         xPassedTicks = xTaskGetTickCount() - xLastTickCount;
243 
244         while( xPassedTicks )
245         {
246             xCoRoutineTickCount++;
247             xPassedTicks--;
248 
249             /* If the tick count has overflowed we need to swap the ready lists. */
250             if( xCoRoutineTickCount == 0 )
251             {
252                 List_t * pxTemp;
253 
254                 /* Tick count has overflowed so we need to swap the delay lists.  If there are
255                  * any items in pxDelayedCoRoutineList here then there is an error! */
256                 pxTemp = pxDelayedCoRoutineList;
257                 pxDelayedCoRoutineList = pxOverflowDelayedCoRoutineList;
258                 pxOverflowDelayedCoRoutineList = pxTemp;
259             }
260 
261             /* See if this tick has made a timeout expire. */
262             while( listLIST_IS_EMPTY( pxDelayedCoRoutineList ) == pdFALSE )
263             {
264                 pxCRCB = ( CRCB_t * ) listGET_OWNER_OF_HEAD_ENTRY( pxDelayedCoRoutineList );
265 
266                 if( xCoRoutineTickCount < listGET_LIST_ITEM_VALUE( &( pxCRCB->xGenericListItem ) ) )
267                 {
268                     /* Timeout not yet expired. */
269                     break;
270                 }
271 
272                 portDISABLE_INTERRUPTS();
273                 {
274                     /* The event could have occurred just before this critical
275                      *  section.  If this is the case then the generic list item will
276                      *  have been moved to the pending ready list and the following
277                      *  line is still valid.  Also the pvContainer parameter will have
278                      *  been set to NULL so the following lines are also valid. */
279                     ( void ) uxListRemove( &( pxCRCB->xGenericListItem ) );
280 
281                     /* Is the co-routine waiting on an event also? */
282                     if( pxCRCB->xEventListItem.pxContainer )
283                     {
284                         ( void ) uxListRemove( &( pxCRCB->xEventListItem ) );
285                     }
286                 }
287                 portENABLE_INTERRUPTS();
288 
289                 prvAddCoRoutineToReadyQueue( pxCRCB );
290             }
291         }
292 
293         xLastTickCount = xCoRoutineTickCount;
294     }
295 /*-----------------------------------------------------------*/
296 
vCoRoutineSchedule(void)297     void vCoRoutineSchedule( void )
298     {
299         traceENTER_vCoRoutineSchedule();
300 
301         /* Only run a co-routine after prvInitialiseCoRoutineLists() has been
302          * called.  prvInitialiseCoRoutineLists() is called automatically when a
303          * co-routine is created. */
304         if( pxDelayedCoRoutineList != NULL )
305         {
306             /* See if any co-routines readied by events need moving to the ready lists. */
307             prvCheckPendingReadyList();
308 
309             /* See if any delayed co-routines have timed out. */
310             prvCheckDelayedList();
311 
312             /* Find the highest priority queue that contains ready co-routines. */
313             while( listLIST_IS_EMPTY( &( pxReadyCoRoutineLists[ uxTopCoRoutineReadyPriority ] ) ) )
314             {
315                 if( uxTopCoRoutineReadyPriority == 0 )
316                 {
317                     /* No more co-routines to check. */
318                     return;
319                 }
320 
321                 --uxTopCoRoutineReadyPriority;
322             }
323 
324             /* listGET_OWNER_OF_NEXT_ENTRY walks through the list, so the co-routines
325              * of the same priority get an equal share of the processor time. */
326             listGET_OWNER_OF_NEXT_ENTRY( pxCurrentCoRoutine, &( pxReadyCoRoutineLists[ uxTopCoRoutineReadyPriority ] ) );
327 
328             /* Call the co-routine. */
329             ( pxCurrentCoRoutine->pxCoRoutineFunction )( pxCurrentCoRoutine, pxCurrentCoRoutine->uxIndex );
330         }
331 
332         traceRETURN_vCoRoutineSchedule();
333     }
334 /*-----------------------------------------------------------*/
335 
prvInitialiseCoRoutineLists(void)336     static void prvInitialiseCoRoutineLists( void )
337     {
338         UBaseType_t uxPriority;
339 
340         for( uxPriority = 0; uxPriority < configMAX_CO_ROUTINE_PRIORITIES; uxPriority++ )
341         {
342             vListInitialise( ( List_t * ) &( pxReadyCoRoutineLists[ uxPriority ] ) );
343         }
344 
345         vListInitialise( ( List_t * ) &xDelayedCoRoutineList1 );
346         vListInitialise( ( List_t * ) &xDelayedCoRoutineList2 );
347         vListInitialise( ( List_t * ) &xPendingReadyCoRoutineList );
348 
349         /* Start with pxDelayedCoRoutineList using list1 and the
350          * pxOverflowDelayedCoRoutineList using list2. */
351         pxDelayedCoRoutineList = &xDelayedCoRoutineList1;
352         pxOverflowDelayedCoRoutineList = &xDelayedCoRoutineList2;
353     }
354 /*-----------------------------------------------------------*/
355 
xCoRoutineRemoveFromEventList(const List_t * pxEventList)356     BaseType_t xCoRoutineRemoveFromEventList( const List_t * pxEventList )
357     {
358         CRCB_t * pxUnblockedCRCB;
359         BaseType_t xReturn;
360 
361         traceENTER_xCoRoutineRemoveFromEventList( pxEventList );
362 
363         /* This function is called from within an interrupt.  It can only access
364          * event lists and the pending ready list.  This function assumes that a
365          * check has already been made to ensure pxEventList is not empty. */
366         pxUnblockedCRCB = ( CRCB_t * ) listGET_OWNER_OF_HEAD_ENTRY( pxEventList );
367         ( void ) uxListRemove( &( pxUnblockedCRCB->xEventListItem ) );
368         vListInsertEnd( ( List_t * ) &( xPendingReadyCoRoutineList ), &( pxUnblockedCRCB->xEventListItem ) );
369 
370         if( pxUnblockedCRCB->uxPriority >= pxCurrentCoRoutine->uxPriority )
371         {
372             xReturn = pdTRUE;
373         }
374         else
375         {
376             xReturn = pdFALSE;
377         }
378 
379         traceRETURN_xCoRoutineRemoveFromEventList( xReturn );
380 
381         return xReturn;
382     }
383 /*-----------------------------------------------------------*/
384 
385 /*
386  * Reset state in this file. This state is normally initialized at start up.
387  * This function must be called by the application before restarting the
388  * scheduler.
389  */
vCoRoutineResetState(void)390     void vCoRoutineResetState( void )
391     {
392         /* Lists for ready and blocked co-routines. */
393         pxDelayedCoRoutineList = NULL;
394         pxOverflowDelayedCoRoutineList = NULL;
395 
396         /* Other file private variables. */
397         pxCurrentCoRoutine = NULL;
398         uxTopCoRoutineReadyPriority = ( UBaseType_t ) 0U;
399         xCoRoutineTickCount = ( TickType_t ) 0U;
400         xLastTickCount = ( TickType_t ) 0U;
401         xPassedTicks = ( TickType_t ) 0U;
402     }
403 /*-----------------------------------------------------------*/
404 
405 #endif /* configUSE_CO_ROUTINES == 0 */
406