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