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