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