1 /*
2  * FreeRTOS Kernel V11.0.1
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 is 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 = 0;
56     static TickType_t xCoRoutineTickCount = 0, xLastTickCount = 0, xPassedTicks = 0;
57 
58 /* The initial state of the co-routine when it is created. */
59     #define corINITIAL_STATE    ( 0 )
60 
61 /*
62  * Place the co-routine represented by pxCRCB into the appropriate ready queue
63  * for the priority.  It is inserted at the end of the list.
64  *
65  * This macro accesses the co-routine ready lists and therefore must not be
66  * used from within an ISR.
67  */
68     #define prvAddCoRoutineToReadyQueue( pxCRCB )                                                                               \
69     do {                                                                                                                        \
70         if( ( pxCRCB )->uxPriority > uxTopCoRoutineReadyPriority )                                                              \
71         {                                                                                                                       \
72             uxTopCoRoutineReadyPriority = ( pxCRCB )->uxPriority;                                                               \
73         }                                                                                                                       \
74         vListInsertEnd( ( List_t * ) &( pxReadyCoRoutineLists[ ( pxCRCB )->uxPriority ] ), &( ( pxCRCB )->xGenericListItem ) ); \
75     } while( 0 )
76 
77 /*
78  * Utility to ready all the lists used by the scheduler.  This is called
79  * automatically upon the creation of the first co-routine.
80  */
81     static void prvInitialiseCoRoutineLists( void );
82 
83 /*
84  * Co-routines that are readied by an interrupt cannot be placed directly into
85  * the ready lists (there is no mutual exclusion).  Instead they are placed in
86  * in the pending ready list in order that they can later be moved to the ready
87  * list by the co-routine scheduler.
88  */
89     static void prvCheckPendingReadyList( void );
90 
91 /*
92  * Macro that looks at the list of co-routines that are currently delayed to
93  * see if any require waking.
94  *
95  * Co-routines are stored in the queue in the order of their wake time -
96  * meaning once one co-routine has been found whose timer has not expired
97  * we need not look any further down the list.
98  */
99     static void prvCheckDelayedList( void );
100 
101 /*-----------------------------------------------------------*/
102 
xCoRoutineCreate(crCOROUTINE_CODE pxCoRoutineCode,UBaseType_t uxPriority,UBaseType_t uxIndex)103     BaseType_t xCoRoutineCreate( crCOROUTINE_CODE pxCoRoutineCode,
104                                  UBaseType_t uxPriority,
105                                  UBaseType_t uxIndex )
106     {
107         BaseType_t xReturn;
108         CRCB_t * pxCoRoutine;
109 
110         traceENTER_xCoRoutineCreate( pxCoRoutineCode, uxPriority, uxIndex );
111 
112         /* Allocate the memory that will store the co-routine control block. */
113         /* MISRA Ref 11.5.1 [Malloc memory assignment] */
114         /* More details at: https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/MISRA.md#rule-115 */
115         /* coverity[misra_c_2012_rule_11_5_violation] */
116         pxCoRoutine = ( CRCB_t * ) pvPortMalloc( sizeof( CRCB_t ) );
117 
118         if( pxCoRoutine )
119         {
120             /* If pxCurrentCoRoutine is NULL then this is the first co-routine to
121             * be created and the co-routine data structures need initialising. */
122             if( pxCurrentCoRoutine == NULL )
123             {
124                 pxCurrentCoRoutine = pxCoRoutine;
125                 prvInitialiseCoRoutineLists();
126             }
127 
128             /* Check the priority is within limits. */
129             if( uxPriority >= configMAX_CO_ROUTINE_PRIORITIES )
130             {
131                 uxPriority = configMAX_CO_ROUTINE_PRIORITIES - 1;
132             }
133 
134             /* Fill out the co-routine control block from the function parameters. */
135             pxCoRoutine->uxState = corINITIAL_STATE;
136             pxCoRoutine->uxPriority = uxPriority;
137             pxCoRoutine->uxIndex = uxIndex;
138             pxCoRoutine->pxCoRoutineFunction = pxCoRoutineCode;
139 
140             /* Initialise all the other co-routine control block parameters. */
141             vListInitialiseItem( &( pxCoRoutine->xGenericListItem ) );
142             vListInitialiseItem( &( pxCoRoutine->xEventListItem ) );
143 
144             /* Set the co-routine control block as a link back from the ListItem_t.
145              * This is so we can get back to the containing CRCB from a generic item
146              * in a list. */
147             listSET_LIST_ITEM_OWNER( &( pxCoRoutine->xGenericListItem ), pxCoRoutine );
148             listSET_LIST_ITEM_OWNER( &( pxCoRoutine->xEventListItem ), pxCoRoutine );
149 
150             /* Event lists are always in priority order. */
151             listSET_LIST_ITEM_VALUE( &( pxCoRoutine->xEventListItem ), ( ( TickType_t ) configMAX_CO_ROUTINE_PRIORITIES - ( TickType_t ) uxPriority ) );
152 
153             /* Now the co-routine has been initialised it can be added to the ready
154              * list at the correct priority. */
155             prvAddCoRoutineToReadyQueue( pxCoRoutine );
156 
157             xReturn = pdPASS;
158         }
159         else
160         {
161             xReturn = errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY;
162         }
163 
164         traceRETURN_xCoRoutineCreate( xReturn );
165 
166         return xReturn;
167     }
168 /*-----------------------------------------------------------*/
169 
vCoRoutineAddToDelayedList(TickType_t xTicksToDelay,List_t * pxEventList)170     void vCoRoutineAddToDelayedList( TickType_t xTicksToDelay,
171                                      List_t * pxEventList )
172     {
173         TickType_t xTimeToWake;
174 
175         traceENTER_vCoRoutineAddToDelayedList( xTicksToDelay, pxEventList );
176 
177         /* Calculate the time to wake - this may overflow but this is
178          * not a problem. */
179         xTimeToWake = xCoRoutineTickCount + xTicksToDelay;
180 
181         /* We must remove ourselves from the ready list before adding
182          * ourselves to the blocked list as the same list item is used for
183          * both lists. */
184         ( void ) uxListRemove( ( ListItem_t * ) &( pxCurrentCoRoutine->xGenericListItem ) );
185 
186         /* The list item will be inserted in wake time order. */
187         listSET_LIST_ITEM_VALUE( &( pxCurrentCoRoutine->xGenericListItem ), xTimeToWake );
188 
189         if( xTimeToWake < xCoRoutineTickCount )
190         {
191             /* Wake time has overflowed.  Place this item in the
192              * overflow list. */
193             vListInsert( ( List_t * ) pxOverflowDelayedCoRoutineList, ( ListItem_t * ) &( pxCurrentCoRoutine->xGenericListItem ) );
194         }
195         else
196         {
197             /* The wake time has not overflowed, so we can use the
198              * current block list. */
199             vListInsert( ( List_t * ) pxDelayedCoRoutineList, ( ListItem_t * ) &( pxCurrentCoRoutine->xGenericListItem ) );
200         }
201 
202         if( pxEventList )
203         {
204             /* Also add the co-routine to an event list.  If this is done then the
205              * function must be called with interrupts disabled. */
206             vListInsert( pxEventList, &( pxCurrentCoRoutine->xEventListItem ) );
207         }
208 
209         traceRETURN_vCoRoutineAddToDelayedList();
210     }
211 /*-----------------------------------------------------------*/
212 
prvCheckPendingReadyList(void)213     static void prvCheckPendingReadyList( void )
214     {
215         /* Are there any co-routines waiting to get moved to the ready list?  These
216          * are co-routines that have been readied by an ISR.  The ISR cannot access
217          * the ready lists itself. */
218         while( listLIST_IS_EMPTY( &xPendingReadyCoRoutineList ) == pdFALSE )
219         {
220             CRCB_t * pxUnblockedCRCB;
221 
222             /* The pending ready list can be accessed by an ISR. */
223             portDISABLE_INTERRUPTS();
224             {
225                 pxUnblockedCRCB = ( CRCB_t * ) listGET_OWNER_OF_HEAD_ENTRY( ( &xPendingReadyCoRoutineList ) );
226                 ( void ) uxListRemove( &( pxUnblockedCRCB->xEventListItem ) );
227             }
228             portENABLE_INTERRUPTS();
229 
230             ( void ) uxListRemove( &( pxUnblockedCRCB->xGenericListItem ) );
231             prvAddCoRoutineToReadyQueue( pxUnblockedCRCB );
232         }
233     }
234 /*-----------------------------------------------------------*/
235 
prvCheckDelayedList(void)236     static void prvCheckDelayedList( void )
237     {
238         CRCB_t * pxCRCB;
239 
240         xPassedTicks = xTaskGetTickCount() - xLastTickCount;
241 
242         while( xPassedTicks )
243         {
244             xCoRoutineTickCount++;
245             xPassedTicks--;
246 
247             /* If the tick count has overflowed we need to swap the ready lists. */
248             if( xCoRoutineTickCount == 0 )
249             {
250                 List_t * pxTemp;
251 
252                 /* Tick count has overflowed so we need to swap the delay lists.  If there are
253                  * any items in pxDelayedCoRoutineList here then there is an error! */
254                 pxTemp = pxDelayedCoRoutineList;
255                 pxDelayedCoRoutineList = pxOverflowDelayedCoRoutineList;
256                 pxOverflowDelayedCoRoutineList = pxTemp;
257             }
258 
259             /* See if this tick has made a timeout expire. */
260             while( listLIST_IS_EMPTY( pxDelayedCoRoutineList ) == pdFALSE )
261             {
262                 pxCRCB = ( CRCB_t * ) listGET_OWNER_OF_HEAD_ENTRY( pxDelayedCoRoutineList );
263 
264                 if( xCoRoutineTickCount < listGET_LIST_ITEM_VALUE( &( pxCRCB->xGenericListItem ) ) )
265                 {
266                     /* Timeout not yet expired. */
267                     break;
268                 }
269 
270                 portDISABLE_INTERRUPTS();
271                 {
272                     /* The event could have occurred just before this critical
273                      *  section.  If this is the case then the generic list item will
274                      *  have been moved to the pending ready list and the following
275                      *  line is still valid.  Also the pvContainer parameter will have
276                      *  been set to NULL so the following lines are also valid. */
277                     ( void ) uxListRemove( &( pxCRCB->xGenericListItem ) );
278 
279                     /* Is the co-routine waiting on an event also? */
280                     if( pxCRCB->xEventListItem.pxContainer )
281                     {
282                         ( void ) uxListRemove( &( pxCRCB->xEventListItem ) );
283                     }
284                 }
285                 portENABLE_INTERRUPTS();
286 
287                 prvAddCoRoutineToReadyQueue( pxCRCB );
288             }
289         }
290 
291         xLastTickCount = xCoRoutineTickCount;
292     }
293 /*-----------------------------------------------------------*/
294 
vCoRoutineSchedule(void)295     void vCoRoutineSchedule( void )
296     {
297         traceENTER_vCoRoutineSchedule();
298 
299         /* Only run a co-routine after prvInitialiseCoRoutineLists() has been
300          * called.  prvInitialiseCoRoutineLists() is called automatically when a
301          * co-routine is created. */
302         if( pxDelayedCoRoutineList != NULL )
303         {
304             /* See if any co-routines readied by events need moving to the ready lists. */
305             prvCheckPendingReadyList();
306 
307             /* See if any delayed co-routines have timed out. */
308             prvCheckDelayedList();
309 
310             /* Find the highest priority queue that contains ready co-routines. */
311             while( listLIST_IS_EMPTY( &( pxReadyCoRoutineLists[ uxTopCoRoutineReadyPriority ] ) ) )
312             {
313                 if( uxTopCoRoutineReadyPriority == 0 )
314                 {
315                     /* No more co-routines to check. */
316                     return;
317                 }
318 
319                 --uxTopCoRoutineReadyPriority;
320             }
321 
322             /* listGET_OWNER_OF_NEXT_ENTRY walks through the list, so the co-routines
323              * of the same priority get an equal share of the processor time. */
324             listGET_OWNER_OF_NEXT_ENTRY( pxCurrentCoRoutine, &( pxReadyCoRoutineLists[ uxTopCoRoutineReadyPriority ] ) );
325 
326             /* Call the co-routine. */
327             ( pxCurrentCoRoutine->pxCoRoutineFunction )( pxCurrentCoRoutine, pxCurrentCoRoutine->uxIndex );
328         }
329 
330         traceRETURN_vCoRoutineSchedule();
331     }
332 /*-----------------------------------------------------------*/
333 
prvInitialiseCoRoutineLists(void)334     static void prvInitialiseCoRoutineLists( void )
335     {
336         UBaseType_t uxPriority;
337 
338         for( uxPriority = 0; uxPriority < configMAX_CO_ROUTINE_PRIORITIES; uxPriority++ )
339         {
340             vListInitialise( ( List_t * ) &( pxReadyCoRoutineLists[ uxPriority ] ) );
341         }
342 
343         vListInitialise( ( List_t * ) &xDelayedCoRoutineList1 );
344         vListInitialise( ( List_t * ) &xDelayedCoRoutineList2 );
345         vListInitialise( ( List_t * ) &xPendingReadyCoRoutineList );
346 
347         /* Start with pxDelayedCoRoutineList using list1 and the
348          * pxOverflowDelayedCoRoutineList using list2. */
349         pxDelayedCoRoutineList = &xDelayedCoRoutineList1;
350         pxOverflowDelayedCoRoutineList = &xDelayedCoRoutineList2;
351     }
352 /*-----------------------------------------------------------*/
353 
xCoRoutineRemoveFromEventList(const List_t * pxEventList)354     BaseType_t xCoRoutineRemoveFromEventList( const List_t * pxEventList )
355     {
356         CRCB_t * pxUnblockedCRCB;
357         BaseType_t xReturn;
358 
359         traceENTER_xCoRoutineRemoveFromEventList( pxEventList );
360 
361         /* This function is called from within an interrupt.  It can only access
362          * event lists and the pending ready list.  This function assumes that a
363          * check has already been made to ensure pxEventList is not empty. */
364         pxUnblockedCRCB = ( CRCB_t * ) listGET_OWNER_OF_HEAD_ENTRY( pxEventList );
365         ( void ) uxListRemove( &( pxUnblockedCRCB->xEventListItem ) );
366         vListInsertEnd( ( List_t * ) &( xPendingReadyCoRoutineList ), &( pxUnblockedCRCB->xEventListItem ) );
367 
368         if( pxUnblockedCRCB->uxPriority >= pxCurrentCoRoutine->uxPriority )
369         {
370             xReturn = pdTRUE;
371         }
372         else
373         {
374             xReturn = pdFALSE;
375         }
376 
377         traceRETURN_xCoRoutineRemoveFromEventList( xReturn );
378 
379         return xReturn;
380     }
381 
382 #endif /* configUSE_CO_ROUTINES == 0 */
383