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