2 * FreeRTOS Kernel <DEVELOPMENT BRANCH>
3 * Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
5 * SPDX-License-Identifier: MIT
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:
14 * The above copyright notice and this permission notice shall be included in all
15 * copies or substantial portions of the Software.
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.
24 * https://www.FreeRTOS.org
25 * https://github.com/FreeRTOS
29 /* Standard includes. */
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
37 /* FreeRTOS includes. */
40 #include "stream_buffer.h"
42 #if ( configUSE_TASK_NOTIFICATIONS != 1 )
43 #error configUSE_TASK_NOTIFICATIONS must be set to 1 to build stream_buffer.c
46 #if ( INCLUDE_xTaskGetCurrentTaskHandle != 1 )
47 #error INCLUDE_xTaskGetCurrentTaskHandle must be set to 1 to build stream_buffer.c
50 /* The MPU ports require MPU_WRAPPERS_INCLUDED_FROM_API_FILE to be defined
51 * for the header files above, but not in this file, in order to generate the
52 * correct privileged Vs unprivileged linkage and placement. */
53 #undef MPU_WRAPPERS_INCLUDED_FROM_API_FILE
55 /* This entire source file will be skipped if the application is not configured
56 * to include stream buffer functionality. This #if is closed at the very bottom
57 * of this file. If you want to include stream buffers then ensure
58 * configUSE_STREAM_BUFFERS is set to 1 in FreeRTOSConfig.h. */
59 #if ( configUSE_STREAM_BUFFERS == 1 )
61 /* If the user has not provided application specific Rx notification macros,
62 * or #defined the notification macros away, then provide default implementations
63 * that uses task notifications. */
64 #ifndef sbRECEIVE_COMPLETED
65 #define sbRECEIVE_COMPLETED( pxStreamBuffer ) \
70 if( ( pxStreamBuffer )->xTaskWaitingToSend != NULL ) \
72 ( void ) xTaskNotifyIndexed( ( pxStreamBuffer )->xTaskWaitingToSend, \
73 ( pxStreamBuffer )->uxNotificationIndex, \
76 ( pxStreamBuffer )->xTaskWaitingToSend = NULL; \
79 ( void ) xTaskResumeAll(); \
81 #endif /* sbRECEIVE_COMPLETED */
83 /* If user has provided a per-instance receive complete callback, then
84 * invoke the callback else use the receive complete macro which is provided by default for all instances.
86 #if ( configUSE_SB_COMPLETED_CALLBACK == 1 )
87 #define prvRECEIVE_COMPLETED( pxStreamBuffer ) \
89 if( ( pxStreamBuffer )->pxReceiveCompletedCallback != NULL ) \
91 ( pxStreamBuffer )->pxReceiveCompletedCallback( ( pxStreamBuffer ), pdFALSE, NULL ); \
95 sbRECEIVE_COMPLETED( ( pxStreamBuffer ) ); \
98 #else /* if ( configUSE_SB_COMPLETED_CALLBACK == 1 ) */
99 #define prvRECEIVE_COMPLETED( pxStreamBuffer ) sbRECEIVE_COMPLETED( ( pxStreamBuffer ) )
100 #endif /* if ( configUSE_SB_COMPLETED_CALLBACK == 1 ) */
102 #ifndef sbRECEIVE_COMPLETED_FROM_ISR
103 #define sbRECEIVE_COMPLETED_FROM_ISR( pxStreamBuffer, \
104 pxHigherPriorityTaskWoken ) \
106 UBaseType_t uxSavedInterruptStatus; \
108 uxSavedInterruptStatus = taskENTER_CRITICAL_FROM_ISR(); \
110 if( ( pxStreamBuffer )->xTaskWaitingToSend != NULL ) \
112 ( void ) xTaskNotifyIndexedFromISR( ( pxStreamBuffer )->xTaskWaitingToSend, \
113 ( pxStreamBuffer )->uxNotificationIndex, \
116 ( pxHigherPriorityTaskWoken ) ); \
117 ( pxStreamBuffer )->xTaskWaitingToSend = NULL; \
120 taskEXIT_CRITICAL_FROM_ISR( uxSavedInterruptStatus ); \
122 #endif /* sbRECEIVE_COMPLETED_FROM_ISR */
124 #if ( configUSE_SB_COMPLETED_CALLBACK == 1 )
125 #define prvRECEIVE_COMPLETED_FROM_ISR( pxStreamBuffer, \
126 pxHigherPriorityTaskWoken ) \
128 if( ( pxStreamBuffer )->pxReceiveCompletedCallback != NULL ) \
130 ( pxStreamBuffer )->pxReceiveCompletedCallback( ( pxStreamBuffer ), pdTRUE, ( pxHigherPriorityTaskWoken ) ); \
134 sbRECEIVE_COMPLETED_FROM_ISR( ( pxStreamBuffer ), ( pxHigherPriorityTaskWoken ) ); \
137 #else /* if ( configUSE_SB_COMPLETED_CALLBACK == 1 ) */
138 #define prvRECEIVE_COMPLETED_FROM_ISR( pxStreamBuffer, pxHigherPriorityTaskWoken ) \
139 sbRECEIVE_COMPLETED_FROM_ISR( ( pxStreamBuffer ), ( pxHigherPriorityTaskWoken ) )
140 #endif /* if ( configUSE_SB_COMPLETED_CALLBACK == 1 ) */
142 /* If the user has not provided an application specific Tx notification macro,
143 * or #defined the notification macro away, then provide a default
144 * implementation that uses task notifications.
146 #ifndef sbSEND_COMPLETED
147 #define sbSEND_COMPLETED( pxStreamBuffer ) \
150 if( ( pxStreamBuffer )->xTaskWaitingToReceive != NULL ) \
152 ( void ) xTaskNotifyIndexed( ( pxStreamBuffer )->xTaskWaitingToReceive, \
153 ( pxStreamBuffer )->uxNotificationIndex, \
156 ( pxStreamBuffer )->xTaskWaitingToReceive = NULL; \
159 ( void ) xTaskResumeAll()
160 #endif /* sbSEND_COMPLETED */
162 /* If user has provided a per-instance send completed callback, then
163 * invoke the callback else use the send complete macro which is provided by default for all instances.
165 #if ( configUSE_SB_COMPLETED_CALLBACK == 1 )
166 #define prvSEND_COMPLETED( pxStreamBuffer ) \
168 if( ( pxStreamBuffer )->pxSendCompletedCallback != NULL ) \
170 ( pxStreamBuffer )->pxSendCompletedCallback( ( pxStreamBuffer ), pdFALSE, NULL ); \
174 sbSEND_COMPLETED( ( pxStreamBuffer ) ); \
177 #else /* if ( configUSE_SB_COMPLETED_CALLBACK == 1 ) */
178 #define prvSEND_COMPLETED( pxStreamBuffer ) sbSEND_COMPLETED( ( pxStreamBuffer ) )
179 #endif /* if ( configUSE_SB_COMPLETED_CALLBACK == 1 ) */
182 #ifndef sbSEND_COMPLETE_FROM_ISR
183 #define sbSEND_COMPLETE_FROM_ISR( pxStreamBuffer, pxHigherPriorityTaskWoken ) \
185 UBaseType_t uxSavedInterruptStatus; \
187 uxSavedInterruptStatus = taskENTER_CRITICAL_FROM_ISR(); \
189 if( ( pxStreamBuffer )->xTaskWaitingToReceive != NULL ) \
191 ( void ) xTaskNotifyIndexedFromISR( ( pxStreamBuffer )->xTaskWaitingToReceive, \
192 ( pxStreamBuffer )->uxNotificationIndex, \
195 ( pxHigherPriorityTaskWoken ) ); \
196 ( pxStreamBuffer )->xTaskWaitingToReceive = NULL; \
199 taskEXIT_CRITICAL_FROM_ISR( uxSavedInterruptStatus ); \
201 #endif /* sbSEND_COMPLETE_FROM_ISR */
204 #if ( configUSE_SB_COMPLETED_CALLBACK == 1 )
205 #define prvSEND_COMPLETE_FROM_ISR( pxStreamBuffer, pxHigherPriorityTaskWoken ) \
207 if( ( pxStreamBuffer )->pxSendCompletedCallback != NULL ) \
209 ( pxStreamBuffer )->pxSendCompletedCallback( ( pxStreamBuffer ), pdTRUE, ( pxHigherPriorityTaskWoken ) ); \
213 sbSEND_COMPLETE_FROM_ISR( ( pxStreamBuffer ), ( pxHigherPriorityTaskWoken ) ); \
216 #else /* if ( configUSE_SB_COMPLETED_CALLBACK == 1 ) */
217 #define prvSEND_COMPLETE_FROM_ISR( pxStreamBuffer, pxHigherPriorityTaskWoken ) \
218 sbSEND_COMPLETE_FROM_ISR( ( pxStreamBuffer ), ( pxHigherPriorityTaskWoken ) )
219 #endif /* if ( configUSE_SB_COMPLETED_CALLBACK == 1 ) */
221 /* The number of bytes used to hold the length of a message in the buffer. */
222 #define sbBYTES_TO_STORE_MESSAGE_LENGTH ( sizeof( configMESSAGE_BUFFER_LENGTH_TYPE ) )
224 /* Bits stored in the ucFlags field of the stream buffer. */
225 #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. */
226 #define sbFLAGS_IS_STATICALLY_ALLOCATED ( ( uint8_t ) 2 ) /* Set if the stream buffer was created using statically allocated memory. */
227 #define sbFLAGS_IS_BATCHING_BUFFER ( ( uint8_t ) 4 ) /* Set if the stream buffer was created as a batching buffer, meaning the receiver task will only unblock when the trigger level exceededs. */
229 /*-----------------------------------------------------------*/
231 /* Structure that hold state information on the buffer. */
232 typedef struct StreamBufferDef_t
234 volatile size_t xTail; /* Index to the next item to read within the buffer. */
235 volatile size_t xHead; /* Index to the next item to write within the buffer. */
236 size_t xLength; /* The length of the buffer pointed to by pucBuffer. */
237 size_t xTriggerLevelBytes; /* The number of bytes that must be in the stream buffer before a task that is waiting for data is unblocked. */
238 volatile TaskHandle_t xTaskWaitingToReceive; /* Holds the handle of a task waiting for data, or NULL if no tasks are waiting. */
239 volatile TaskHandle_t xTaskWaitingToSend; /* Holds the handle of a task waiting to send data to a message buffer that is full. */
240 uint8_t * pucBuffer; /* Points to the buffer itself - that is - the RAM that stores the data passed through the buffer. */
243 #if ( configUSE_TRACE_FACILITY == 1 )
244 UBaseType_t uxStreamBufferNumber; /* Used for tracing purposes. */
247 #if ( configUSE_SB_COMPLETED_CALLBACK == 1 )
248 StreamBufferCallbackFunction_t pxSendCompletedCallback; /* Optional callback called on send complete. sbSEND_COMPLETED is called if this is NULL. */
249 StreamBufferCallbackFunction_t pxReceiveCompletedCallback; /* Optional callback called on receive complete. sbRECEIVE_COMPLETED is called if this is NULL. */
251 UBaseType_t uxNotificationIndex; /* The index we are using for notification, by default tskDEFAULT_INDEX_TO_NOTIFY. */
255 * The number of bytes available to be read from the buffer.
257 static size_t prvBytesInBuffer( const StreamBuffer_t * const pxStreamBuffer ) PRIVILEGED_FUNCTION;
260 * Add xCount bytes from pucData into the pxStreamBuffer's data storage area.
261 * This function does not update the buffer's xHead pointer, so multiple writes
262 * may be chained together "atomically". This is useful for Message Buffers where
263 * the length and data bytes are written in two separate chunks, and we don't want
264 * the reader to see the buffer as having grown until after all data is copied over.
265 * This function takes a custom xHead value to indicate where to write to (necessary
266 * for chaining) and returns the the resulting xHead position.
267 * To mark the write as complete, manually set the buffer's xHead field with the
268 * returned xHead from this function.
270 static size_t prvWriteBytesToBuffer( StreamBuffer_t * const pxStreamBuffer,
271 const uint8_t * pucData,
273 size_t xHead ) PRIVILEGED_FUNCTION;
276 * If the stream buffer is being used as a message buffer, then reads an entire
277 * message out of the buffer. If the stream buffer is being used as a stream
278 * buffer then read as many bytes as possible from the buffer.
279 * prvReadBytesFromBuffer() is called to actually extract the bytes from the
280 * buffer's data storage area.
282 static size_t prvReadMessageFromBuffer( StreamBuffer_t * pxStreamBuffer,
284 size_t xBufferLengthBytes,
285 size_t xBytesAvailable ) PRIVILEGED_FUNCTION;
288 * If the stream buffer is being used as a message buffer, then writes an entire
289 * message to the buffer. If the stream buffer is being used as a stream
290 * buffer then write as many bytes as possible to the buffer.
291 * prvWriteBytestoBuffer() is called to actually send the bytes to the buffer's
294 static size_t prvWriteMessageToBuffer( StreamBuffer_t * const pxStreamBuffer,
295 const void * pvTxData,
296 size_t xDataLengthBytes,
298 size_t xRequiredSpace ) PRIVILEGED_FUNCTION;
301 * Copies xCount bytes from the pxStreamBuffer's data storage area to pucData.
302 * This function does not update the buffer's xTail pointer, so multiple reads
303 * may be chained together "atomically". This is useful for Message Buffers where
304 * the length and data bytes are read in two separate chunks, and we don't want
305 * the writer to see the buffer as having more free space until after all data is
306 * copied over, especially if we have to abort the read due to insufficient receiving space.
307 * This function takes a custom xTail value to indicate where to read from (necessary
308 * for chaining) and returns the the resulting xTail position.
309 * To mark the read as complete, manually set the buffer's xTail field with the
310 * returned xTail from this function.
312 static size_t prvReadBytesFromBuffer( StreamBuffer_t * pxStreamBuffer,
315 size_t xTail ) PRIVILEGED_FUNCTION;
318 * Called by both pxStreamBufferCreate() and pxStreamBufferCreateStatic() to
319 * initialise the members of the newly created stream buffer structure.
321 static void prvInitialiseNewStreamBuffer( StreamBuffer_t * const pxStreamBuffer,
322 uint8_t * const pucBuffer,
323 size_t xBufferSizeBytes,
324 size_t xTriggerLevelBytes,
326 StreamBufferCallbackFunction_t pxSendCompletedCallback,
327 StreamBufferCallbackFunction_t pxReceiveCompletedCallback ) PRIVILEGED_FUNCTION;
329 /*-----------------------------------------------------------*/
330 #if ( configSUPPORT_DYNAMIC_ALLOCATION == 1 )
331 StreamBufferHandle_t xStreamBufferGenericCreate( size_t xBufferSizeBytes,
332 size_t xTriggerLevelBytes,
333 BaseType_t xStreamBufferType,
334 StreamBufferCallbackFunction_t pxSendCompletedCallback,
335 StreamBufferCallbackFunction_t pxReceiveCompletedCallback )
337 void * pvAllocatedMemory;
340 traceENTER_xStreamBufferGenericCreate( xBufferSizeBytes, xTriggerLevelBytes, xStreamBufferType, pxSendCompletedCallback, pxReceiveCompletedCallback );
342 /* In case the stream buffer is going to be used as a message buffer
343 * (that is, it will hold discrete messages with a little meta data that
344 * says how big the next message is) check the buffer will be large enough
345 * to hold at least one message. */
346 if( xStreamBufferType == sbTYPE_MESSAGE_BUFFER )
348 /* Is a message buffer but not statically allocated. */
349 ucFlags = sbFLAGS_IS_MESSAGE_BUFFER;
350 configASSERT( xBufferSizeBytes > sbBYTES_TO_STORE_MESSAGE_LENGTH );
352 else if( xStreamBufferType == sbTYPE_STREAM_BATCHING_BUFFER )
354 /* Is a batching buffer but not statically allocated. */
355 ucFlags = sbFLAGS_IS_BATCHING_BUFFER;
356 configASSERT( xBufferSizeBytes > 0 );
360 /* Not a message buffer and not statically allocated. */
362 configASSERT( xBufferSizeBytes > 0 );
365 configASSERT( xTriggerLevelBytes <= xBufferSizeBytes );
367 /* A trigger level of 0 would cause a waiting task to unblock even when
368 * the buffer was empty. */
369 if( xTriggerLevelBytes == ( size_t ) 0 )
371 xTriggerLevelBytes = ( size_t ) 1;
374 /* A stream buffer requires a StreamBuffer_t structure and a buffer.
375 * Both are allocated in a single call to pvPortMalloc(). The
376 * StreamBuffer_t structure is placed at the start of the allocated memory
377 * and the buffer follows immediately after. The requested size is
378 * incremented so the free space is returned as the user would expect -
379 * this is a quirk of the implementation that means otherwise the free
380 * space would be reported as one byte smaller than would be logically
382 if( xBufferSizeBytes < ( xBufferSizeBytes + 1U + sizeof( StreamBuffer_t ) ) )
385 pvAllocatedMemory = pvPortMalloc( xBufferSizeBytes + sizeof( StreamBuffer_t ) );
389 pvAllocatedMemory = NULL;
392 if( pvAllocatedMemory != NULL )
394 /* MISRA Ref 11.5.1 [Malloc memory assignment] */
395 /* More details at: https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/MISRA.md#rule-115 */
396 /* coverity[misra_c_2012_rule_11_5_violation] */
397 prvInitialiseNewStreamBuffer( ( StreamBuffer_t * ) pvAllocatedMemory, /* Structure at the start of the allocated memory. */
398 /* MISRA Ref 11.5.1 [Malloc memory assignment] */
399 /* More details at: https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/MISRA.md#rule-115 */
400 /* coverity[misra_c_2012_rule_11_5_violation] */
401 ( ( uint8_t * ) pvAllocatedMemory ) + sizeof( StreamBuffer_t ), /* Storage area follows. */
405 pxSendCompletedCallback,
406 pxReceiveCompletedCallback );
408 traceSTREAM_BUFFER_CREATE( ( ( StreamBuffer_t * ) pvAllocatedMemory ), xStreamBufferType );
412 traceSTREAM_BUFFER_CREATE_FAILED( xStreamBufferType );
415 traceRETURN_xStreamBufferGenericCreate( pvAllocatedMemory );
417 /* MISRA Ref 11.5.1 [Malloc memory assignment] */
418 /* More details at: https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/MISRA.md#rule-115 */
419 /* coverity[misra_c_2012_rule_11_5_violation] */
420 return ( StreamBufferHandle_t ) pvAllocatedMemory;
422 #endif /* configSUPPORT_DYNAMIC_ALLOCATION */
423 /*-----------------------------------------------------------*/
425 #if ( configSUPPORT_STATIC_ALLOCATION == 1 )
427 StreamBufferHandle_t xStreamBufferGenericCreateStatic( size_t xBufferSizeBytes,
428 size_t xTriggerLevelBytes,
429 BaseType_t xStreamBufferType,
430 uint8_t * const pucStreamBufferStorageArea,
431 StaticStreamBuffer_t * const pxStaticStreamBuffer,
432 StreamBufferCallbackFunction_t pxSendCompletedCallback,
433 StreamBufferCallbackFunction_t pxReceiveCompletedCallback )
435 /* MISRA Ref 11.3.1 [Misaligned access] */
436 /* More details at: https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/MISRA.md#rule-113 */
437 /* coverity[misra_c_2012_rule_11_3_violation] */
438 StreamBuffer_t * const pxStreamBuffer = ( StreamBuffer_t * ) pxStaticStreamBuffer;
439 StreamBufferHandle_t xReturn;
442 traceENTER_xStreamBufferGenericCreateStatic( xBufferSizeBytes, xTriggerLevelBytes, xStreamBufferType, pucStreamBufferStorageArea, pxStaticStreamBuffer, pxSendCompletedCallback, pxReceiveCompletedCallback );
444 configASSERT( pucStreamBufferStorageArea );
445 configASSERT( pxStaticStreamBuffer );
446 configASSERT( xTriggerLevelBytes <= xBufferSizeBytes );
448 /* A trigger level of 0 would cause a waiting task to unblock even when
449 * the buffer was empty. */
450 if( xTriggerLevelBytes == ( size_t ) 0 )
452 xTriggerLevelBytes = ( size_t ) 1;
455 /* In case the stream buffer is going to be used as a message buffer
456 * (that is, it will hold discrete messages with a little meta data that
457 * says how big the next message is) check the buffer will be large enough
458 * to hold at least one message. */
460 if( xStreamBufferType == sbTYPE_MESSAGE_BUFFER )
462 /* Statically allocated message buffer. */
463 ucFlags = sbFLAGS_IS_MESSAGE_BUFFER | sbFLAGS_IS_STATICALLY_ALLOCATED;
464 configASSERT( xBufferSizeBytes > sbBYTES_TO_STORE_MESSAGE_LENGTH );
466 else if( xStreamBufferType == sbTYPE_STREAM_BATCHING_BUFFER )
468 /* Statically allocated batching buffer. */
469 ucFlags = sbFLAGS_IS_BATCHING_BUFFER | sbFLAGS_IS_STATICALLY_ALLOCATED;
470 configASSERT( xBufferSizeBytes > 0 );
474 /* Statically allocated stream buffer. */
475 ucFlags = sbFLAGS_IS_STATICALLY_ALLOCATED;
478 #if ( configASSERT_DEFINED == 1 )
480 /* Sanity check that the size of the structure used to declare a
481 * variable of type StaticStreamBuffer_t equals the size of the real
482 * message buffer structure. */
483 volatile size_t xSize = sizeof( StaticStreamBuffer_t );
484 configASSERT( xSize == sizeof( StreamBuffer_t ) );
486 #endif /* configASSERT_DEFINED */
488 if( ( pucStreamBufferStorageArea != NULL ) && ( pxStaticStreamBuffer != NULL ) )
490 prvInitialiseNewStreamBuffer( pxStreamBuffer,
491 pucStreamBufferStorageArea,
495 pxSendCompletedCallback,
496 pxReceiveCompletedCallback );
498 /* Remember this was statically allocated in case it is ever deleted
500 pxStreamBuffer->ucFlags |= sbFLAGS_IS_STATICALLY_ALLOCATED;
502 traceSTREAM_BUFFER_CREATE( pxStreamBuffer, xStreamBufferType );
504 /* MISRA Ref 11.3.1 [Misaligned access] */
505 /* More details at: https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/MISRA.md#rule-113 */
506 /* coverity[misra_c_2012_rule_11_3_violation] */
507 xReturn = ( StreamBufferHandle_t ) pxStaticStreamBuffer;
512 traceSTREAM_BUFFER_CREATE_STATIC_FAILED( xReturn, xStreamBufferType );
515 traceRETURN_xStreamBufferGenericCreateStatic( xReturn );
519 #endif /* ( configSUPPORT_STATIC_ALLOCATION == 1 ) */
520 /*-----------------------------------------------------------*/
522 #if ( configSUPPORT_STATIC_ALLOCATION == 1 )
523 BaseType_t xStreamBufferGetStaticBuffers( StreamBufferHandle_t xStreamBuffer,
524 uint8_t ** ppucStreamBufferStorageArea,
525 StaticStreamBuffer_t ** ppxStaticStreamBuffer )
528 StreamBuffer_t * const pxStreamBuffer = xStreamBuffer;
530 traceENTER_xStreamBufferGetStaticBuffers( xStreamBuffer, ppucStreamBufferStorageArea, ppxStaticStreamBuffer );
532 configASSERT( pxStreamBuffer );
533 configASSERT( ppucStreamBufferStorageArea );
534 configASSERT( ppxStaticStreamBuffer );
536 if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_STATICALLY_ALLOCATED ) != ( uint8_t ) 0 )
538 *ppucStreamBufferStorageArea = pxStreamBuffer->pucBuffer;
539 /* MISRA Ref 11.3.1 [Misaligned access] */
540 /* More details at: https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/MISRA.md#rule-113 */
541 /* coverity[misra_c_2012_rule_11_3_violation] */
542 *ppxStaticStreamBuffer = ( StaticStreamBuffer_t * ) pxStreamBuffer;
550 traceRETURN_xStreamBufferGetStaticBuffers( xReturn );
554 #endif /* configSUPPORT_STATIC_ALLOCATION */
555 /*-----------------------------------------------------------*/
557 void vStreamBufferDelete( StreamBufferHandle_t xStreamBuffer )
559 StreamBuffer_t * pxStreamBuffer = xStreamBuffer;
561 traceENTER_vStreamBufferDelete( xStreamBuffer );
563 configASSERT( pxStreamBuffer );
565 traceSTREAM_BUFFER_DELETE( xStreamBuffer );
567 if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_STATICALLY_ALLOCATED ) == ( uint8_t ) pdFALSE )
569 #if ( configSUPPORT_DYNAMIC_ALLOCATION == 1 )
571 /* Both the structure and the buffer were allocated using a single call
572 * to pvPortMalloc(), hence only one call to vPortFree() is required. */
573 vPortFree( ( void * ) pxStreamBuffer );
577 /* Should not be possible to get here, ucFlags must be corrupt.
578 * Force an assert. */
579 configASSERT( xStreamBuffer == ( StreamBufferHandle_t ) ~0 );
585 /* The structure and buffer were not allocated dynamically and cannot be
586 * freed - just scrub the structure so future use will assert. */
587 ( void ) memset( pxStreamBuffer, 0x00, sizeof( StreamBuffer_t ) );
590 traceRETURN_vStreamBufferDelete();
592 /*-----------------------------------------------------------*/
594 BaseType_t xStreamBufferReset( StreamBufferHandle_t xStreamBuffer )
596 StreamBuffer_t * const pxStreamBuffer = xStreamBuffer;
597 BaseType_t xReturn = pdFAIL;
598 StreamBufferCallbackFunction_t pxSendCallback = NULL, pxReceiveCallback = NULL;
600 #if ( configUSE_TRACE_FACILITY == 1 )
601 UBaseType_t uxStreamBufferNumber;
604 traceENTER_xStreamBufferReset( xStreamBuffer );
606 configASSERT( pxStreamBuffer );
608 #if ( configUSE_TRACE_FACILITY == 1 )
610 /* Store the stream buffer number so it can be restored after the
612 uxStreamBufferNumber = pxStreamBuffer->uxStreamBufferNumber;
616 /* Can only reset a message buffer if there are no tasks blocked on it. */
617 taskENTER_CRITICAL();
619 if( ( pxStreamBuffer->xTaskWaitingToReceive == NULL ) && ( pxStreamBuffer->xTaskWaitingToSend == NULL ) )
621 #if ( configUSE_SB_COMPLETED_CALLBACK == 1 )
623 pxSendCallback = pxStreamBuffer->pxSendCompletedCallback;
624 pxReceiveCallback = pxStreamBuffer->pxReceiveCompletedCallback;
628 prvInitialiseNewStreamBuffer( pxStreamBuffer,
629 pxStreamBuffer->pucBuffer,
630 pxStreamBuffer->xLength,
631 pxStreamBuffer->xTriggerLevelBytes,
632 pxStreamBuffer->ucFlags,
636 #if ( configUSE_TRACE_FACILITY == 1 )
638 pxStreamBuffer->uxStreamBufferNumber = uxStreamBufferNumber;
642 traceSTREAM_BUFFER_RESET( xStreamBuffer );
649 traceRETURN_xStreamBufferReset( xReturn );
653 /*-----------------------------------------------------------*/
655 BaseType_t xStreamBufferResetFromISR( StreamBufferHandle_t xStreamBuffer )
657 StreamBuffer_t * const pxStreamBuffer = xStreamBuffer;
658 BaseType_t xReturn = pdFAIL;
659 StreamBufferCallbackFunction_t pxSendCallback = NULL, pxReceiveCallback = NULL;
660 UBaseType_t uxSavedInterruptStatus;
662 #if ( configUSE_TRACE_FACILITY == 1 )
663 UBaseType_t uxStreamBufferNumber;
666 traceENTER_xStreamBufferResetFromISR( xStreamBuffer );
668 configASSERT( pxStreamBuffer );
670 #if ( configUSE_TRACE_FACILITY == 1 )
672 /* Store the stream buffer number so it can be restored after the
674 uxStreamBufferNumber = pxStreamBuffer->uxStreamBufferNumber;
678 /* Can only reset a message buffer if there are no tasks blocked on it. */
679 /* MISRA Ref 4.7.1 [Return value shall be checked] */
680 /* More details at: https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/MISRA.md#dir-47 */
681 /* coverity[misra_c_2012_directive_4_7_violation] */
682 uxSavedInterruptStatus = taskENTER_CRITICAL_FROM_ISR();
684 if( ( pxStreamBuffer->xTaskWaitingToReceive == NULL ) && ( pxStreamBuffer->xTaskWaitingToSend == NULL ) )
686 #if ( configUSE_SB_COMPLETED_CALLBACK == 1 )
688 pxSendCallback = pxStreamBuffer->pxSendCompletedCallback;
689 pxReceiveCallback = pxStreamBuffer->pxReceiveCompletedCallback;
693 prvInitialiseNewStreamBuffer( pxStreamBuffer,
694 pxStreamBuffer->pucBuffer,
695 pxStreamBuffer->xLength,
696 pxStreamBuffer->xTriggerLevelBytes,
697 pxStreamBuffer->ucFlags,
701 #if ( configUSE_TRACE_FACILITY == 1 )
703 pxStreamBuffer->uxStreamBufferNumber = uxStreamBufferNumber;
707 traceSTREAM_BUFFER_RESET_FROM_ISR( xStreamBuffer );
712 taskEXIT_CRITICAL_FROM_ISR( uxSavedInterruptStatus );
714 traceRETURN_xStreamBufferResetFromISR( xReturn );
718 /*-----------------------------------------------------------*/
720 BaseType_t xStreamBufferSetTriggerLevel( StreamBufferHandle_t xStreamBuffer,
721 size_t xTriggerLevel )
723 StreamBuffer_t * const pxStreamBuffer = xStreamBuffer;
726 traceENTER_xStreamBufferSetTriggerLevel( xStreamBuffer, xTriggerLevel );
728 configASSERT( pxStreamBuffer );
730 /* It is not valid for the trigger level to be 0. */
731 if( xTriggerLevel == ( size_t ) 0 )
733 xTriggerLevel = ( size_t ) 1;
736 /* The trigger level is the number of bytes that must be in the stream
737 * buffer before a task that is waiting for data is unblocked. */
738 if( xTriggerLevel < pxStreamBuffer->xLength )
740 pxStreamBuffer->xTriggerLevelBytes = xTriggerLevel;
748 traceRETURN_xStreamBufferSetTriggerLevel( xReturn );
752 /*-----------------------------------------------------------*/
754 size_t xStreamBufferSpacesAvailable( StreamBufferHandle_t xStreamBuffer )
756 const StreamBuffer_t * const pxStreamBuffer = xStreamBuffer;
758 size_t xOriginalTail;
760 traceENTER_xStreamBufferSpacesAvailable( xStreamBuffer );
762 configASSERT( pxStreamBuffer );
764 /* The code below reads xTail and then xHead. This is safe if the stream
765 * buffer is updated once between the two reads - but not if the stream buffer
766 * is updated more than once between the two reads - hence the loop. */
769 xOriginalTail = pxStreamBuffer->xTail;
770 xSpace = pxStreamBuffer->xLength + pxStreamBuffer->xTail;
771 xSpace -= pxStreamBuffer->xHead;
772 } while( xOriginalTail != pxStreamBuffer->xTail );
774 xSpace -= ( size_t ) 1;
776 if( xSpace >= pxStreamBuffer->xLength )
778 xSpace -= pxStreamBuffer->xLength;
782 mtCOVERAGE_TEST_MARKER();
785 traceRETURN_xStreamBufferSpacesAvailable( xSpace );
789 /*-----------------------------------------------------------*/
791 size_t xStreamBufferBytesAvailable( StreamBufferHandle_t xStreamBuffer )
793 const StreamBuffer_t * const pxStreamBuffer = xStreamBuffer;
796 traceENTER_xStreamBufferBytesAvailable( xStreamBuffer );
798 configASSERT( pxStreamBuffer );
800 xReturn = prvBytesInBuffer( pxStreamBuffer );
802 traceRETURN_xStreamBufferBytesAvailable( xReturn );
806 /*-----------------------------------------------------------*/
808 size_t xStreamBufferSend( StreamBufferHandle_t xStreamBuffer,
809 const void * pvTxData,
810 size_t xDataLengthBytes,
811 TickType_t xTicksToWait )
813 StreamBuffer_t * const pxStreamBuffer = xStreamBuffer;
814 size_t xReturn, xSpace = 0;
815 size_t xRequiredSpace = xDataLengthBytes;
817 size_t xMaxReportedSpace = 0;
819 traceENTER_xStreamBufferSend( xStreamBuffer, pvTxData, xDataLengthBytes, xTicksToWait );
821 configASSERT( pvTxData );
822 configASSERT( pxStreamBuffer );
824 /* The maximum amount of space a stream buffer will ever report is its length
826 xMaxReportedSpace = pxStreamBuffer->xLength - ( size_t ) 1;
828 /* This send function is used to write to both message buffers and stream
829 * buffers. If this is a message buffer then the space needed must be
830 * increased by the amount of bytes needed to store the length of the
832 if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) != ( uint8_t ) 0 )
834 xRequiredSpace += sbBYTES_TO_STORE_MESSAGE_LENGTH;
837 configASSERT( xRequiredSpace > xDataLengthBytes );
839 /* If this is a message buffer then it must be possible to write the
841 if( xRequiredSpace > xMaxReportedSpace )
843 /* The message would not fit even if the entire buffer was empty,
844 * so don't wait for space. */
845 xTicksToWait = ( TickType_t ) 0;
849 mtCOVERAGE_TEST_MARKER();
854 /* If this is a stream buffer then it is acceptable to write only part
855 * of the message to the buffer. Cap the length to the total length of
857 if( xRequiredSpace > xMaxReportedSpace )
859 xRequiredSpace = xMaxReportedSpace;
863 mtCOVERAGE_TEST_MARKER();
867 if( xTicksToWait != ( TickType_t ) 0 )
869 vTaskSetTimeOutState( &xTimeOut );
873 /* Wait until the required number of bytes are free in the message
875 taskENTER_CRITICAL();
877 xSpace = xStreamBufferSpacesAvailable( pxStreamBuffer );
879 if( xSpace < xRequiredSpace )
881 /* Clear notification state as going to wait for space. */
882 ( void ) xTaskNotifyStateClearIndexed( NULL, pxStreamBuffer->uxNotificationIndex );
884 /* Should only be one writer. */
885 configASSERT( pxStreamBuffer->xTaskWaitingToSend == NULL );
886 pxStreamBuffer->xTaskWaitingToSend = xTaskGetCurrentTaskHandle();
896 traceBLOCKING_ON_STREAM_BUFFER_SEND( xStreamBuffer );
897 ( void ) xTaskNotifyWaitIndexed( pxStreamBuffer->uxNotificationIndex, ( uint32_t ) 0, ( uint32_t ) 0, NULL, xTicksToWait );
898 pxStreamBuffer->xTaskWaitingToSend = NULL;
899 } while( xTaskCheckForTimeOut( &xTimeOut, &xTicksToWait ) == pdFALSE );
903 mtCOVERAGE_TEST_MARKER();
906 if( xSpace == ( size_t ) 0 )
908 xSpace = xStreamBufferSpacesAvailable( pxStreamBuffer );
912 mtCOVERAGE_TEST_MARKER();
915 xReturn = prvWriteMessageToBuffer( pxStreamBuffer, pvTxData, xDataLengthBytes, xSpace, xRequiredSpace );
917 if( xReturn > ( size_t ) 0 )
919 traceSTREAM_BUFFER_SEND( xStreamBuffer, xReturn );
921 /* Was a task waiting for the data? */
922 if( prvBytesInBuffer( pxStreamBuffer ) >= pxStreamBuffer->xTriggerLevelBytes )
924 prvSEND_COMPLETED( pxStreamBuffer );
928 mtCOVERAGE_TEST_MARKER();
933 mtCOVERAGE_TEST_MARKER();
934 traceSTREAM_BUFFER_SEND_FAILED( xStreamBuffer );
937 traceRETURN_xStreamBufferSend( xReturn );
941 /*-----------------------------------------------------------*/
943 size_t xStreamBufferSendFromISR( StreamBufferHandle_t xStreamBuffer,
944 const void * pvTxData,
945 size_t xDataLengthBytes,
946 BaseType_t * const pxHigherPriorityTaskWoken )
948 StreamBuffer_t * const pxStreamBuffer = xStreamBuffer;
949 size_t xReturn, xSpace;
950 size_t xRequiredSpace = xDataLengthBytes;
952 traceENTER_xStreamBufferSendFromISR( xStreamBuffer, pvTxData, xDataLengthBytes, pxHigherPriorityTaskWoken );
954 configASSERT( pvTxData );
955 configASSERT( pxStreamBuffer );
957 /* This send function is used to write to both message buffers and stream
958 * buffers. If this is a message buffer then the space needed must be
959 * increased by the amount of bytes needed to store the length of the
961 if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) != ( uint8_t ) 0 )
963 xRequiredSpace += sbBYTES_TO_STORE_MESSAGE_LENGTH;
967 mtCOVERAGE_TEST_MARKER();
970 xSpace = xStreamBufferSpacesAvailable( pxStreamBuffer );
971 xReturn = prvWriteMessageToBuffer( pxStreamBuffer, pvTxData, xDataLengthBytes, xSpace, xRequiredSpace );
973 if( xReturn > ( size_t ) 0 )
975 /* Was a task waiting for the data? */
976 if( prvBytesInBuffer( pxStreamBuffer ) >= pxStreamBuffer->xTriggerLevelBytes )
978 /* MISRA Ref 4.7.1 [Return value shall be checked] */
979 /* More details at: https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/MISRA.md#dir-47 */
980 /* coverity[misra_c_2012_directive_4_7_violation] */
981 prvSEND_COMPLETE_FROM_ISR( pxStreamBuffer, pxHigherPriorityTaskWoken );
985 mtCOVERAGE_TEST_MARKER();
990 mtCOVERAGE_TEST_MARKER();
993 traceSTREAM_BUFFER_SEND_FROM_ISR( xStreamBuffer, xReturn );
994 traceRETURN_xStreamBufferSendFromISR( xReturn );
998 /*-----------------------------------------------------------*/
1000 static size_t prvWriteMessageToBuffer( StreamBuffer_t * const pxStreamBuffer,
1001 const void * pvTxData,
1002 size_t xDataLengthBytes,
1004 size_t xRequiredSpace )
1006 size_t xNextHead = pxStreamBuffer->xHead;
1007 configMESSAGE_BUFFER_LENGTH_TYPE xMessageLength;
1009 if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) != ( uint8_t ) 0 )
1011 /* This is a message buffer, as opposed to a stream buffer. */
1013 /* Convert xDataLengthBytes to the message length type. */
1014 xMessageLength = ( configMESSAGE_BUFFER_LENGTH_TYPE ) xDataLengthBytes;
1016 /* Ensure the data length given fits within configMESSAGE_BUFFER_LENGTH_TYPE. */
1017 configASSERT( ( size_t ) xMessageLength == xDataLengthBytes );
1019 if( xSpace >= xRequiredSpace )
1021 /* There is enough space to write both the message length and the message
1022 * itself into the buffer. Start by writing the length of the data, the data
1023 * itself will be written later in this function. */
1024 xNextHead = prvWriteBytesToBuffer( pxStreamBuffer, ( const uint8_t * ) &( xMessageLength ), sbBYTES_TO_STORE_MESSAGE_LENGTH, xNextHead );
1028 /* Not enough space, so do not write data to the buffer. */
1029 xDataLengthBytes = 0;
1034 /* This is a stream buffer, as opposed to a message buffer, so writing a
1035 * stream of bytes rather than discrete messages. Plan to write as many
1036 * bytes as possible. */
1037 xDataLengthBytes = configMIN( xDataLengthBytes, xSpace );
1040 if( xDataLengthBytes != ( size_t ) 0 )
1042 /* Write the data to the buffer. */
1043 /* MISRA Ref 11.5.5 [Void pointer assignment] */
1044 /* More details at: https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/MISRA.md#rule-115 */
1045 /* coverity[misra_c_2012_rule_11_5_violation] */
1046 pxStreamBuffer->xHead = prvWriteBytesToBuffer( pxStreamBuffer, ( const uint8_t * ) pvTxData, xDataLengthBytes, xNextHead );
1049 return xDataLengthBytes;
1051 /*-----------------------------------------------------------*/
1053 size_t xStreamBufferReceive( StreamBufferHandle_t xStreamBuffer,
1055 size_t xBufferLengthBytes,
1056 TickType_t xTicksToWait )
1058 StreamBuffer_t * const pxStreamBuffer = xStreamBuffer;
1059 size_t xReceivedLength = 0, xBytesAvailable, xBytesToStoreMessageLength;
1061 traceENTER_xStreamBufferReceive( xStreamBuffer, pvRxData, xBufferLengthBytes, xTicksToWait );
1063 configASSERT( pvRxData );
1064 configASSERT( pxStreamBuffer );
1066 /* This receive function is used by both message buffers, which store
1067 * discrete messages, and stream buffers, which store a continuous stream of
1068 * bytes. Discrete messages include an additional
1069 * sbBYTES_TO_STORE_MESSAGE_LENGTH bytes that hold the length of the
1071 if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) != ( uint8_t ) 0 )
1073 xBytesToStoreMessageLength = sbBYTES_TO_STORE_MESSAGE_LENGTH;
1075 else if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_BATCHING_BUFFER ) != ( uint8_t ) 0 )
1077 /* Force task to block if the batching buffer contains less bytes than
1078 * the trigger level. */
1079 xBytesToStoreMessageLength = pxStreamBuffer->xTriggerLevelBytes;
1083 xBytesToStoreMessageLength = 0;
1086 if( xTicksToWait != ( TickType_t ) 0 )
1088 /* Checking if there is data and clearing the notification state must be
1089 * performed atomically. */
1090 taskENTER_CRITICAL();
1092 xBytesAvailable = prvBytesInBuffer( pxStreamBuffer );
1094 /* If this function was invoked by a message buffer read then
1095 * xBytesToStoreMessageLength holds the number of bytes used to hold
1096 * the length of the next discrete message. If this function was
1097 * invoked by a stream buffer read then xBytesToStoreMessageLength will
1098 * be 0. If this function was invoked by a stream batch buffer read
1099 * then xBytesToStoreMessageLength will be xTriggerLevelBytes value
1101 if( xBytesAvailable <= xBytesToStoreMessageLength )
1103 /* Clear notification state as going to wait for data. */
1104 ( void ) xTaskNotifyStateClearIndexed( NULL, pxStreamBuffer->uxNotificationIndex );
1106 /* Should only be one reader. */
1107 configASSERT( pxStreamBuffer->xTaskWaitingToReceive == NULL );
1108 pxStreamBuffer->xTaskWaitingToReceive = xTaskGetCurrentTaskHandle();
1112 mtCOVERAGE_TEST_MARKER();
1115 taskEXIT_CRITICAL();
1117 if( xBytesAvailable <= xBytesToStoreMessageLength )
1119 /* Wait for data to be available. */
1120 traceBLOCKING_ON_STREAM_BUFFER_RECEIVE( xStreamBuffer );
1121 ( void ) xTaskNotifyWaitIndexed( pxStreamBuffer->uxNotificationIndex, ( uint32_t ) 0, ( uint32_t ) 0, NULL, xTicksToWait );
1122 pxStreamBuffer->xTaskWaitingToReceive = NULL;
1124 /* Recheck the data available after blocking. */
1125 xBytesAvailable = prvBytesInBuffer( pxStreamBuffer );
1129 mtCOVERAGE_TEST_MARKER();
1134 xBytesAvailable = prvBytesInBuffer( pxStreamBuffer );
1137 /* Whether receiving a discrete message (where xBytesToStoreMessageLength
1138 * holds the number of bytes used to store the message length) or a stream of
1139 * bytes (where xBytesToStoreMessageLength is zero), the number of bytes
1140 * available must be greater than xBytesToStoreMessageLength to be able to
1141 * read bytes from the buffer. */
1142 if( xBytesAvailable > xBytesToStoreMessageLength )
1144 xReceivedLength = prvReadMessageFromBuffer( pxStreamBuffer, pvRxData, xBufferLengthBytes, xBytesAvailable );
1146 /* Was a task waiting for space in the buffer? */
1147 if( xReceivedLength != ( size_t ) 0 )
1149 traceSTREAM_BUFFER_RECEIVE( xStreamBuffer, xReceivedLength );
1150 prvRECEIVE_COMPLETED( xStreamBuffer );
1154 mtCOVERAGE_TEST_MARKER();
1159 traceSTREAM_BUFFER_RECEIVE_FAILED( xStreamBuffer );
1160 mtCOVERAGE_TEST_MARKER();
1163 traceRETURN_xStreamBufferReceive( xReceivedLength );
1165 return xReceivedLength;
1167 /*-----------------------------------------------------------*/
1169 size_t xStreamBufferNextMessageLengthBytes( StreamBufferHandle_t xStreamBuffer )
1171 StreamBuffer_t * const pxStreamBuffer = xStreamBuffer;
1172 size_t xReturn, xBytesAvailable;
1173 configMESSAGE_BUFFER_LENGTH_TYPE xTempReturn;
1175 traceENTER_xStreamBufferNextMessageLengthBytes( xStreamBuffer );
1177 configASSERT( pxStreamBuffer );
1179 /* Ensure the stream buffer is being used as a message buffer. */
1180 if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) != ( uint8_t ) 0 )
1182 xBytesAvailable = prvBytesInBuffer( pxStreamBuffer );
1184 if( xBytesAvailable > sbBYTES_TO_STORE_MESSAGE_LENGTH )
1186 /* The number of bytes available is greater than the number of bytes
1187 * required to hold the length of the next message, so another message
1189 ( void ) prvReadBytesFromBuffer( pxStreamBuffer, ( uint8_t * ) &xTempReturn, sbBYTES_TO_STORE_MESSAGE_LENGTH, pxStreamBuffer->xTail );
1190 xReturn = ( size_t ) xTempReturn;
1194 /* The minimum amount of bytes in a message buffer is
1195 * ( sbBYTES_TO_STORE_MESSAGE_LENGTH + 1 ), so if xBytesAvailable is
1196 * less than sbBYTES_TO_STORE_MESSAGE_LENGTH the only other valid
1198 configASSERT( xBytesAvailable == 0 );
1207 traceRETURN_xStreamBufferNextMessageLengthBytes( xReturn );
1211 /*-----------------------------------------------------------*/
1213 size_t xStreamBufferReceiveFromISR( StreamBufferHandle_t xStreamBuffer,
1215 size_t xBufferLengthBytes,
1216 BaseType_t * const pxHigherPriorityTaskWoken )
1218 StreamBuffer_t * const pxStreamBuffer = xStreamBuffer;
1219 size_t xReceivedLength = 0, xBytesAvailable, xBytesToStoreMessageLength;
1221 traceENTER_xStreamBufferReceiveFromISR( xStreamBuffer, pvRxData, xBufferLengthBytes, pxHigherPriorityTaskWoken );
1223 configASSERT( pvRxData );
1224 configASSERT( pxStreamBuffer );
1226 /* This receive function is used by both message buffers, which store
1227 * discrete messages, and stream buffers, which store a continuous stream of
1228 * bytes. Discrete messages include an additional
1229 * sbBYTES_TO_STORE_MESSAGE_LENGTH bytes that hold the length of the
1231 if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) != ( uint8_t ) 0 )
1233 xBytesToStoreMessageLength = sbBYTES_TO_STORE_MESSAGE_LENGTH;
1237 xBytesToStoreMessageLength = 0;
1240 xBytesAvailable = prvBytesInBuffer( pxStreamBuffer );
1242 /* Whether receiving a discrete message (where xBytesToStoreMessageLength
1243 * holds the number of bytes used to store the message length) or a stream of
1244 * bytes (where xBytesToStoreMessageLength is zero), the number of bytes
1245 * available must be greater than xBytesToStoreMessageLength to be able to
1246 * read bytes from the buffer. */
1247 if( xBytesAvailable > xBytesToStoreMessageLength )
1249 xReceivedLength = prvReadMessageFromBuffer( pxStreamBuffer, pvRxData, xBufferLengthBytes, xBytesAvailable );
1251 /* Was a task waiting for space in the buffer? */
1252 if( xReceivedLength != ( size_t ) 0 )
1254 /* MISRA Ref 4.7.1 [Return value shall be checked] */
1255 /* More details at: https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/MISRA.md#dir-47 */
1256 /* coverity[misra_c_2012_directive_4_7_violation] */
1257 prvRECEIVE_COMPLETED_FROM_ISR( pxStreamBuffer, pxHigherPriorityTaskWoken );
1261 mtCOVERAGE_TEST_MARKER();
1266 mtCOVERAGE_TEST_MARKER();
1269 traceSTREAM_BUFFER_RECEIVE_FROM_ISR( xStreamBuffer, xReceivedLength );
1270 traceRETURN_xStreamBufferReceiveFromISR( xReceivedLength );
1272 return xReceivedLength;
1274 /*-----------------------------------------------------------*/
1276 static size_t prvReadMessageFromBuffer( StreamBuffer_t * pxStreamBuffer,
1278 size_t xBufferLengthBytes,
1279 size_t xBytesAvailable )
1281 size_t xCount, xNextMessageLength;
1282 configMESSAGE_BUFFER_LENGTH_TYPE xTempNextMessageLength;
1283 size_t xNextTail = pxStreamBuffer->xTail;
1285 if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) != ( uint8_t ) 0 )
1287 /* A discrete message is being received. First receive the length
1288 * of the message. */
1289 xNextTail = prvReadBytesFromBuffer( pxStreamBuffer, ( uint8_t * ) &xTempNextMessageLength, sbBYTES_TO_STORE_MESSAGE_LENGTH, xNextTail );
1290 xNextMessageLength = ( size_t ) xTempNextMessageLength;
1292 /* Reduce the number of bytes available by the number of bytes just
1294 xBytesAvailable -= sbBYTES_TO_STORE_MESSAGE_LENGTH;
1296 /* Check there is enough space in the buffer provided by the
1298 if( xNextMessageLength > xBufferLengthBytes )
1300 /* The user has provided insufficient space to read the message. */
1301 xNextMessageLength = 0;
1305 mtCOVERAGE_TEST_MARKER();
1310 /* A stream of bytes is being received (as opposed to a discrete
1311 * message), so read as many bytes as possible. */
1312 xNextMessageLength = xBufferLengthBytes;
1315 /* Use the minimum of the wanted bytes and the available bytes. */
1316 xCount = configMIN( xNextMessageLength, xBytesAvailable );
1318 if( xCount != ( size_t ) 0 )
1320 /* Read the actual data and update the tail to mark the data as officially consumed. */
1321 /* MISRA Ref 11.5.5 [Void pointer assignment] */
1322 /* More details at: https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/MISRA.md#rule-115 */
1323 /* coverity[misra_c_2012_rule_11_5_violation] */
1324 pxStreamBuffer->xTail = prvReadBytesFromBuffer( pxStreamBuffer, ( uint8_t * ) pvRxData, xCount, xNextTail );
1329 /*-----------------------------------------------------------*/
1331 BaseType_t xStreamBufferIsEmpty( StreamBufferHandle_t xStreamBuffer )
1333 const StreamBuffer_t * const pxStreamBuffer = xStreamBuffer;
1337 traceENTER_xStreamBufferIsEmpty( xStreamBuffer );
1339 configASSERT( pxStreamBuffer );
1341 /* True if no bytes are available. */
1342 xTail = pxStreamBuffer->xTail;
1344 if( pxStreamBuffer->xHead == xTail )
1353 traceRETURN_xStreamBufferIsEmpty( xReturn );
1357 /*-----------------------------------------------------------*/
1359 BaseType_t xStreamBufferIsFull( StreamBufferHandle_t xStreamBuffer )
1362 size_t xBytesToStoreMessageLength;
1363 const StreamBuffer_t * const pxStreamBuffer = xStreamBuffer;
1365 traceENTER_xStreamBufferIsFull( xStreamBuffer );
1367 configASSERT( pxStreamBuffer );
1369 /* This generic version of the receive function is used by both message
1370 * buffers, which store discrete messages, and stream buffers, which store a
1371 * continuous stream of bytes. Discrete messages include an additional
1372 * sbBYTES_TO_STORE_MESSAGE_LENGTH bytes that hold the length of the message. */
1373 if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) != ( uint8_t ) 0 )
1375 xBytesToStoreMessageLength = sbBYTES_TO_STORE_MESSAGE_LENGTH;
1379 xBytesToStoreMessageLength = 0;
1382 /* True if the available space equals zero. */
1383 if( xStreamBufferSpacesAvailable( xStreamBuffer ) <= xBytesToStoreMessageLength )
1392 traceRETURN_xStreamBufferIsFull( xReturn );
1396 /*-----------------------------------------------------------*/
1398 BaseType_t xStreamBufferSendCompletedFromISR( StreamBufferHandle_t xStreamBuffer,
1399 BaseType_t * pxHigherPriorityTaskWoken )
1401 StreamBuffer_t * const pxStreamBuffer = xStreamBuffer;
1403 UBaseType_t uxSavedInterruptStatus;
1405 traceENTER_xStreamBufferSendCompletedFromISR( xStreamBuffer, pxHigherPriorityTaskWoken );
1407 configASSERT( pxStreamBuffer );
1409 /* MISRA Ref 4.7.1 [Return value shall be checked] */
1410 /* More details at: https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/MISRA.md#dir-47 */
1411 /* coverity[misra_c_2012_directive_4_7_violation] */
1412 uxSavedInterruptStatus = taskENTER_CRITICAL_FROM_ISR();
1414 if( ( pxStreamBuffer )->xTaskWaitingToReceive != NULL )
1416 ( void ) xTaskNotifyIndexedFromISR( ( pxStreamBuffer )->xTaskWaitingToReceive,
1417 ( pxStreamBuffer )->uxNotificationIndex,
1420 pxHigherPriorityTaskWoken );
1421 ( pxStreamBuffer )->xTaskWaitingToReceive = NULL;
1429 taskEXIT_CRITICAL_FROM_ISR( uxSavedInterruptStatus );
1431 traceRETURN_xStreamBufferSendCompletedFromISR( xReturn );
1435 /*-----------------------------------------------------------*/
1437 BaseType_t xStreamBufferReceiveCompletedFromISR( StreamBufferHandle_t xStreamBuffer,
1438 BaseType_t * pxHigherPriorityTaskWoken )
1440 StreamBuffer_t * const pxStreamBuffer = xStreamBuffer;
1442 UBaseType_t uxSavedInterruptStatus;
1444 traceENTER_xStreamBufferReceiveCompletedFromISR( xStreamBuffer, pxHigherPriorityTaskWoken );
1446 configASSERT( pxStreamBuffer );
1448 /* MISRA Ref 4.7.1 [Return value shall be checked] */
1449 /* More details at: https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/MISRA.md#dir-47 */
1450 /* coverity[misra_c_2012_directive_4_7_violation] */
1451 uxSavedInterruptStatus = taskENTER_CRITICAL_FROM_ISR();
1453 if( ( pxStreamBuffer )->xTaskWaitingToSend != NULL )
1455 ( void ) xTaskNotifyIndexedFromISR( ( pxStreamBuffer )->xTaskWaitingToSend,
1456 ( pxStreamBuffer )->uxNotificationIndex,
1459 pxHigherPriorityTaskWoken );
1460 ( pxStreamBuffer )->xTaskWaitingToSend = NULL;
1468 taskEXIT_CRITICAL_FROM_ISR( uxSavedInterruptStatus );
1470 traceRETURN_xStreamBufferReceiveCompletedFromISR( xReturn );
1474 /*-----------------------------------------------------------*/
1476 static size_t prvWriteBytesToBuffer( StreamBuffer_t * const pxStreamBuffer,
1477 const uint8_t * pucData,
1481 size_t xFirstLength;
1483 configASSERT( xCount > ( size_t ) 0 );
1485 /* Calculate the number of bytes that can be added in the first write -
1486 * which may be less than the total number of bytes that need to be added if
1487 * the buffer will wrap back to the beginning. */
1488 xFirstLength = configMIN( pxStreamBuffer->xLength - xHead, xCount );
1490 /* Write as many bytes as can be written in the first write. */
1491 configASSERT( ( xHead + xFirstLength ) <= pxStreamBuffer->xLength );
1492 ( void ) memcpy( ( void * ) ( &( pxStreamBuffer->pucBuffer[ xHead ] ) ), ( const void * ) pucData, xFirstLength );
1494 /* If the number of bytes written was less than the number that could be
1495 * written in the first write... */
1496 if( xCount > xFirstLength )
1498 /* ...then write the remaining bytes to the start of the buffer. */
1499 configASSERT( ( xCount - xFirstLength ) <= pxStreamBuffer->xLength );
1500 ( void ) memcpy( ( void * ) pxStreamBuffer->pucBuffer, ( const void * ) &( pucData[ xFirstLength ] ), xCount - xFirstLength );
1504 mtCOVERAGE_TEST_MARKER();
1509 if( xHead >= pxStreamBuffer->xLength )
1511 xHead -= pxStreamBuffer->xLength;
1515 mtCOVERAGE_TEST_MARKER();
1520 /*-----------------------------------------------------------*/
1522 static size_t prvReadBytesFromBuffer( StreamBuffer_t * pxStreamBuffer,
1527 size_t xFirstLength;
1529 configASSERT( xCount != ( size_t ) 0 );
1531 /* Calculate the number of bytes that can be read - which may be
1532 * less than the number wanted if the data wraps around to the start of
1534 xFirstLength = configMIN( pxStreamBuffer->xLength - xTail, xCount );
1536 /* Obtain the number of bytes it is possible to obtain in the first
1537 * read. Asserts check bounds of read and write. */
1538 configASSERT( xFirstLength <= xCount );
1539 configASSERT( ( xTail + xFirstLength ) <= pxStreamBuffer->xLength );
1540 ( void ) memcpy( ( void * ) pucData, ( const void * ) &( pxStreamBuffer->pucBuffer[ xTail ] ), xFirstLength );
1542 /* If the total number of wanted bytes is greater than the number
1543 * that could be read in the first read... */
1544 if( xCount > xFirstLength )
1546 /* ...then read the remaining bytes from the start of the buffer. */
1547 ( void ) memcpy( ( void * ) &( pucData[ xFirstLength ] ), ( void * ) ( pxStreamBuffer->pucBuffer ), xCount - xFirstLength );
1551 mtCOVERAGE_TEST_MARKER();
1554 /* Move the tail pointer to effectively remove the data read from the buffer. */
1557 if( xTail >= pxStreamBuffer->xLength )
1559 xTail -= pxStreamBuffer->xLength;
1564 /*-----------------------------------------------------------*/
1566 static size_t prvBytesInBuffer( const StreamBuffer_t * const pxStreamBuffer )
1568 /* Returns the distance between xTail and xHead. */
1571 xCount = pxStreamBuffer->xLength + pxStreamBuffer->xHead;
1572 xCount -= pxStreamBuffer->xTail;
1574 if( xCount >= pxStreamBuffer->xLength )
1576 xCount -= pxStreamBuffer->xLength;
1580 mtCOVERAGE_TEST_MARKER();
1585 /*-----------------------------------------------------------*/
1587 static void prvInitialiseNewStreamBuffer( StreamBuffer_t * const pxStreamBuffer,
1588 uint8_t * const pucBuffer,
1589 size_t xBufferSizeBytes,
1590 size_t xTriggerLevelBytes,
1592 StreamBufferCallbackFunction_t pxSendCompletedCallback,
1593 StreamBufferCallbackFunction_t pxReceiveCompletedCallback )
1595 /* Assert here is deliberately writing to the entire buffer to ensure it can
1596 * be written to without generating exceptions, and is setting the buffer to a
1597 * known value to assist in development/debugging. */
1598 #if ( configASSERT_DEFINED == 1 )
1600 /* The value written just has to be identifiable when looking at the
1601 * memory. Don't use 0xA5 as that is the stack fill value and could
1602 * result in confusion as to what is actually being observed. */
1603 #define STREAM_BUFFER_BUFFER_WRITE_VALUE ( 0x55 )
1604 configASSERT( memset( pucBuffer, ( int ) STREAM_BUFFER_BUFFER_WRITE_VALUE, xBufferSizeBytes ) == pucBuffer );
1608 ( void ) memset( ( void * ) pxStreamBuffer, 0x00, sizeof( StreamBuffer_t ) );
1609 pxStreamBuffer->pucBuffer = pucBuffer;
1610 pxStreamBuffer->xLength = xBufferSizeBytes;
1611 pxStreamBuffer->xTriggerLevelBytes = xTriggerLevelBytes;
1612 pxStreamBuffer->ucFlags = ucFlags;
1613 pxStreamBuffer->uxNotificationIndex = tskDEFAULT_INDEX_TO_NOTIFY;
1614 #if ( configUSE_SB_COMPLETED_CALLBACK == 1 )
1616 pxStreamBuffer->pxSendCompletedCallback = pxSendCompletedCallback;
1617 pxStreamBuffer->pxReceiveCompletedCallback = pxReceiveCompletedCallback;
1621 /* MISRA Ref 11.1.1 [Object type casting] */
1622 /* More details at: https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/MISRA.md#rule-111 */
1623 /* coverity[misra_c_2012_rule_11_1_violation] */
1624 ( void ) pxSendCompletedCallback;
1626 /* MISRA Ref 11.1.1 [Object type casting] */
1627 /* More details at: https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/MISRA.md#rule-111 */
1628 /* coverity[misra_c_2012_rule_11_1_violation] */
1629 ( void ) pxReceiveCompletedCallback;
1631 #endif /* if ( configUSE_SB_COMPLETED_CALLBACK == 1 ) */
1633 /*-----------------------------------------------------------*/
1635 UBaseType_t uxStreamBufferGetStreamBufferNotificationIndex( StreamBufferHandle_t xStreamBuffer )
1637 StreamBuffer_t * const pxStreamBuffer = xStreamBuffer;
1639 traceENTER_uxStreamBufferGetStreamBufferNotificationIndex( xStreamBuffer );
1641 configASSERT( pxStreamBuffer );
1643 traceRETURN_uxStreamBufferGetStreamBufferNotificationIndex( pxStreamBuffer->uxNotificationIndex );
1645 return pxStreamBuffer->uxNotificationIndex;
1647 /*-----------------------------------------------------------*/
1649 void vStreamBufferSetStreamBufferNotificationIndex( StreamBufferHandle_t xStreamBuffer,
1650 UBaseType_t uxNotificationIndex )
1652 StreamBuffer_t * const pxStreamBuffer = xStreamBuffer;
1654 traceENTER_vStreamBufferSetStreamBufferNotificationIndex( xStreamBuffer, uxNotificationIndex );
1656 configASSERT( pxStreamBuffer );
1658 /* There should be no task waiting otherwise we'd never resume them. */
1659 configASSERT( pxStreamBuffer->xTaskWaitingToReceive == NULL );
1660 configASSERT( pxStreamBuffer->xTaskWaitingToSend == NULL );
1662 /* Check that the task notification index is valid. */
1663 configASSERT( uxNotificationIndex < configTASK_NOTIFICATION_ARRAY_ENTRIES );
1665 pxStreamBuffer->uxNotificationIndex = uxNotificationIndex;
1667 traceRETURN_vStreamBufferSetStreamBufferNotificationIndex();
1669 /*-----------------------------------------------------------*/
1671 #if ( configUSE_TRACE_FACILITY == 1 )
1673 UBaseType_t uxStreamBufferGetStreamBufferNumber( StreamBufferHandle_t xStreamBuffer )
1675 traceENTER_uxStreamBufferGetStreamBufferNumber( xStreamBuffer );
1677 traceRETURN_uxStreamBufferGetStreamBufferNumber( xStreamBuffer->uxStreamBufferNumber );
1679 return xStreamBuffer->uxStreamBufferNumber;
1682 #endif /* configUSE_TRACE_FACILITY */
1683 /*-----------------------------------------------------------*/
1685 #if ( configUSE_TRACE_FACILITY == 1 )
1687 void vStreamBufferSetStreamBufferNumber( StreamBufferHandle_t xStreamBuffer,
1688 UBaseType_t uxStreamBufferNumber )
1690 traceENTER_vStreamBufferSetStreamBufferNumber( xStreamBuffer, uxStreamBufferNumber );
1692 xStreamBuffer->uxStreamBufferNumber = uxStreamBufferNumber;
1694 traceRETURN_vStreamBufferSetStreamBufferNumber();
1697 #endif /* configUSE_TRACE_FACILITY */
1698 /*-----------------------------------------------------------*/
1700 #if ( configUSE_TRACE_FACILITY == 1 )
1702 uint8_t ucStreamBufferGetStreamBufferType( StreamBufferHandle_t xStreamBuffer )
1704 traceENTER_ucStreamBufferGetStreamBufferType( xStreamBuffer );
1706 traceRETURN_ucStreamBufferGetStreamBufferType( ( uint8_t ) ( xStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) );
1708 return( ( uint8_t ) ( xStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) );
1711 #endif /* configUSE_TRACE_FACILITY */
1712 /*-----------------------------------------------------------*/
1714 /* This entire source file will be skipped if the application is not configured
1715 * to include stream buffer functionality. This #if is closed at the very bottom
1716 * of this file. If you want to include stream buffers then ensure
1717 * configUSE_STREAM_BUFFERS is set to 1 in FreeRTOSConfig.h. */
1718 #endif /* configUSE_STREAM_BUFFERS == 1 */