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