]> begriffs open source - freertos/blob - stream_buffer.c
Fix MISRA_C_2012 rule 20.7 violation (#843)
[freertos] / stream_buffer.c
1 /*
2  * FreeRTOS Kernel <DEVELOPMENT BRANCH>
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 /* Standard includes. */
30 #include <string.h>
31
32 /* Defining MPU_WRAPPERS_INCLUDED_FROM_API_FILE prevents task.h from redefining
33  * all the API functions to use the MPU wrappers.  That should only be done when
34  * task.h is included from an application file. */
35 #define MPU_WRAPPERS_INCLUDED_FROM_API_FILE
36
37 /* FreeRTOS includes. */
38 #include "FreeRTOS.h"
39 #include "task.h"
40 #include "stream_buffer.h"
41
42 #if ( configUSE_TASK_NOTIFICATIONS != 1 )
43     #error configUSE_TASK_NOTIFICATIONS must be set to 1 to build stream_buffer.c
44 #endif
45
46 #if ( INCLUDE_xTaskGetCurrentTaskHandle != 1 )
47     #error INCLUDE_xTaskGetCurrentTaskHandle must be set to 1 to build stream_buffer.c
48 #endif
49
50 /* Lint e961, e9021 and e750 are suppressed as a MISRA exception justified
51  * because the MPU ports require MPU_WRAPPERS_INCLUDED_FROM_API_FILE to be defined
52  * for the header files above, but not in this file, in order to generate the
53  * correct privileged Vs unprivileged linkage and placement. */
54 #undef MPU_WRAPPERS_INCLUDED_FROM_API_FILE /*lint !e961 !e750 !e9021. */
55
56 /* If the user has not provided application specific Rx notification macros,
57  * or #defined the notification macros away, then provide default implementations
58  * that uses task notifications. */
59 /*lint -save -e9026 Function like macros allowed and needed here so they can be overridden. */
60 #ifndef sbRECEIVE_COMPLETED
61     #define sbRECEIVE_COMPLETED( pxStreamBuffer )                         \
62     vTaskSuspendAll();                                                    \
63     {                                                                     \
64         if( ( pxStreamBuffer )->xTaskWaitingToSend != NULL )              \
65         {                                                                 \
66             ( void ) xTaskNotify( ( pxStreamBuffer )->xTaskWaitingToSend, \
67                                   ( uint32_t ) 0,                         \
68                                   eNoAction );                            \
69             ( pxStreamBuffer )->xTaskWaitingToSend = NULL;                \
70         }                                                                 \
71     }                                                                     \
72     ( void ) xTaskResumeAll()
73 #endif /* sbRECEIVE_COMPLETED */
74
75 /* If user has provided a per-instance receive complete callback, then
76  * invoke the callback else use the receive complete macro which is provided by default for all instances.
77  */
78 #if ( configUSE_SB_COMPLETED_CALLBACK == 1 )
79     #define prvRECEIVE_COMPLETED( pxStreamBuffer )                                               \
80     do {                                                                                         \
81         if( ( pxStreamBuffer )->pxReceiveCompletedCallback != NULL )                             \
82         {                                                                                        \
83             ( pxStreamBuffer )->pxReceiveCompletedCallback( ( pxStreamBuffer ), pdFALSE, NULL ); \
84         }                                                                                        \
85         else                                                                                     \
86         {                                                                                        \
87             sbRECEIVE_COMPLETED( ( pxStreamBuffer ) );                                           \
88         }                                                                                        \
89     } while( 0 )
90 #else /* if ( configUSE_SB_COMPLETED_CALLBACK == 1 ) */
91     #define prvRECEIVE_COMPLETED( pxStreamBuffer )    sbRECEIVE_COMPLETED( ( pxStreamBuffer ) )
92 #endif /* if ( configUSE_SB_COMPLETED_CALLBACK == 1 ) */
93
94 #ifndef sbRECEIVE_COMPLETED_FROM_ISR
95     #define sbRECEIVE_COMPLETED_FROM_ISR( pxStreamBuffer,                            \
96                                           pxHigherPriorityTaskWoken )                \
97     do {                                                                             \
98         UBaseType_t uxSavedInterruptStatus;                                          \
99                                                                                      \
100         uxSavedInterruptStatus = taskENTER_CRITICAL_FROM_ISR();                      \
101         {                                                                            \
102             if( ( pxStreamBuffer )->xTaskWaitingToSend != NULL )                     \
103             {                                                                        \
104                 ( void ) xTaskNotifyFromISR( ( pxStreamBuffer )->xTaskWaitingToSend, \
105                                              ( uint32_t ) 0,                         \
106                                              eNoAction,                              \
107                                              ( pxHigherPriorityTaskWoken ) );        \
108                 ( pxStreamBuffer )->xTaskWaitingToSend = NULL;                       \
109             }                                                                        \
110         }                                                                            \
111         taskEXIT_CRITICAL_FROM_ISR( uxSavedInterruptStatus );                        \
112     } while( 0 )
113 #endif /* sbRECEIVE_COMPLETED_FROM_ISR */
114
115 #if ( configUSE_SB_COMPLETED_CALLBACK == 1 )
116     #define prvRECEIVE_COMPLETED_FROM_ISR( pxStreamBuffer,                                                               \
117                                            pxHigherPriorityTaskWoken )                                                   \
118     do {                                                                                                                 \
119         if( ( pxStreamBuffer )->pxReceiveCompletedCallback != NULL )                                                     \
120         {                                                                                                                \
121             ( pxStreamBuffer )->pxReceiveCompletedCallback( ( pxStreamBuffer ), pdTRUE, ( pxHigherPriorityTaskWoken ) ); \
122         }                                                                                                                \
123         else                                                                                                             \
124         {                                                                                                                \
125             sbRECEIVE_COMPLETED_FROM_ISR( ( pxStreamBuffer ), ( pxHigherPriorityTaskWoken ) );                           \
126         }                                                                                                                \
127     } while( 0 )
128 #else /* if ( configUSE_SB_COMPLETED_CALLBACK == 1 ) */
129     #define prvRECEIVE_COMPLETED_FROM_ISR( pxStreamBuffer, pxHigherPriorityTaskWoken ) \
130     sbRECEIVE_COMPLETED_FROM_ISR( ( pxStreamBuffer ), ( pxHigherPriorityTaskWoken ) )
131 #endif /* if ( configUSE_SB_COMPLETED_CALLBACK == 1 ) */
132
133 /* If the user has not provided an application specific Tx notification macro,
134  * or #defined the notification macro away, then provide a default
135  * implementation that uses task notifications.
136  */
137 #ifndef sbSEND_COMPLETED
138     #define sbSEND_COMPLETED( pxStreamBuffer )                               \
139     vTaskSuspendAll();                                                       \
140     {                                                                        \
141         if( ( pxStreamBuffer )->xTaskWaitingToReceive != NULL )              \
142         {                                                                    \
143             ( void ) xTaskNotify( ( pxStreamBuffer )->xTaskWaitingToReceive, \
144                                   ( uint32_t ) 0,                            \
145                                   eNoAction );                               \
146             ( pxStreamBuffer )->xTaskWaitingToReceive = NULL;                \
147         }                                                                    \
148     }                                                                        \
149     ( void ) xTaskResumeAll()
150 #endif /* sbSEND_COMPLETED */
151
152 /* If user has provided a per-instance send completed callback, then
153  * invoke the callback else use the send complete macro which is provided by default for all instances.
154  */
155 #if ( configUSE_SB_COMPLETED_CALLBACK == 1 )
156     #define prvSEND_COMPLETED( pxStreamBuffer )                                               \
157     do {                                                                                      \
158         if( ( pxStreamBuffer )->pxSendCompletedCallback != NULL )                             \
159         {                                                                                     \
160             ( pxStreamBuffer )->pxSendCompletedCallback( ( pxStreamBuffer ), pdFALSE, NULL ); \
161         }                                                                                     \
162         else                                                                                  \
163         {                                                                                     \
164             sbSEND_COMPLETED( ( pxStreamBuffer ) );                                           \
165         }                                                                                     \
166     } while( 0 )
167 #else /* if ( configUSE_SB_COMPLETED_CALLBACK == 1 ) */
168     #define prvSEND_COMPLETED( pxStreamBuffer )    sbSEND_COMPLETED( ( pxStreamBuffer ) )
169 #endif /* if ( configUSE_SB_COMPLETED_CALLBACK == 1 ) */
170
171
172 #ifndef sbSEND_COMPLETE_FROM_ISR
173     #define sbSEND_COMPLETE_FROM_ISR( pxStreamBuffer, pxHigherPriorityTaskWoken )       \
174     do {                                                                                \
175         UBaseType_t uxSavedInterruptStatus;                                             \
176                                                                                         \
177         uxSavedInterruptStatus = taskENTER_CRITICAL_FROM_ISR();                         \
178         {                                                                               \
179             if( ( pxStreamBuffer )->xTaskWaitingToReceive != NULL )                     \
180             {                                                                           \
181                 ( void ) xTaskNotifyFromISR( ( pxStreamBuffer )->xTaskWaitingToReceive, \
182                                              ( uint32_t ) 0,                            \
183                                              eNoAction,                                 \
184                                              ( pxHigherPriorityTaskWoken ) );           \
185                 ( pxStreamBuffer )->xTaskWaitingToReceive = NULL;                       \
186             }                                                                           \
187         }                                                                               \
188         taskEXIT_CRITICAL_FROM_ISR( uxSavedInterruptStatus );                           \
189     } while( 0 )
190 #endif /* sbSEND_COMPLETE_FROM_ISR */
191
192
193 #if ( configUSE_SB_COMPLETED_CALLBACK == 1 )
194     #define prvSEND_COMPLETE_FROM_ISR( pxStreamBuffer, pxHigherPriorityTaskWoken )                                    \
195     do {                                                                                                              \
196         if( ( pxStreamBuffer )->pxSendCompletedCallback != NULL )                                                     \
197         {                                                                                                             \
198             ( pxStreamBuffer )->pxSendCompletedCallback( ( pxStreamBuffer ), pdTRUE, ( pxHigherPriorityTaskWoken ) ); \
199         }                                                                                                             \
200         else                                                                                                          \
201         {                                                                                                             \
202             sbSEND_COMPLETE_FROM_ISR( ( pxStreamBuffer ), ( pxHigherPriorityTaskWoken ) );                            \
203         }                                                                                                             \
204     } while( 0 )
205 #else /* if ( configUSE_SB_COMPLETED_CALLBACK == 1 ) */
206     #define prvSEND_COMPLETE_FROM_ISR( pxStreamBuffer, pxHigherPriorityTaskWoken ) \
207     sbSEND_COMPLETE_FROM_ISR( ( pxStreamBuffer ), ( pxHigherPriorityTaskWoken ) )
208 #endif /* if ( configUSE_SB_COMPLETED_CALLBACK == 1 ) */
209
210 /*lint -restore (9026) */
211
212 /* The number of bytes used to hold the length of a message in the buffer. */
213 #define sbBYTES_TO_STORE_MESSAGE_LENGTH    ( sizeof( configMESSAGE_BUFFER_LENGTH_TYPE ) )
214
215 /* Bits stored in the ucFlags field of the stream buffer. */
216 #define sbFLAGS_IS_MESSAGE_BUFFER          ( ( uint8_t ) 1 ) /* Set if the stream buffer was created as a message buffer, in which case it holds discrete messages rather than a stream. */
217 #define sbFLAGS_IS_STATICALLY_ALLOCATED    ( ( uint8_t ) 2 ) /* Set if the stream buffer was created using statically allocated memory. */
218
219 /*-----------------------------------------------------------*/
220
221 /* Structure that hold state information on the buffer. */
222 typedef struct StreamBufferDef_t                 /*lint !e9058 Style convention uses tag. */
223 {
224     volatile size_t xTail;                       /* Index to the next item to read within the buffer. */
225     volatile size_t xHead;                       /* Index to the next item to write within the buffer. */
226     size_t xLength;                              /* The length of the buffer pointed to by pucBuffer. */
227     size_t xTriggerLevelBytes;                   /* The number of bytes that must be in the stream buffer before a task that is waiting for data is unblocked. */
228     volatile TaskHandle_t xTaskWaitingToReceive; /* Holds the handle of a task waiting for data, or NULL if no tasks are waiting. */
229     volatile TaskHandle_t xTaskWaitingToSend;    /* Holds the handle of a task waiting to send data to a message buffer that is full. */
230     uint8_t * pucBuffer;                         /* Points to the buffer itself - that is - the RAM that stores the data passed through the buffer. */
231     uint8_t ucFlags;
232
233     #if ( configUSE_TRACE_FACILITY == 1 )
234         UBaseType_t uxStreamBufferNumber; /* Used for tracing purposes. */
235     #endif
236
237     #if ( configUSE_SB_COMPLETED_CALLBACK == 1 )
238         StreamBufferCallbackFunction_t pxSendCompletedCallback;    /* Optional callback called on send complete. sbSEND_COMPLETED is called if this is NULL. */
239         StreamBufferCallbackFunction_t pxReceiveCompletedCallback; /* Optional callback called on receive complete.  sbRECEIVE_COMPLETED is called if this is NULL. */
240     #endif
241 } StreamBuffer_t;
242
243 /*
244  * The number of bytes available to be read from the buffer.
245  */
246 static size_t prvBytesInBuffer( const StreamBuffer_t * const pxStreamBuffer ) PRIVILEGED_FUNCTION;
247
248 /*
249  * Add xCount bytes from pucData into the pxStreamBuffer's data storage area.
250  * This function does not update the buffer's xHead pointer, so multiple writes
251  * may be chained together "atomically". This is useful for Message Buffers where
252  * the length and data bytes are written in two separate chunks, and we don't want
253  * the reader to see the buffer as having grown until after all data is copied over.
254  * This function takes a custom xHead value to indicate where to write to (necessary
255  * for chaining) and returns the the resulting xHead position.
256  * To mark the write as complete, manually set the buffer's xHead field with the
257  * returned xHead from this function.
258  */
259 static size_t prvWriteBytesToBuffer( StreamBuffer_t * const pxStreamBuffer,
260                                      const uint8_t * pucData,
261                                      size_t xCount,
262                                      size_t xHead ) PRIVILEGED_FUNCTION;
263
264 /*
265  * If the stream buffer is being used as a message buffer, then reads an entire
266  * message out of the buffer.  If the stream buffer is being used as a stream
267  * buffer then read as many bytes as possible from the buffer.
268  * prvReadBytesFromBuffer() is called to actually extract the bytes from the
269  * buffer's data storage area.
270  */
271 static size_t prvReadMessageFromBuffer( StreamBuffer_t * pxStreamBuffer,
272                                         void * pvRxData,
273                                         size_t xBufferLengthBytes,
274                                         size_t xBytesAvailable ) PRIVILEGED_FUNCTION;
275
276 /*
277  * If the stream buffer is being used as a message buffer, then writes an entire
278  * message to the buffer.  If the stream buffer is being used as a stream
279  * buffer then write as many bytes as possible to the buffer.
280  * prvWriteBytestoBuffer() is called to actually send the bytes to the buffer's
281  * data storage area.
282  */
283 static size_t prvWriteMessageToBuffer( StreamBuffer_t * const pxStreamBuffer,
284                                        const void * pvTxData,
285                                        size_t xDataLengthBytes,
286                                        size_t xSpace,
287                                        size_t xRequiredSpace ) PRIVILEGED_FUNCTION;
288
289 /*
290  * Copies xCount bytes from the pxStreamBuffer's data storage area to pucData.
291  * This function does not update the buffer's xTail pointer, so multiple reads
292  * may be chained together "atomically". This is useful for Message Buffers where
293  * the length and data bytes are read in two separate chunks, and we don't want
294  * the writer to see the buffer as having more free space until after all data is
295  * copied over, especially if we have to abort the read due to insufficient receiving space.
296  * This function takes a custom xTail value to indicate where to read from (necessary
297  * for chaining) and returns the the resulting xTail position.
298  * To mark the read as complete, manually set the buffer's xTail field with the
299  * returned xTail from this function.
300  */
301 static size_t prvReadBytesFromBuffer( StreamBuffer_t * pxStreamBuffer,
302                                       uint8_t * pucData,
303                                       size_t xCount,
304                                       size_t xTail ) PRIVILEGED_FUNCTION;
305
306 /*
307  * Called by both pxStreamBufferCreate() and pxStreamBufferCreateStatic() to
308  * initialise the members of the newly created stream buffer structure.
309  */
310 static void prvInitialiseNewStreamBuffer( StreamBuffer_t * const pxStreamBuffer,
311                                           uint8_t * const pucBuffer,
312                                           size_t xBufferSizeBytes,
313                                           size_t xTriggerLevelBytes,
314                                           uint8_t ucFlags,
315                                           StreamBufferCallbackFunction_t pxSendCompletedCallback,
316                                           StreamBufferCallbackFunction_t pxReceiveCompletedCallback ) PRIVILEGED_FUNCTION;
317
318 /*-----------------------------------------------------------*/
319 #if ( configSUPPORT_DYNAMIC_ALLOCATION == 1 )
320     StreamBufferHandle_t xStreamBufferGenericCreate( size_t xBufferSizeBytes,
321                                                      size_t xTriggerLevelBytes,
322                                                      BaseType_t xIsMessageBuffer,
323                                                      StreamBufferCallbackFunction_t pxSendCompletedCallback,
324                                                      StreamBufferCallbackFunction_t pxReceiveCompletedCallback )
325     {
326         void * pvAllocatedMemory;
327         uint8_t ucFlags;
328
329         traceENTER_xStreamBufferGenericCreate( xBufferSizeBytes, xTriggerLevelBytes, xIsMessageBuffer, pxSendCompletedCallback, pxReceiveCompletedCallback );
330
331         /* In case the stream buffer is going to be used as a message buffer
332          * (that is, it will hold discrete messages with a little meta data that
333          * says how big the next message is) check the buffer will be large enough
334          * to hold at least one message. */
335         if( xIsMessageBuffer == pdTRUE )
336         {
337             /* Is a message buffer but not statically allocated. */
338             ucFlags = sbFLAGS_IS_MESSAGE_BUFFER;
339             configASSERT( xBufferSizeBytes > sbBYTES_TO_STORE_MESSAGE_LENGTH );
340         }
341         else
342         {
343             /* Not a message buffer and not statically allocated. */
344             ucFlags = 0;
345             configASSERT( xBufferSizeBytes > 0 );
346         }
347
348         configASSERT( xTriggerLevelBytes <= xBufferSizeBytes );
349
350         /* A trigger level of 0 would cause a waiting task to unblock even when
351          * the buffer was empty. */
352         if( xTriggerLevelBytes == ( size_t ) 0 )
353         {
354             xTriggerLevelBytes = ( size_t ) 1;
355         }
356
357         /* A stream buffer requires a StreamBuffer_t structure and a buffer.
358          * Both are allocated in a single call to pvPortMalloc().  The
359          * StreamBuffer_t structure is placed at the start of the allocated memory
360          * and the buffer follows immediately after.  The requested size is
361          * incremented so the free space is returned as the user would expect -
362          * this is a quirk of the implementation that means otherwise the free
363          * space would be reported as one byte smaller than would be logically
364          * expected. */
365         if( xBufferSizeBytes < ( xBufferSizeBytes + 1U + sizeof( StreamBuffer_t ) ) )
366         {
367             xBufferSizeBytes++;
368             pvAllocatedMemory = pvPortMalloc( xBufferSizeBytes + sizeof( StreamBuffer_t ) );
369         }
370         else
371         {
372             pvAllocatedMemory = NULL;
373         }
374
375         if( pvAllocatedMemory != NULL )
376         {
377             /* MISRA Ref 11.5.1 [Malloc memory assignment] */
378             /* More details at: https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/MISRA.md#rule-115 */
379             /* coverity[misra_c_2012_rule_11_5_violation] */
380             prvInitialiseNewStreamBuffer( ( StreamBuffer_t * ) pvAllocatedMemory,                         /* Structure at the start of the allocated memory. */
381                                                                                                           /* MISRA Ref 11.5.1 [Malloc memory assignment] */
382                                                                                                           /* More details at: https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/MISRA.md#rule-115 */
383                                                                                                           /* coverity[misra_c_2012_rule_11_5_violation] */
384                                           ( ( uint8_t * ) pvAllocatedMemory ) + sizeof( StreamBuffer_t ), /* Storage area follows. */
385                                           xBufferSizeBytes,
386                                           xTriggerLevelBytes,
387                                           ucFlags,
388                                           pxSendCompletedCallback,
389                                           pxReceiveCompletedCallback );
390
391             traceSTREAM_BUFFER_CREATE( ( ( StreamBuffer_t * ) pvAllocatedMemory ), xIsMessageBuffer );
392         }
393         else
394         {
395             traceSTREAM_BUFFER_CREATE_FAILED( xIsMessageBuffer );
396         }
397
398         traceRETURN_xStreamBufferGenericCreate( pvAllocatedMemory );
399
400         /* MISRA Ref 11.5.1 [Malloc memory assignment] */
401         /* More details at: https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/MISRA.md#rule-115 */
402         /* coverity[misra_c_2012_rule_11_5_violation] */
403         return ( StreamBufferHandle_t ) pvAllocatedMemory;
404     }
405 #endif /* configSUPPORT_DYNAMIC_ALLOCATION */
406 /*-----------------------------------------------------------*/
407
408 #if ( configSUPPORT_STATIC_ALLOCATION == 1 )
409
410     StreamBufferHandle_t xStreamBufferGenericCreateStatic( size_t xBufferSizeBytes,
411                                                            size_t xTriggerLevelBytes,
412                                                            BaseType_t xIsMessageBuffer,
413                                                            uint8_t * const pucStreamBufferStorageArea,
414                                                            StaticStreamBuffer_t * const pxStaticStreamBuffer,
415                                                            StreamBufferCallbackFunction_t pxSendCompletedCallback,
416                                                            StreamBufferCallbackFunction_t pxReceiveCompletedCallback )
417     {
418         /* MISRA Ref 11.3.1 [Misaligned access] */
419         /* More details at: https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/MISRA.md#rule-113 */
420         /* coverity[misra_c_2012_rule_11_3_violation] */
421         StreamBuffer_t * const pxStreamBuffer = ( StreamBuffer_t * ) pxStaticStreamBuffer;
422         StreamBufferHandle_t xReturn;
423         uint8_t ucFlags;
424
425         traceENTER_xStreamBufferGenericCreateStatic( xBufferSizeBytes, xTriggerLevelBytes, xIsMessageBuffer, pucStreamBufferStorageArea, pxStaticStreamBuffer, pxSendCompletedCallback, pxReceiveCompletedCallback );
426
427         configASSERT( pucStreamBufferStorageArea );
428         configASSERT( pxStaticStreamBuffer );
429         configASSERT( xTriggerLevelBytes <= xBufferSizeBytes );
430
431         /* A trigger level of 0 would cause a waiting task to unblock even when
432          * the buffer was empty. */
433         if( xTriggerLevelBytes == ( size_t ) 0 )
434         {
435             xTriggerLevelBytes = ( size_t ) 1;
436         }
437
438         /* In case the stream buffer is going to be used as a message buffer
439          * (that is, it will hold discrete messages with a little meta data that
440          * says how big the next message is) check the buffer will be large enough
441          * to hold at least one message. */
442
443         if( xIsMessageBuffer != pdFALSE )
444         {
445             /* Statically allocated message buffer. */
446             ucFlags = sbFLAGS_IS_MESSAGE_BUFFER | sbFLAGS_IS_STATICALLY_ALLOCATED;
447             configASSERT( xBufferSizeBytes > sbBYTES_TO_STORE_MESSAGE_LENGTH );
448         }
449         else
450         {
451             /* Statically allocated stream buffer. */
452             ucFlags = sbFLAGS_IS_STATICALLY_ALLOCATED;
453         }
454
455         #if ( configASSERT_DEFINED == 1 )
456         {
457             /* Sanity check that the size of the structure used to declare a
458              * variable of type StaticStreamBuffer_t equals the size of the real
459              * message buffer structure. */
460             volatile size_t xSize = sizeof( StaticStreamBuffer_t );
461             configASSERT( xSize == sizeof( StreamBuffer_t ) );
462         } /*lint !e529 xSize is referenced is configASSERT() is defined. */
463         #endif /* configASSERT_DEFINED */
464
465         if( ( pucStreamBufferStorageArea != NULL ) && ( pxStaticStreamBuffer != NULL ) )
466         {
467             prvInitialiseNewStreamBuffer( pxStreamBuffer,
468                                           pucStreamBufferStorageArea,
469                                           xBufferSizeBytes,
470                                           xTriggerLevelBytes,
471                                           ucFlags,
472                                           pxSendCompletedCallback,
473                                           pxReceiveCompletedCallback );
474
475             /* Remember this was statically allocated in case it is ever deleted
476              * again. */
477             pxStreamBuffer->ucFlags |= sbFLAGS_IS_STATICALLY_ALLOCATED;
478
479             traceSTREAM_BUFFER_CREATE( pxStreamBuffer, xIsMessageBuffer );
480
481             /* MISRA Ref 11.3.1 [Misaligned access] */
482             /* More details at: https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/MISRA.md#rule-113 */
483             /* coverity[misra_c_2012_rule_11_3_violation] */
484             xReturn = ( StreamBufferHandle_t ) pxStaticStreamBuffer;
485         }
486         else
487         {
488             xReturn = NULL;
489             traceSTREAM_BUFFER_CREATE_STATIC_FAILED( xReturn, xIsMessageBuffer );
490         }
491
492         traceRETURN_xStreamBufferGenericCreateStatic( xReturn );
493
494         return xReturn;
495     }
496 #endif /* ( configSUPPORT_STATIC_ALLOCATION == 1 ) */
497 /*-----------------------------------------------------------*/
498
499 #if ( configSUPPORT_STATIC_ALLOCATION == 1 )
500     BaseType_t xStreamBufferGetStaticBuffers( StreamBufferHandle_t xStreamBuffer,
501                                               uint8_t ** ppucStreamBufferStorageArea,
502                                               StaticStreamBuffer_t ** ppxStaticStreamBuffer )
503     {
504         BaseType_t xReturn;
505         StreamBuffer_t * const pxStreamBuffer = xStreamBuffer;
506
507         traceENTER_xStreamBufferGetStaticBuffers( xStreamBuffer, ppucStreamBufferStorageArea, ppxStaticStreamBuffer );
508
509         configASSERT( pxStreamBuffer );
510         configASSERT( ppucStreamBufferStorageArea );
511         configASSERT( ppxStaticStreamBuffer );
512
513         if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_STATICALLY_ALLOCATED ) != ( uint8_t ) 0 )
514         {
515             *ppucStreamBufferStorageArea = pxStreamBuffer->pucBuffer;
516             /* MISRA Ref 11.3.1 [Misaligned access] */
517             /* More details at: https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/MISRA.md#rule-113 */
518             /* coverity[misra_c_2012_rule_11_3_violation] */
519             *ppxStaticStreamBuffer = ( StaticStreamBuffer_t * ) pxStreamBuffer;
520             xReturn = pdTRUE;
521         }
522         else
523         {
524             xReturn = pdFALSE;
525         }
526
527         traceRETURN_xStreamBufferGetStaticBuffers( xReturn );
528
529         return xReturn;
530     }
531 #endif /* configSUPPORT_STATIC_ALLOCATION */
532 /*-----------------------------------------------------------*/
533
534 void vStreamBufferDelete( StreamBufferHandle_t xStreamBuffer )
535 {
536     StreamBuffer_t * pxStreamBuffer = xStreamBuffer;
537
538     traceENTER_vStreamBufferDelete( xStreamBuffer );
539
540     configASSERT( pxStreamBuffer );
541
542     traceSTREAM_BUFFER_DELETE( xStreamBuffer );
543
544     if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_STATICALLY_ALLOCATED ) == ( uint8_t ) pdFALSE )
545     {
546         #if ( configSUPPORT_DYNAMIC_ALLOCATION == 1 )
547         {
548             /* Both the structure and the buffer were allocated using a single call
549             * to pvPortMalloc(), hence only one call to vPortFree() is required. */
550             vPortFree( ( void * ) pxStreamBuffer ); /*lint !e9087 Standard free() semantics require void *, plus pxStreamBuffer was allocated by pvPortMalloc(). */
551         }
552         #else
553         {
554             /* Should not be possible to get here, ucFlags must be corrupt.
555              * Force an assert. */
556             configASSERT( xStreamBuffer == ( StreamBufferHandle_t ) ~0 );
557         }
558         #endif
559     }
560     else
561     {
562         /* The structure and buffer were not allocated dynamically and cannot be
563          * freed - just scrub the structure so future use will assert. */
564         ( void ) memset( pxStreamBuffer, 0x00, sizeof( StreamBuffer_t ) );
565     }
566
567     traceRETURN_vStreamBufferDelete();
568 }
569 /*-----------------------------------------------------------*/
570
571 BaseType_t xStreamBufferReset( StreamBufferHandle_t xStreamBuffer )
572 {
573     StreamBuffer_t * const pxStreamBuffer = xStreamBuffer;
574     BaseType_t xReturn = pdFAIL;
575     StreamBufferCallbackFunction_t pxSendCallback = NULL, pxReceiveCallback = NULL;
576
577     #if ( configUSE_TRACE_FACILITY == 1 )
578         UBaseType_t uxStreamBufferNumber;
579     #endif
580
581     traceENTER_xStreamBufferReset( xStreamBuffer );
582
583     configASSERT( pxStreamBuffer );
584
585     #if ( configUSE_TRACE_FACILITY == 1 )
586     {
587         /* Store the stream buffer number so it can be restored after the
588          * reset. */
589         uxStreamBufferNumber = pxStreamBuffer->uxStreamBufferNumber;
590     }
591     #endif
592
593     /* Can only reset a message buffer if there are no tasks blocked on it. */
594     taskENTER_CRITICAL();
595     {
596         if( ( pxStreamBuffer->xTaskWaitingToReceive == NULL ) && ( pxStreamBuffer->xTaskWaitingToSend == NULL ) )
597         {
598             #if ( configUSE_SB_COMPLETED_CALLBACK == 1 )
599             {
600                 pxSendCallback = pxStreamBuffer->pxSendCompletedCallback;
601                 pxReceiveCallback = pxStreamBuffer->pxReceiveCompletedCallback;
602             }
603             #endif
604
605             prvInitialiseNewStreamBuffer( pxStreamBuffer,
606                                           pxStreamBuffer->pucBuffer,
607                                           pxStreamBuffer->xLength,
608                                           pxStreamBuffer->xTriggerLevelBytes,
609                                           pxStreamBuffer->ucFlags,
610                                           pxSendCallback,
611                                           pxReceiveCallback );
612
613             #if ( configUSE_TRACE_FACILITY == 1 )
614             {
615                 pxStreamBuffer->uxStreamBufferNumber = uxStreamBufferNumber;
616             }
617             #endif
618
619             traceSTREAM_BUFFER_RESET( xStreamBuffer );
620
621             xReturn = pdPASS;
622         }
623     }
624     taskEXIT_CRITICAL();
625
626     traceRETURN_xStreamBufferReset( xReturn );
627
628     return xReturn;
629 }
630 /*-----------------------------------------------------------*/
631
632 BaseType_t xStreamBufferSetTriggerLevel( StreamBufferHandle_t xStreamBuffer,
633                                          size_t xTriggerLevel )
634 {
635     StreamBuffer_t * const pxStreamBuffer = xStreamBuffer;
636     BaseType_t xReturn;
637
638     traceENTER_xStreamBufferSetTriggerLevel( xStreamBuffer, xTriggerLevel );
639
640     configASSERT( pxStreamBuffer );
641
642     /* It is not valid for the trigger level to be 0. */
643     if( xTriggerLevel == ( size_t ) 0 )
644     {
645         xTriggerLevel = ( size_t ) 1;
646     }
647
648     /* The trigger level is the number of bytes that must be in the stream
649      * buffer before a task that is waiting for data is unblocked. */
650     if( xTriggerLevel < pxStreamBuffer->xLength )
651     {
652         pxStreamBuffer->xTriggerLevelBytes = xTriggerLevel;
653         xReturn = pdPASS;
654     }
655     else
656     {
657         xReturn = pdFALSE;
658     }
659
660     traceRETURN_xStreamBufferSetTriggerLevel( xReturn );
661
662     return xReturn;
663 }
664 /*-----------------------------------------------------------*/
665
666 size_t xStreamBufferSpacesAvailable( StreamBufferHandle_t xStreamBuffer )
667 {
668     const StreamBuffer_t * const pxStreamBuffer = xStreamBuffer;
669     size_t xSpace;
670     size_t xOriginalTail;
671
672     traceENTER_xStreamBufferSpacesAvailable( xStreamBuffer );
673
674     configASSERT( pxStreamBuffer );
675
676     /* The code below reads xTail and then xHead.  This is safe if the stream
677      * buffer is updated once between the two reads - but not if the stream buffer
678      * is updated more than once between the two reads - hence the loop. */
679     do
680     {
681         xOriginalTail = pxStreamBuffer->xTail;
682         xSpace = pxStreamBuffer->xLength + pxStreamBuffer->xTail;
683         xSpace -= pxStreamBuffer->xHead;
684     } while( xOriginalTail != pxStreamBuffer->xTail );
685
686     xSpace -= ( size_t ) 1;
687
688     if( xSpace >= pxStreamBuffer->xLength )
689     {
690         xSpace -= pxStreamBuffer->xLength;
691     }
692     else
693     {
694         mtCOVERAGE_TEST_MARKER();
695     }
696
697     traceRETURN_xStreamBufferSpacesAvailable( xSpace );
698
699     return xSpace;
700 }
701 /*-----------------------------------------------------------*/
702
703 size_t xStreamBufferBytesAvailable( StreamBufferHandle_t xStreamBuffer )
704 {
705     const StreamBuffer_t * const pxStreamBuffer = xStreamBuffer;
706     size_t xReturn;
707
708     traceENTER_xStreamBufferBytesAvailable( xStreamBuffer );
709
710     configASSERT( pxStreamBuffer );
711
712     xReturn = prvBytesInBuffer( pxStreamBuffer );
713
714     traceRETURN_xStreamBufferBytesAvailable( xReturn );
715
716     return xReturn;
717 }
718 /*-----------------------------------------------------------*/
719
720 size_t xStreamBufferSend( StreamBufferHandle_t xStreamBuffer,
721                           const void * pvTxData,
722                           size_t xDataLengthBytes,
723                           TickType_t xTicksToWait )
724 {
725     StreamBuffer_t * const pxStreamBuffer = xStreamBuffer;
726     size_t xReturn, xSpace = 0;
727     size_t xRequiredSpace = xDataLengthBytes;
728     TimeOut_t xTimeOut;
729     size_t xMaxReportedSpace = 0;
730
731     traceENTER_xStreamBufferSend( xStreamBuffer, pvTxData, xDataLengthBytes, xTicksToWait );
732
733     configASSERT( pvTxData );
734     configASSERT( pxStreamBuffer );
735
736     /* The maximum amount of space a stream buffer will ever report is its length
737      * minus 1. */
738     xMaxReportedSpace = pxStreamBuffer->xLength - ( size_t ) 1;
739
740     /* This send function is used to write to both message buffers and stream
741      * buffers.  If this is a message buffer then the space needed must be
742      * increased by the amount of bytes needed to store the length of the
743      * message. */
744     if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) != ( uint8_t ) 0 )
745     {
746         xRequiredSpace += sbBYTES_TO_STORE_MESSAGE_LENGTH;
747
748         /* Overflow? */
749         configASSERT( xRequiredSpace > xDataLengthBytes );
750
751         /* If this is a message buffer then it must be possible to write the
752          * whole message. */
753         if( xRequiredSpace > xMaxReportedSpace )
754         {
755             /* The message would not fit even if the entire buffer was empty,
756              * so don't wait for space. */
757             xTicksToWait = ( TickType_t ) 0;
758         }
759         else
760         {
761             mtCOVERAGE_TEST_MARKER();
762         }
763     }
764     else
765     {
766         /* If this is a stream buffer then it is acceptable to write only part
767          * of the message to the buffer.  Cap the length to the total length of
768          * the buffer. */
769         if( xRequiredSpace > xMaxReportedSpace )
770         {
771             xRequiredSpace = xMaxReportedSpace;
772         }
773         else
774         {
775             mtCOVERAGE_TEST_MARKER();
776         }
777     }
778
779     if( xTicksToWait != ( TickType_t ) 0 )
780     {
781         vTaskSetTimeOutState( &xTimeOut );
782
783         do
784         {
785             /* Wait until the required number of bytes are free in the message
786              * buffer. */
787             taskENTER_CRITICAL();
788             {
789                 xSpace = xStreamBufferSpacesAvailable( pxStreamBuffer );
790
791                 if( xSpace < xRequiredSpace )
792                 {
793                     /* Clear notification state as going to wait for space. */
794                     ( void ) xTaskNotifyStateClear( NULL );
795
796                     /* Should only be one writer. */
797                     configASSERT( pxStreamBuffer->xTaskWaitingToSend == NULL );
798                     pxStreamBuffer->xTaskWaitingToSend = xTaskGetCurrentTaskHandle();
799                 }
800                 else
801                 {
802                     taskEXIT_CRITICAL();
803                     break;
804                 }
805             }
806             taskEXIT_CRITICAL();
807
808             traceBLOCKING_ON_STREAM_BUFFER_SEND( xStreamBuffer );
809             ( void ) xTaskNotifyWait( ( uint32_t ) 0, ( uint32_t ) 0, NULL, xTicksToWait );
810             pxStreamBuffer->xTaskWaitingToSend = NULL;
811         } while( xTaskCheckForTimeOut( &xTimeOut, &xTicksToWait ) == pdFALSE );
812     }
813     else
814     {
815         mtCOVERAGE_TEST_MARKER();
816     }
817
818     if( xSpace == ( size_t ) 0 )
819     {
820         xSpace = xStreamBufferSpacesAvailable( pxStreamBuffer );
821     }
822     else
823     {
824         mtCOVERAGE_TEST_MARKER();
825     }
826
827     xReturn = prvWriteMessageToBuffer( pxStreamBuffer, pvTxData, xDataLengthBytes, xSpace, xRequiredSpace );
828
829     if( xReturn > ( size_t ) 0 )
830     {
831         traceSTREAM_BUFFER_SEND( xStreamBuffer, xReturn );
832
833         /* Was a task waiting for the data? */
834         if( prvBytesInBuffer( pxStreamBuffer ) >= pxStreamBuffer->xTriggerLevelBytes )
835         {
836             prvSEND_COMPLETED( pxStreamBuffer );
837         }
838         else
839         {
840             mtCOVERAGE_TEST_MARKER();
841         }
842     }
843     else
844     {
845         mtCOVERAGE_TEST_MARKER();
846         traceSTREAM_BUFFER_SEND_FAILED( xStreamBuffer );
847     }
848
849     traceRETURN_xStreamBufferSend( xReturn );
850
851     return xReturn;
852 }
853 /*-----------------------------------------------------------*/
854
855 size_t xStreamBufferSendFromISR( StreamBufferHandle_t xStreamBuffer,
856                                  const void * pvTxData,
857                                  size_t xDataLengthBytes,
858                                  BaseType_t * const pxHigherPriorityTaskWoken )
859 {
860     StreamBuffer_t * const pxStreamBuffer = xStreamBuffer;
861     size_t xReturn, xSpace;
862     size_t xRequiredSpace = xDataLengthBytes;
863
864     traceENTER_xStreamBufferSendFromISR( xStreamBuffer, pvTxData, xDataLengthBytes, pxHigherPriorityTaskWoken );
865
866     configASSERT( pvTxData );
867     configASSERT( pxStreamBuffer );
868
869     /* This send function is used to write to both message buffers and stream
870      * buffers.  If this is a message buffer then the space needed must be
871      * increased by the amount of bytes needed to store the length of the
872      * message. */
873     if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) != ( uint8_t ) 0 )
874     {
875         xRequiredSpace += sbBYTES_TO_STORE_MESSAGE_LENGTH;
876     }
877     else
878     {
879         mtCOVERAGE_TEST_MARKER();
880     }
881
882     xSpace = xStreamBufferSpacesAvailable( pxStreamBuffer );
883     xReturn = prvWriteMessageToBuffer( pxStreamBuffer, pvTxData, xDataLengthBytes, xSpace, xRequiredSpace );
884
885     if( xReturn > ( size_t ) 0 )
886     {
887         /* Was a task waiting for the data? */
888         if( prvBytesInBuffer( pxStreamBuffer ) >= pxStreamBuffer->xTriggerLevelBytes )
889         {
890             prvSEND_COMPLETE_FROM_ISR( pxStreamBuffer, pxHigherPriorityTaskWoken );
891         }
892         else
893         {
894             mtCOVERAGE_TEST_MARKER();
895         }
896     }
897     else
898     {
899         mtCOVERAGE_TEST_MARKER();
900     }
901
902     traceSTREAM_BUFFER_SEND_FROM_ISR( xStreamBuffer, xReturn );
903     traceRETURN_xStreamBufferSendFromISR( xReturn );
904
905     return xReturn;
906 }
907 /*-----------------------------------------------------------*/
908
909 static size_t prvWriteMessageToBuffer( StreamBuffer_t * const pxStreamBuffer,
910                                        const void * pvTxData,
911                                        size_t xDataLengthBytes,
912                                        size_t xSpace,
913                                        size_t xRequiredSpace )
914 {
915     size_t xNextHead = pxStreamBuffer->xHead;
916     configMESSAGE_BUFFER_LENGTH_TYPE xMessageLength;
917
918     if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) != ( uint8_t ) 0 )
919     {
920         /* This is a message buffer, as opposed to a stream buffer. */
921
922         /* Convert xDataLengthBytes to the message length type. */
923         xMessageLength = ( configMESSAGE_BUFFER_LENGTH_TYPE ) xDataLengthBytes;
924
925         /* Ensure the data length given fits within configMESSAGE_BUFFER_LENGTH_TYPE. */
926         configASSERT( ( size_t ) xMessageLength == xDataLengthBytes );
927
928         if( xSpace >= xRequiredSpace )
929         {
930             /* There is enough space to write both the message length and the message
931              * itself into the buffer.  Start by writing the length of the data, the data
932              * itself will be written later in this function. */
933             xNextHead = prvWriteBytesToBuffer( pxStreamBuffer, ( const uint8_t * ) &( xMessageLength ), sbBYTES_TO_STORE_MESSAGE_LENGTH, xNextHead );
934         }
935         else
936         {
937             /* Not enough space, so do not write data to the buffer. */
938             xDataLengthBytes = 0;
939         }
940     }
941     else
942     {
943         /* This is a stream buffer, as opposed to a message buffer, so writing a
944          * stream of bytes rather than discrete messages.  Plan to write as many
945          * bytes as possible. */
946         xDataLengthBytes = configMIN( xDataLengthBytes, xSpace );
947     }
948
949     if( xDataLengthBytes != ( size_t ) 0 )
950     {
951         /* Write the data to the buffer. */
952         /* MISRA Ref 11.5.5 [Void pointer assignment] */
953         /* More details at: https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/MISRA.md#rule-115 */
954         /* coverity[misra_c_2012_rule_11_5_violation] */
955         pxStreamBuffer->xHead = prvWriteBytesToBuffer( pxStreamBuffer, ( const uint8_t * ) pvTxData, xDataLengthBytes, xNextHead );
956     }
957
958     return xDataLengthBytes;
959 }
960 /*-----------------------------------------------------------*/
961
962 size_t xStreamBufferReceive( StreamBufferHandle_t xStreamBuffer,
963                              void * pvRxData,
964                              size_t xBufferLengthBytes,
965                              TickType_t xTicksToWait )
966 {
967     StreamBuffer_t * const pxStreamBuffer = xStreamBuffer;
968     size_t xReceivedLength = 0, xBytesAvailable, xBytesToStoreMessageLength;
969
970     traceENTER_xStreamBufferReceive( xStreamBuffer, pvRxData, xBufferLengthBytes, xTicksToWait );
971
972     configASSERT( pvRxData );
973     configASSERT( pxStreamBuffer );
974
975     /* This receive function is used by both message buffers, which store
976      * discrete messages, and stream buffers, which store a continuous stream of
977      * bytes.  Discrete messages include an additional
978      * sbBYTES_TO_STORE_MESSAGE_LENGTH bytes that hold the length of the
979      * message. */
980     if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) != ( uint8_t ) 0 )
981     {
982         xBytesToStoreMessageLength = sbBYTES_TO_STORE_MESSAGE_LENGTH;
983     }
984     else
985     {
986         xBytesToStoreMessageLength = 0;
987     }
988
989     if( xTicksToWait != ( TickType_t ) 0 )
990     {
991         /* Checking if there is data and clearing the notification state must be
992          * performed atomically. */
993         taskENTER_CRITICAL();
994         {
995             xBytesAvailable = prvBytesInBuffer( pxStreamBuffer );
996
997             /* If this function was invoked by a message buffer read then
998              * xBytesToStoreMessageLength holds the number of bytes used to hold
999              * the length of the next discrete message.  If this function was
1000              * invoked by a stream buffer read then xBytesToStoreMessageLength will
1001              * be 0. */
1002             if( xBytesAvailable <= xBytesToStoreMessageLength )
1003             {
1004                 /* Clear notification state as going to wait for data. */
1005                 ( void ) xTaskNotifyStateClear( NULL );
1006
1007                 /* Should only be one reader. */
1008                 configASSERT( pxStreamBuffer->xTaskWaitingToReceive == NULL );
1009                 pxStreamBuffer->xTaskWaitingToReceive = xTaskGetCurrentTaskHandle();
1010             }
1011             else
1012             {
1013                 mtCOVERAGE_TEST_MARKER();
1014             }
1015         }
1016         taskEXIT_CRITICAL();
1017
1018         if( xBytesAvailable <= xBytesToStoreMessageLength )
1019         {
1020             /* Wait for data to be available. */
1021             traceBLOCKING_ON_STREAM_BUFFER_RECEIVE( xStreamBuffer );
1022             ( void ) xTaskNotifyWait( ( uint32_t ) 0, ( uint32_t ) 0, NULL, xTicksToWait );
1023             pxStreamBuffer->xTaskWaitingToReceive = NULL;
1024
1025             /* Recheck the data available after blocking. */
1026             xBytesAvailable = prvBytesInBuffer( pxStreamBuffer );
1027         }
1028         else
1029         {
1030             mtCOVERAGE_TEST_MARKER();
1031         }
1032     }
1033     else
1034     {
1035         xBytesAvailable = prvBytesInBuffer( pxStreamBuffer );
1036     }
1037
1038     /* Whether receiving a discrete message (where xBytesToStoreMessageLength
1039      * holds the number of bytes used to store the message length) or a stream of
1040      * bytes (where xBytesToStoreMessageLength is zero), the number of bytes
1041      * available must be greater than xBytesToStoreMessageLength to be able to
1042      * read bytes from the buffer. */
1043     if( xBytesAvailable > xBytesToStoreMessageLength )
1044     {
1045         xReceivedLength = prvReadMessageFromBuffer( pxStreamBuffer, pvRxData, xBufferLengthBytes, xBytesAvailable );
1046
1047         /* Was a task waiting for space in the buffer? */
1048         if( xReceivedLength != ( size_t ) 0 )
1049         {
1050             traceSTREAM_BUFFER_RECEIVE( xStreamBuffer, xReceivedLength );
1051             prvRECEIVE_COMPLETED( xStreamBuffer );
1052         }
1053         else
1054         {
1055             mtCOVERAGE_TEST_MARKER();
1056         }
1057     }
1058     else
1059     {
1060         traceSTREAM_BUFFER_RECEIVE_FAILED( xStreamBuffer );
1061         mtCOVERAGE_TEST_MARKER();
1062     }
1063
1064     traceRETURN_xStreamBufferReceive( xReceivedLength );
1065
1066     return xReceivedLength;
1067 }
1068 /*-----------------------------------------------------------*/
1069
1070 size_t xStreamBufferNextMessageLengthBytes( StreamBufferHandle_t xStreamBuffer )
1071 {
1072     StreamBuffer_t * const pxStreamBuffer = xStreamBuffer;
1073     size_t xReturn, xBytesAvailable;
1074     configMESSAGE_BUFFER_LENGTH_TYPE xTempReturn;
1075
1076     traceENTER_xStreamBufferNextMessageLengthBytes( xStreamBuffer );
1077
1078     configASSERT( pxStreamBuffer );
1079
1080     /* Ensure the stream buffer is being used as a message buffer. */
1081     if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) != ( uint8_t ) 0 )
1082     {
1083         xBytesAvailable = prvBytesInBuffer( pxStreamBuffer );
1084
1085         if( xBytesAvailable > sbBYTES_TO_STORE_MESSAGE_LENGTH )
1086         {
1087             /* The number of bytes available is greater than the number of bytes
1088              * required to hold the length of the next message, so another message
1089              * is available. */
1090             ( void ) prvReadBytesFromBuffer( pxStreamBuffer, ( uint8_t * ) &xTempReturn, sbBYTES_TO_STORE_MESSAGE_LENGTH, pxStreamBuffer->xTail );
1091             xReturn = ( size_t ) xTempReturn;
1092         }
1093         else
1094         {
1095             /* The minimum amount of bytes in a message buffer is
1096              * ( sbBYTES_TO_STORE_MESSAGE_LENGTH + 1 ), so if xBytesAvailable is
1097              * less than sbBYTES_TO_STORE_MESSAGE_LENGTH the only other valid
1098              * value is 0. */
1099             configASSERT( xBytesAvailable == 0 );
1100             xReturn = 0;
1101         }
1102     }
1103     else
1104     {
1105         xReturn = 0;
1106     }
1107
1108     traceRETURN_xStreamBufferNextMessageLengthBytes( xReturn );
1109
1110     return xReturn;
1111 }
1112 /*-----------------------------------------------------------*/
1113
1114 size_t xStreamBufferReceiveFromISR( StreamBufferHandle_t xStreamBuffer,
1115                                     void * pvRxData,
1116                                     size_t xBufferLengthBytes,
1117                                     BaseType_t * const pxHigherPriorityTaskWoken )
1118 {
1119     StreamBuffer_t * const pxStreamBuffer = xStreamBuffer;
1120     size_t xReceivedLength = 0, xBytesAvailable, xBytesToStoreMessageLength;
1121
1122     traceENTER_xStreamBufferReceiveFromISR( xStreamBuffer, pvRxData, xBufferLengthBytes, pxHigherPriorityTaskWoken );
1123
1124     configASSERT( pvRxData );
1125     configASSERT( pxStreamBuffer );
1126
1127     /* This receive function is used by both message buffers, which store
1128      * discrete messages, and stream buffers, which store a continuous stream of
1129      * bytes.  Discrete messages include an additional
1130      * sbBYTES_TO_STORE_MESSAGE_LENGTH bytes that hold the length of the
1131      * message. */
1132     if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) != ( uint8_t ) 0 )
1133     {
1134         xBytesToStoreMessageLength = sbBYTES_TO_STORE_MESSAGE_LENGTH;
1135     }
1136     else
1137     {
1138         xBytesToStoreMessageLength = 0;
1139     }
1140
1141     xBytesAvailable = prvBytesInBuffer( pxStreamBuffer );
1142
1143     /* Whether receiving a discrete message (where xBytesToStoreMessageLength
1144      * holds the number of bytes used to store the message length) or a stream of
1145      * bytes (where xBytesToStoreMessageLength is zero), the number of bytes
1146      * available must be greater than xBytesToStoreMessageLength to be able to
1147      * read bytes from the buffer. */
1148     if( xBytesAvailable > xBytesToStoreMessageLength )
1149     {
1150         xReceivedLength = prvReadMessageFromBuffer( pxStreamBuffer, pvRxData, xBufferLengthBytes, xBytesAvailable );
1151
1152         /* Was a task waiting for space in the buffer? */
1153         if( xReceivedLength != ( size_t ) 0 )
1154         {
1155             prvRECEIVE_COMPLETED_FROM_ISR( pxStreamBuffer, pxHigherPriorityTaskWoken );
1156         }
1157         else
1158         {
1159             mtCOVERAGE_TEST_MARKER();
1160         }
1161     }
1162     else
1163     {
1164         mtCOVERAGE_TEST_MARKER();
1165     }
1166
1167     traceSTREAM_BUFFER_RECEIVE_FROM_ISR( xStreamBuffer, xReceivedLength );
1168     traceRETURN_xStreamBufferReceiveFromISR( xReceivedLength );
1169
1170     return xReceivedLength;
1171 }
1172 /*-----------------------------------------------------------*/
1173
1174 static size_t prvReadMessageFromBuffer( StreamBuffer_t * pxStreamBuffer,
1175                                         void * pvRxData,
1176                                         size_t xBufferLengthBytes,
1177                                         size_t xBytesAvailable )
1178 {
1179     size_t xCount, xNextMessageLength;
1180     configMESSAGE_BUFFER_LENGTH_TYPE xTempNextMessageLength;
1181     size_t xNextTail = pxStreamBuffer->xTail;
1182
1183     if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) != ( uint8_t ) 0 )
1184     {
1185         /* A discrete message is being received.  First receive the length
1186          * of the message. */
1187         xNextTail = prvReadBytesFromBuffer( pxStreamBuffer, ( uint8_t * ) &xTempNextMessageLength, sbBYTES_TO_STORE_MESSAGE_LENGTH, xNextTail );
1188         xNextMessageLength = ( size_t ) xTempNextMessageLength;
1189
1190         /* Reduce the number of bytes available by the number of bytes just
1191          * read out. */
1192         xBytesAvailable -= sbBYTES_TO_STORE_MESSAGE_LENGTH;
1193
1194         /* Check there is enough space in the buffer provided by the
1195          * user. */
1196         if( xNextMessageLength > xBufferLengthBytes )
1197         {
1198             /* The user has provided insufficient space to read the message. */
1199             xNextMessageLength = 0;
1200         }
1201         else
1202         {
1203             mtCOVERAGE_TEST_MARKER();
1204         }
1205     }
1206     else
1207     {
1208         /* A stream of bytes is being received (as opposed to a discrete
1209          * message), so read as many bytes as possible. */
1210         xNextMessageLength = xBufferLengthBytes;
1211     }
1212
1213     /* Use the minimum of the wanted bytes and the available bytes. */
1214     xCount = configMIN( xNextMessageLength, xBytesAvailable );
1215
1216     if( xCount != ( size_t ) 0 )
1217     {
1218         /* Read the actual data and update the tail to mark the data as officially consumed. */
1219         /* MISRA Ref 11.5.5 [Void pointer assignment] */
1220         /* More details at: https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/MISRA.md#rule-115 */
1221         /* coverity[misra_c_2012_rule_11_5_violation] */
1222         pxStreamBuffer->xTail = prvReadBytesFromBuffer( pxStreamBuffer, ( uint8_t * ) pvRxData, xCount, xNextTail );
1223     }
1224
1225     return xCount;
1226 }
1227 /*-----------------------------------------------------------*/
1228
1229 BaseType_t xStreamBufferIsEmpty( StreamBufferHandle_t xStreamBuffer )
1230 {
1231     const StreamBuffer_t * const pxStreamBuffer = xStreamBuffer;
1232     BaseType_t xReturn;
1233     size_t xTail;
1234
1235     traceENTER_xStreamBufferIsEmpty( xStreamBuffer );
1236
1237     configASSERT( pxStreamBuffer );
1238
1239     /* True if no bytes are available. */
1240     xTail = pxStreamBuffer->xTail;
1241
1242     if( pxStreamBuffer->xHead == xTail )
1243     {
1244         xReturn = pdTRUE;
1245     }
1246     else
1247     {
1248         xReturn = pdFALSE;
1249     }
1250
1251     traceRETURN_xStreamBufferIsEmpty( xReturn );
1252
1253     return xReturn;
1254 }
1255 /*-----------------------------------------------------------*/
1256
1257 BaseType_t xStreamBufferIsFull( StreamBufferHandle_t xStreamBuffer )
1258 {
1259     BaseType_t xReturn;
1260     size_t xBytesToStoreMessageLength;
1261     const StreamBuffer_t * const pxStreamBuffer = xStreamBuffer;
1262
1263     traceENTER_xStreamBufferIsFull( xStreamBuffer );
1264
1265     configASSERT( pxStreamBuffer );
1266
1267     /* This generic version of the receive function is used by both message
1268      * buffers, which store discrete messages, and stream buffers, which store a
1269      * continuous stream of bytes.  Discrete messages include an additional
1270      * sbBYTES_TO_STORE_MESSAGE_LENGTH bytes that hold the length of the message. */
1271     if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) != ( uint8_t ) 0 )
1272     {
1273         xBytesToStoreMessageLength = sbBYTES_TO_STORE_MESSAGE_LENGTH;
1274     }
1275     else
1276     {
1277         xBytesToStoreMessageLength = 0;
1278     }
1279
1280     /* True if the available space equals zero. */
1281     if( xStreamBufferSpacesAvailable( xStreamBuffer ) <= xBytesToStoreMessageLength )
1282     {
1283         xReturn = pdTRUE;
1284     }
1285     else
1286     {
1287         xReturn = pdFALSE;
1288     }
1289
1290     traceRETURN_xStreamBufferIsFull( xReturn );
1291
1292     return xReturn;
1293 }
1294 /*-----------------------------------------------------------*/
1295
1296 BaseType_t xStreamBufferSendCompletedFromISR( StreamBufferHandle_t xStreamBuffer,
1297                                               BaseType_t * pxHigherPriorityTaskWoken )
1298 {
1299     StreamBuffer_t * const pxStreamBuffer = xStreamBuffer;
1300     BaseType_t xReturn;
1301     UBaseType_t uxSavedInterruptStatus;
1302
1303     traceENTER_xStreamBufferSendCompletedFromISR( xStreamBuffer, pxHigherPriorityTaskWoken );
1304
1305     configASSERT( pxStreamBuffer );
1306
1307     uxSavedInterruptStatus = taskENTER_CRITICAL_FROM_ISR();
1308     {
1309         if( ( pxStreamBuffer )->xTaskWaitingToReceive != NULL )
1310         {
1311             ( void ) xTaskNotifyFromISR( ( pxStreamBuffer )->xTaskWaitingToReceive,
1312                                          ( uint32_t ) 0,
1313                                          eNoAction,
1314                                          pxHigherPriorityTaskWoken );
1315             ( pxStreamBuffer )->xTaskWaitingToReceive = NULL;
1316             xReturn = pdTRUE;
1317         }
1318         else
1319         {
1320             xReturn = pdFALSE;
1321         }
1322     }
1323     taskEXIT_CRITICAL_FROM_ISR( uxSavedInterruptStatus );
1324
1325     traceRETURN_xStreamBufferSendCompletedFromISR( xReturn );
1326
1327     return xReturn;
1328 }
1329 /*-----------------------------------------------------------*/
1330
1331 BaseType_t xStreamBufferReceiveCompletedFromISR( StreamBufferHandle_t xStreamBuffer,
1332                                                  BaseType_t * pxHigherPriorityTaskWoken )
1333 {
1334     StreamBuffer_t * const pxStreamBuffer = xStreamBuffer;
1335     BaseType_t xReturn;
1336     UBaseType_t uxSavedInterruptStatus;
1337
1338     traceENTER_xStreamBufferReceiveCompletedFromISR( xStreamBuffer, pxHigherPriorityTaskWoken );
1339
1340     configASSERT( pxStreamBuffer );
1341
1342     uxSavedInterruptStatus = taskENTER_CRITICAL_FROM_ISR();
1343     {
1344         if( ( pxStreamBuffer )->xTaskWaitingToSend != NULL )
1345         {
1346             ( void ) xTaskNotifyFromISR( ( pxStreamBuffer )->xTaskWaitingToSend,
1347                                          ( uint32_t ) 0,
1348                                          eNoAction,
1349                                          pxHigherPriorityTaskWoken );
1350             ( pxStreamBuffer )->xTaskWaitingToSend = NULL;
1351             xReturn = pdTRUE;
1352         }
1353         else
1354         {
1355             xReturn = pdFALSE;
1356         }
1357     }
1358     taskEXIT_CRITICAL_FROM_ISR( uxSavedInterruptStatus );
1359
1360     traceRETURN_xStreamBufferReceiveCompletedFromISR( xReturn );
1361
1362     return xReturn;
1363 }
1364 /*-----------------------------------------------------------*/
1365
1366 static size_t prvWriteBytesToBuffer( StreamBuffer_t * const pxStreamBuffer,
1367                                      const uint8_t * pucData,
1368                                      size_t xCount,
1369                                      size_t xHead )
1370 {
1371     size_t xFirstLength;
1372
1373     configASSERT( xCount > ( size_t ) 0 );
1374
1375     /* Calculate the number of bytes that can be added in the first write -
1376      * which may be less than the total number of bytes that need to be added if
1377      * the buffer will wrap back to the beginning. */
1378     xFirstLength = configMIN( pxStreamBuffer->xLength - xHead, xCount );
1379
1380     /* Write as many bytes as can be written in the first write. */
1381     configASSERT( ( xHead + xFirstLength ) <= pxStreamBuffer->xLength );
1382     ( void ) memcpy( ( void * ) ( &( pxStreamBuffer->pucBuffer[ xHead ] ) ), ( const void * ) pucData, xFirstLength ); /*lint !e9087 memcpy() requires void *. */
1383
1384     /* If the number of bytes written was less than the number that could be
1385      * written in the first write... */
1386     if( xCount > xFirstLength )
1387     {
1388         /* ...then write the remaining bytes to the start of the buffer. */
1389         configASSERT( ( xCount - xFirstLength ) <= pxStreamBuffer->xLength );
1390         ( void ) memcpy( ( void * ) pxStreamBuffer->pucBuffer, ( const void * ) &( pucData[ xFirstLength ] ), xCount - xFirstLength ); /*lint !e9087 memcpy() requires void *. */
1391     }
1392     else
1393     {
1394         mtCOVERAGE_TEST_MARKER();
1395     }
1396
1397     xHead += xCount;
1398
1399     if( xHead >= pxStreamBuffer->xLength )
1400     {
1401         xHead -= pxStreamBuffer->xLength;
1402     }
1403     else
1404     {
1405         mtCOVERAGE_TEST_MARKER();
1406     }
1407
1408     return xHead;
1409 }
1410 /*-----------------------------------------------------------*/
1411
1412 static size_t prvReadBytesFromBuffer( StreamBuffer_t * pxStreamBuffer,
1413                                       uint8_t * pucData,
1414                                       size_t xCount,
1415                                       size_t xTail )
1416 {
1417     size_t xFirstLength;
1418
1419     configASSERT( xCount != ( size_t ) 0 );
1420
1421     /* Calculate the number of bytes that can be read - which may be
1422      * less than the number wanted if the data wraps around to the start of
1423      * the buffer. */
1424     xFirstLength = configMIN( pxStreamBuffer->xLength - xTail, xCount );
1425
1426     /* Obtain the number of bytes it is possible to obtain in the first
1427      * read.  Asserts check bounds of read and write. */
1428     configASSERT( xFirstLength <= xCount );
1429     configASSERT( ( xTail + xFirstLength ) <= pxStreamBuffer->xLength );
1430     ( void ) memcpy( ( void * ) pucData, ( const void * ) &( pxStreamBuffer->pucBuffer[ xTail ] ), xFirstLength ); /*lint !e9087 memcpy() requires void *. */
1431
1432     /* If the total number of wanted bytes is greater than the number
1433      * that could be read in the first read... */
1434     if( xCount > xFirstLength )
1435     {
1436         /* ...then read the remaining bytes from the start of the buffer. */
1437         ( void ) memcpy( ( void * ) &( pucData[ xFirstLength ] ), ( void * ) ( pxStreamBuffer->pucBuffer ), xCount - xFirstLength ); /*lint !e9087 memcpy() requires void *. */
1438     }
1439     else
1440     {
1441         mtCOVERAGE_TEST_MARKER();
1442     }
1443
1444     /* Move the tail pointer to effectively remove the data read from the buffer. */
1445     xTail += xCount;
1446
1447     if( xTail >= pxStreamBuffer->xLength )
1448     {
1449         xTail -= pxStreamBuffer->xLength;
1450     }
1451
1452     return xTail;
1453 }
1454 /*-----------------------------------------------------------*/
1455
1456 static size_t prvBytesInBuffer( const StreamBuffer_t * const pxStreamBuffer )
1457 {
1458 /* Returns the distance between xTail and xHead. */
1459     size_t xCount;
1460
1461     xCount = pxStreamBuffer->xLength + pxStreamBuffer->xHead;
1462     xCount -= pxStreamBuffer->xTail;
1463
1464     if( xCount >= pxStreamBuffer->xLength )
1465     {
1466         xCount -= pxStreamBuffer->xLength;
1467     }
1468     else
1469     {
1470         mtCOVERAGE_TEST_MARKER();
1471     }
1472
1473     return xCount;
1474 }
1475 /*-----------------------------------------------------------*/
1476
1477 static void prvInitialiseNewStreamBuffer( StreamBuffer_t * const pxStreamBuffer,
1478                                           uint8_t * const pucBuffer,
1479                                           size_t xBufferSizeBytes,
1480                                           size_t xTriggerLevelBytes,
1481                                           uint8_t ucFlags,
1482                                           StreamBufferCallbackFunction_t pxSendCompletedCallback,
1483                                           StreamBufferCallbackFunction_t pxReceiveCompletedCallback )
1484 {
1485     /* Assert here is deliberately writing to the entire buffer to ensure it can
1486      * be written to without generating exceptions, and is setting the buffer to a
1487      * known value to assist in development/debugging. */
1488     #if ( configASSERT_DEFINED == 1 )
1489     {
1490         /* The value written just has to be identifiable when looking at the
1491          * memory.  Don't use 0xA5 as that is the stack fill value and could
1492          * result in confusion as to what is actually being observed. */
1493     #define STREAM_BUFFER_BUFFER_WRITE_VALUE    ( 0x55 )
1494         configASSERT( memset( pucBuffer, ( int ) STREAM_BUFFER_BUFFER_WRITE_VALUE, xBufferSizeBytes ) == pucBuffer );
1495     }
1496     #endif
1497
1498     ( void ) memset( ( void * ) pxStreamBuffer, 0x00, sizeof( StreamBuffer_t ) ); /*lint !e9087 memset() requires void *. */
1499     pxStreamBuffer->pucBuffer = pucBuffer;
1500     pxStreamBuffer->xLength = xBufferSizeBytes;
1501     pxStreamBuffer->xTriggerLevelBytes = xTriggerLevelBytes;
1502     pxStreamBuffer->ucFlags = ucFlags;
1503     #if ( configUSE_SB_COMPLETED_CALLBACK == 1 )
1504     {
1505         pxStreamBuffer->pxSendCompletedCallback = pxSendCompletedCallback;
1506         pxStreamBuffer->pxReceiveCompletedCallback = pxReceiveCompletedCallback;
1507     }
1508     #else
1509     {
1510         ( void ) pxSendCompletedCallback;
1511         ( void ) pxReceiveCompletedCallback;
1512     }
1513     #endif
1514 }
1515
1516 #if ( configUSE_TRACE_FACILITY == 1 )
1517
1518     UBaseType_t uxStreamBufferGetStreamBufferNumber( StreamBufferHandle_t xStreamBuffer )
1519     {
1520         traceENTER_uxStreamBufferGetStreamBufferNumber( xStreamBuffer );
1521
1522         traceRETURN_uxStreamBufferGetStreamBufferNumber( xStreamBuffer->uxStreamBufferNumber );
1523
1524         return xStreamBuffer->uxStreamBufferNumber;
1525     }
1526
1527 #endif /* configUSE_TRACE_FACILITY */
1528 /*-----------------------------------------------------------*/
1529
1530 #if ( configUSE_TRACE_FACILITY == 1 )
1531
1532     void vStreamBufferSetStreamBufferNumber( StreamBufferHandle_t xStreamBuffer,
1533                                              UBaseType_t uxStreamBufferNumber )
1534     {
1535         traceENTER_vStreamBufferSetStreamBufferNumber( xStreamBuffer, uxStreamBufferNumber );
1536
1537         xStreamBuffer->uxStreamBufferNumber = uxStreamBufferNumber;
1538
1539         traceRETURN_vStreamBufferSetStreamBufferNumber();
1540     }
1541
1542 #endif /* configUSE_TRACE_FACILITY */
1543 /*-----------------------------------------------------------*/
1544
1545 #if ( configUSE_TRACE_FACILITY == 1 )
1546
1547     uint8_t ucStreamBufferGetStreamBufferType( StreamBufferHandle_t xStreamBuffer )
1548     {
1549         traceENTER_ucStreamBufferGetStreamBufferType( xStreamBuffer );
1550
1551         traceRETURN_ucStreamBufferGetStreamBufferType( ( uint8_t ) ( xStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) );
1552
1553         return( ( uint8_t ) ( xStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) );
1554     }
1555
1556 #endif /* configUSE_TRACE_FACILITY */
1557 /*-----------------------------------------------------------*/