]> begriffs open source - freertos/blob - stream_buffer.c
Upgrade msvc port to winsock2 (#895)
[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             prvInitialiseNewStreamBuffer( ( StreamBuffer_t * ) pvAllocatedMemory,                         /* Structure at the start of the allocated memory. */ /*lint !e9087 Safe cast as allocated memory is aligned. */ /*lint !e826 Area is not too small and alignment is guaranteed provided malloc() behaves as expected and returns aligned buffer. */
378                                           ( ( uint8_t * ) pvAllocatedMemory ) + sizeof( StreamBuffer_t ), /* Storage area follows. */ /*lint !e9016 Indexing past structure valid for uint8_t pointer, also storage area has no alignment requirement. */
379                                           xBufferSizeBytes,
380                                           xTriggerLevelBytes,
381                                           ucFlags,
382                                           pxSendCompletedCallback,
383                                           pxReceiveCompletedCallback );
384
385             traceSTREAM_BUFFER_CREATE( ( ( StreamBuffer_t * ) pvAllocatedMemory ), xIsMessageBuffer );
386         }
387         else
388         {
389             traceSTREAM_BUFFER_CREATE_FAILED( xIsMessageBuffer );
390         }
391
392         traceRETURN_xStreamBufferGenericCreate( pvAllocatedMemory );
393
394         return ( StreamBufferHandle_t ) pvAllocatedMemory; /*lint !e9087 !e826 Safe cast as allocated memory is aligned. */
395     }
396 #endif /* configSUPPORT_DYNAMIC_ALLOCATION */
397 /*-----------------------------------------------------------*/
398
399 #if ( configSUPPORT_STATIC_ALLOCATION == 1 )
400
401     StreamBufferHandle_t xStreamBufferGenericCreateStatic( size_t xBufferSizeBytes,
402                                                            size_t xTriggerLevelBytes,
403                                                            BaseType_t xIsMessageBuffer,
404                                                            uint8_t * const pucStreamBufferStorageArea,
405                                                            StaticStreamBuffer_t * const pxStaticStreamBuffer,
406                                                            StreamBufferCallbackFunction_t pxSendCompletedCallback,
407                                                            StreamBufferCallbackFunction_t pxReceiveCompletedCallback )
408     {
409         /* MISRA Ref 11.3.1 [Misaligned access] */
410         /* More details at: https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/MISRA.md#rule-113 */
411         /* coverity[misra_c_2012_rule_11_3_violation] */
412         StreamBuffer_t * const pxStreamBuffer = ( StreamBuffer_t * ) pxStaticStreamBuffer;
413         StreamBufferHandle_t xReturn;
414         uint8_t ucFlags;
415
416         traceENTER_xStreamBufferGenericCreateStatic( xBufferSizeBytes, xTriggerLevelBytes, xIsMessageBuffer, pucStreamBufferStorageArea, pxStaticStreamBuffer, pxSendCompletedCallback, pxReceiveCompletedCallback );
417
418         configASSERT( pucStreamBufferStorageArea );
419         configASSERT( pxStaticStreamBuffer );
420         configASSERT( xTriggerLevelBytes <= xBufferSizeBytes );
421
422         /* A trigger level of 0 would cause a waiting task to unblock even when
423          * the buffer was empty. */
424         if( xTriggerLevelBytes == ( size_t ) 0 )
425         {
426             xTriggerLevelBytes = ( size_t ) 1;
427         }
428
429         /* In case the stream buffer is going to be used as a message buffer
430          * (that is, it will hold discrete messages with a little meta data that
431          * says how big the next message is) check the buffer will be large enough
432          * to hold at least one message. */
433
434         if( xIsMessageBuffer != pdFALSE )
435         {
436             /* Statically allocated message buffer. */
437             ucFlags = sbFLAGS_IS_MESSAGE_BUFFER | sbFLAGS_IS_STATICALLY_ALLOCATED;
438             configASSERT( xBufferSizeBytes > sbBYTES_TO_STORE_MESSAGE_LENGTH );
439         }
440         else
441         {
442             /* Statically allocated stream buffer. */
443             ucFlags = sbFLAGS_IS_STATICALLY_ALLOCATED;
444         }
445
446         #if ( configASSERT_DEFINED == 1 )
447         {
448             /* Sanity check that the size of the structure used to declare a
449              * variable of type StaticStreamBuffer_t equals the size of the real
450              * message buffer structure. */
451             volatile size_t xSize = sizeof( StaticStreamBuffer_t );
452             configASSERT( xSize == sizeof( StreamBuffer_t ) );
453         } /*lint !e529 xSize is referenced is configASSERT() is defined. */
454         #endif /* configASSERT_DEFINED */
455
456         if( ( pucStreamBufferStorageArea != NULL ) && ( pxStaticStreamBuffer != NULL ) )
457         {
458             prvInitialiseNewStreamBuffer( pxStreamBuffer,
459                                           pucStreamBufferStorageArea,
460                                           xBufferSizeBytes,
461                                           xTriggerLevelBytes,
462                                           ucFlags,
463                                           pxSendCompletedCallback,
464                                           pxReceiveCompletedCallback );
465
466             /* Remember this was statically allocated in case it is ever deleted
467              * again. */
468             pxStreamBuffer->ucFlags |= sbFLAGS_IS_STATICALLY_ALLOCATED;
469
470             traceSTREAM_BUFFER_CREATE( pxStreamBuffer, xIsMessageBuffer );
471
472             /* MISRA Ref 11.3.1 [Misaligned access] */
473             /* More details at: https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/MISRA.md#rule-113 */
474             /* coverity[misra_c_2012_rule_11_3_violation] */
475             xReturn = ( StreamBufferHandle_t ) pxStaticStreamBuffer;
476         }
477         else
478         {
479             xReturn = NULL;
480             traceSTREAM_BUFFER_CREATE_STATIC_FAILED( xReturn, xIsMessageBuffer );
481         }
482
483         traceRETURN_xStreamBufferGenericCreateStatic( xReturn );
484
485         return xReturn;
486     }
487 #endif /* ( configSUPPORT_STATIC_ALLOCATION == 1 ) */
488 /*-----------------------------------------------------------*/
489
490 #if ( configSUPPORT_STATIC_ALLOCATION == 1 )
491     BaseType_t xStreamBufferGetStaticBuffers( StreamBufferHandle_t xStreamBuffer,
492                                               uint8_t ** ppucStreamBufferStorageArea,
493                                               StaticStreamBuffer_t ** ppxStaticStreamBuffer )
494     {
495         BaseType_t xReturn;
496         StreamBuffer_t * const pxStreamBuffer = xStreamBuffer;
497
498         traceENTER_xStreamBufferGetStaticBuffers( xStreamBuffer, ppucStreamBufferStorageArea, ppxStaticStreamBuffer );
499
500         configASSERT( pxStreamBuffer );
501         configASSERT( ppucStreamBufferStorageArea );
502         configASSERT( ppxStaticStreamBuffer );
503
504         if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_STATICALLY_ALLOCATED ) != ( uint8_t ) 0 )
505         {
506             *ppucStreamBufferStorageArea = pxStreamBuffer->pucBuffer;
507             /* MISRA Ref 11.3.1 [Misaligned access] */
508             /* More details at: https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/MISRA.md#rule-113 */
509             /* coverity[misra_c_2012_rule_11_3_violation] */
510             *ppxStaticStreamBuffer = ( StaticStreamBuffer_t * ) pxStreamBuffer;
511             xReturn = pdTRUE;
512         }
513         else
514         {
515             xReturn = pdFALSE;
516         }
517
518         traceRETURN_xStreamBufferGetStaticBuffers( xReturn );
519
520         return xReturn;
521     }
522 #endif /* configSUPPORT_STATIC_ALLOCATION */
523 /*-----------------------------------------------------------*/
524
525 void vStreamBufferDelete( StreamBufferHandle_t xStreamBuffer )
526 {
527     StreamBuffer_t * pxStreamBuffer = xStreamBuffer;
528
529     traceENTER_vStreamBufferDelete( xStreamBuffer );
530
531     configASSERT( pxStreamBuffer );
532
533     traceSTREAM_BUFFER_DELETE( xStreamBuffer );
534
535     if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_STATICALLY_ALLOCATED ) == ( uint8_t ) pdFALSE )
536     {
537         #if ( configSUPPORT_DYNAMIC_ALLOCATION == 1 )
538         {
539             /* Both the structure and the buffer were allocated using a single call
540             * to pvPortMalloc(), hence only one call to vPortFree() is required. */
541             vPortFree( ( void * ) pxStreamBuffer ); /*lint !e9087 Standard free() semantics require void *, plus pxStreamBuffer was allocated by pvPortMalloc(). */
542         }
543         #else
544         {
545             /* Should not be possible to get here, ucFlags must be corrupt.
546              * Force an assert. */
547             configASSERT( xStreamBuffer == ( StreamBufferHandle_t ) ~0 );
548         }
549         #endif
550     }
551     else
552     {
553         /* The structure and buffer were not allocated dynamically and cannot be
554          * freed - just scrub the structure so future use will assert. */
555         ( void ) memset( pxStreamBuffer, 0x00, sizeof( StreamBuffer_t ) );
556     }
557
558     traceRETURN_vStreamBufferDelete();
559 }
560 /*-----------------------------------------------------------*/
561
562 BaseType_t xStreamBufferReset( StreamBufferHandle_t xStreamBuffer )
563 {
564     StreamBuffer_t * const pxStreamBuffer = xStreamBuffer;
565     BaseType_t xReturn = pdFAIL;
566     StreamBufferCallbackFunction_t pxSendCallback = NULL, pxReceiveCallback = NULL;
567
568     #if ( configUSE_TRACE_FACILITY == 1 )
569         UBaseType_t uxStreamBufferNumber;
570     #endif
571
572     traceENTER_xStreamBufferReset( xStreamBuffer );
573
574     configASSERT( pxStreamBuffer );
575
576     #if ( configUSE_TRACE_FACILITY == 1 )
577     {
578         /* Store the stream buffer number so it can be restored after the
579          * reset. */
580         uxStreamBufferNumber = pxStreamBuffer->uxStreamBufferNumber;
581     }
582     #endif
583
584     /* Can only reset a message buffer if there are no tasks blocked on it. */
585     taskENTER_CRITICAL();
586     {
587         if( ( pxStreamBuffer->xTaskWaitingToReceive == NULL ) && ( pxStreamBuffer->xTaskWaitingToSend == NULL ) )
588         {
589             #if ( configUSE_SB_COMPLETED_CALLBACK == 1 )
590             {
591                 pxSendCallback = pxStreamBuffer->pxSendCompletedCallback;
592                 pxReceiveCallback = pxStreamBuffer->pxReceiveCompletedCallback;
593             }
594             #endif
595
596             prvInitialiseNewStreamBuffer( pxStreamBuffer,
597                                           pxStreamBuffer->pucBuffer,
598                                           pxStreamBuffer->xLength,
599                                           pxStreamBuffer->xTriggerLevelBytes,
600                                           pxStreamBuffer->ucFlags,
601                                           pxSendCallback,
602                                           pxReceiveCallback );
603
604             #if ( configUSE_TRACE_FACILITY == 1 )
605             {
606                 pxStreamBuffer->uxStreamBufferNumber = uxStreamBufferNumber;
607             }
608             #endif
609
610             traceSTREAM_BUFFER_RESET( xStreamBuffer );
611
612             xReturn = pdPASS;
613         }
614     }
615     taskEXIT_CRITICAL();
616
617     traceRETURN_xStreamBufferReset( xReturn );
618
619     return xReturn;
620 }
621 /*-----------------------------------------------------------*/
622
623 BaseType_t xStreamBufferSetTriggerLevel( StreamBufferHandle_t xStreamBuffer,
624                                          size_t xTriggerLevel )
625 {
626     StreamBuffer_t * const pxStreamBuffer = xStreamBuffer;
627     BaseType_t xReturn;
628
629     traceENTER_xStreamBufferSetTriggerLevel( xStreamBuffer, xTriggerLevel );
630
631     configASSERT( pxStreamBuffer );
632
633     /* It is not valid for the trigger level to be 0. */
634     if( xTriggerLevel == ( size_t ) 0 )
635     {
636         xTriggerLevel = ( size_t ) 1;
637     }
638
639     /* The trigger level is the number of bytes that must be in the stream
640      * buffer before a task that is waiting for data is unblocked. */
641     if( xTriggerLevel < pxStreamBuffer->xLength )
642     {
643         pxStreamBuffer->xTriggerLevelBytes = xTriggerLevel;
644         xReturn = pdPASS;
645     }
646     else
647     {
648         xReturn = pdFALSE;
649     }
650
651     traceRETURN_xStreamBufferSetTriggerLevel( xReturn );
652
653     return xReturn;
654 }
655 /*-----------------------------------------------------------*/
656
657 size_t xStreamBufferSpacesAvailable( StreamBufferHandle_t xStreamBuffer )
658 {
659     const StreamBuffer_t * const pxStreamBuffer = xStreamBuffer;
660     size_t xSpace;
661     size_t xOriginalTail;
662
663     traceENTER_xStreamBufferSpacesAvailable( xStreamBuffer );
664
665     configASSERT( pxStreamBuffer );
666
667     /* The code below reads xTail and then xHead.  This is safe if the stream
668      * buffer is updated once between the two reads - but not if the stream buffer
669      * is updated more than once between the two reads - hence the loop. */
670     do
671     {
672         xOriginalTail = pxStreamBuffer->xTail;
673         xSpace = pxStreamBuffer->xLength + pxStreamBuffer->xTail;
674         xSpace -= pxStreamBuffer->xHead;
675     } while( xOriginalTail != pxStreamBuffer->xTail );
676
677     xSpace -= ( size_t ) 1;
678
679     if( xSpace >= pxStreamBuffer->xLength )
680     {
681         xSpace -= pxStreamBuffer->xLength;
682     }
683     else
684     {
685         mtCOVERAGE_TEST_MARKER();
686     }
687
688     traceRETURN_xStreamBufferSpacesAvailable( xSpace );
689
690     return xSpace;
691 }
692 /*-----------------------------------------------------------*/
693
694 size_t xStreamBufferBytesAvailable( StreamBufferHandle_t xStreamBuffer )
695 {
696     const StreamBuffer_t * const pxStreamBuffer = xStreamBuffer;
697     size_t xReturn;
698
699     traceENTER_xStreamBufferBytesAvailable( xStreamBuffer );
700
701     configASSERT( pxStreamBuffer );
702
703     xReturn = prvBytesInBuffer( pxStreamBuffer );
704
705     traceRETURN_xStreamBufferBytesAvailable( xReturn );
706
707     return xReturn;
708 }
709 /*-----------------------------------------------------------*/
710
711 size_t xStreamBufferSend( StreamBufferHandle_t xStreamBuffer,
712                           const void * pvTxData,
713                           size_t xDataLengthBytes,
714                           TickType_t xTicksToWait )
715 {
716     StreamBuffer_t * const pxStreamBuffer = xStreamBuffer;
717     size_t xReturn, xSpace = 0;
718     size_t xRequiredSpace = xDataLengthBytes;
719     TimeOut_t xTimeOut;
720     size_t xMaxReportedSpace = 0;
721
722     traceENTER_xStreamBufferSend( xStreamBuffer, pvTxData, xDataLengthBytes, xTicksToWait );
723
724     configASSERT( pvTxData );
725     configASSERT( pxStreamBuffer );
726
727     /* The maximum amount of space a stream buffer will ever report is its length
728      * minus 1. */
729     xMaxReportedSpace = pxStreamBuffer->xLength - ( size_t ) 1;
730
731     /* This send function is used to write to both message buffers and stream
732      * buffers.  If this is a message buffer then the space needed must be
733      * increased by the amount of bytes needed to store the length of the
734      * message. */
735     if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) != ( uint8_t ) 0 )
736     {
737         xRequiredSpace += sbBYTES_TO_STORE_MESSAGE_LENGTH;
738
739         /* Overflow? */
740         configASSERT( xRequiredSpace > xDataLengthBytes );
741
742         /* If this is a message buffer then it must be possible to write the
743          * whole message. */
744         if( xRequiredSpace > xMaxReportedSpace )
745         {
746             /* The message would not fit even if the entire buffer was empty,
747              * so don't wait for space. */
748             xTicksToWait = ( TickType_t ) 0;
749         }
750         else
751         {
752             mtCOVERAGE_TEST_MARKER();
753         }
754     }
755     else
756     {
757         /* If this is a stream buffer then it is acceptable to write only part
758          * of the message to the buffer.  Cap the length to the total length of
759          * the buffer. */
760         if( xRequiredSpace > xMaxReportedSpace )
761         {
762             xRequiredSpace = xMaxReportedSpace;
763         }
764         else
765         {
766             mtCOVERAGE_TEST_MARKER();
767         }
768     }
769
770     if( xTicksToWait != ( TickType_t ) 0 )
771     {
772         vTaskSetTimeOutState( &xTimeOut );
773
774         do
775         {
776             /* Wait until the required number of bytes are free in the message
777              * buffer. */
778             taskENTER_CRITICAL();
779             {
780                 xSpace = xStreamBufferSpacesAvailable( pxStreamBuffer );
781
782                 if( xSpace < xRequiredSpace )
783                 {
784                     /* Clear notification state as going to wait for space. */
785                     ( void ) xTaskNotifyStateClear( NULL );
786
787                     /* Should only be one writer. */
788                     configASSERT( pxStreamBuffer->xTaskWaitingToSend == NULL );
789                     pxStreamBuffer->xTaskWaitingToSend = xTaskGetCurrentTaskHandle();
790                 }
791                 else
792                 {
793                     taskEXIT_CRITICAL();
794                     break;
795                 }
796             }
797             taskEXIT_CRITICAL();
798
799             traceBLOCKING_ON_STREAM_BUFFER_SEND( xStreamBuffer );
800             ( void ) xTaskNotifyWait( ( uint32_t ) 0, ( uint32_t ) 0, NULL, xTicksToWait );
801             pxStreamBuffer->xTaskWaitingToSend = NULL;
802         } while( xTaskCheckForTimeOut( &xTimeOut, &xTicksToWait ) == pdFALSE );
803     }
804     else
805     {
806         mtCOVERAGE_TEST_MARKER();
807     }
808
809     if( xSpace == ( size_t ) 0 )
810     {
811         xSpace = xStreamBufferSpacesAvailable( pxStreamBuffer );
812     }
813     else
814     {
815         mtCOVERAGE_TEST_MARKER();
816     }
817
818     xReturn = prvWriteMessageToBuffer( pxStreamBuffer, pvTxData, xDataLengthBytes, xSpace, xRequiredSpace );
819
820     if( xReturn > ( size_t ) 0 )
821     {
822         traceSTREAM_BUFFER_SEND( xStreamBuffer, xReturn );
823
824         /* Was a task waiting for the data? */
825         if( prvBytesInBuffer( pxStreamBuffer ) >= pxStreamBuffer->xTriggerLevelBytes )
826         {
827             prvSEND_COMPLETED( pxStreamBuffer );
828         }
829         else
830         {
831             mtCOVERAGE_TEST_MARKER();
832         }
833     }
834     else
835     {
836         mtCOVERAGE_TEST_MARKER();
837         traceSTREAM_BUFFER_SEND_FAILED( xStreamBuffer );
838     }
839
840     traceRETURN_xStreamBufferSend( xReturn );
841
842     return xReturn;
843 }
844 /*-----------------------------------------------------------*/
845
846 size_t xStreamBufferSendFromISR( StreamBufferHandle_t xStreamBuffer,
847                                  const void * pvTxData,
848                                  size_t xDataLengthBytes,
849                                  BaseType_t * const pxHigherPriorityTaskWoken )
850 {
851     StreamBuffer_t * const pxStreamBuffer = xStreamBuffer;
852     size_t xReturn, xSpace;
853     size_t xRequiredSpace = xDataLengthBytes;
854
855     traceENTER_xStreamBufferSendFromISR( xStreamBuffer, pvTxData, xDataLengthBytes, pxHigherPriorityTaskWoken );
856
857     configASSERT( pvTxData );
858     configASSERT( pxStreamBuffer );
859
860     /* This send function is used to write to both message buffers and stream
861      * buffers.  If this is a message buffer then the space needed must be
862      * increased by the amount of bytes needed to store the length of the
863      * message. */
864     if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) != ( uint8_t ) 0 )
865     {
866         xRequiredSpace += sbBYTES_TO_STORE_MESSAGE_LENGTH;
867     }
868     else
869     {
870         mtCOVERAGE_TEST_MARKER();
871     }
872
873     xSpace = xStreamBufferSpacesAvailable( pxStreamBuffer );
874     xReturn = prvWriteMessageToBuffer( pxStreamBuffer, pvTxData, xDataLengthBytes, xSpace, xRequiredSpace );
875
876     if( xReturn > ( size_t ) 0 )
877     {
878         /* Was a task waiting for the data? */
879         if( prvBytesInBuffer( pxStreamBuffer ) >= pxStreamBuffer->xTriggerLevelBytes )
880         {
881             prvSEND_COMPLETE_FROM_ISR( pxStreamBuffer, pxHigherPriorityTaskWoken );
882         }
883         else
884         {
885             mtCOVERAGE_TEST_MARKER();
886         }
887     }
888     else
889     {
890         mtCOVERAGE_TEST_MARKER();
891     }
892
893     traceSTREAM_BUFFER_SEND_FROM_ISR( xStreamBuffer, xReturn );
894     traceRETURN_xStreamBufferSendFromISR( xReturn );
895
896     return xReturn;
897 }
898 /*-----------------------------------------------------------*/
899
900 static size_t prvWriteMessageToBuffer( StreamBuffer_t * const pxStreamBuffer,
901                                        const void * pvTxData,
902                                        size_t xDataLengthBytes,
903                                        size_t xSpace,
904                                        size_t xRequiredSpace )
905 {
906     size_t xNextHead = pxStreamBuffer->xHead;
907     configMESSAGE_BUFFER_LENGTH_TYPE xMessageLength;
908
909     if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) != ( uint8_t ) 0 )
910     {
911         /* This is a message buffer, as opposed to a stream buffer. */
912
913         /* Convert xDataLengthBytes to the message length type. */
914         xMessageLength = ( configMESSAGE_BUFFER_LENGTH_TYPE ) xDataLengthBytes;
915
916         /* Ensure the data length given fits within configMESSAGE_BUFFER_LENGTH_TYPE. */
917         configASSERT( ( size_t ) xMessageLength == xDataLengthBytes );
918
919         if( xSpace >= xRequiredSpace )
920         {
921             /* There is enough space to write both the message length and the message
922              * itself into the buffer.  Start by writing the length of the data, the data
923              * itself will be written later in this function. */
924             xNextHead = prvWriteBytesToBuffer( pxStreamBuffer, ( const uint8_t * ) &( xMessageLength ), sbBYTES_TO_STORE_MESSAGE_LENGTH, xNextHead );
925         }
926         else
927         {
928             /* Not enough space, so do not write data to the buffer. */
929             xDataLengthBytes = 0;
930         }
931     }
932     else
933     {
934         /* This is a stream buffer, as opposed to a message buffer, so writing a
935          * stream of bytes rather than discrete messages.  Plan to write as many
936          * bytes as possible. */
937         xDataLengthBytes = configMIN( xDataLengthBytes, xSpace );
938     }
939
940     if( xDataLengthBytes != ( size_t ) 0 )
941     {
942         /* Write the data to the buffer. */
943         pxStreamBuffer->xHead = prvWriteBytesToBuffer( pxStreamBuffer, ( const uint8_t * ) pvTxData, xDataLengthBytes, xNextHead ); /*lint !e9079 Storage buffer is implemented as uint8_t for ease of sizing, alignment and access. */
944     }
945
946     return xDataLengthBytes;
947 }
948 /*-----------------------------------------------------------*/
949
950 size_t xStreamBufferReceive( StreamBufferHandle_t xStreamBuffer,
951                              void * pvRxData,
952                              size_t xBufferLengthBytes,
953                              TickType_t xTicksToWait )
954 {
955     StreamBuffer_t * const pxStreamBuffer = xStreamBuffer;
956     size_t xReceivedLength = 0, xBytesAvailable, xBytesToStoreMessageLength;
957
958     traceENTER_xStreamBufferReceive( xStreamBuffer, pvRxData, xBufferLengthBytes, xTicksToWait );
959
960     configASSERT( pvRxData );
961     configASSERT( pxStreamBuffer );
962
963     /* This receive function is used by both message buffers, which store
964      * discrete messages, and stream buffers, which store a continuous stream of
965      * bytes.  Discrete messages include an additional
966      * sbBYTES_TO_STORE_MESSAGE_LENGTH bytes that hold the length of the
967      * message. */
968     if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) != ( uint8_t ) 0 )
969     {
970         xBytesToStoreMessageLength = sbBYTES_TO_STORE_MESSAGE_LENGTH;
971     }
972     else
973     {
974         xBytesToStoreMessageLength = 0;
975     }
976
977     if( xTicksToWait != ( TickType_t ) 0 )
978     {
979         /* Checking if there is data and clearing the notification state must be
980          * performed atomically. */
981         taskENTER_CRITICAL();
982         {
983             xBytesAvailable = prvBytesInBuffer( pxStreamBuffer );
984
985             /* If this function was invoked by a message buffer read then
986              * xBytesToStoreMessageLength holds the number of bytes used to hold
987              * the length of the next discrete message.  If this function was
988              * invoked by a stream buffer read then xBytesToStoreMessageLength will
989              * be 0. */
990             if( xBytesAvailable <= xBytesToStoreMessageLength )
991             {
992                 /* Clear notification state as going to wait for data. */
993                 ( void ) xTaskNotifyStateClear( NULL );
994
995                 /* Should only be one reader. */
996                 configASSERT( pxStreamBuffer->xTaskWaitingToReceive == NULL );
997                 pxStreamBuffer->xTaskWaitingToReceive = xTaskGetCurrentTaskHandle();
998             }
999             else
1000             {
1001                 mtCOVERAGE_TEST_MARKER();
1002             }
1003         }
1004         taskEXIT_CRITICAL();
1005
1006         if( xBytesAvailable <= xBytesToStoreMessageLength )
1007         {
1008             /* Wait for data to be available. */
1009             traceBLOCKING_ON_STREAM_BUFFER_RECEIVE( xStreamBuffer );
1010             ( void ) xTaskNotifyWait( ( uint32_t ) 0, ( uint32_t ) 0, NULL, xTicksToWait );
1011             pxStreamBuffer->xTaskWaitingToReceive = NULL;
1012
1013             /* Recheck the data available after blocking. */
1014             xBytesAvailable = prvBytesInBuffer( pxStreamBuffer );
1015         }
1016         else
1017         {
1018             mtCOVERAGE_TEST_MARKER();
1019         }
1020     }
1021     else
1022     {
1023         xBytesAvailable = prvBytesInBuffer( pxStreamBuffer );
1024     }
1025
1026     /* Whether receiving a discrete message (where xBytesToStoreMessageLength
1027      * holds the number of bytes used to store the message length) or a stream of
1028      * bytes (where xBytesToStoreMessageLength is zero), the number of bytes
1029      * available must be greater than xBytesToStoreMessageLength to be able to
1030      * read bytes from the buffer. */
1031     if( xBytesAvailable > xBytesToStoreMessageLength )
1032     {
1033         xReceivedLength = prvReadMessageFromBuffer( pxStreamBuffer, pvRxData, xBufferLengthBytes, xBytesAvailable );
1034
1035         /* Was a task waiting for space in the buffer? */
1036         if( xReceivedLength != ( size_t ) 0 )
1037         {
1038             traceSTREAM_BUFFER_RECEIVE( xStreamBuffer, xReceivedLength );
1039             prvRECEIVE_COMPLETED( xStreamBuffer );
1040         }
1041         else
1042         {
1043             mtCOVERAGE_TEST_MARKER();
1044         }
1045     }
1046     else
1047     {
1048         traceSTREAM_BUFFER_RECEIVE_FAILED( xStreamBuffer );
1049         mtCOVERAGE_TEST_MARKER();
1050     }
1051
1052     traceRETURN_xStreamBufferReceive( xReceivedLength );
1053
1054     return xReceivedLength;
1055 }
1056 /*-----------------------------------------------------------*/
1057
1058 size_t xStreamBufferNextMessageLengthBytes( StreamBufferHandle_t xStreamBuffer )
1059 {
1060     StreamBuffer_t * const pxStreamBuffer = xStreamBuffer;
1061     size_t xReturn, xBytesAvailable;
1062     configMESSAGE_BUFFER_LENGTH_TYPE xTempReturn;
1063
1064     traceENTER_xStreamBufferNextMessageLengthBytes( xStreamBuffer );
1065
1066     configASSERT( pxStreamBuffer );
1067
1068     /* Ensure the stream buffer is being used as a message buffer. */
1069     if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) != ( uint8_t ) 0 )
1070     {
1071         xBytesAvailable = prvBytesInBuffer( pxStreamBuffer );
1072
1073         if( xBytesAvailable > sbBYTES_TO_STORE_MESSAGE_LENGTH )
1074         {
1075             /* The number of bytes available is greater than the number of bytes
1076              * required to hold the length of the next message, so another message
1077              * is available. */
1078             ( void ) prvReadBytesFromBuffer( pxStreamBuffer, ( uint8_t * ) &xTempReturn, sbBYTES_TO_STORE_MESSAGE_LENGTH, pxStreamBuffer->xTail );
1079             xReturn = ( size_t ) xTempReturn;
1080         }
1081         else
1082         {
1083             /* The minimum amount of bytes in a message buffer is
1084              * ( sbBYTES_TO_STORE_MESSAGE_LENGTH + 1 ), so if xBytesAvailable is
1085              * less than sbBYTES_TO_STORE_MESSAGE_LENGTH the only other valid
1086              * value is 0. */
1087             configASSERT( xBytesAvailable == 0 );
1088             xReturn = 0;
1089         }
1090     }
1091     else
1092     {
1093         xReturn = 0;
1094     }
1095
1096     traceRETURN_xStreamBufferNextMessageLengthBytes( xReturn );
1097
1098     return xReturn;
1099 }
1100 /*-----------------------------------------------------------*/
1101
1102 size_t xStreamBufferReceiveFromISR( StreamBufferHandle_t xStreamBuffer,
1103                                     void * pvRxData,
1104                                     size_t xBufferLengthBytes,
1105                                     BaseType_t * const pxHigherPriorityTaskWoken )
1106 {
1107     StreamBuffer_t * const pxStreamBuffer = xStreamBuffer;
1108     size_t xReceivedLength = 0, xBytesAvailable, xBytesToStoreMessageLength;
1109
1110     traceENTER_xStreamBufferReceiveFromISR( xStreamBuffer, pvRxData, xBufferLengthBytes, pxHigherPriorityTaskWoken );
1111
1112     configASSERT( pvRxData );
1113     configASSERT( pxStreamBuffer );
1114
1115     /* This receive function is used by both message buffers, which store
1116      * discrete messages, and stream buffers, which store a continuous stream of
1117      * bytes.  Discrete messages include an additional
1118      * sbBYTES_TO_STORE_MESSAGE_LENGTH bytes that hold the length of the
1119      * message. */
1120     if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) != ( uint8_t ) 0 )
1121     {
1122         xBytesToStoreMessageLength = sbBYTES_TO_STORE_MESSAGE_LENGTH;
1123     }
1124     else
1125     {
1126         xBytesToStoreMessageLength = 0;
1127     }
1128
1129     xBytesAvailable = prvBytesInBuffer( pxStreamBuffer );
1130
1131     /* Whether receiving a discrete message (where xBytesToStoreMessageLength
1132      * holds the number of bytes used to store the message length) or a stream of
1133      * bytes (where xBytesToStoreMessageLength is zero), the number of bytes
1134      * available must be greater than xBytesToStoreMessageLength to be able to
1135      * read bytes from the buffer. */
1136     if( xBytesAvailable > xBytesToStoreMessageLength )
1137     {
1138         xReceivedLength = prvReadMessageFromBuffer( pxStreamBuffer, pvRxData, xBufferLengthBytes, xBytesAvailable );
1139
1140         /* Was a task waiting for space in the buffer? */
1141         if( xReceivedLength != ( size_t ) 0 )
1142         {
1143             prvRECEIVE_COMPLETED_FROM_ISR( pxStreamBuffer, pxHigherPriorityTaskWoken );
1144         }
1145         else
1146         {
1147             mtCOVERAGE_TEST_MARKER();
1148         }
1149     }
1150     else
1151     {
1152         mtCOVERAGE_TEST_MARKER();
1153     }
1154
1155     traceSTREAM_BUFFER_RECEIVE_FROM_ISR( xStreamBuffer, xReceivedLength );
1156     traceRETURN_xStreamBufferReceiveFromISR( xReceivedLength );
1157
1158     return xReceivedLength;
1159 }
1160 /*-----------------------------------------------------------*/
1161
1162 static size_t prvReadMessageFromBuffer( StreamBuffer_t * pxStreamBuffer,
1163                                         void * pvRxData,
1164                                         size_t xBufferLengthBytes,
1165                                         size_t xBytesAvailable )
1166 {
1167     size_t xCount, xNextMessageLength;
1168     configMESSAGE_BUFFER_LENGTH_TYPE xTempNextMessageLength;
1169     size_t xNextTail = pxStreamBuffer->xTail;
1170
1171     if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) != ( uint8_t ) 0 )
1172     {
1173         /* A discrete message is being received.  First receive the length
1174          * of the message. */
1175         xNextTail = prvReadBytesFromBuffer( pxStreamBuffer, ( uint8_t * ) &xTempNextMessageLength, sbBYTES_TO_STORE_MESSAGE_LENGTH, xNextTail );
1176         xNextMessageLength = ( size_t ) xTempNextMessageLength;
1177
1178         /* Reduce the number of bytes available by the number of bytes just
1179          * read out. */
1180         xBytesAvailable -= sbBYTES_TO_STORE_MESSAGE_LENGTH;
1181
1182         /* Check there is enough space in the buffer provided by the
1183          * user. */
1184         if( xNextMessageLength > xBufferLengthBytes )
1185         {
1186             /* The user has provided insufficient space to read the message. */
1187             xNextMessageLength = 0;
1188         }
1189         else
1190         {
1191             mtCOVERAGE_TEST_MARKER();
1192         }
1193     }
1194     else
1195     {
1196         /* A stream of bytes is being received (as opposed to a discrete
1197          * message), so read as many bytes as possible. */
1198         xNextMessageLength = xBufferLengthBytes;
1199     }
1200
1201     /* Use the minimum of the wanted bytes and the available bytes. */
1202     xCount = configMIN( xNextMessageLength, xBytesAvailable );
1203
1204     if( xCount != ( size_t ) 0 )
1205     {
1206         /* Read the actual data and update the tail to mark the data as officially consumed. */
1207         pxStreamBuffer->xTail = prvReadBytesFromBuffer( pxStreamBuffer, ( uint8_t * ) pvRxData, xCount, xNextTail ); /*lint !e9079 Data storage area is implemented as uint8_t array for ease of sizing, indexing and alignment. */
1208     }
1209
1210     return xCount;
1211 }
1212 /*-----------------------------------------------------------*/
1213
1214 BaseType_t xStreamBufferIsEmpty( StreamBufferHandle_t xStreamBuffer )
1215 {
1216     const StreamBuffer_t * const pxStreamBuffer = xStreamBuffer;
1217     BaseType_t xReturn;
1218     size_t xTail;
1219
1220     traceENTER_xStreamBufferIsEmpty( xStreamBuffer );
1221
1222     configASSERT( pxStreamBuffer );
1223
1224     /* True if no bytes are available. */
1225     xTail = pxStreamBuffer->xTail;
1226
1227     if( pxStreamBuffer->xHead == xTail )
1228     {
1229         xReturn = pdTRUE;
1230     }
1231     else
1232     {
1233         xReturn = pdFALSE;
1234     }
1235
1236     traceRETURN_xStreamBufferIsEmpty( xReturn );
1237
1238     return xReturn;
1239 }
1240 /*-----------------------------------------------------------*/
1241
1242 BaseType_t xStreamBufferIsFull( StreamBufferHandle_t xStreamBuffer )
1243 {
1244     BaseType_t xReturn;
1245     size_t xBytesToStoreMessageLength;
1246     const StreamBuffer_t * const pxStreamBuffer = xStreamBuffer;
1247
1248     traceENTER_xStreamBufferIsFull( xStreamBuffer );
1249
1250     configASSERT( pxStreamBuffer );
1251
1252     /* This generic version of the receive function is used by both message
1253      * buffers, which store discrete messages, and stream buffers, which store a
1254      * continuous stream of bytes.  Discrete messages include an additional
1255      * sbBYTES_TO_STORE_MESSAGE_LENGTH bytes that hold the length of the message. */
1256     if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) != ( uint8_t ) 0 )
1257     {
1258         xBytesToStoreMessageLength = sbBYTES_TO_STORE_MESSAGE_LENGTH;
1259     }
1260     else
1261     {
1262         xBytesToStoreMessageLength = 0;
1263     }
1264
1265     /* True if the available space equals zero. */
1266     if( xStreamBufferSpacesAvailable( xStreamBuffer ) <= xBytesToStoreMessageLength )
1267     {
1268         xReturn = pdTRUE;
1269     }
1270     else
1271     {
1272         xReturn = pdFALSE;
1273     }
1274
1275     traceRETURN_xStreamBufferIsFull( xReturn );
1276
1277     return xReturn;
1278 }
1279 /*-----------------------------------------------------------*/
1280
1281 BaseType_t xStreamBufferSendCompletedFromISR( StreamBufferHandle_t xStreamBuffer,
1282                                               BaseType_t * pxHigherPriorityTaskWoken )
1283 {
1284     StreamBuffer_t * const pxStreamBuffer = xStreamBuffer;
1285     BaseType_t xReturn;
1286     UBaseType_t uxSavedInterruptStatus;
1287
1288     traceENTER_xStreamBufferSendCompletedFromISR( xStreamBuffer, pxHigherPriorityTaskWoken );
1289
1290     configASSERT( pxStreamBuffer );
1291
1292     uxSavedInterruptStatus = taskENTER_CRITICAL_FROM_ISR();
1293     {
1294         if( ( pxStreamBuffer )->xTaskWaitingToReceive != NULL )
1295         {
1296             ( void ) xTaskNotifyFromISR( ( pxStreamBuffer )->xTaskWaitingToReceive,
1297                                          ( uint32_t ) 0,
1298                                          eNoAction,
1299                                          pxHigherPriorityTaskWoken );
1300             ( pxStreamBuffer )->xTaskWaitingToReceive = NULL;
1301             xReturn = pdTRUE;
1302         }
1303         else
1304         {
1305             xReturn = pdFALSE;
1306         }
1307     }
1308     taskEXIT_CRITICAL_FROM_ISR( uxSavedInterruptStatus );
1309
1310     traceRETURN_xStreamBufferSendCompletedFromISR( xReturn );
1311
1312     return xReturn;
1313 }
1314 /*-----------------------------------------------------------*/
1315
1316 BaseType_t xStreamBufferReceiveCompletedFromISR( StreamBufferHandle_t xStreamBuffer,
1317                                                  BaseType_t * pxHigherPriorityTaskWoken )
1318 {
1319     StreamBuffer_t * const pxStreamBuffer = xStreamBuffer;
1320     BaseType_t xReturn;
1321     UBaseType_t uxSavedInterruptStatus;
1322
1323     traceENTER_xStreamBufferReceiveCompletedFromISR( xStreamBuffer, pxHigherPriorityTaskWoken );
1324
1325     configASSERT( pxStreamBuffer );
1326
1327     uxSavedInterruptStatus = taskENTER_CRITICAL_FROM_ISR();
1328     {
1329         if( ( pxStreamBuffer )->xTaskWaitingToSend != NULL )
1330         {
1331             ( void ) xTaskNotifyFromISR( ( pxStreamBuffer )->xTaskWaitingToSend,
1332                                          ( uint32_t ) 0,
1333                                          eNoAction,
1334                                          pxHigherPriorityTaskWoken );
1335             ( pxStreamBuffer )->xTaskWaitingToSend = NULL;
1336             xReturn = pdTRUE;
1337         }
1338         else
1339         {
1340             xReturn = pdFALSE;
1341         }
1342     }
1343     taskEXIT_CRITICAL_FROM_ISR( uxSavedInterruptStatus );
1344
1345     traceRETURN_xStreamBufferReceiveCompletedFromISR( xReturn );
1346
1347     return xReturn;
1348 }
1349 /*-----------------------------------------------------------*/
1350
1351 static size_t prvWriteBytesToBuffer( StreamBuffer_t * const pxStreamBuffer,
1352                                      const uint8_t * pucData,
1353                                      size_t xCount,
1354                                      size_t xHead )
1355 {
1356     size_t xFirstLength;
1357
1358     configASSERT( xCount > ( size_t ) 0 );
1359
1360     /* Calculate the number of bytes that can be added in the first write -
1361      * which may be less than the total number of bytes that need to be added if
1362      * the buffer will wrap back to the beginning. */
1363     xFirstLength = configMIN( pxStreamBuffer->xLength - xHead, xCount );
1364
1365     /* Write as many bytes as can be written in the first write. */
1366     configASSERT( ( xHead + xFirstLength ) <= pxStreamBuffer->xLength );
1367     ( void ) memcpy( ( void * ) ( &( pxStreamBuffer->pucBuffer[ xHead ] ) ), ( const void * ) pucData, xFirstLength ); /*lint !e9087 memcpy() requires void *. */
1368
1369     /* If the number of bytes written was less than the number that could be
1370      * written in the first write... */
1371     if( xCount > xFirstLength )
1372     {
1373         /* ...then write the remaining bytes to the start of the buffer. */
1374         configASSERT( ( xCount - xFirstLength ) <= pxStreamBuffer->xLength );
1375         ( void ) memcpy( ( void * ) pxStreamBuffer->pucBuffer, ( const void * ) &( pucData[ xFirstLength ] ), xCount - xFirstLength ); /*lint !e9087 memcpy() requires void *. */
1376     }
1377     else
1378     {
1379         mtCOVERAGE_TEST_MARKER();
1380     }
1381
1382     xHead += xCount;
1383
1384     if( xHead >= pxStreamBuffer->xLength )
1385     {
1386         xHead -= pxStreamBuffer->xLength;
1387     }
1388     else
1389     {
1390         mtCOVERAGE_TEST_MARKER();
1391     }
1392
1393     return xHead;
1394 }
1395 /*-----------------------------------------------------------*/
1396
1397 static size_t prvReadBytesFromBuffer( StreamBuffer_t * pxStreamBuffer,
1398                                       uint8_t * pucData,
1399                                       size_t xCount,
1400                                       size_t xTail )
1401 {
1402     size_t xFirstLength;
1403
1404     configASSERT( xCount != ( size_t ) 0 );
1405
1406     /* Calculate the number of bytes that can be read - which may be
1407      * less than the number wanted if the data wraps around to the start of
1408      * the buffer. */
1409     xFirstLength = configMIN( pxStreamBuffer->xLength - xTail, xCount );
1410
1411     /* Obtain the number of bytes it is possible to obtain in the first
1412      * read.  Asserts check bounds of read and write. */
1413     configASSERT( xFirstLength <= xCount );
1414     configASSERT( ( xTail + xFirstLength ) <= pxStreamBuffer->xLength );
1415     ( void ) memcpy( ( void * ) pucData, ( const void * ) &( pxStreamBuffer->pucBuffer[ xTail ] ), xFirstLength ); /*lint !e9087 memcpy() requires void *. */
1416
1417     /* If the total number of wanted bytes is greater than the number
1418      * that could be read in the first read... */
1419     if( xCount > xFirstLength )
1420     {
1421         /* ...then read the remaining bytes from the start of the buffer. */
1422         ( void ) memcpy( ( void * ) &( pucData[ xFirstLength ] ), ( void * ) ( pxStreamBuffer->pucBuffer ), xCount - xFirstLength ); /*lint !e9087 memcpy() requires void *. */
1423     }
1424     else
1425     {
1426         mtCOVERAGE_TEST_MARKER();
1427     }
1428
1429     /* Move the tail pointer to effectively remove the data read from the buffer. */
1430     xTail += xCount;
1431
1432     if( xTail >= pxStreamBuffer->xLength )
1433     {
1434         xTail -= pxStreamBuffer->xLength;
1435     }
1436
1437     return xTail;
1438 }
1439 /*-----------------------------------------------------------*/
1440
1441 static size_t prvBytesInBuffer( const StreamBuffer_t * const pxStreamBuffer )
1442 {
1443 /* Returns the distance between xTail and xHead. */
1444     size_t xCount;
1445
1446     xCount = pxStreamBuffer->xLength + pxStreamBuffer->xHead;
1447     xCount -= pxStreamBuffer->xTail;
1448
1449     if( xCount >= pxStreamBuffer->xLength )
1450     {
1451         xCount -= pxStreamBuffer->xLength;
1452     }
1453     else
1454     {
1455         mtCOVERAGE_TEST_MARKER();
1456     }
1457
1458     return xCount;
1459 }
1460 /*-----------------------------------------------------------*/
1461
1462 static void prvInitialiseNewStreamBuffer( StreamBuffer_t * const pxStreamBuffer,
1463                                           uint8_t * const pucBuffer,
1464                                           size_t xBufferSizeBytes,
1465                                           size_t xTriggerLevelBytes,
1466                                           uint8_t ucFlags,
1467                                           StreamBufferCallbackFunction_t pxSendCompletedCallback,
1468                                           StreamBufferCallbackFunction_t pxReceiveCompletedCallback )
1469 {
1470     /* Assert here is deliberately writing to the entire buffer to ensure it can
1471      * be written to without generating exceptions, and is setting the buffer to a
1472      * known value to assist in development/debugging. */
1473     #if ( configASSERT_DEFINED == 1 )
1474     {
1475         /* The value written just has to be identifiable when looking at the
1476          * memory.  Don't use 0xA5 as that is the stack fill value and could
1477          * result in confusion as to what is actually being observed. */
1478     #define STREAM_BUFFER_BUFFER_WRITE_VALUE    ( 0x55 )
1479         configASSERT( memset( pucBuffer, ( int ) STREAM_BUFFER_BUFFER_WRITE_VALUE, xBufferSizeBytes ) == pucBuffer );
1480     }
1481     #endif
1482
1483     ( void ) memset( ( void * ) pxStreamBuffer, 0x00, sizeof( StreamBuffer_t ) ); /*lint !e9087 memset() requires void *. */
1484     pxStreamBuffer->pucBuffer = pucBuffer;
1485     pxStreamBuffer->xLength = xBufferSizeBytes;
1486     pxStreamBuffer->xTriggerLevelBytes = xTriggerLevelBytes;
1487     pxStreamBuffer->ucFlags = ucFlags;
1488     #if ( configUSE_SB_COMPLETED_CALLBACK == 1 )
1489     {
1490         pxStreamBuffer->pxSendCompletedCallback = pxSendCompletedCallback;
1491         pxStreamBuffer->pxReceiveCompletedCallback = pxReceiveCompletedCallback;
1492     }
1493     #else
1494     {
1495         ( void ) pxSendCompletedCallback;
1496         ( void ) pxReceiveCompletedCallback;
1497     }
1498     #endif
1499 }
1500
1501 #if ( configUSE_TRACE_FACILITY == 1 )
1502
1503     UBaseType_t uxStreamBufferGetStreamBufferNumber( StreamBufferHandle_t xStreamBuffer )
1504     {
1505         traceENTER_uxStreamBufferGetStreamBufferNumber( xStreamBuffer );
1506
1507         traceRETURN_uxStreamBufferGetStreamBufferNumber( xStreamBuffer->uxStreamBufferNumber );
1508
1509         return xStreamBuffer->uxStreamBufferNumber;
1510     }
1511
1512 #endif /* configUSE_TRACE_FACILITY */
1513 /*-----------------------------------------------------------*/
1514
1515 #if ( configUSE_TRACE_FACILITY == 1 )
1516
1517     void vStreamBufferSetStreamBufferNumber( StreamBufferHandle_t xStreamBuffer,
1518                                              UBaseType_t uxStreamBufferNumber )
1519     {
1520         traceENTER_vStreamBufferSetStreamBufferNumber( xStreamBuffer, uxStreamBufferNumber );
1521
1522         xStreamBuffer->uxStreamBufferNumber = uxStreamBufferNumber;
1523
1524         traceRETURN_vStreamBufferSetStreamBufferNumber();
1525     }
1526
1527 #endif /* configUSE_TRACE_FACILITY */
1528 /*-----------------------------------------------------------*/
1529
1530 #if ( configUSE_TRACE_FACILITY == 1 )
1531
1532     uint8_t ucStreamBufferGetStreamBufferType( StreamBufferHandle_t xStreamBuffer )
1533     {
1534         traceENTER_ucStreamBufferGetStreamBufferType( xStreamBuffer );
1535
1536         traceRETURN_ucStreamBufferGetStreamBufferType( ( uint8_t ) ( xStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) );
1537
1538         return( ( uint8_t ) ( xStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) );
1539     }
1540
1541 #endif /* configUSE_TRACE_FACILITY */
1542 /*-----------------------------------------------------------*/