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